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.

283011 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 (JUCE_ANDROID)
  45. #undef JUCE_ANDROID
  46. #define JUCE_ANDROID 1
  47. #elif defined (LINUX) || defined (__linux__)
  48. #define JUCE_LINUX 1
  49. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  50. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  51. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  52. #define JUCE_IPHONE 1
  53. #define JUCE_IOS 1
  54. #else
  55. #define JUCE_MAC 1
  56. #endif
  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 <sys/prctl.h>
  634. #include <signal.h>
  635. /* Got a build error here? You'll need to install the freetype library...
  636. The name of the package to install is "libfreetype6-dev".
  637. */
  638. #include <ft2build.h>
  639. #include FT_FREETYPE_H
  640. #include <X11/Xlib.h>
  641. #include <X11/Xatom.h>
  642. #include <X11/Xresource.h>
  643. #include <X11/Xutil.h>
  644. #include <X11/Xmd.h>
  645. #include <X11/keysym.h>
  646. #include <X11/cursorfont.h>
  647. #if JUCE_USE_XINERAMA
  648. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  649. #include <X11/extensions/Xinerama.h>
  650. #endif
  651. #if JUCE_USE_XSHM
  652. #include <X11/extensions/XShm.h>
  653. #include <sys/shm.h>
  654. #include <sys/ipc.h>
  655. #endif
  656. #if JUCE_USE_XRENDER
  657. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  658. #include <X11/extensions/Xrender.h>
  659. #include <X11/extensions/Xcomposite.h>
  660. #endif
  661. #if JUCE_USE_XCURSOR
  662. // If you're missing this header, try installing the libxcursor-dev package
  663. #include <X11/Xcursor/Xcursor.h>
  664. #endif
  665. #if JUCE_OPENGL
  666. /* Got an include error here?
  667. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  668. and "freeglut3-dev".
  669. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  670. want to disable it.
  671. */
  672. #include <GL/glx.h>
  673. #endif
  674. #undef KeyPress
  675. #if JUCE_ALSA
  676. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  677. not got your paths set up correctly to find its header files.
  678. The package you need to install to get ASLA support is "libasound2-dev".
  679. If you don't have the ALSA library and don't want to build Juce with audio support,
  680. just disable the JUCE_ALSA flag in juce_Config.h
  681. */
  682. #include <alsa/asoundlib.h>
  683. #endif
  684. #if JUCE_JACK
  685. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  686. installed, or you've not got your paths set up correctly to find its header files.
  687. The package you need to install to get JACK support is "libjack-dev".
  688. If you don't have the jack-audio-connection-kit library and don't want to build
  689. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  690. */
  691. #include <jack/jack.h>
  692. //#include <jack/transport.h>
  693. #endif
  694. #undef SIZEOF
  695. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  696. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  697. #elif JUCE_MAC || JUCE_IOS
  698. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  699. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  700. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  701. #define USE_COREGRAPHICS_RENDERING 1
  702. #if JUCE_IOS
  703. #import <Foundation/Foundation.h>
  704. #import <UIKit/UIKit.h>
  705. #import <AudioToolbox/AudioToolbox.h>
  706. #import <AVFoundation/AVFoundation.h>
  707. #import <CoreData/CoreData.h>
  708. #import <MobileCoreServices/MobileCoreServices.h>
  709. #import <QuartzCore/QuartzCore.h>
  710. #include <sys/fcntl.h>
  711. #if JUCE_OPENGL
  712. #include <OpenGLES/ES1/gl.h>
  713. #include <OpenGLES/ES1/glext.h>
  714. #endif
  715. #else
  716. #import <Cocoa/Cocoa.h>
  717. #import <CoreAudio/HostTime.h>
  718. #if JUCE_BUILD_NATIVE
  719. #import <CoreAudio/AudioHardware.h>
  720. #import <CoreMIDI/MIDIServices.h>
  721. #import <QTKit/QTKit.h>
  722. #import <WebKit/WebKit.h>
  723. #import <DiscRecording/DiscRecording.h>
  724. #import <IOKit/IOKitLib.h>
  725. #import <IOKit/IOCFPlugIn.h>
  726. #import <IOKit/hid/IOHIDLib.h>
  727. #import <IOKit/hid/IOHIDKeys.h>
  728. #import <IOKit/pwr_mgt/IOPMLib.h>
  729. #endif
  730. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  731. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  732. #include <Carbon/Carbon.h>
  733. #endif
  734. #include <sys/dir.h>
  735. #endif
  736. #include <sys/socket.h>
  737. #include <sys/sysctl.h>
  738. #include <sys/stat.h>
  739. #include <sys/param.h>
  740. #include <sys/mount.h>
  741. #include <fnmatch.h>
  742. #include <utime.h>
  743. #include <dlfcn.h>
  744. #include <ifaddrs.h>
  745. #include <net/if_dl.h>
  746. #include <mach/mach_time.h>
  747. #include <mach-o/dyld.h>
  748. #if MACOS_10_4_OR_EARLIER
  749. #include <GLUT/glut.h>
  750. #endif
  751. #if ! CGFLOAT_DEFINED
  752. #define CGFloat float
  753. #endif
  754. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  755. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  756. #elif JUCE_ANDROID
  757. /*** Start of inlined file: juce_android_NativeIncludes.h ***/
  758. #ifndef __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  759. #define __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  760. #include <jni.h>
  761. #include <pthread.h>
  762. #include <sched.h>
  763. #include <sys/time.h>
  764. #include <utime.h>
  765. #include <errno.h>
  766. #include <fcntl.h>
  767. #include <dlfcn.h>
  768. #include <sys/stat.h>
  769. #include <sys/statfs.h>
  770. #include <sys/ptrace.h>
  771. #include <sys/sysinfo.h>
  772. #include <pwd.h>
  773. #include <dirent.h>
  774. #include <fnmatch.h>
  775. #if JUCE_OPENGL
  776. #include <GLES/gl.h>
  777. #endif
  778. #endif // __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  779. /*** End of inlined file: juce_android_NativeIncludes.h ***/
  780. #else
  781. #error "Unknown platform!"
  782. #endif
  783. #endif
  784. //==============================================================================
  785. #define DONT_SET_USING_JUCE_NAMESPACE 1
  786. #undef max
  787. #undef min
  788. #define NO_DUMMY_DECL
  789. #define JUCE_AMALGAMATED_TEMPLATE 1
  790. #if JUCE_BUILD_NATIVE
  791. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  792. #endif
  793. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  794. #pragma warning (disable: 4309 4305)
  795. #endif
  796. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  797. BEGIN_JUCE_NAMESPACE
  798. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  799. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  800. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  801. /**
  802. Creates a floating carbon window that can be used to hold a carbon UI.
  803. This is a handy class that's designed to be inlined where needed, e.g.
  804. in the audio plugin hosting code.
  805. */
  806. class CarbonViewWrapperComponent : public Component,
  807. public ComponentMovementWatcher,
  808. public Timer
  809. {
  810. public:
  811. CarbonViewWrapperComponent()
  812. : ComponentMovementWatcher (this),
  813. wrapperWindow (0),
  814. carbonWindow (0),
  815. embeddedView (0),
  816. recursiveResize (false)
  817. {
  818. }
  819. virtual ~CarbonViewWrapperComponent()
  820. {
  821. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  822. }
  823. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  824. virtual void removeView (HIViewRef embeddedView) = 0;
  825. virtual void mouseDown (int, int) {}
  826. virtual void paint() {}
  827. virtual bool getEmbeddedViewSize (int& w, int& h)
  828. {
  829. if (embeddedView == 0)
  830. return false;
  831. HIRect bounds;
  832. HIViewGetBounds (embeddedView, &bounds);
  833. w = jmax (1, roundToInt (bounds.size.width));
  834. h = jmax (1, roundToInt (bounds.size.height));
  835. return true;
  836. }
  837. void createWindow()
  838. {
  839. if (wrapperWindow == 0)
  840. {
  841. Rect r;
  842. r.left = getScreenX();
  843. r.top = getScreenY();
  844. r.right = r.left + getWidth();
  845. r.bottom = r.top + getHeight();
  846. CreateNewWindow (kDocumentWindowClass,
  847. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  848. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  849. &r, &wrapperWindow);
  850. jassert (wrapperWindow != 0);
  851. if (wrapperWindow == 0)
  852. return;
  853. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  854. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  855. [ownerWindow addChildWindow: carbonWindow
  856. ordered: NSWindowAbove];
  857. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  858. EventTypeSpec windowEventTypes[] =
  859. {
  860. { kEventClassWindow, kEventWindowGetClickActivation },
  861. { kEventClassWindow, kEventWindowHandleDeactivate },
  862. { kEventClassWindow, kEventWindowBoundsChanging },
  863. { kEventClassMouse, kEventMouseDown },
  864. { kEventClassMouse, kEventMouseMoved },
  865. { kEventClassMouse, kEventMouseDragged },
  866. { kEventClassMouse, kEventMouseUp},
  867. { kEventClassWindow, kEventWindowDrawContent },
  868. { kEventClassWindow, kEventWindowShown },
  869. { kEventClassWindow, kEventWindowHidden }
  870. };
  871. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  872. InstallWindowEventHandler (wrapperWindow, upp,
  873. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  874. windowEventTypes, this, &eventHandlerRef);
  875. setOurSizeToEmbeddedViewSize();
  876. setEmbeddedWindowToOurSize();
  877. creationTime = Time::getCurrentTime();
  878. }
  879. }
  880. void deleteWindow()
  881. {
  882. removeView (embeddedView);
  883. embeddedView = 0;
  884. if (wrapperWindow != 0)
  885. {
  886. RemoveEventHandler (eventHandlerRef);
  887. DisposeWindow (wrapperWindow);
  888. wrapperWindow = 0;
  889. }
  890. }
  891. void setOurSizeToEmbeddedViewSize()
  892. {
  893. int w, h;
  894. if (getEmbeddedViewSize (w, h))
  895. {
  896. if (w != getWidth() || h != getHeight())
  897. {
  898. startTimer (50);
  899. setSize (w, h);
  900. if (getParentComponent() != 0)
  901. getParentComponent()->setSize (w, h);
  902. }
  903. else
  904. {
  905. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  906. }
  907. }
  908. else
  909. {
  910. stopTimer();
  911. }
  912. }
  913. void setEmbeddedWindowToOurSize()
  914. {
  915. if (! recursiveResize)
  916. {
  917. recursiveResize = true;
  918. if (embeddedView != 0)
  919. {
  920. HIRect r;
  921. r.origin.x = 0;
  922. r.origin.y = 0;
  923. r.size.width = (float) getWidth();
  924. r.size.height = (float) getHeight();
  925. HIViewSetFrame (embeddedView, &r);
  926. }
  927. if (wrapperWindow != 0)
  928. {
  929. Rect wr;
  930. wr.left = getScreenX();
  931. wr.top = getScreenY();
  932. wr.right = wr.left + getWidth();
  933. wr.bottom = wr.top + getHeight();
  934. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  935. ShowWindow (wrapperWindow);
  936. }
  937. recursiveResize = false;
  938. }
  939. }
  940. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  941. {
  942. setEmbeddedWindowToOurSize();
  943. }
  944. void componentPeerChanged()
  945. {
  946. deleteWindow();
  947. createWindow();
  948. }
  949. void componentVisibilityChanged()
  950. {
  951. if (isShowing())
  952. createWindow();
  953. else
  954. deleteWindow();
  955. setEmbeddedWindowToOurSize();
  956. }
  957. static void recursiveHIViewRepaint (HIViewRef view)
  958. {
  959. HIViewSetNeedsDisplay (view, true);
  960. HIViewRef child = HIViewGetFirstSubview (view);
  961. while (child != 0)
  962. {
  963. recursiveHIViewRepaint (child);
  964. child = HIViewGetNextView (child);
  965. }
  966. }
  967. void timerCallback()
  968. {
  969. setOurSizeToEmbeddedViewSize();
  970. // To avoid strange overpainting problems when the UI is first opened, we'll
  971. // repaint it a few times during the first second that it's on-screen..
  972. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  973. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  974. }
  975. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  976. {
  977. switch (GetEventKind (event))
  978. {
  979. case kEventWindowHandleDeactivate:
  980. ActivateWindow (wrapperWindow, TRUE);
  981. return noErr;
  982. case kEventWindowGetClickActivation:
  983. {
  984. getTopLevelComponent()->toFront (false);
  985. [carbonWindow makeKeyAndOrderFront: nil];
  986. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  987. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  988. sizeof (ClickActivationResult), &howToHandleClick);
  989. HIViewSetNeedsDisplay (embeddedView, true);
  990. return noErr;
  991. }
  992. }
  993. return eventNotHandledErr;
  994. }
  995. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  996. {
  997. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  998. }
  999. protected:
  1000. WindowRef wrapperWindow;
  1001. NSWindow* carbonWindow;
  1002. HIViewRef embeddedView;
  1003. bool recursiveResize;
  1004. Time creationTime;
  1005. EventHandlerRef eventHandlerRef;
  1006. };
  1007. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  1008. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  1009. END_JUCE_NAMESPACE
  1010. #endif
  1011. //==============================================================================
  1012. #if JUCE_BUILD_CORE
  1013. /*** Start of inlined file: juce_FileLogger.cpp ***/
  1014. BEGIN_JUCE_NAMESPACE
  1015. FileLogger::FileLogger (const File& logFile_,
  1016. const String& welcomeMessage,
  1017. const int maxInitialFileSizeBytes)
  1018. : logFile (logFile_)
  1019. {
  1020. if (maxInitialFileSizeBytes >= 0)
  1021. trimFileSize (maxInitialFileSizeBytes);
  1022. if (! logFile_.exists())
  1023. {
  1024. // do this so that the parent directories get created..
  1025. logFile_.create();
  1026. }
  1027. String welcome;
  1028. welcome << newLine
  1029. << "**********************************************************" << newLine
  1030. << welcomeMessage << newLine
  1031. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1032. logMessage (welcome);
  1033. }
  1034. FileLogger::~FileLogger()
  1035. {
  1036. }
  1037. void FileLogger::logMessage (const String& message)
  1038. {
  1039. DBG (message);
  1040. const ScopedLock sl (logLock);
  1041. FileOutputStream out (logFile, 256);
  1042. out << message << newLine;
  1043. }
  1044. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1045. {
  1046. if (maxFileSizeBytes <= 0)
  1047. {
  1048. logFile.deleteFile();
  1049. }
  1050. else
  1051. {
  1052. const int64 fileSize = logFile.getSize();
  1053. if (fileSize > maxFileSizeBytes)
  1054. {
  1055. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1056. jassert (in != 0);
  1057. if (in != 0)
  1058. {
  1059. in->setPosition (fileSize - maxFileSizeBytes);
  1060. String content;
  1061. {
  1062. MemoryBlock contentToSave;
  1063. contentToSave.setSize (maxFileSizeBytes + 4);
  1064. contentToSave.fillWith (0);
  1065. in->read (contentToSave.getData(), maxFileSizeBytes);
  1066. in = 0;
  1067. content = contentToSave.toString();
  1068. }
  1069. int newStart = 0;
  1070. while (newStart < fileSize
  1071. && content[newStart] != '\n'
  1072. && content[newStart] != '\r')
  1073. ++newStart;
  1074. logFile.deleteFile();
  1075. logFile.appendText (content.substring (newStart), false, false);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1081. const String& logFileName,
  1082. const String& welcomeMessage,
  1083. const int maxInitialFileSizeBytes)
  1084. {
  1085. #if JUCE_MAC
  1086. File logFile ("~/Library/Logs");
  1087. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1088. .getChildFile (logFileName);
  1089. #else
  1090. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1091. if (logFile.isDirectory())
  1092. {
  1093. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1094. .getChildFile (logFileName);
  1095. }
  1096. #endif
  1097. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1098. }
  1099. END_JUCE_NAMESPACE
  1100. /*** End of inlined file: juce_FileLogger.cpp ***/
  1101. /*** Start of inlined file: juce_Logger.cpp ***/
  1102. BEGIN_JUCE_NAMESPACE
  1103. Logger::Logger()
  1104. {
  1105. }
  1106. Logger::~Logger()
  1107. {
  1108. }
  1109. Logger* Logger::currentLogger = 0;
  1110. void Logger::setCurrentLogger (Logger* const newLogger,
  1111. const bool deleteOldLogger)
  1112. {
  1113. Logger* const oldLogger = currentLogger;
  1114. currentLogger = newLogger;
  1115. if (deleteOldLogger)
  1116. delete oldLogger;
  1117. }
  1118. void Logger::writeToLog (const String& message)
  1119. {
  1120. if (currentLogger != 0)
  1121. currentLogger->logMessage (message);
  1122. else
  1123. outputDebugString (message);
  1124. }
  1125. #if JUCE_LOG_ASSERTIONS
  1126. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1127. {
  1128. String m ("JUCE Assertion failure in ");
  1129. m << filename << ", line " << lineNum;
  1130. Logger::writeToLog (m);
  1131. }
  1132. #endif
  1133. END_JUCE_NAMESPACE
  1134. /*** End of inlined file: juce_Logger.cpp ***/
  1135. /*** Start of inlined file: juce_Random.cpp ***/
  1136. BEGIN_JUCE_NAMESPACE
  1137. Random::Random (const int64 seedValue) throw()
  1138. : seed (seedValue)
  1139. {
  1140. }
  1141. Random::~Random() throw()
  1142. {
  1143. }
  1144. void Random::setSeed (const int64 newSeed) throw()
  1145. {
  1146. seed = newSeed;
  1147. }
  1148. void Random::combineSeed (const int64 seedValue) throw()
  1149. {
  1150. seed ^= nextInt64() ^ seedValue;
  1151. }
  1152. void Random::setSeedRandomly()
  1153. {
  1154. combineSeed ((int64) (pointer_sized_int) this);
  1155. combineSeed (Time::getMillisecondCounter());
  1156. combineSeed (Time::getHighResolutionTicks());
  1157. combineSeed (Time::getHighResolutionTicksPerSecond());
  1158. combineSeed (Time::currentTimeMillis());
  1159. }
  1160. int Random::nextInt() throw()
  1161. {
  1162. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1163. return (int) (seed >> 16);
  1164. }
  1165. int Random::nextInt (const int maxValue) throw()
  1166. {
  1167. jassert (maxValue > 0);
  1168. return (nextInt() & 0x7fffffff) % maxValue;
  1169. }
  1170. int64 Random::nextInt64() throw()
  1171. {
  1172. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1173. }
  1174. bool Random::nextBool() throw()
  1175. {
  1176. return (nextInt() & 0x80000000) != 0;
  1177. }
  1178. float Random::nextFloat() throw()
  1179. {
  1180. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1181. }
  1182. double Random::nextDouble() throw()
  1183. {
  1184. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1185. }
  1186. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1187. {
  1188. BigInteger n;
  1189. do
  1190. {
  1191. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1192. }
  1193. while (n >= maximumValue);
  1194. return n;
  1195. }
  1196. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1197. {
  1198. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1199. while ((startBit & 31) != 0 && numBits > 0)
  1200. {
  1201. arrayToChange.setBit (startBit++, nextBool());
  1202. --numBits;
  1203. }
  1204. while (numBits >= 32)
  1205. {
  1206. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1207. startBit += 32;
  1208. numBits -= 32;
  1209. }
  1210. while (--numBits >= 0)
  1211. arrayToChange.setBit (startBit + numBits, nextBool());
  1212. }
  1213. Random& Random::getSystemRandom() throw()
  1214. {
  1215. static Random sysRand (1);
  1216. return sysRand;
  1217. }
  1218. END_JUCE_NAMESPACE
  1219. /*** End of inlined file: juce_Random.cpp ***/
  1220. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1221. BEGIN_JUCE_NAMESPACE
  1222. RelativeTime::RelativeTime (const double seconds_) throw()
  1223. : seconds (seconds_)
  1224. {
  1225. }
  1226. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1227. : seconds (other.seconds)
  1228. {
  1229. }
  1230. RelativeTime::~RelativeTime() throw()
  1231. {
  1232. }
  1233. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1234. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1235. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1236. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1237. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1238. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1239. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1240. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1241. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1242. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1243. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1244. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1245. {
  1246. if (seconds < 0.001 && seconds > -0.001)
  1247. return returnValueForZeroTime;
  1248. String result;
  1249. result.preallocateStorage (16);
  1250. if (seconds < 0)
  1251. result << '-';
  1252. int fieldsShown = 0;
  1253. int n = std::abs ((int) inWeeks());
  1254. if (n > 0)
  1255. {
  1256. result << n << (n == 1 ? TRANS(" week ")
  1257. : TRANS(" weeks "));
  1258. ++fieldsShown;
  1259. }
  1260. n = std::abs ((int) inDays()) % 7;
  1261. if (n > 0)
  1262. {
  1263. result << n << (n == 1 ? TRANS(" day ")
  1264. : TRANS(" days "));
  1265. ++fieldsShown;
  1266. }
  1267. if (fieldsShown < 2)
  1268. {
  1269. n = std::abs ((int) inHours()) % 24;
  1270. if (n > 0)
  1271. {
  1272. result << n << (n == 1 ? TRANS(" hr ")
  1273. : TRANS(" hrs "));
  1274. ++fieldsShown;
  1275. }
  1276. if (fieldsShown < 2)
  1277. {
  1278. n = std::abs ((int) inMinutes()) % 60;
  1279. if (n > 0)
  1280. {
  1281. result << n << (n == 1 ? TRANS(" min ")
  1282. : TRANS(" mins "));
  1283. ++fieldsShown;
  1284. }
  1285. if (fieldsShown < 2)
  1286. {
  1287. n = std::abs ((int) inSeconds()) % 60;
  1288. if (n > 0)
  1289. {
  1290. result << n << (n == 1 ? TRANS(" sec ")
  1291. : TRANS(" secs "));
  1292. ++fieldsShown;
  1293. }
  1294. if (fieldsShown == 0)
  1295. {
  1296. n = std::abs ((int) inMilliseconds()) % 1000;
  1297. if (n > 0)
  1298. result << n << TRANS(" ms");
  1299. }
  1300. }
  1301. }
  1302. }
  1303. return result.trimEnd();
  1304. }
  1305. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1306. {
  1307. seconds = other.seconds;
  1308. return *this;
  1309. }
  1310. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1311. {
  1312. seconds += timeToAdd.seconds;
  1313. return *this;
  1314. }
  1315. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1316. {
  1317. seconds -= timeToSubtract.seconds;
  1318. return *this;
  1319. }
  1320. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1321. {
  1322. seconds += secondsToAdd;
  1323. return *this;
  1324. }
  1325. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1326. {
  1327. seconds -= secondsToSubtract;
  1328. return *this;
  1329. }
  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. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1336. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1337. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1338. END_JUCE_NAMESPACE
  1339. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1340. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1341. BEGIN_JUCE_NAMESPACE
  1342. SystemStats::CPUFlags SystemStats::cpuFlags;
  1343. const String SystemStats::getJUCEVersion()
  1344. {
  1345. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1346. + "." + String (JUCE_MINOR_VERSION)
  1347. + "." + String (JUCE_BUILDNUMBER);
  1348. }
  1349. #ifdef JUCE_DLL
  1350. void* juce_Malloc (int size) { return malloc (size); }
  1351. void* juce_Calloc (int size) { return calloc (1, size); }
  1352. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1353. void juce_Free (void* block) { free (block); }
  1354. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1355. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1356. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1357. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1358. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1359. #endif
  1360. #endif
  1361. END_JUCE_NAMESPACE
  1362. /*** End of inlined file: juce_SystemStats.cpp ***/
  1363. /*** Start of inlined file: juce_Time.cpp ***/
  1364. #if JUCE_MSVC
  1365. #pragma warning (push)
  1366. #pragma warning (disable: 4514)
  1367. #endif
  1368. #ifndef JUCE_WINDOWS
  1369. #include <sys/time.h>
  1370. #else
  1371. #include <ctime>
  1372. #endif
  1373. #include <sys/timeb.h>
  1374. #if JUCE_MSVC
  1375. #pragma warning (pop)
  1376. #ifdef _INC_TIME_INL
  1377. #define USE_NEW_SECURE_TIME_FNS
  1378. #endif
  1379. #endif
  1380. BEGIN_JUCE_NAMESPACE
  1381. namespace TimeHelpers
  1382. {
  1383. static struct tm millisToLocal (const int64 millis) throw()
  1384. {
  1385. struct tm result;
  1386. const int64 seconds = millis / 1000;
  1387. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1388. {
  1389. // use extended maths for dates beyond 1970 to 2037..
  1390. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1391. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1392. const int days = (int) (jdm / literal64bit (86400));
  1393. const int a = 32044 + days;
  1394. const int b = (4 * a + 3) / 146097;
  1395. const int c = a - (b * 146097) / 4;
  1396. const int d = (4 * c + 3) / 1461;
  1397. const int e = c - (d * 1461) / 4;
  1398. const int m = (5 * e + 2) / 153;
  1399. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1400. result.tm_mon = m + 2 - 12 * (m / 10);
  1401. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1402. result.tm_wday = (days + 1) % 7;
  1403. result.tm_yday = -1;
  1404. int t = (int) (jdm % literal64bit (86400));
  1405. result.tm_hour = t / 3600;
  1406. t %= 3600;
  1407. result.tm_min = t / 60;
  1408. result.tm_sec = t % 60;
  1409. result.tm_isdst = -1;
  1410. }
  1411. else
  1412. {
  1413. time_t now = static_cast <time_t> (seconds);
  1414. #if JUCE_WINDOWS
  1415. #ifdef USE_NEW_SECURE_TIME_FNS
  1416. if (now >= 0 && now <= 0x793406fff)
  1417. localtime_s (&result, &now);
  1418. else
  1419. zeromem (&result, sizeof (result));
  1420. #else
  1421. result = *localtime (&now);
  1422. #endif
  1423. #else
  1424. // more thread-safe
  1425. localtime_r (&now, &result);
  1426. #endif
  1427. }
  1428. return result;
  1429. }
  1430. static int extendedModulo (const int64 value, const int modulo) throw()
  1431. {
  1432. return (int) (value >= 0 ? (value % modulo)
  1433. : (value - ((value / modulo) + 1) * modulo));
  1434. }
  1435. static uint32 lastMSCounterValue = 0;
  1436. }
  1437. Time::Time() throw()
  1438. : millisSinceEpoch (0)
  1439. {
  1440. }
  1441. Time::Time (const Time& other) throw()
  1442. : millisSinceEpoch (other.millisSinceEpoch)
  1443. {
  1444. }
  1445. Time::Time (const int64 ms) throw()
  1446. : millisSinceEpoch (ms)
  1447. {
  1448. }
  1449. Time::Time (const int year,
  1450. const int month,
  1451. const int day,
  1452. const int hours,
  1453. const int minutes,
  1454. const int seconds,
  1455. const int milliseconds,
  1456. const bool useLocalTime) throw()
  1457. {
  1458. jassert (year > 100); // year must be a 4-digit version
  1459. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1460. {
  1461. // use extended maths for dates beyond 1970 to 2037..
  1462. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1463. : 0;
  1464. const int a = (13 - month) / 12;
  1465. const int y = year + 4800 - a;
  1466. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1467. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1468. - 32045;
  1469. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1470. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1471. + milliseconds;
  1472. }
  1473. else
  1474. {
  1475. struct tm t;
  1476. t.tm_year = year - 1900;
  1477. t.tm_mon = month;
  1478. t.tm_mday = day;
  1479. t.tm_hour = hours;
  1480. t.tm_min = minutes;
  1481. t.tm_sec = seconds;
  1482. t.tm_isdst = -1;
  1483. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1484. if (millisSinceEpoch < 0)
  1485. millisSinceEpoch = 0;
  1486. else
  1487. millisSinceEpoch += milliseconds;
  1488. }
  1489. }
  1490. Time::~Time() throw()
  1491. {
  1492. }
  1493. Time& Time::operator= (const Time& other) throw()
  1494. {
  1495. millisSinceEpoch = other.millisSinceEpoch;
  1496. return *this;
  1497. }
  1498. int64 Time::currentTimeMillis() throw()
  1499. {
  1500. static uint32 lastCounterResult = 0xffffffff;
  1501. static int64 correction = 0;
  1502. const uint32 now = getMillisecondCounter();
  1503. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1504. if (now < lastCounterResult)
  1505. {
  1506. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1507. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1508. {
  1509. // get the time once using normal library calls, and store the difference needed to
  1510. // turn the millisecond counter into a real time.
  1511. #if JUCE_WINDOWS
  1512. struct _timeb t;
  1513. #ifdef USE_NEW_SECURE_TIME_FNS
  1514. _ftime_s (&t);
  1515. #else
  1516. _ftime (&t);
  1517. #endif
  1518. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1519. #else
  1520. struct timeval tv;
  1521. struct timezone tz;
  1522. gettimeofday (&tv, &tz);
  1523. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1524. #endif
  1525. }
  1526. }
  1527. lastCounterResult = now;
  1528. return correction + now;
  1529. }
  1530. uint32 juce_millisecondsSinceStartup() throw();
  1531. uint32 Time::getMillisecondCounter() throw()
  1532. {
  1533. const uint32 now = juce_millisecondsSinceStartup();
  1534. if (now < TimeHelpers::lastMSCounterValue)
  1535. {
  1536. // in multi-threaded apps this might be called concurrently, so
  1537. // make sure that our last counter value only increases and doesn't
  1538. // go backwards..
  1539. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1540. TimeHelpers::lastMSCounterValue = now;
  1541. }
  1542. else
  1543. {
  1544. TimeHelpers::lastMSCounterValue = now;
  1545. }
  1546. return now;
  1547. }
  1548. uint32 Time::getApproximateMillisecondCounter() throw()
  1549. {
  1550. jassert (TimeHelpers::lastMSCounterValue != 0);
  1551. return TimeHelpers::lastMSCounterValue;
  1552. }
  1553. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1554. {
  1555. for (;;)
  1556. {
  1557. const uint32 now = getMillisecondCounter();
  1558. if (now >= targetTime)
  1559. break;
  1560. const int toWait = targetTime - now;
  1561. if (toWait > 2)
  1562. {
  1563. Thread::sleep (jmin (20, toWait >> 1));
  1564. }
  1565. else
  1566. {
  1567. // xxx should consider using mutex_pause on the mac as it apparently
  1568. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1569. for (int i = 10; --i >= 0;)
  1570. Thread::yield();
  1571. }
  1572. }
  1573. }
  1574. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1575. {
  1576. return ticks / (double) getHighResolutionTicksPerSecond();
  1577. }
  1578. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1579. {
  1580. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1581. }
  1582. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1583. {
  1584. return Time (currentTimeMillis());
  1585. }
  1586. const String Time::toString (const bool includeDate,
  1587. const bool includeTime,
  1588. const bool includeSeconds,
  1589. const bool use24HourClock) const throw()
  1590. {
  1591. String result;
  1592. if (includeDate)
  1593. {
  1594. result << getDayOfMonth() << ' '
  1595. << getMonthName (true) << ' '
  1596. << getYear();
  1597. if (includeTime)
  1598. result << ' ';
  1599. }
  1600. if (includeTime)
  1601. {
  1602. const int mins = getMinutes();
  1603. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1604. << (mins < 10 ? ":0" : ":") << mins;
  1605. if (includeSeconds)
  1606. {
  1607. const int secs = getSeconds();
  1608. result << (secs < 10 ? ":0" : ":") << secs;
  1609. }
  1610. if (! use24HourClock)
  1611. result << (isAfternoon() ? "pm" : "am");
  1612. }
  1613. return result.trimEnd();
  1614. }
  1615. const String Time::formatted (const String& format) const
  1616. {
  1617. String buffer;
  1618. int bufferSize = 128;
  1619. buffer.preallocateStorage (bufferSize);
  1620. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1621. while (CharacterFunctions::ftime (buffer.getCharPointer().getAddress(), bufferSize, format.getCharPointer(), &t) <= 0)
  1622. {
  1623. bufferSize += 128;
  1624. buffer.preallocateStorage (bufferSize);
  1625. }
  1626. return buffer;
  1627. }
  1628. int Time::getYear() const throw()
  1629. {
  1630. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1631. }
  1632. int Time::getMonth() const throw()
  1633. {
  1634. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1635. }
  1636. int Time::getDayOfMonth() const throw()
  1637. {
  1638. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1639. }
  1640. int Time::getDayOfWeek() const throw()
  1641. {
  1642. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1643. }
  1644. int Time::getHours() const throw()
  1645. {
  1646. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1647. }
  1648. int Time::getHoursInAmPmFormat() const throw()
  1649. {
  1650. const int hours = getHours();
  1651. if (hours == 0)
  1652. return 12;
  1653. else if (hours <= 12)
  1654. return hours;
  1655. else
  1656. return hours - 12;
  1657. }
  1658. bool Time::isAfternoon() const throw()
  1659. {
  1660. return getHours() >= 12;
  1661. }
  1662. int Time::getMinutes() const throw()
  1663. {
  1664. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1665. }
  1666. int Time::getSeconds() const throw()
  1667. {
  1668. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1669. }
  1670. int Time::getMilliseconds() const throw()
  1671. {
  1672. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1673. }
  1674. bool Time::isDaylightSavingTime() const throw()
  1675. {
  1676. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1677. }
  1678. const String Time::getTimeZone() const throw()
  1679. {
  1680. String zone[2];
  1681. #if JUCE_WINDOWS
  1682. _tzset();
  1683. #ifdef USE_NEW_SECURE_TIME_FNS
  1684. {
  1685. char name [128];
  1686. size_t length;
  1687. for (int i = 0; i < 2; ++i)
  1688. {
  1689. zeromem (name, sizeof (name));
  1690. _get_tzname (&length, name, 127, i);
  1691. zone[i] = name;
  1692. }
  1693. }
  1694. #else
  1695. const char** const zonePtr = (const char**) _tzname;
  1696. zone[0] = zonePtr[0];
  1697. zone[1] = zonePtr[1];
  1698. #endif
  1699. #else
  1700. tzset();
  1701. const char** const zonePtr = (const char**) tzname;
  1702. zone[0] = zonePtr[0];
  1703. zone[1] = zonePtr[1];
  1704. #endif
  1705. if (isDaylightSavingTime())
  1706. {
  1707. zone[0] = zone[1];
  1708. if (zone[0].length() > 3
  1709. && zone[0].containsIgnoreCase ("daylight")
  1710. && zone[0].contains ("GMT"))
  1711. zone[0] = "BST";
  1712. }
  1713. return zone[0].substring (0, 3);
  1714. }
  1715. const String Time::getMonthName (const bool threeLetterVersion) const
  1716. {
  1717. return getMonthName (getMonth(), threeLetterVersion);
  1718. }
  1719. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1720. {
  1721. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1722. }
  1723. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1724. {
  1725. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1726. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1727. monthNumber %= 12;
  1728. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1729. : longMonthNames [monthNumber]);
  1730. }
  1731. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1732. {
  1733. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1734. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1735. day %= 7;
  1736. return TRANS (threeLetterVersion ? shortDayNames [day]
  1737. : longDayNames [day]);
  1738. }
  1739. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1740. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1741. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1742. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1743. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1744. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (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. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1751. END_JUCE_NAMESPACE
  1752. /*** End of inlined file: juce_Time.cpp ***/
  1753. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1754. BEGIN_JUCE_NAMESPACE
  1755. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1756. #endif
  1757. #if JUCE_WINDOWS
  1758. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1759. #endif
  1760. #if JUCE_DEBUG
  1761. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1762. #endif
  1763. static bool juceInitialisedNonGUI = false;
  1764. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1765. {
  1766. if (! juceInitialisedNonGUI)
  1767. {
  1768. juceInitialisedNonGUI = true;
  1769. JUCE_AUTORELEASEPOOL
  1770. DBG (SystemStats::getJUCEVersion());
  1771. SystemStats::initialiseStats();
  1772. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1773. }
  1774. // Some basic tests, to keep an eye on things and make sure these types work ok
  1775. // on all platforms. Let me know if any of these assertions fail on your system!
  1776. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1777. static_jassert (sizeof (int8) == 1);
  1778. static_jassert (sizeof (uint8) == 1);
  1779. static_jassert (sizeof (int16) == 2);
  1780. static_jassert (sizeof (uint16) == 2);
  1781. static_jassert (sizeof (int32) == 4);
  1782. static_jassert (sizeof (uint32) == 4);
  1783. static_jassert (sizeof (int64) == 8);
  1784. static_jassert (sizeof (uint64) == 8);
  1785. #if JUCE_NATIVE_WCHAR_IS_UTF8
  1786. static_jassert (sizeof (wchar_t) == 1);
  1787. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  1788. static_jassert (sizeof (wchar_t) == 2);
  1789. #elif JUCE_NATIVE_WCHAR_IS_UTF32
  1790. static_jassert (sizeof (wchar_t) == 4);
  1791. #else
  1792. #error "native wchar_t size is unknown"
  1793. #endif
  1794. }
  1795. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1796. {
  1797. if (juceInitialisedNonGUI)
  1798. {
  1799. juceInitialisedNonGUI = false;
  1800. JUCE_AUTORELEASEPOOL
  1801. LocalisedStrings::setCurrentMappings (0);
  1802. Thread::stopAllThreads (3000);
  1803. #if JUCE_WINDOWS
  1804. juce_shutdownWin32Sockets();
  1805. #endif
  1806. #if JUCE_DEBUG
  1807. juce_CheckForDanglingStreams();
  1808. #endif
  1809. }
  1810. }
  1811. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1812. static bool juceInitialisedGUI = false;
  1813. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1814. {
  1815. if (! juceInitialisedGUI)
  1816. {
  1817. juceInitialisedGUI = true;
  1818. JUCE_AUTORELEASEPOOL
  1819. initialiseJuce_NonGUI();
  1820. MessageManager::getInstance();
  1821. LookAndFeel::setDefaultLookAndFeel (0);
  1822. #if JUCE_DEBUG
  1823. try // This section is just a safety-net for catching builds without RTTI enabled..
  1824. {
  1825. MemoryOutputStream mo;
  1826. OutputStream* o = &mo;
  1827. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1828. o = dynamic_cast <MemoryOutputStream*> (o);
  1829. jassert (o != 0);
  1830. }
  1831. catch (...)
  1832. {
  1833. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1834. jassertfalse;
  1835. }
  1836. #endif
  1837. }
  1838. }
  1839. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1840. {
  1841. if (juceInitialisedGUI)
  1842. {
  1843. juceInitialisedGUI = false;
  1844. JUCE_AUTORELEASEPOOL
  1845. DeletedAtShutdown::deleteAll();
  1846. LookAndFeel::clearDefaultLookAndFeel();
  1847. delete MessageManager::getInstance();
  1848. shutdownJuce_NonGUI();
  1849. }
  1850. }
  1851. #endif
  1852. #if JUCE_UNIT_TESTS
  1853. class AtomicTests : public UnitTest
  1854. {
  1855. public:
  1856. AtomicTests() : UnitTest ("Atomics") {}
  1857. void runTest()
  1858. {
  1859. beginTest ("Misc");
  1860. char a1[7];
  1861. expect (numElementsInArray(a1) == 7);
  1862. int a2[3];
  1863. expect (numElementsInArray(a2) == 3);
  1864. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1865. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1866. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1867. beginTest ("Atomic int");
  1868. AtomicTester <int>::testInteger (*this);
  1869. beginTest ("Atomic unsigned int");
  1870. AtomicTester <unsigned int>::testInteger (*this);
  1871. beginTest ("Atomic int32");
  1872. AtomicTester <int32>::testInteger (*this);
  1873. beginTest ("Atomic uint32");
  1874. AtomicTester <uint32>::testInteger (*this);
  1875. beginTest ("Atomic long");
  1876. AtomicTester <long>::testInteger (*this);
  1877. beginTest ("Atomic void*");
  1878. AtomicTester <void*>::testInteger (*this);
  1879. beginTest ("Atomic int*");
  1880. AtomicTester <int*>::testInteger (*this);
  1881. beginTest ("Atomic float");
  1882. AtomicTester <float>::testFloat (*this);
  1883. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1884. beginTest ("Atomic int64");
  1885. AtomicTester <int64>::testInteger (*this);
  1886. beginTest ("Atomic uint64");
  1887. AtomicTester <uint64>::testInteger (*this);
  1888. beginTest ("Atomic double");
  1889. AtomicTester <double>::testFloat (*this);
  1890. #endif
  1891. }
  1892. template <typename Type>
  1893. class AtomicTester
  1894. {
  1895. public:
  1896. AtomicTester() {}
  1897. static void testInteger (UnitTest& test)
  1898. {
  1899. Atomic<Type> a, b;
  1900. a.set ((Type) 10);
  1901. test.expect (a.value == (Type) 10);
  1902. test.expect (a.get() == (Type) 10);
  1903. a += (Type) 15;
  1904. test.expect (a.get() == (Type) 25);
  1905. a.memoryBarrier();
  1906. a -= (Type) 5;
  1907. test.expect (a.get() == (Type) 20);
  1908. test.expect (++a == (Type) 21);
  1909. ++a;
  1910. test.expect (--a == (Type) 21);
  1911. test.expect (a.get() == (Type) 21);
  1912. a.memoryBarrier();
  1913. testFloat (test);
  1914. }
  1915. static void testFloat (UnitTest& test)
  1916. {
  1917. Atomic<Type> a, b;
  1918. a = (Type) 21;
  1919. a.memoryBarrier();
  1920. /* These are some simple test cases to check the atomics - let me know
  1921. if any of these assertions fail on your system!
  1922. */
  1923. test.expect (a.get() == (Type) 21);
  1924. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1925. test.expect (a.get() == (Type) 21);
  1926. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1927. test.expect (a.get() == (Type) 101);
  1928. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1929. test.expect (a.get() == (Type) 101);
  1930. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1931. test.expect (a.get() == (Type) 200);
  1932. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1933. test.expect (a.get() == (Type) 300);
  1934. b = a;
  1935. test.expect (b.get() == a.get());
  1936. }
  1937. };
  1938. };
  1939. static AtomicTests atomicUnitTests;
  1940. #endif
  1941. END_JUCE_NAMESPACE
  1942. /*** End of inlined file: juce_Initialisation.cpp ***/
  1943. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1944. BEGIN_JUCE_NAMESPACE
  1945. AbstractFifo::AbstractFifo (const int capacity) throw()
  1946. : bufferSize (capacity)
  1947. {
  1948. jassert (bufferSize > 0);
  1949. }
  1950. AbstractFifo::~AbstractFifo() {}
  1951. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1952. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1953. int AbstractFifo::getNumReady() const throw()
  1954. {
  1955. const int vs = validStart.get();
  1956. const int ve = validEnd.get();
  1957. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1958. }
  1959. void AbstractFifo::reset() throw()
  1960. {
  1961. validEnd = 0;
  1962. validStart = 0;
  1963. }
  1964. void AbstractFifo::setTotalSize (int newSize) throw()
  1965. {
  1966. jassert (newSize > 0);
  1967. reset();
  1968. bufferSize = newSize;
  1969. }
  1970. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1971. {
  1972. const int vs = validStart.get();
  1973. const int ve = validEnd.value;
  1974. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1975. numToWrite = jmin (numToWrite, freeSpace - 1);
  1976. if (numToWrite <= 0)
  1977. {
  1978. startIndex1 = 0;
  1979. startIndex2 = 0;
  1980. blockSize1 = 0;
  1981. blockSize2 = 0;
  1982. }
  1983. else
  1984. {
  1985. startIndex1 = ve;
  1986. startIndex2 = 0;
  1987. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1988. numToWrite -= blockSize1;
  1989. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1990. }
  1991. }
  1992. void AbstractFifo::finishedWrite (int numWritten) throw()
  1993. {
  1994. jassert (numWritten >= 0 && numWritten < bufferSize);
  1995. int newEnd = validEnd.value + numWritten;
  1996. if (newEnd >= bufferSize)
  1997. newEnd -= bufferSize;
  1998. validEnd = newEnd;
  1999. }
  2000. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2001. {
  2002. const int vs = validStart.value;
  2003. const int ve = validEnd.get();
  2004. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  2005. numWanted = jmin (numWanted, numReady);
  2006. if (numWanted <= 0)
  2007. {
  2008. startIndex1 = 0;
  2009. startIndex2 = 0;
  2010. blockSize1 = 0;
  2011. blockSize2 = 0;
  2012. }
  2013. else
  2014. {
  2015. startIndex1 = vs;
  2016. startIndex2 = 0;
  2017. blockSize1 = jmin (bufferSize - vs, numWanted);
  2018. numWanted -= blockSize1;
  2019. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  2020. }
  2021. }
  2022. void AbstractFifo::finishedRead (int numRead) throw()
  2023. {
  2024. jassert (numRead >= 0 && numRead <= bufferSize);
  2025. int newStart = validStart.value + numRead;
  2026. if (newStart >= bufferSize)
  2027. newStart -= bufferSize;
  2028. validStart = newStart;
  2029. }
  2030. #if JUCE_UNIT_TESTS
  2031. class AbstractFifoTests : public UnitTest
  2032. {
  2033. public:
  2034. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2035. class WriteThread : public Thread
  2036. {
  2037. public:
  2038. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2039. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2040. {
  2041. startThread();
  2042. }
  2043. ~WriteThread()
  2044. {
  2045. stopThread (5000);
  2046. }
  2047. void run()
  2048. {
  2049. int n = 0;
  2050. while (! threadShouldExit())
  2051. {
  2052. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2053. int start1, size1, start2, size2;
  2054. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2055. jassert (size1 >= 0 && size2 >= 0);
  2056. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2057. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2058. int i;
  2059. for (i = 0; i < size1; ++i)
  2060. buffer [start1 + i] = n++;
  2061. for (i = 0; i < size2; ++i)
  2062. buffer [start2 + i] = n++;
  2063. fifo.finishedWrite (size1 + size2);
  2064. }
  2065. }
  2066. private:
  2067. AbstractFifo& fifo;
  2068. int* buffer;
  2069. };
  2070. void runTest()
  2071. {
  2072. beginTest ("AbstractFifo");
  2073. int buffer [5000];
  2074. AbstractFifo fifo (numElementsInArray (buffer));
  2075. WriteThread writer (fifo, buffer);
  2076. int n = 0;
  2077. for (int count = 1000000; --count >= 0;)
  2078. {
  2079. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2080. int start1, size1, start2, size2;
  2081. fifo.prepareToRead (num, start1, size1, start2, size2);
  2082. if (! (size1 >= 0 && size2 >= 0)
  2083. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2084. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2085. {
  2086. expect (false, "prepareToRead returned -ve values");
  2087. break;
  2088. }
  2089. bool failed = false;
  2090. int i;
  2091. for (i = 0; i < size1; ++i)
  2092. failed = (buffer [start1 + i] != n++) || failed;
  2093. for (i = 0; i < size2; ++i)
  2094. failed = (buffer [start2 + i] != n++) || failed;
  2095. if (failed)
  2096. {
  2097. expect (false, "read values were incorrect");
  2098. break;
  2099. }
  2100. fifo.finishedRead (size1 + size2);
  2101. }
  2102. }
  2103. };
  2104. static AbstractFifoTests fifoUnitTests;
  2105. #endif
  2106. END_JUCE_NAMESPACE
  2107. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2108. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2109. BEGIN_JUCE_NAMESPACE
  2110. BigInteger::BigInteger()
  2111. : numValues (4),
  2112. highestBit (-1),
  2113. negative (false)
  2114. {
  2115. values.calloc (numValues + 1);
  2116. }
  2117. BigInteger::BigInteger (const int32 value)
  2118. : numValues (4),
  2119. highestBit (31),
  2120. negative (value < 0)
  2121. {
  2122. values.calloc (numValues + 1);
  2123. values[0] = abs (value);
  2124. highestBit = getHighestBit();
  2125. }
  2126. BigInteger::BigInteger (const uint32 value)
  2127. : numValues (4),
  2128. highestBit (31),
  2129. negative (false)
  2130. {
  2131. values.calloc (numValues + 1);
  2132. values[0] = value;
  2133. highestBit = getHighestBit();
  2134. }
  2135. BigInteger::BigInteger (int64 value)
  2136. : numValues (4),
  2137. highestBit (63),
  2138. negative (value < 0)
  2139. {
  2140. values.calloc (numValues + 1);
  2141. if (value < 0)
  2142. value = -value;
  2143. values[0] = (uint32) value;
  2144. values[1] = (uint32) (value >> 32);
  2145. highestBit = getHighestBit();
  2146. }
  2147. BigInteger::BigInteger (const BigInteger& other)
  2148. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2149. highestBit (other.getHighestBit()),
  2150. negative (other.negative)
  2151. {
  2152. values.malloc (numValues + 1);
  2153. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2154. }
  2155. BigInteger::~BigInteger()
  2156. {
  2157. }
  2158. void BigInteger::swapWith (BigInteger& other) throw()
  2159. {
  2160. values.swapWith (other.values);
  2161. swapVariables (numValues, other.numValues);
  2162. swapVariables (highestBit, other.highestBit);
  2163. swapVariables (negative, other.negative);
  2164. }
  2165. BigInteger& BigInteger::operator= (const BigInteger& other)
  2166. {
  2167. if (this != &other)
  2168. {
  2169. highestBit = other.getHighestBit();
  2170. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2171. negative = other.negative;
  2172. values.malloc (numValues + 1);
  2173. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2174. }
  2175. return *this;
  2176. }
  2177. void BigInteger::ensureSize (const int numVals)
  2178. {
  2179. if (numVals + 2 >= numValues)
  2180. {
  2181. int oldSize = numValues;
  2182. numValues = ((numVals + 2) * 3) / 2;
  2183. values.realloc (numValues + 1);
  2184. while (oldSize < numValues)
  2185. values [oldSize++] = 0;
  2186. }
  2187. }
  2188. bool BigInteger::operator[] (const int bit) const throw()
  2189. {
  2190. return bit <= highestBit && bit >= 0
  2191. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2192. }
  2193. int BigInteger::toInteger() const throw()
  2194. {
  2195. const int n = (int) (values[0] & 0x7fffffff);
  2196. return negative ? -n : n;
  2197. }
  2198. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2199. {
  2200. BigInteger r;
  2201. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2202. r.ensureSize (bitToIndex (numBits));
  2203. r.highestBit = numBits;
  2204. int i = 0;
  2205. while (numBits > 0)
  2206. {
  2207. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2208. numBits -= 32;
  2209. startBit += 32;
  2210. }
  2211. r.highestBit = r.getHighestBit();
  2212. return r;
  2213. }
  2214. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2215. {
  2216. if (numBits > 32)
  2217. {
  2218. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2219. numBits = 32;
  2220. }
  2221. numBits = jmin (numBits, highestBit + 1 - startBit);
  2222. if (numBits <= 0)
  2223. return 0;
  2224. const int pos = bitToIndex (startBit);
  2225. const int offset = startBit & 31;
  2226. const int endSpace = 32 - numBits;
  2227. uint32 n = ((uint32) values [pos]) >> offset;
  2228. if (offset > endSpace)
  2229. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2230. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2231. }
  2232. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2233. {
  2234. if (numBits > 32)
  2235. {
  2236. jassertfalse;
  2237. numBits = 32;
  2238. }
  2239. for (int i = 0; i < numBits; ++i)
  2240. {
  2241. setBit (startBit + i, (valueToSet & 1) != 0);
  2242. valueToSet >>= 1;
  2243. }
  2244. }
  2245. void BigInteger::clear()
  2246. {
  2247. if (numValues > 16)
  2248. {
  2249. numValues = 4;
  2250. values.calloc (numValues + 1);
  2251. }
  2252. else
  2253. {
  2254. zeromem (values, sizeof (uint32) * (numValues + 1));
  2255. }
  2256. highestBit = -1;
  2257. negative = false;
  2258. }
  2259. void BigInteger::setBit (const int bit)
  2260. {
  2261. if (bit >= 0)
  2262. {
  2263. if (bit > highestBit)
  2264. {
  2265. ensureSize (bitToIndex (bit));
  2266. highestBit = bit;
  2267. }
  2268. values [bitToIndex (bit)] |= bitToMask (bit);
  2269. }
  2270. }
  2271. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2272. {
  2273. if (shouldBeSet)
  2274. setBit (bit);
  2275. else
  2276. clearBit (bit);
  2277. }
  2278. void BigInteger::clearBit (const int bit) throw()
  2279. {
  2280. if (bit >= 0 && bit <= highestBit)
  2281. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2282. }
  2283. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2284. {
  2285. while (--numBits >= 0)
  2286. setBit (startBit++, shouldBeSet);
  2287. }
  2288. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2289. {
  2290. if (bit >= 0)
  2291. shiftBits (1, bit);
  2292. setBit (bit, shouldBeSet);
  2293. }
  2294. bool BigInteger::isZero() const throw()
  2295. {
  2296. return getHighestBit() < 0;
  2297. }
  2298. bool BigInteger::isOne() const throw()
  2299. {
  2300. return getHighestBit() == 0 && ! negative;
  2301. }
  2302. bool BigInteger::isNegative() const throw()
  2303. {
  2304. return negative && ! isZero();
  2305. }
  2306. void BigInteger::setNegative (const bool neg) throw()
  2307. {
  2308. negative = neg;
  2309. }
  2310. void BigInteger::negate() throw()
  2311. {
  2312. negative = (! negative) && ! isZero();
  2313. }
  2314. #if JUCE_USE_INTRINSICS
  2315. #pragma intrinsic (_BitScanReverse)
  2316. #endif
  2317. namespace BitFunctions
  2318. {
  2319. inline int countBitsInInt32 (uint32 n) throw()
  2320. {
  2321. n -= ((n >> 1) & 0x55555555);
  2322. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2323. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2324. n += (n >> 8);
  2325. n += (n >> 16);
  2326. return n & 0x3f;
  2327. }
  2328. inline int highestBitInInt (uint32 n) throw()
  2329. {
  2330. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2331. #if JUCE_GCC
  2332. return 31 - __builtin_clz (n);
  2333. #elif JUCE_USE_INTRINSICS
  2334. unsigned long highest;
  2335. _BitScanReverse (&highest, n);
  2336. return (int) highest;
  2337. #else
  2338. n |= (n >> 1);
  2339. n |= (n >> 2);
  2340. n |= (n >> 4);
  2341. n |= (n >> 8);
  2342. n |= (n >> 16);
  2343. return countBitsInInt32 (n >> 1);
  2344. #endif
  2345. }
  2346. }
  2347. int BigInteger::countNumberOfSetBits() const throw()
  2348. {
  2349. int total = 0;
  2350. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2351. total += BitFunctions::countBitsInInt32 (values[i]);
  2352. return total;
  2353. }
  2354. int BigInteger::getHighestBit() const throw()
  2355. {
  2356. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2357. {
  2358. const uint32 n = values[i];
  2359. if (n != 0)
  2360. return BitFunctions::highestBitInInt (n) + (i << 5);
  2361. }
  2362. return -1;
  2363. }
  2364. int BigInteger::findNextSetBit (int i) const throw()
  2365. {
  2366. for (; i <= highestBit; ++i)
  2367. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2368. return i;
  2369. return -1;
  2370. }
  2371. int BigInteger::findNextClearBit (int i) const throw()
  2372. {
  2373. for (; i <= highestBit; ++i)
  2374. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2375. break;
  2376. return i;
  2377. }
  2378. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2379. {
  2380. if (other.isNegative())
  2381. return operator-= (-other);
  2382. if (isNegative())
  2383. {
  2384. if (compareAbsolute (other) < 0)
  2385. {
  2386. BigInteger temp (*this);
  2387. temp.negate();
  2388. *this = other;
  2389. operator-= (temp);
  2390. }
  2391. else
  2392. {
  2393. negate();
  2394. operator-= (other);
  2395. negate();
  2396. }
  2397. }
  2398. else
  2399. {
  2400. if (other.highestBit > highestBit)
  2401. highestBit = other.highestBit;
  2402. ++highestBit;
  2403. const int numInts = bitToIndex (highestBit) + 1;
  2404. ensureSize (numInts);
  2405. int64 remainder = 0;
  2406. for (int i = 0; i <= numInts; ++i)
  2407. {
  2408. if (i < numValues)
  2409. remainder += values[i];
  2410. if (i < other.numValues)
  2411. remainder += other.values[i];
  2412. values[i] = (uint32) remainder;
  2413. remainder >>= 32;
  2414. }
  2415. jassert (remainder == 0);
  2416. highestBit = getHighestBit();
  2417. }
  2418. return *this;
  2419. }
  2420. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2421. {
  2422. if (other.isNegative())
  2423. return operator+= (-other);
  2424. if (! isNegative())
  2425. {
  2426. if (compareAbsolute (other) < 0)
  2427. {
  2428. BigInteger temp (other);
  2429. swapWith (temp);
  2430. operator-= (temp);
  2431. negate();
  2432. return *this;
  2433. }
  2434. }
  2435. else
  2436. {
  2437. negate();
  2438. operator+= (other);
  2439. negate();
  2440. return *this;
  2441. }
  2442. const int numInts = bitToIndex (highestBit) + 1;
  2443. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2444. int64 amountToSubtract = 0;
  2445. for (int i = 0; i <= numInts; ++i)
  2446. {
  2447. if (i <= maxOtherInts)
  2448. amountToSubtract += (int64) other.values[i];
  2449. if (values[i] >= amountToSubtract)
  2450. {
  2451. values[i] = (uint32) (values[i] - amountToSubtract);
  2452. amountToSubtract = 0;
  2453. }
  2454. else
  2455. {
  2456. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2457. values[i] = (uint32) n;
  2458. amountToSubtract = 1;
  2459. }
  2460. }
  2461. return *this;
  2462. }
  2463. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2464. {
  2465. BigInteger total;
  2466. highestBit = getHighestBit();
  2467. const bool wasNegative = isNegative();
  2468. setNegative (false);
  2469. for (int i = 0; i <= highestBit; ++i)
  2470. {
  2471. if (operator[](i))
  2472. {
  2473. BigInteger n (other);
  2474. n.setNegative (false);
  2475. n <<= i;
  2476. total += n;
  2477. }
  2478. }
  2479. total.setNegative (wasNegative ^ other.isNegative());
  2480. swapWith (total);
  2481. return *this;
  2482. }
  2483. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2484. {
  2485. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2486. const int divHB = divisor.getHighestBit();
  2487. const int ourHB = getHighestBit();
  2488. if (divHB < 0 || ourHB < 0)
  2489. {
  2490. // division by zero
  2491. remainder.clear();
  2492. clear();
  2493. }
  2494. else
  2495. {
  2496. const bool wasNegative = isNegative();
  2497. swapWith (remainder);
  2498. remainder.setNegative (false);
  2499. clear();
  2500. BigInteger temp (divisor);
  2501. temp.setNegative (false);
  2502. int leftShift = ourHB - divHB;
  2503. temp <<= leftShift;
  2504. while (leftShift >= 0)
  2505. {
  2506. if (remainder.compareAbsolute (temp) >= 0)
  2507. {
  2508. remainder -= temp;
  2509. setBit (leftShift);
  2510. }
  2511. if (--leftShift >= 0)
  2512. temp >>= 1;
  2513. }
  2514. negative = wasNegative ^ divisor.isNegative();
  2515. remainder.setNegative (wasNegative);
  2516. }
  2517. }
  2518. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2519. {
  2520. BigInteger remainder;
  2521. divideBy (other, remainder);
  2522. return *this;
  2523. }
  2524. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2525. {
  2526. // this operation doesn't take into account negative values..
  2527. jassert (isNegative() == other.isNegative());
  2528. if (other.highestBit >= 0)
  2529. {
  2530. ensureSize (bitToIndex (other.highestBit));
  2531. int n = bitToIndex (other.highestBit) + 1;
  2532. while (--n >= 0)
  2533. values[n] |= other.values[n];
  2534. if (other.highestBit > highestBit)
  2535. highestBit = other.highestBit;
  2536. highestBit = getHighestBit();
  2537. }
  2538. return *this;
  2539. }
  2540. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2541. {
  2542. // this operation doesn't take into account negative values..
  2543. jassert (isNegative() == other.isNegative());
  2544. int n = numValues;
  2545. while (n > other.numValues)
  2546. values[--n] = 0;
  2547. while (--n >= 0)
  2548. values[n] &= other.values[n];
  2549. if (other.highestBit < highestBit)
  2550. highestBit = other.highestBit;
  2551. highestBit = getHighestBit();
  2552. return *this;
  2553. }
  2554. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2555. {
  2556. // this operation will only work with the absolute values
  2557. jassert (isNegative() == other.isNegative());
  2558. if (other.highestBit >= 0)
  2559. {
  2560. ensureSize (bitToIndex (other.highestBit));
  2561. int n = bitToIndex (other.highestBit) + 1;
  2562. while (--n >= 0)
  2563. values[n] ^= other.values[n];
  2564. if (other.highestBit > highestBit)
  2565. highestBit = other.highestBit;
  2566. highestBit = getHighestBit();
  2567. }
  2568. return *this;
  2569. }
  2570. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2571. {
  2572. BigInteger remainder;
  2573. divideBy (divisor, remainder);
  2574. swapWith (remainder);
  2575. return *this;
  2576. }
  2577. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2578. {
  2579. shiftBits (numBitsToShift, 0);
  2580. return *this;
  2581. }
  2582. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2583. {
  2584. return operator<<= (-numBitsToShift);
  2585. }
  2586. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2587. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2588. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2589. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2590. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2591. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2592. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2593. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2594. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2595. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2596. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2597. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2598. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2599. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2600. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2601. int BigInteger::compare (const BigInteger& other) const throw()
  2602. {
  2603. if (isNegative() == other.isNegative())
  2604. {
  2605. const int absComp = compareAbsolute (other);
  2606. return isNegative() ? -absComp : absComp;
  2607. }
  2608. else
  2609. {
  2610. return isNegative() ? -1 : 1;
  2611. }
  2612. }
  2613. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2614. {
  2615. const int h1 = getHighestBit();
  2616. const int h2 = other.getHighestBit();
  2617. if (h1 > h2)
  2618. return 1;
  2619. else if (h1 < h2)
  2620. return -1;
  2621. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2622. if (values[i] != other.values[i])
  2623. return (values[i] > other.values[i]) ? 1 : -1;
  2624. return 0;
  2625. }
  2626. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2627. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2628. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2629. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2630. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2631. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2632. void BigInteger::shiftBits (int bits, const int startBit)
  2633. {
  2634. if (highestBit < 0)
  2635. return;
  2636. if (startBit > 0)
  2637. {
  2638. if (bits < 0)
  2639. {
  2640. // right shift
  2641. for (int i = startBit; i <= highestBit; ++i)
  2642. setBit (i, operator[] (i - bits));
  2643. highestBit = getHighestBit();
  2644. }
  2645. else if (bits > 0)
  2646. {
  2647. // left shift
  2648. for (int i = highestBit + 1; --i >= startBit;)
  2649. setBit (i + bits, operator[] (i));
  2650. while (--bits >= 0)
  2651. clearBit (bits + startBit);
  2652. }
  2653. }
  2654. else
  2655. {
  2656. if (bits < 0)
  2657. {
  2658. // right shift
  2659. bits = -bits;
  2660. if (bits > highestBit)
  2661. {
  2662. clear();
  2663. }
  2664. else
  2665. {
  2666. const int wordsToMove = bitToIndex (bits);
  2667. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2668. highestBit -= bits;
  2669. if (wordsToMove > 0)
  2670. {
  2671. int i;
  2672. for (i = 0; i < top; ++i)
  2673. values [i] = values [i + wordsToMove];
  2674. for (i = 0; i < wordsToMove; ++i)
  2675. values [top + i] = 0;
  2676. bits &= 31;
  2677. }
  2678. if (bits != 0)
  2679. {
  2680. const int invBits = 32 - bits;
  2681. --top;
  2682. for (int i = 0; i < top; ++i)
  2683. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2684. values[top] = (values[top] >> bits);
  2685. }
  2686. highestBit = getHighestBit();
  2687. }
  2688. }
  2689. else if (bits > 0)
  2690. {
  2691. // left shift
  2692. ensureSize (bitToIndex (highestBit + bits) + 1);
  2693. const int wordsToMove = bitToIndex (bits);
  2694. int top = 1 + bitToIndex (highestBit);
  2695. highestBit += bits;
  2696. if (wordsToMove > 0)
  2697. {
  2698. int i;
  2699. for (i = top; --i >= 0;)
  2700. values [i + wordsToMove] = values [i];
  2701. for (i = 0; i < wordsToMove; ++i)
  2702. values [i] = 0;
  2703. bits &= 31;
  2704. }
  2705. if (bits != 0)
  2706. {
  2707. const int invBits = 32 - bits;
  2708. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2709. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2710. values [wordsToMove] = values [wordsToMove] << bits;
  2711. }
  2712. highestBit = getHighestBit();
  2713. }
  2714. }
  2715. }
  2716. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2717. {
  2718. while (! m->isZero())
  2719. {
  2720. if (n->compareAbsolute (*m) > 0)
  2721. swapVariables (m, n);
  2722. *m -= *n;
  2723. }
  2724. return *n;
  2725. }
  2726. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2727. {
  2728. BigInteger m (*this);
  2729. while (! n.isZero())
  2730. {
  2731. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2732. return simpleGCD (&m, &n);
  2733. BigInteger temp1 (m), temp2;
  2734. temp1.divideBy (n, temp2);
  2735. m = n;
  2736. n = temp2;
  2737. }
  2738. return m;
  2739. }
  2740. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2741. {
  2742. BigInteger exp (exponent);
  2743. exp %= modulus;
  2744. BigInteger value (1);
  2745. swapWith (value);
  2746. value %= modulus;
  2747. while (! exp.isZero())
  2748. {
  2749. if (exp [0])
  2750. {
  2751. operator*= (value);
  2752. operator%= (modulus);
  2753. }
  2754. value *= value;
  2755. value %= modulus;
  2756. exp >>= 1;
  2757. }
  2758. }
  2759. void BigInteger::inverseModulo (const BigInteger& modulus)
  2760. {
  2761. if (modulus.isOne() || modulus.isNegative())
  2762. {
  2763. clear();
  2764. return;
  2765. }
  2766. if (isNegative() || compareAbsolute (modulus) >= 0)
  2767. operator%= (modulus);
  2768. if (isOne())
  2769. return;
  2770. if (! (*this)[0])
  2771. {
  2772. // not invertible
  2773. clear();
  2774. return;
  2775. }
  2776. BigInteger a1 (modulus);
  2777. BigInteger a2 (*this);
  2778. BigInteger b1 (modulus);
  2779. BigInteger b2 (1);
  2780. while (! a2.isOne())
  2781. {
  2782. BigInteger temp1, temp2, multiplier (a1);
  2783. multiplier.divideBy (a2, temp1);
  2784. temp1 = a2;
  2785. temp1 *= multiplier;
  2786. temp2 = a1;
  2787. temp2 -= temp1;
  2788. a1 = a2;
  2789. a2 = temp2;
  2790. temp1 = b2;
  2791. temp1 *= multiplier;
  2792. temp2 = b1;
  2793. temp2 -= temp1;
  2794. b1 = b2;
  2795. b2 = temp2;
  2796. }
  2797. while (b2.isNegative())
  2798. b2 += modulus;
  2799. b2 %= modulus;
  2800. swapWith (b2);
  2801. }
  2802. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2803. {
  2804. return stream << value.toString (10);
  2805. }
  2806. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2807. {
  2808. String s;
  2809. BigInteger v (*this);
  2810. if (base == 2 || base == 8 || base == 16)
  2811. {
  2812. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2813. static const char* const hexDigits = "0123456789abcdef";
  2814. for (;;)
  2815. {
  2816. const int remainder = v.getBitRangeAsInt (0, bits);
  2817. v >>= bits;
  2818. if (remainder == 0 && v.isZero())
  2819. break;
  2820. s = String::charToString (hexDigits [remainder]) + s;
  2821. }
  2822. }
  2823. else if (base == 10)
  2824. {
  2825. const BigInteger ten (10);
  2826. BigInteger remainder;
  2827. for (;;)
  2828. {
  2829. v.divideBy (ten, remainder);
  2830. if (remainder.isZero() && v.isZero())
  2831. break;
  2832. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2833. }
  2834. }
  2835. else
  2836. {
  2837. jassertfalse; // can't do the specified base!
  2838. return String::empty;
  2839. }
  2840. s = s.paddedLeft ('0', minimumNumCharacters);
  2841. return isNegative() ? "-" + s : s;
  2842. }
  2843. void BigInteger::parseString (const String& text, const int base)
  2844. {
  2845. clear();
  2846. String::CharPointerType t (text.getCharPointer());
  2847. if (base == 2 || base == 8 || base == 16)
  2848. {
  2849. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2850. for (;;)
  2851. {
  2852. const juce_wchar c = t.getAndAdvance();
  2853. const int digit = CharacterFunctions::getHexDigitValue (c);
  2854. if (((uint32) digit) < (uint32) base)
  2855. {
  2856. operator<<= (bits);
  2857. operator+= (digit);
  2858. }
  2859. else if (c == 0)
  2860. {
  2861. break;
  2862. }
  2863. }
  2864. }
  2865. else if (base == 10)
  2866. {
  2867. const BigInteger ten ((uint32) 10);
  2868. for (;;)
  2869. {
  2870. const juce_wchar c = t.getAndAdvance();
  2871. if (c >= '0' && c <= '9')
  2872. {
  2873. operator*= (ten);
  2874. operator+= ((int) (c - '0'));
  2875. }
  2876. else if (c == 0)
  2877. {
  2878. break;
  2879. }
  2880. }
  2881. }
  2882. setNegative (text.trimStart().startsWithChar ('-'));
  2883. }
  2884. const MemoryBlock BigInteger::toMemoryBlock() const
  2885. {
  2886. const int numBytes = (getHighestBit() + 8) >> 3;
  2887. MemoryBlock mb ((size_t) numBytes);
  2888. for (int i = 0; i < numBytes; ++i)
  2889. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2890. return mb;
  2891. }
  2892. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2893. {
  2894. clear();
  2895. for (int i = (int) data.getSize(); --i >= 0;)
  2896. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2897. }
  2898. END_JUCE_NAMESPACE
  2899. /*** End of inlined file: juce_BigInteger.cpp ***/
  2900. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2901. BEGIN_JUCE_NAMESPACE
  2902. MemoryBlock::MemoryBlock() throw()
  2903. : size (0)
  2904. {
  2905. }
  2906. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2907. {
  2908. if (initialSize > 0)
  2909. {
  2910. size = initialSize;
  2911. data.allocate (initialSize, initialiseToZero);
  2912. }
  2913. else
  2914. {
  2915. size = 0;
  2916. }
  2917. }
  2918. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2919. : size (other.size)
  2920. {
  2921. if (size > 0)
  2922. {
  2923. jassert (other.data != 0);
  2924. data.malloc (size);
  2925. memcpy (data, other.data, size);
  2926. }
  2927. }
  2928. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2929. : size (jmax ((size_t) 0, sizeInBytes))
  2930. {
  2931. jassert (sizeInBytes >= 0);
  2932. if (size > 0)
  2933. {
  2934. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2935. data.malloc (size);
  2936. if (dataToInitialiseFrom != 0)
  2937. memcpy (data, dataToInitialiseFrom, size);
  2938. }
  2939. }
  2940. MemoryBlock::~MemoryBlock() throw()
  2941. {
  2942. jassert (size >= 0); // should never happen
  2943. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2944. }
  2945. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2946. {
  2947. if (this != &other)
  2948. {
  2949. setSize (other.size, false);
  2950. memcpy (data, other.data, size);
  2951. }
  2952. return *this;
  2953. }
  2954. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2955. {
  2956. return matches (other.data, other.size);
  2957. }
  2958. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2959. {
  2960. return ! operator== (other);
  2961. }
  2962. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2963. {
  2964. return size == dataSize
  2965. && memcmp (data, dataToCompare, size) == 0;
  2966. }
  2967. // this will resize the block to this size
  2968. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2969. {
  2970. if (size != newSize)
  2971. {
  2972. if (newSize <= 0)
  2973. {
  2974. data.free();
  2975. size = 0;
  2976. }
  2977. else
  2978. {
  2979. if (data != 0)
  2980. {
  2981. data.realloc (newSize);
  2982. if (initialiseToZero && (newSize > size))
  2983. zeromem (data + size, newSize - size);
  2984. }
  2985. else
  2986. {
  2987. data.allocate (newSize, initialiseToZero);
  2988. }
  2989. size = newSize;
  2990. }
  2991. }
  2992. }
  2993. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2994. {
  2995. if (size < minimumSize)
  2996. setSize (minimumSize, initialiseToZero);
  2997. }
  2998. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2999. {
  3000. swapVariables (size, other.size);
  3001. data.swapWith (other.data);
  3002. }
  3003. void MemoryBlock::fillWith (const uint8 value) throw()
  3004. {
  3005. memset (data, (int) value, size);
  3006. }
  3007. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  3008. {
  3009. if (numBytes > 0)
  3010. {
  3011. const size_t oldSize = size;
  3012. setSize (size + numBytes);
  3013. memcpy (data + oldSize, srcData, numBytes);
  3014. }
  3015. }
  3016. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  3017. {
  3018. const char* d = static_cast<const char*> (src);
  3019. if (offset < 0)
  3020. {
  3021. d -= offset;
  3022. num -= offset;
  3023. offset = 0;
  3024. }
  3025. if (offset + num > size)
  3026. num = size - offset;
  3027. if (num > 0)
  3028. memcpy (data + offset, d, num);
  3029. }
  3030. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3031. {
  3032. char* d = static_cast<char*> (dst);
  3033. if (offset < 0)
  3034. {
  3035. zeromem (d, -offset);
  3036. d -= offset;
  3037. num += offset;
  3038. offset = 0;
  3039. }
  3040. if (offset + num > size)
  3041. {
  3042. const size_t newNum = size - offset;
  3043. zeromem (d + newNum, num - newNum);
  3044. num = newNum;
  3045. }
  3046. if (num > 0)
  3047. memcpy (d, data + offset, num);
  3048. }
  3049. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3050. {
  3051. if (startByte + numBytesToRemove >= size)
  3052. {
  3053. setSize (startByte);
  3054. }
  3055. else if (numBytesToRemove > 0)
  3056. {
  3057. memmove (data + startByte,
  3058. data + startByte + numBytesToRemove,
  3059. size - (startByte + numBytesToRemove));
  3060. setSize (size - numBytesToRemove);
  3061. }
  3062. }
  3063. const String MemoryBlock::toString() const
  3064. {
  3065. return String (static_cast <const char*> (getData()), size);
  3066. }
  3067. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3068. {
  3069. int res = 0;
  3070. size_t byte = bitRangeStart >> 3;
  3071. int offsetInByte = (int) bitRangeStart & 7;
  3072. size_t bitsSoFar = 0;
  3073. while (numBits > 0 && (size_t) byte < size)
  3074. {
  3075. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3076. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3077. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3078. bitsSoFar += bitsThisTime;
  3079. numBits -= bitsThisTime;
  3080. ++byte;
  3081. offsetInByte = 0;
  3082. }
  3083. return res;
  3084. }
  3085. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3086. {
  3087. size_t byte = bitRangeStart >> 3;
  3088. int offsetInByte = (int) bitRangeStart & 7;
  3089. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3090. while (numBits > 0 && (size_t) byte < size)
  3091. {
  3092. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3093. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3094. const unsigned int tempBits = bitsToSet << offsetInByte;
  3095. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3096. ++byte;
  3097. numBits -= bitsThisTime;
  3098. bitsToSet >>= bitsThisTime;
  3099. mask >>= bitsThisTime;
  3100. offsetInByte = 0;
  3101. }
  3102. }
  3103. void MemoryBlock::loadFromHexString (const String& hex)
  3104. {
  3105. ensureSize (hex.length() >> 1);
  3106. char* dest = data;
  3107. int i = 0;
  3108. for (;;)
  3109. {
  3110. int byte = 0;
  3111. for (int loop = 2; --loop >= 0;)
  3112. {
  3113. byte <<= 4;
  3114. for (;;)
  3115. {
  3116. const juce_wchar c = hex [i++];
  3117. if (c >= '0' && c <= '9')
  3118. {
  3119. byte |= c - '0';
  3120. break;
  3121. }
  3122. else if (c >= 'a' && c <= 'z')
  3123. {
  3124. byte |= c - ('a' - 10);
  3125. break;
  3126. }
  3127. else if (c >= 'A' && c <= 'Z')
  3128. {
  3129. byte |= c - ('A' - 10);
  3130. break;
  3131. }
  3132. else if (c == 0)
  3133. {
  3134. setSize (static_cast <size_t> (dest - data));
  3135. return;
  3136. }
  3137. }
  3138. }
  3139. *dest++ = (char) byte;
  3140. }
  3141. }
  3142. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3143. const String MemoryBlock::toBase64Encoding() const
  3144. {
  3145. const size_t numChars = ((size << 3) + 5) / 6;
  3146. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3147. const int initialLen = destString.length();
  3148. destString.preallocateStorage (initialLen + 2 + numChars);
  3149. String::CharPointerType d (destString.getCharPointer());
  3150. d += initialLen;
  3151. d.write ('.');
  3152. for (size_t i = 0; i < numChars; ++i)
  3153. d.write (encodingTable [getBitRange (i * 6, 6)]);
  3154. d.writeNull();
  3155. return destString;
  3156. }
  3157. bool MemoryBlock::fromBase64Encoding (const String& s)
  3158. {
  3159. const int startPos = s.indexOfChar ('.') + 1;
  3160. if (startPos <= 0)
  3161. return false;
  3162. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3163. setSize (numBytesNeeded, true);
  3164. const int numChars = s.length() - startPos;
  3165. String::CharPointerType srcChars (s.getCharPointer());
  3166. srcChars += startPos;
  3167. int pos = 0;
  3168. for (int i = 0; i < numChars; ++i)
  3169. {
  3170. const char c = (char) srcChars.getAndAdvance();
  3171. for (int j = 0; j < 64; ++j)
  3172. {
  3173. if (encodingTable[j] == c)
  3174. {
  3175. setBitRange (pos, 6, j);
  3176. pos += 6;
  3177. break;
  3178. }
  3179. }
  3180. }
  3181. return true;
  3182. }
  3183. END_JUCE_NAMESPACE
  3184. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3185. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3186. BEGIN_JUCE_NAMESPACE
  3187. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3188. : properties (ignoreCaseOfKeyNames),
  3189. fallbackProperties (0),
  3190. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3191. {
  3192. }
  3193. PropertySet::PropertySet (const PropertySet& other)
  3194. : properties (other.properties),
  3195. fallbackProperties (other.fallbackProperties),
  3196. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3197. {
  3198. }
  3199. PropertySet& PropertySet::operator= (const PropertySet& other)
  3200. {
  3201. properties = other.properties;
  3202. fallbackProperties = other.fallbackProperties;
  3203. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3204. propertyChanged();
  3205. return *this;
  3206. }
  3207. PropertySet::~PropertySet()
  3208. {
  3209. }
  3210. void PropertySet::clear()
  3211. {
  3212. const ScopedLock sl (lock);
  3213. if (properties.size() > 0)
  3214. {
  3215. properties.clear();
  3216. propertyChanged();
  3217. }
  3218. }
  3219. const String PropertySet::getValue (const String& keyName,
  3220. const String& defaultValue) const throw()
  3221. {
  3222. const ScopedLock sl (lock);
  3223. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3224. if (index >= 0)
  3225. return properties.getAllValues() [index];
  3226. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3227. : defaultValue;
  3228. }
  3229. int PropertySet::getIntValue (const String& keyName,
  3230. const int defaultValue) const throw()
  3231. {
  3232. const ScopedLock sl (lock);
  3233. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3234. if (index >= 0)
  3235. return properties.getAllValues() [index].getIntValue();
  3236. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3237. : defaultValue;
  3238. }
  3239. double PropertySet::getDoubleValue (const String& keyName,
  3240. const double defaultValue) const throw()
  3241. {
  3242. const ScopedLock sl (lock);
  3243. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3244. if (index >= 0)
  3245. return properties.getAllValues()[index].getDoubleValue();
  3246. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3247. : defaultValue;
  3248. }
  3249. bool PropertySet::getBoolValue (const String& keyName,
  3250. const bool defaultValue) const throw()
  3251. {
  3252. const ScopedLock sl (lock);
  3253. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3254. if (index >= 0)
  3255. return properties.getAllValues() [index].getIntValue() != 0;
  3256. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3257. : defaultValue;
  3258. }
  3259. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3260. {
  3261. return XmlDocument::parse (getValue (keyName));
  3262. }
  3263. void PropertySet::setValue (const String& keyName, const var& v)
  3264. {
  3265. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3266. if (keyName.isNotEmpty())
  3267. {
  3268. const String value (v.toString());
  3269. const ScopedLock sl (lock);
  3270. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3271. if (index < 0 || properties.getAllValues() [index] != value)
  3272. {
  3273. properties.set (keyName, value);
  3274. propertyChanged();
  3275. }
  3276. }
  3277. }
  3278. void PropertySet::removeValue (const String& keyName)
  3279. {
  3280. if (keyName.isNotEmpty())
  3281. {
  3282. const ScopedLock sl (lock);
  3283. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3284. if (index >= 0)
  3285. {
  3286. properties.remove (keyName);
  3287. propertyChanged();
  3288. }
  3289. }
  3290. }
  3291. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3292. {
  3293. setValue (keyName, xml == 0 ? var::null
  3294. : var (xml->createDocument (String::empty, true)));
  3295. }
  3296. bool PropertySet::containsKey (const String& keyName) const throw()
  3297. {
  3298. const ScopedLock sl (lock);
  3299. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3300. }
  3301. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3302. {
  3303. const ScopedLock sl (lock);
  3304. fallbackProperties = fallbackProperties_;
  3305. }
  3306. XmlElement* PropertySet::createXml (const String& nodeName) const
  3307. {
  3308. const ScopedLock sl (lock);
  3309. XmlElement* const xml = new XmlElement (nodeName);
  3310. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3311. {
  3312. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3313. e->setAttribute ("name", properties.getAllKeys()[i]);
  3314. e->setAttribute ("val", properties.getAllValues()[i]);
  3315. }
  3316. return xml;
  3317. }
  3318. void PropertySet::restoreFromXml (const XmlElement& xml)
  3319. {
  3320. const ScopedLock sl (lock);
  3321. clear();
  3322. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3323. {
  3324. if (e->hasAttribute ("name")
  3325. && e->hasAttribute ("val"))
  3326. {
  3327. properties.set (e->getStringAttribute ("name"),
  3328. e->getStringAttribute ("val"));
  3329. }
  3330. }
  3331. if (properties.size() > 0)
  3332. propertyChanged();
  3333. }
  3334. void PropertySet::propertyChanged()
  3335. {
  3336. }
  3337. END_JUCE_NAMESPACE
  3338. /*** End of inlined file: juce_PropertySet.cpp ***/
  3339. /*** Start of inlined file: juce_Identifier.cpp ***/
  3340. BEGIN_JUCE_NAMESPACE
  3341. StringPool& Identifier::getPool()
  3342. {
  3343. static StringPool pool;
  3344. return pool;
  3345. }
  3346. Identifier::Identifier() throw()
  3347. : name (0)
  3348. {
  3349. }
  3350. Identifier::Identifier (const Identifier& other) throw()
  3351. : name (other.name)
  3352. {
  3353. }
  3354. Identifier& Identifier::operator= (const Identifier& other) throw()
  3355. {
  3356. name = other.name;
  3357. return *this;
  3358. }
  3359. Identifier::Identifier (const String& name_)
  3360. : name (Identifier::getPool().getPooledString (name_))
  3361. {
  3362. /* An Identifier string must be suitable for use as a script variable or XML
  3363. attribute, so it can only contain this limited set of characters.. */
  3364. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3365. }
  3366. Identifier::Identifier (const char* const name_)
  3367. : name (Identifier::getPool().getPooledString (name_))
  3368. {
  3369. /* An Identifier string must be suitable for use as a script variable or XML
  3370. attribute, so it can only contain this limited set of characters.. */
  3371. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3372. }
  3373. Identifier::~Identifier()
  3374. {
  3375. }
  3376. END_JUCE_NAMESPACE
  3377. /*** End of inlined file: juce_Identifier.cpp ***/
  3378. /*** Start of inlined file: juce_Variant.cpp ***/
  3379. BEGIN_JUCE_NAMESPACE
  3380. enum VariantStreamMarkers
  3381. {
  3382. varMarker_Int = 1,
  3383. varMarker_BoolTrue = 2,
  3384. varMarker_BoolFalse = 3,
  3385. varMarker_Double = 4,
  3386. varMarker_String = 5,
  3387. varMarker_Int64 = 6
  3388. };
  3389. class var::VariantType
  3390. {
  3391. public:
  3392. VariantType() {}
  3393. virtual ~VariantType() {}
  3394. virtual int toInt (const ValueUnion&) const { return 0; }
  3395. virtual int64 toInt64 (const ValueUnion&) const { return 0; }
  3396. virtual double toDouble (const ValueUnion&) const { return 0; }
  3397. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3398. virtual bool toBool (const ValueUnion&) const { return false; }
  3399. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3400. virtual bool isVoid() const throw() { return false; }
  3401. virtual bool isInt() const throw() { return false; }
  3402. virtual bool isInt64() const throw() { return false; }
  3403. virtual bool isBool() const throw() { return false; }
  3404. virtual bool isDouble() const throw() { return false; }
  3405. virtual bool isString() const throw() { return false; }
  3406. virtual bool isObject() const throw() { return false; }
  3407. virtual bool isMethod() const throw() { return false; }
  3408. virtual void cleanUp (ValueUnion&) const throw() {}
  3409. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3410. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3411. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3412. };
  3413. class var::VariantType_Void : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Void() {}
  3417. static const VariantType_Void instance;
  3418. bool isVoid() const throw() { return true; }
  3419. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3420. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3421. };
  3422. class var::VariantType_Int : public var::VariantType
  3423. {
  3424. public:
  3425. VariantType_Int() {}
  3426. static const VariantType_Int instance;
  3427. int toInt (const ValueUnion& data) const { return data.intValue; };
  3428. int64 toInt64 (const ValueUnion& data) const { return (int64) data.intValue; };
  3429. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3430. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3431. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3432. bool isInt() const throw() { return true; }
  3433. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3434. {
  3435. return otherType.toInt (otherData) == data.intValue;
  3436. }
  3437. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3438. {
  3439. output.writeCompressedInt (5);
  3440. output.writeByte (varMarker_Int);
  3441. output.writeInt (data.intValue);
  3442. }
  3443. };
  3444. class var::VariantType_Int64 : public var::VariantType
  3445. {
  3446. public:
  3447. VariantType_Int64() {}
  3448. static const VariantType_Int64 instance;
  3449. int toInt (const ValueUnion& data) const { return (int) data.int64Value; };
  3450. int64 toInt64 (const ValueUnion& data) const { return data.int64Value; };
  3451. double toDouble (const ValueUnion& data) const { return (double) data.int64Value; }
  3452. const String toString (const ValueUnion& data) const { return String (data.int64Value); }
  3453. bool toBool (const ValueUnion& data) const { return data.int64Value != 0; }
  3454. bool isInt64() const throw() { return true; }
  3455. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3456. {
  3457. return otherType.toInt64 (otherData) == data.int64Value;
  3458. }
  3459. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3460. {
  3461. output.writeCompressedInt (9);
  3462. output.writeByte (varMarker_Int64);
  3463. output.writeInt64 (data.int64Value);
  3464. }
  3465. };
  3466. class var::VariantType_Double : public var::VariantType
  3467. {
  3468. public:
  3469. VariantType_Double() {}
  3470. static const VariantType_Double instance;
  3471. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3472. int64 toInt64 (const ValueUnion& data) const { return (int64) data.doubleValue; };
  3473. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3474. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3475. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3476. bool isDouble() const throw() { return true; }
  3477. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3478. {
  3479. return otherType.toDouble (otherData) == data.doubleValue;
  3480. }
  3481. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3482. {
  3483. output.writeCompressedInt (9);
  3484. output.writeByte (varMarker_Double);
  3485. output.writeDouble (data.doubleValue);
  3486. }
  3487. };
  3488. class var::VariantType_Bool : public var::VariantType
  3489. {
  3490. public:
  3491. VariantType_Bool() {}
  3492. static const VariantType_Bool instance;
  3493. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3494. int64 toInt64 (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3495. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3496. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3497. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3498. bool isBool() const throw() { return true; }
  3499. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3500. {
  3501. return otherType.toBool (otherData) == data.boolValue;
  3502. }
  3503. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3504. {
  3505. output.writeCompressedInt (1);
  3506. output.writeByte (data.boolValue ? (char) varMarker_BoolTrue : (char) varMarker_BoolFalse);
  3507. }
  3508. };
  3509. class var::VariantType_String : public var::VariantType
  3510. {
  3511. public:
  3512. VariantType_String() {}
  3513. static const VariantType_String instance;
  3514. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3515. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3516. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3517. int64 toInt64 (const ValueUnion& data) const { return data.stringValue->getLargeIntValue(); };
  3518. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3519. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3520. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3521. || data.stringValue->trim().equalsIgnoreCase ("true")
  3522. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3523. bool isString() const throw() { return true; }
  3524. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3525. {
  3526. return otherType.toString (otherData) == *data.stringValue;
  3527. }
  3528. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3529. {
  3530. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3531. output.writeCompressedInt (len + 1);
  3532. output.writeByte (varMarker_String);
  3533. HeapBlock<char> temp (len);
  3534. data.stringValue->copyToUTF8 (temp, len);
  3535. output.write (temp, len);
  3536. }
  3537. };
  3538. class var::VariantType_Object : public var::VariantType
  3539. {
  3540. public:
  3541. VariantType_Object() {}
  3542. static const VariantType_Object instance;
  3543. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3544. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3545. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3546. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3547. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3548. bool isObject() const throw() { return true; }
  3549. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3550. {
  3551. return otherType.toObject (otherData) == data.objectValue;
  3552. }
  3553. void writeToStream (const ValueUnion&, OutputStream& output) const
  3554. {
  3555. jassertfalse; // Can't write an object to a stream!
  3556. output.writeCompressedInt (0);
  3557. }
  3558. };
  3559. class var::VariantType_Method : public var::VariantType
  3560. {
  3561. public:
  3562. VariantType_Method() {}
  3563. static const VariantType_Method instance;
  3564. const String toString (const ValueUnion&) const { return "Method"; }
  3565. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3566. bool isMethod() const throw() { return true; }
  3567. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3568. {
  3569. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3570. }
  3571. void writeToStream (const ValueUnion&, OutputStream& output) const
  3572. {
  3573. jassertfalse; // Can't write a method to a stream!
  3574. output.writeCompressedInt (0);
  3575. }
  3576. };
  3577. const var::VariantType_Void var::VariantType_Void::instance;
  3578. const var::VariantType_Int var::VariantType_Int::instance;
  3579. const var::VariantType_Int64 var::VariantType_Int64::instance;
  3580. const var::VariantType_Bool var::VariantType_Bool::instance;
  3581. const var::VariantType_Double var::VariantType_Double::instance;
  3582. const var::VariantType_String var::VariantType_String::instance;
  3583. const var::VariantType_Object var::VariantType_Object::instance;
  3584. const var::VariantType_Method var::VariantType_Method::instance;
  3585. var::var() throw() : type (&VariantType_Void::instance)
  3586. {
  3587. }
  3588. var::~var() throw()
  3589. {
  3590. type->cleanUp (value);
  3591. }
  3592. const var var::null;
  3593. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3594. {
  3595. type->createCopy (value, valueToCopy.value);
  3596. }
  3597. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3598. {
  3599. value.intValue = value_;
  3600. }
  3601. var::var (const int64 value_) throw() : type (&VariantType_Int64::instance)
  3602. {
  3603. value.int64Value = value_;
  3604. }
  3605. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3606. {
  3607. value.boolValue = value_;
  3608. }
  3609. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3610. {
  3611. value.doubleValue = value_;
  3612. }
  3613. var::var (const String& value_) : type (&VariantType_String::instance)
  3614. {
  3615. value.stringValue = new String (value_);
  3616. }
  3617. var::var (const char* const value_) : type (&VariantType_String::instance)
  3618. {
  3619. value.stringValue = new String (value_);
  3620. }
  3621. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3622. {
  3623. value.stringValue = new String (value_);
  3624. }
  3625. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3626. {
  3627. value.objectValue = object;
  3628. if (object != 0)
  3629. object->incReferenceCount();
  3630. }
  3631. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3632. {
  3633. value.methodValue = method_;
  3634. }
  3635. bool var::isVoid() const throw() { return type->isVoid(); }
  3636. bool var::isInt() const throw() { return type->isInt(); }
  3637. bool var::isInt64() const throw() { return type->isInt64(); }
  3638. bool var::isBool() const throw() { return type->isBool(); }
  3639. bool var::isDouble() const throw() { return type->isDouble(); }
  3640. bool var::isString() const throw() { return type->isString(); }
  3641. bool var::isObject() const throw() { return type->isObject(); }
  3642. bool var::isMethod() const throw() { return type->isMethod(); }
  3643. var::operator int() const { return type->toInt (value); }
  3644. var::operator int64() const { return type->toInt64 (value); }
  3645. var::operator bool() const { return type->toBool (value); }
  3646. var::operator float() const { return (float) type->toDouble (value); }
  3647. var::operator double() const { return type->toDouble (value); }
  3648. const String var::toString() const { return type->toString (value); }
  3649. var::operator const String() const { return type->toString (value); }
  3650. DynamicObject* var::getObject() const { return type->toObject (value); }
  3651. void var::swapWith (var& other) throw()
  3652. {
  3653. swapVariables (type, other.type);
  3654. swapVariables (value, other.value);
  3655. }
  3656. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3657. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3658. var& var::operator= (int64 newValue) { var v (newValue); swapWith (v); return *this; }
  3659. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3660. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3661. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3662. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3663. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3664. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3665. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3666. bool var::equals (const var& other) const throw()
  3667. {
  3668. return type->equals (value, other.value, *other.type);
  3669. }
  3670. bool var::equalsWithSameType (const var& other) const throw()
  3671. {
  3672. return type == other.type && equals (other);
  3673. }
  3674. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3675. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3676. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3677. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3678. void var::writeToStream (OutputStream& output) const
  3679. {
  3680. type->writeToStream (value, output);
  3681. }
  3682. const var var::readFromStream (InputStream& input)
  3683. {
  3684. const int numBytes = input.readCompressedInt();
  3685. if (numBytes > 0)
  3686. {
  3687. switch (input.readByte())
  3688. {
  3689. case varMarker_Int: return var (input.readInt());
  3690. case varMarker_Int64: return var (input.readInt64());
  3691. case varMarker_BoolTrue: return var (true);
  3692. case varMarker_BoolFalse: return var (false);
  3693. case varMarker_Double: return var (input.readDouble());
  3694. case varMarker_String:
  3695. {
  3696. MemoryOutputStream mo;
  3697. mo.writeFromInputStream (input, numBytes - 1);
  3698. return var (mo.toUTF8());
  3699. }
  3700. default: input.skipNextBytes (numBytes - 1); break;
  3701. }
  3702. }
  3703. return var::null;
  3704. }
  3705. const var var::operator[] (const Identifier& propertyName) const
  3706. {
  3707. DynamicObject* const o = getObject();
  3708. return o != 0 ? o->getProperty (propertyName) : var::null;
  3709. }
  3710. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3711. {
  3712. DynamicObject* const o = getObject();
  3713. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3714. }
  3715. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3716. {
  3717. if (isMethod())
  3718. {
  3719. DynamicObject* const target = targetObject.getObject();
  3720. if (target != 0)
  3721. return (target->*(value.methodValue)) (arguments, numArguments);
  3722. }
  3723. return var::null;
  3724. }
  3725. const var var::call (const Identifier& method) const
  3726. {
  3727. return invoke (method, 0, 0);
  3728. }
  3729. const var var::call (const Identifier& method, const var& arg1) const
  3730. {
  3731. return invoke (method, &arg1, 1);
  3732. }
  3733. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3734. {
  3735. var args[] = { arg1, arg2 };
  3736. return invoke (method, args, 2);
  3737. }
  3738. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3739. {
  3740. var args[] = { arg1, arg2, arg3 };
  3741. return invoke (method, args, 3);
  3742. }
  3743. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3744. {
  3745. var args[] = { arg1, arg2, arg3, arg4 };
  3746. return invoke (method, args, 4);
  3747. }
  3748. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3749. {
  3750. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3751. return invoke (method, args, 5);
  3752. }
  3753. END_JUCE_NAMESPACE
  3754. /*** End of inlined file: juce_Variant.cpp ***/
  3755. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3756. BEGIN_JUCE_NAMESPACE
  3757. NamedValueSet::NamedValue::NamedValue() throw()
  3758. {
  3759. }
  3760. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3761. : name (name_), value (value_)
  3762. {
  3763. }
  3764. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3765. : name (other.name), value (other.value)
  3766. {
  3767. }
  3768. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3769. {
  3770. name = other.name;
  3771. value = other.value;
  3772. return *this;
  3773. }
  3774. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3775. {
  3776. return name == other.name && value == other.value;
  3777. }
  3778. NamedValueSet::NamedValueSet() throw()
  3779. {
  3780. }
  3781. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3782. {
  3783. values.addCopyOfList (other.values);
  3784. }
  3785. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3786. {
  3787. clear();
  3788. values.addCopyOfList (other.values);
  3789. return *this;
  3790. }
  3791. NamedValueSet::~NamedValueSet()
  3792. {
  3793. clear();
  3794. }
  3795. void NamedValueSet::clear()
  3796. {
  3797. values.deleteAll();
  3798. }
  3799. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3800. {
  3801. const NamedValue* i1 = values;
  3802. const NamedValue* i2 = other.values;
  3803. while (i1 != 0 && i2 != 0)
  3804. {
  3805. if (! (*i1 == *i2))
  3806. return false;
  3807. i1 = i1->nextListItem;
  3808. i2 = i2->nextListItem;
  3809. }
  3810. return true;
  3811. }
  3812. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3813. {
  3814. return ! operator== (other);
  3815. }
  3816. int NamedValueSet::size() const throw()
  3817. {
  3818. return values.size();
  3819. }
  3820. const var& NamedValueSet::operator[] (const Identifier& name) const
  3821. {
  3822. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3823. if (i->name == name)
  3824. return i->value;
  3825. return var::null;
  3826. }
  3827. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3828. {
  3829. const var* v = getVarPointer (name);
  3830. return v != 0 ? *v : defaultReturnValue;
  3831. }
  3832. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3833. {
  3834. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3835. if (i->name == name)
  3836. return &(i->value);
  3837. return 0;
  3838. }
  3839. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3840. {
  3841. LinkedListPointer<NamedValue>* i = &values;
  3842. while (i->get() != 0)
  3843. {
  3844. NamedValue* const v = i->get();
  3845. if (v->name == name)
  3846. {
  3847. if (v->value == newValue)
  3848. return false;
  3849. v->value = newValue;
  3850. return true;
  3851. }
  3852. i = &(v->nextListItem);
  3853. }
  3854. i->insertNext (new NamedValue (name, newValue));
  3855. return true;
  3856. }
  3857. bool NamedValueSet::contains (const Identifier& name) const
  3858. {
  3859. return getVarPointer (name) != 0;
  3860. }
  3861. bool NamedValueSet::remove (const Identifier& name)
  3862. {
  3863. LinkedListPointer<NamedValue>* i = &values;
  3864. for (;;)
  3865. {
  3866. NamedValue* const v = i->get();
  3867. if (v == 0)
  3868. break;
  3869. if (v->name == name)
  3870. {
  3871. delete i->removeNext();
  3872. return true;
  3873. }
  3874. i = &(v->nextListItem);
  3875. }
  3876. return false;
  3877. }
  3878. const Identifier NamedValueSet::getName (const int index) const
  3879. {
  3880. const NamedValue* const v = values[index];
  3881. jassert (v != 0);
  3882. return v->name;
  3883. }
  3884. const var NamedValueSet::getValueAt (const int index) const
  3885. {
  3886. const NamedValue* const v = values[index];
  3887. jassert (v != 0);
  3888. return v->value;
  3889. }
  3890. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3891. {
  3892. clear();
  3893. LinkedListPointer<NamedValue>::Appender appender (values);
  3894. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3895. for (int i = 0; i < numAtts; ++i)
  3896. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3897. }
  3898. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3899. {
  3900. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3901. {
  3902. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3903. xml.setAttribute (i->name.toString(),
  3904. i->value.toString());
  3905. }
  3906. }
  3907. END_JUCE_NAMESPACE
  3908. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3909. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3910. BEGIN_JUCE_NAMESPACE
  3911. DynamicObject::DynamicObject()
  3912. {
  3913. }
  3914. DynamicObject::~DynamicObject()
  3915. {
  3916. }
  3917. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3918. {
  3919. var* const v = properties.getVarPointer (propertyName);
  3920. return v != 0 && ! v->isMethod();
  3921. }
  3922. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3923. {
  3924. return properties [propertyName];
  3925. }
  3926. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3927. {
  3928. properties.set (propertyName, newValue);
  3929. }
  3930. void DynamicObject::removeProperty (const Identifier& propertyName)
  3931. {
  3932. properties.remove (propertyName);
  3933. }
  3934. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3935. {
  3936. return getProperty (methodName).isMethod();
  3937. }
  3938. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3939. const var* parameters,
  3940. int numParameters)
  3941. {
  3942. return properties [methodName].invoke (var (this), parameters, numParameters);
  3943. }
  3944. void DynamicObject::setMethod (const Identifier& name,
  3945. var::MethodFunction methodFunction)
  3946. {
  3947. properties.set (name, var (methodFunction));
  3948. }
  3949. void DynamicObject::clear()
  3950. {
  3951. properties.clear();
  3952. }
  3953. END_JUCE_NAMESPACE
  3954. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3955. /*** Start of inlined file: juce_Expression.cpp ***/
  3956. BEGIN_JUCE_NAMESPACE
  3957. class Expression::Term : public ReferenceCountedObject
  3958. {
  3959. public:
  3960. Term() {}
  3961. virtual ~Term() {}
  3962. virtual Type getType() const throw() = 0;
  3963. virtual Term* clone() const = 0;
  3964. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3965. virtual const String toString() const = 0;
  3966. virtual double toDouble() const { return 0; }
  3967. virtual int getInputIndexFor (const Term*) const { return -1; }
  3968. virtual int getOperatorPrecedence() const { return 0; }
  3969. virtual int getNumInputs() const { return 0; }
  3970. virtual Term* getInput (int) const { return 0; }
  3971. virtual const ReferenceCountedObjectPtr<Term> negated();
  3972. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3973. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3974. {
  3975. jassertfalse;
  3976. return 0;
  3977. }
  3978. virtual const String getName() const
  3979. {
  3980. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3981. return String::empty;
  3982. }
  3983. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3984. {
  3985. for (int i = getNumInputs(); --i >= 0;)
  3986. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3987. }
  3988. class SymbolVisitor
  3989. {
  3990. public:
  3991. virtual ~SymbolVisitor() {}
  3992. virtual void useSymbol (const Symbol&) = 0;
  3993. };
  3994. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3995. {
  3996. for (int i = getNumInputs(); --i >= 0;)
  3997. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3998. }
  3999. private:
  4000. JUCE_DECLARE_NON_COPYABLE (Term);
  4001. };
  4002. class Expression::Helpers
  4003. {
  4004. public:
  4005. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  4006. // This helper function is needed to work around VC6 scoping bugs
  4007. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  4008. static void checkRecursionDepth (const int depth)
  4009. {
  4010. if (depth > 256)
  4011. throw EvaluationError ("Recursive symbol references");
  4012. }
  4013. friend class Expression::Term; // (also only needed as a VC6 workaround)
  4014. /** An exception that can be thrown by Expression::evaluate(). */
  4015. class EvaluationError : public std::exception
  4016. {
  4017. public:
  4018. EvaluationError (const String& description_)
  4019. : description (description_)
  4020. {
  4021. DBG ("Expression::EvaluationError: " + description);
  4022. }
  4023. String description;
  4024. };
  4025. class Constant : public Term
  4026. {
  4027. public:
  4028. Constant (const double value_, const bool isResolutionTarget_)
  4029. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  4030. Type getType() const throw() { return constantType; }
  4031. Term* clone() const { return new Constant (value, isResolutionTarget); }
  4032. const TermPtr resolve (const Scope&, int) { return this; }
  4033. double toDouble() const { return value; }
  4034. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  4035. const String toString() const
  4036. {
  4037. String s (value);
  4038. if (isResolutionTarget)
  4039. s = "@" + s;
  4040. return s;
  4041. }
  4042. double value;
  4043. bool isResolutionTarget;
  4044. };
  4045. class BinaryTerm : public Term
  4046. {
  4047. public:
  4048. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  4049. {
  4050. jassert (left_ != 0 && right_ != 0);
  4051. }
  4052. int getInputIndexFor (const Term* possibleInput) const
  4053. {
  4054. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  4055. }
  4056. Type getType() const throw() { return operatorType; }
  4057. int getNumInputs() const { return 2; }
  4058. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  4059. virtual double performFunction (double left, double right) const = 0;
  4060. virtual void writeOperator (String& dest) const = 0;
  4061. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4062. {
  4063. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  4064. right->resolve (scope, recursionDepth)->toDouble()), false);
  4065. }
  4066. const String toString() const
  4067. {
  4068. String s;
  4069. const int ourPrecendence = getOperatorPrecedence();
  4070. if (left->getOperatorPrecedence() > ourPrecendence)
  4071. s << '(' << left->toString() << ')';
  4072. else
  4073. s = left->toString();
  4074. writeOperator (s);
  4075. if (right->getOperatorPrecedence() >= ourPrecendence)
  4076. s << '(' << right->toString() << ')';
  4077. else
  4078. s << right->toString();
  4079. return s;
  4080. }
  4081. protected:
  4082. const TermPtr left, right;
  4083. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4084. {
  4085. jassert (input == left || input == right);
  4086. if (input != left && input != right)
  4087. return 0;
  4088. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4089. if (dest == 0)
  4090. return new Constant (overallTarget, false);
  4091. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4092. }
  4093. };
  4094. class SymbolTerm : public Term
  4095. {
  4096. public:
  4097. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4098. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4099. {
  4100. checkRecursionDepth (recursionDepth);
  4101. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4102. }
  4103. Type getType() const throw() { return symbolType; }
  4104. Term* clone() const { return new SymbolTerm (symbol); }
  4105. const String toString() const { return symbol; }
  4106. const String getName() const { return symbol; }
  4107. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4108. {
  4109. checkRecursionDepth (recursionDepth);
  4110. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4111. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4112. }
  4113. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4114. {
  4115. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4116. symbol = newName;
  4117. }
  4118. String symbol;
  4119. };
  4120. class Function : public Term
  4121. {
  4122. public:
  4123. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4124. Function (const String& functionName_, const Array<Expression>& parameters_)
  4125. : functionName (functionName_), parameters (parameters_)
  4126. {}
  4127. Type getType() const throw() { return functionType; }
  4128. Term* clone() const { return new Function (functionName, parameters); }
  4129. int getNumInputs() const { return parameters.size(); }
  4130. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4131. const String getName() const { return functionName; }
  4132. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4133. {
  4134. checkRecursionDepth (recursionDepth);
  4135. double result = 0;
  4136. const int numParams = parameters.size();
  4137. if (numParams > 0)
  4138. {
  4139. HeapBlock<double> params (numParams);
  4140. for (int i = 0; i < numParams; ++i)
  4141. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4142. result = scope.evaluateFunction (functionName, params, numParams);
  4143. }
  4144. else
  4145. {
  4146. result = scope.evaluateFunction (functionName, 0, 0);
  4147. }
  4148. return new Constant (result, false);
  4149. }
  4150. int getInputIndexFor (const Term* possibleInput) const
  4151. {
  4152. for (int i = 0; i < parameters.size(); ++i)
  4153. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4154. return i;
  4155. return -1;
  4156. }
  4157. const String toString() const
  4158. {
  4159. if (parameters.size() == 0)
  4160. return functionName + "()";
  4161. String s (functionName + " (");
  4162. for (int i = 0; i < parameters.size(); ++i)
  4163. {
  4164. s << getTermFor (parameters.getReference(i))->toString();
  4165. if (i < parameters.size() - 1)
  4166. s << ", ";
  4167. }
  4168. s << ')';
  4169. return s;
  4170. }
  4171. const String functionName;
  4172. Array<Expression> parameters;
  4173. };
  4174. class DotOperator : public BinaryTerm
  4175. {
  4176. public:
  4177. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4178. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4179. {
  4180. checkRecursionDepth (recursionDepth);
  4181. EvaluationVisitor visitor (right, recursionDepth + 1);
  4182. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4183. return visitor.output;
  4184. }
  4185. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4186. const String getName() const { return "."; }
  4187. int getOperatorPrecedence() const { return 1; }
  4188. void writeOperator (String& dest) const { dest << '.'; }
  4189. double performFunction (double, double) const { return 0.0; }
  4190. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4191. {
  4192. checkRecursionDepth (recursionDepth);
  4193. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4194. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4195. try
  4196. {
  4197. scope.visitRelativeScope (getSymbol()->symbol, v);
  4198. }
  4199. catch (...) {}
  4200. }
  4201. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4202. {
  4203. checkRecursionDepth (recursionDepth);
  4204. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4205. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4206. try
  4207. {
  4208. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4209. }
  4210. catch (...) {}
  4211. }
  4212. private:
  4213. class EvaluationVisitor : public Scope::Visitor
  4214. {
  4215. public:
  4216. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4217. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4218. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4219. const TermPtr input;
  4220. TermPtr output;
  4221. const int recursionCount;
  4222. private:
  4223. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4224. };
  4225. class SymbolVisitingVisitor : public Scope::Visitor
  4226. {
  4227. public:
  4228. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4229. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4230. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4231. private:
  4232. const TermPtr input;
  4233. SymbolVisitor& visitor;
  4234. const int recursionCount;
  4235. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4236. };
  4237. class SymbolRenamingVisitor : public Scope::Visitor
  4238. {
  4239. public:
  4240. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4241. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4242. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4243. private:
  4244. const TermPtr input;
  4245. const Symbol& symbol;
  4246. const String newName;
  4247. const int recursionCount;
  4248. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4249. };
  4250. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4251. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4252. };
  4253. class Negate : public Term
  4254. {
  4255. public:
  4256. explicit Negate (const TermPtr& input_) : input (input_)
  4257. {
  4258. jassert (input_ != 0);
  4259. }
  4260. Type getType() const throw() { return operatorType; }
  4261. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4262. int getNumInputs() const { return 1; }
  4263. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4264. Term* clone() const { return new Negate (input->clone()); }
  4265. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4266. {
  4267. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4268. }
  4269. const String getName() const { return "-"; }
  4270. const TermPtr negated() { return input; }
  4271. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4272. {
  4273. (void) input_;
  4274. jassert (input_ == input);
  4275. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4276. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4277. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4278. }
  4279. const String toString() const
  4280. {
  4281. if (input->getOperatorPrecedence() > 0)
  4282. return "-(" + input->toString() + ")";
  4283. else
  4284. return "-" + input->toString();
  4285. }
  4286. private:
  4287. const TermPtr input;
  4288. };
  4289. class Add : public BinaryTerm
  4290. {
  4291. public:
  4292. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4293. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4294. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4295. int getOperatorPrecedence() const { return 3; }
  4296. const String getName() const { return "+"; }
  4297. void writeOperator (String& dest) const { dest << " + "; }
  4298. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4299. {
  4300. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4301. if (newDest == 0)
  4302. return 0;
  4303. return new Subtract (newDest, (input == left ? right : left)->clone());
  4304. }
  4305. private:
  4306. JUCE_DECLARE_NON_COPYABLE (Add);
  4307. };
  4308. class Subtract : public BinaryTerm
  4309. {
  4310. public:
  4311. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4312. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4313. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4314. int getOperatorPrecedence() const { return 3; }
  4315. const String getName() const { return "-"; }
  4316. void writeOperator (String& dest) const { dest << " - "; }
  4317. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4318. {
  4319. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4320. if (newDest == 0)
  4321. return 0;
  4322. if (input == left)
  4323. return new Add (newDest, right->clone());
  4324. else
  4325. return new Subtract (left->clone(), newDest);
  4326. }
  4327. private:
  4328. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4329. };
  4330. class Multiply : public BinaryTerm
  4331. {
  4332. public:
  4333. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4334. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4335. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4336. const String getName() const { return "*"; }
  4337. void writeOperator (String& dest) const { dest << " * "; }
  4338. int getOperatorPrecedence() const { return 2; }
  4339. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4340. {
  4341. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4342. if (newDest == 0)
  4343. return 0;
  4344. return new Divide (newDest, (input == left ? right : left)->clone());
  4345. }
  4346. private:
  4347. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4348. };
  4349. class Divide : public BinaryTerm
  4350. {
  4351. public:
  4352. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4353. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4354. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4355. const String getName() const { return "/"; }
  4356. void writeOperator (String& dest) const { dest << " / "; }
  4357. int getOperatorPrecedence() const { return 2; }
  4358. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4359. {
  4360. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4361. if (newDest == 0)
  4362. return 0;
  4363. if (input == left)
  4364. return new Multiply (newDest, right->clone());
  4365. else
  4366. return new Divide (left->clone(), newDest);
  4367. }
  4368. private:
  4369. JUCE_DECLARE_NON_COPYABLE (Divide);
  4370. };
  4371. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4372. {
  4373. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4374. if (inputIndex >= 0)
  4375. return topLevel;
  4376. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4377. {
  4378. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4379. if (t != 0)
  4380. return t;
  4381. }
  4382. return 0;
  4383. }
  4384. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4385. {
  4386. {
  4387. Constant* const c = dynamic_cast<Constant*> (term);
  4388. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4389. return c;
  4390. }
  4391. if (dynamic_cast<Function*> (term) != 0)
  4392. return 0;
  4393. int i;
  4394. const int numIns = term->getNumInputs();
  4395. for (i = 0; i < numIns; ++i)
  4396. {
  4397. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4398. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4399. return c;
  4400. }
  4401. for (i = 0; i < numIns; ++i)
  4402. {
  4403. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4404. if (c != 0)
  4405. return c;
  4406. }
  4407. return 0;
  4408. }
  4409. static bool containsAnySymbols (const Term* const t)
  4410. {
  4411. if (t->getType() == Expression::symbolType)
  4412. return true;
  4413. for (int i = t->getNumInputs(); --i >= 0;)
  4414. if (containsAnySymbols (t->getInput (i)))
  4415. return true;
  4416. return false;
  4417. }
  4418. class SymbolCheckVisitor : public Term::SymbolVisitor
  4419. {
  4420. public:
  4421. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4422. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4423. bool wasFound;
  4424. private:
  4425. const Symbol& symbol;
  4426. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4427. };
  4428. class SymbolListVisitor : public Term::SymbolVisitor
  4429. {
  4430. public:
  4431. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4432. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4433. private:
  4434. Array<Symbol>& list;
  4435. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4436. };
  4437. class Parser
  4438. {
  4439. public:
  4440. Parser (String::CharPointerType& stringToParse)
  4441. : text (stringToParse)
  4442. {
  4443. }
  4444. const TermPtr readUpToComma()
  4445. {
  4446. if (text.isEmpty())
  4447. return new Constant (0.0, false);
  4448. const TermPtr e (readExpression());
  4449. if (e == 0 || ((! readOperator (",")) && ! text.isEmpty()))
  4450. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  4451. return e;
  4452. }
  4453. private:
  4454. String::CharPointerType& text;
  4455. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4456. {
  4457. return c >= '0' && c <= '9';
  4458. }
  4459. bool readChar (const juce_wchar required) throw()
  4460. {
  4461. if (*text == required)
  4462. {
  4463. ++text;
  4464. return true;
  4465. }
  4466. return false;
  4467. }
  4468. bool readOperator (const char* ops, char* const opType = 0) throw()
  4469. {
  4470. text = text.findEndOfWhitespace();
  4471. while (*ops != 0)
  4472. {
  4473. if (readChar (*ops))
  4474. {
  4475. if (opType != 0)
  4476. *opType = *ops;
  4477. return true;
  4478. }
  4479. ++ops;
  4480. }
  4481. return false;
  4482. }
  4483. bool readIdentifier (String& identifier) throw()
  4484. {
  4485. text = text.findEndOfWhitespace();
  4486. String::CharPointerType t (text);
  4487. int numChars = 0;
  4488. if (t.isLetter() || *t == '_')
  4489. {
  4490. ++t;
  4491. ++numChars;
  4492. while (t.isLetterOrDigit() || *t == '_')
  4493. {
  4494. ++t;
  4495. ++numChars;
  4496. }
  4497. }
  4498. if (numChars > 0)
  4499. {
  4500. identifier = String (text, numChars);
  4501. text = t;
  4502. return true;
  4503. }
  4504. return false;
  4505. }
  4506. Term* readNumber() throw()
  4507. {
  4508. text = text.findEndOfWhitespace();
  4509. String::CharPointerType t (text);
  4510. const bool isResolutionTarget = (*t == '@');
  4511. if (isResolutionTarget)
  4512. {
  4513. ++t;
  4514. t = t.findEndOfWhitespace();
  4515. text = t;
  4516. }
  4517. if (*t == '-')
  4518. {
  4519. ++t;
  4520. t = t.findEndOfWhitespace();
  4521. }
  4522. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  4523. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  4524. return 0;
  4525. }
  4526. const TermPtr readExpression()
  4527. {
  4528. TermPtr lhs (readMultiplyOrDivideExpression());
  4529. char opType;
  4530. while (lhs != 0 && readOperator ("+-", &opType))
  4531. {
  4532. TermPtr rhs (readMultiplyOrDivideExpression());
  4533. if (rhs == 0)
  4534. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4535. if (opType == '+')
  4536. lhs = new Add (lhs, rhs);
  4537. else
  4538. lhs = new Subtract (lhs, rhs);
  4539. }
  4540. return lhs;
  4541. }
  4542. const TermPtr readMultiplyOrDivideExpression()
  4543. {
  4544. TermPtr lhs (readUnaryExpression());
  4545. char opType;
  4546. while (lhs != 0 && readOperator ("*/", &opType))
  4547. {
  4548. TermPtr rhs (readUnaryExpression());
  4549. if (rhs == 0)
  4550. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4551. if (opType == '*')
  4552. lhs = new Multiply (lhs, rhs);
  4553. else
  4554. lhs = new Divide (lhs, rhs);
  4555. }
  4556. return lhs;
  4557. }
  4558. const TermPtr readUnaryExpression()
  4559. {
  4560. char opType;
  4561. if (readOperator ("+-", &opType))
  4562. {
  4563. TermPtr term (readUnaryExpression());
  4564. if (term == 0)
  4565. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4566. if (opType == '-')
  4567. term = term->negated();
  4568. return term;
  4569. }
  4570. return readPrimaryExpression();
  4571. }
  4572. const TermPtr readPrimaryExpression()
  4573. {
  4574. TermPtr e (readParenthesisedExpression());
  4575. if (e != 0)
  4576. return e;
  4577. e = readNumber();
  4578. if (e != 0)
  4579. return e;
  4580. return readSymbolOrFunction();
  4581. }
  4582. const TermPtr readSymbolOrFunction()
  4583. {
  4584. String identifier;
  4585. if (readIdentifier (identifier))
  4586. {
  4587. if (readOperator ("(")) // method call...
  4588. {
  4589. Function* const f = new Function (identifier);
  4590. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4591. TermPtr param (readExpression());
  4592. if (param == 0)
  4593. {
  4594. if (readOperator (")"))
  4595. return func.release();
  4596. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4597. }
  4598. f->parameters.add (Expression (param));
  4599. while (readOperator (","))
  4600. {
  4601. param = readExpression();
  4602. if (param == 0)
  4603. throw ParseError ("Expected expression after \",\"");
  4604. f->parameters.add (Expression (param));
  4605. }
  4606. if (readOperator (")"))
  4607. return func.release();
  4608. throw ParseError ("Expected \")\"");
  4609. }
  4610. else if (readOperator ("."))
  4611. {
  4612. TermPtr rhs (readSymbolOrFunction());
  4613. if (rhs == 0)
  4614. throw ParseError ("Expected symbol or function after \".\"");
  4615. if (identifier == "this")
  4616. return rhs;
  4617. return new DotOperator (new SymbolTerm (identifier), rhs);
  4618. }
  4619. else // just a symbol..
  4620. {
  4621. jassert (identifier.trim() == identifier);
  4622. return new SymbolTerm (identifier);
  4623. }
  4624. }
  4625. return 0;
  4626. }
  4627. const TermPtr readParenthesisedExpression()
  4628. {
  4629. if (! readOperator ("("))
  4630. return 0;
  4631. const TermPtr e (readExpression());
  4632. if (e == 0 || ! readOperator (")"))
  4633. return 0;
  4634. return e;
  4635. }
  4636. JUCE_DECLARE_NON_COPYABLE (Parser);
  4637. };
  4638. };
  4639. Expression::Expression()
  4640. : term (new Expression::Helpers::Constant (0, false))
  4641. {
  4642. }
  4643. Expression::~Expression()
  4644. {
  4645. }
  4646. Expression::Expression (Term* const term_)
  4647. : term (term_)
  4648. {
  4649. jassert (term != 0);
  4650. }
  4651. Expression::Expression (const double constant)
  4652. : term (new Expression::Helpers::Constant (constant, false))
  4653. {
  4654. }
  4655. Expression::Expression (const Expression& other)
  4656. : term (other.term)
  4657. {
  4658. }
  4659. Expression& Expression::operator= (const Expression& other)
  4660. {
  4661. term = other.term;
  4662. return *this;
  4663. }
  4664. Expression::Expression (const String& stringToParse)
  4665. {
  4666. String::CharPointerType text (stringToParse.getCharPointer());
  4667. Helpers::Parser parser (text);
  4668. term = parser.readUpToComma();
  4669. }
  4670. const Expression Expression::parse (String::CharPointerType& stringToParse)
  4671. {
  4672. Helpers::Parser parser (stringToParse);
  4673. return Expression (parser.readUpToComma());
  4674. }
  4675. double Expression::evaluate() const
  4676. {
  4677. return evaluate (Expression::Scope());
  4678. }
  4679. double Expression::evaluate (const Expression::Scope& scope) const
  4680. {
  4681. try
  4682. {
  4683. return term->resolve (scope, 0)->toDouble();
  4684. }
  4685. catch (Helpers::EvaluationError&)
  4686. {}
  4687. return 0;
  4688. }
  4689. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4690. {
  4691. try
  4692. {
  4693. return term->resolve (scope, 0)->toDouble();
  4694. }
  4695. catch (Helpers::EvaluationError& e)
  4696. {
  4697. evaluationError = e.description;
  4698. }
  4699. return 0;
  4700. }
  4701. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4702. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4703. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4704. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4705. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4706. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4707. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4708. {
  4709. return Expression (new Helpers::Function (functionName, parameters));
  4710. }
  4711. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4712. {
  4713. ScopedPointer<Term> newTerm (term->clone());
  4714. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4715. if (termToAdjust == 0)
  4716. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4717. if (termToAdjust == 0)
  4718. {
  4719. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4720. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4721. }
  4722. jassert (termToAdjust != 0);
  4723. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4724. if (parent == 0)
  4725. {
  4726. termToAdjust->value = targetValue;
  4727. }
  4728. else
  4729. {
  4730. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4731. if (reverseTerm == 0)
  4732. return Expression (targetValue);
  4733. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4734. }
  4735. return Expression (newTerm.release());
  4736. }
  4737. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4738. {
  4739. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4740. if (oldSymbol.symbolName == newName)
  4741. return *this;
  4742. Expression e (term->clone());
  4743. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4744. return e;
  4745. }
  4746. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4747. {
  4748. Helpers::SymbolCheckVisitor visitor (symbol);
  4749. try
  4750. {
  4751. term->visitAllSymbols (visitor, scope, 0);
  4752. }
  4753. catch (Helpers::EvaluationError&)
  4754. {}
  4755. return visitor.wasFound;
  4756. }
  4757. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4758. {
  4759. try
  4760. {
  4761. Helpers::SymbolListVisitor visitor (results);
  4762. term->visitAllSymbols (visitor, scope, 0);
  4763. }
  4764. catch (Helpers::EvaluationError&)
  4765. {}
  4766. }
  4767. const String Expression::toString() const { return term->toString(); }
  4768. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4769. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4770. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4771. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4772. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4773. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4774. {
  4775. return new Helpers::Negate (this);
  4776. }
  4777. Expression::ParseError::ParseError (const String& message)
  4778. : description (message)
  4779. {
  4780. DBG ("Expression::ParseError: " + message);
  4781. }
  4782. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4783. : scopeUID (scopeUID_), symbolName (symbolName_)
  4784. {
  4785. }
  4786. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4787. {
  4788. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4789. }
  4790. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4791. {
  4792. return ! operator== (other);
  4793. }
  4794. Expression::Scope::Scope() {}
  4795. Expression::Scope::~Scope() {}
  4796. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4797. {
  4798. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4799. }
  4800. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4801. {
  4802. if (numParams > 0)
  4803. {
  4804. if (functionName == "min")
  4805. {
  4806. double v = parameters[0];
  4807. for (int i = 1; i < numParams; ++i)
  4808. v = jmin (v, parameters[i]);
  4809. return v;
  4810. }
  4811. else if (functionName == "max")
  4812. {
  4813. double v = parameters[0];
  4814. for (int i = 1; i < numParams; ++i)
  4815. v = jmax (v, parameters[i]);
  4816. return v;
  4817. }
  4818. else if (numParams == 1)
  4819. {
  4820. if (functionName == "sin") return sin (parameters[0]);
  4821. else if (functionName == "cos") return cos (parameters[0]);
  4822. else if (functionName == "tan") return tan (parameters[0]);
  4823. else if (functionName == "abs") return std::abs (parameters[0]);
  4824. }
  4825. }
  4826. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4827. }
  4828. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4829. {
  4830. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4831. }
  4832. const String Expression::Scope::getScopeUID() const
  4833. {
  4834. return String::empty;
  4835. }
  4836. END_JUCE_NAMESPACE
  4837. /*** End of inlined file: juce_Expression.cpp ***/
  4838. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4839. BEGIN_JUCE_NAMESPACE
  4840. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4841. {
  4842. jassert (keyData != 0);
  4843. jassert (keyBytes > 0);
  4844. static const uint32 initialPValues [18] =
  4845. {
  4846. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4847. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4848. 0x9216d5d9, 0x8979fb1b
  4849. };
  4850. static const uint32 initialSValues [4 * 256] =
  4851. {
  4852. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4853. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4854. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4855. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4856. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4857. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4858. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4859. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4860. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4861. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4862. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4863. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4864. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4865. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4866. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4867. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4868. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4869. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4870. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4871. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4872. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4873. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4874. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4875. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4876. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4877. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4878. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4879. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4880. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4881. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4882. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4883. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4884. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4885. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4886. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4887. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4888. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4889. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4890. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4891. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4892. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4893. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4894. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4895. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4896. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4897. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4898. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4899. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4900. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4901. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4902. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4903. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4904. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4905. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4906. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4907. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4908. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4909. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4910. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4911. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4912. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4913. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4914. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4915. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4916. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4917. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4918. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4919. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4920. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4921. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4922. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4923. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4924. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4925. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4926. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4927. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4928. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4929. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4930. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4931. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4932. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4933. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4934. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4935. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4936. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4937. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4938. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4939. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4940. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4941. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4942. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4943. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4944. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4945. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4946. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4947. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4948. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4949. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4950. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4951. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4952. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4953. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4954. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4955. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4956. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4957. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4958. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4959. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4960. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4961. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4962. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4963. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4964. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4965. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4966. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4967. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4968. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4969. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4970. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4971. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4972. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4973. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4974. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4975. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4976. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4977. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4978. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4979. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4980. };
  4981. memcpy (p, initialPValues, sizeof (p));
  4982. int i, j = 0;
  4983. for (i = 4; --i >= 0;)
  4984. {
  4985. s[i].malloc (256);
  4986. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4987. }
  4988. for (i = 0; i < 18; ++i)
  4989. {
  4990. uint32 d = 0;
  4991. for (int k = 0; k < 4; ++k)
  4992. {
  4993. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4994. if (++j >= keyBytes)
  4995. j = 0;
  4996. }
  4997. p[i] = initialPValues[i] ^ d;
  4998. }
  4999. uint32 l = 0, r = 0;
  5000. for (i = 0; i < 18; i += 2)
  5001. {
  5002. encrypt (l, r);
  5003. p[i] = l;
  5004. p[i + 1] = r;
  5005. }
  5006. for (i = 0; i < 4; ++i)
  5007. {
  5008. for (j = 0; j < 256; j += 2)
  5009. {
  5010. encrypt (l, r);
  5011. s[i][j] = l;
  5012. s[i][j + 1] = r;
  5013. }
  5014. }
  5015. }
  5016. BlowFish::BlowFish (const BlowFish& other)
  5017. {
  5018. for (int i = 4; --i >= 0;)
  5019. s[i].malloc (256);
  5020. operator= (other);
  5021. }
  5022. BlowFish& BlowFish::operator= (const BlowFish& other)
  5023. {
  5024. memcpy (p, other.p, sizeof (p));
  5025. for (int i = 4; --i >= 0;)
  5026. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  5027. return *this;
  5028. }
  5029. BlowFish::~BlowFish()
  5030. {
  5031. }
  5032. uint32 BlowFish::F (const uint32 x) const throw()
  5033. {
  5034. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  5035. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  5036. }
  5037. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  5038. {
  5039. uint32 l = data1;
  5040. uint32 r = data2;
  5041. for (int i = 0; i < 16; ++i)
  5042. {
  5043. l ^= p[i];
  5044. r ^= F(l);
  5045. swapVariables (l, r);
  5046. }
  5047. data1 = r ^ p[17];
  5048. data2 = l ^ p[16];
  5049. }
  5050. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  5051. {
  5052. uint32 l = data1;
  5053. uint32 r = data2;
  5054. for (int i = 17; i > 1; --i)
  5055. {
  5056. l ^= p[i];
  5057. r ^= F(l);
  5058. swapVariables (l, r);
  5059. }
  5060. data1 = r ^ p[0];
  5061. data2 = l ^ p[1];
  5062. }
  5063. END_JUCE_NAMESPACE
  5064. /*** End of inlined file: juce_BlowFish.cpp ***/
  5065. /*** Start of inlined file: juce_MD5.cpp ***/
  5066. BEGIN_JUCE_NAMESPACE
  5067. MD5::MD5()
  5068. {
  5069. zerostruct (result);
  5070. }
  5071. MD5::MD5 (const MD5& other)
  5072. {
  5073. memcpy (result, other.result, sizeof (result));
  5074. }
  5075. MD5& MD5::operator= (const MD5& other)
  5076. {
  5077. memcpy (result, other.result, sizeof (result));
  5078. return *this;
  5079. }
  5080. MD5::MD5 (const MemoryBlock& data)
  5081. {
  5082. ProcessContext context;
  5083. context.processBlock (data.getData(), data.getSize());
  5084. context.finish (result);
  5085. }
  5086. MD5::MD5 (const void* data, const size_t numBytes)
  5087. {
  5088. ProcessContext context;
  5089. context.processBlock (data, numBytes);
  5090. context.finish (result);
  5091. }
  5092. MD5::MD5 (const String& text)
  5093. {
  5094. ProcessContext context;
  5095. String::CharPointerType t (text.getCharPointer());
  5096. while (! t.isEmpty())
  5097. {
  5098. // force the string into integer-sized unicode characters, to try to make it
  5099. // get the same results on all platforms + compilers.
  5100. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t.getAndAdvance());
  5101. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5102. }
  5103. context.finish (result);
  5104. }
  5105. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5106. {
  5107. ProcessContext context;
  5108. if (numBytesToRead < 0)
  5109. numBytesToRead = std::numeric_limits<int64>::max();
  5110. while (numBytesToRead > 0)
  5111. {
  5112. uint8 tempBuffer [512];
  5113. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5114. if (bytesRead <= 0)
  5115. break;
  5116. numBytesToRead -= bytesRead;
  5117. context.processBlock (tempBuffer, bytesRead);
  5118. }
  5119. context.finish (result);
  5120. }
  5121. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5122. {
  5123. processStream (input, numBytesToRead);
  5124. }
  5125. MD5::MD5 (const File& file)
  5126. {
  5127. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5128. if (fin != 0)
  5129. processStream (*fin, -1);
  5130. else
  5131. zerostruct (result);
  5132. }
  5133. MD5::~MD5()
  5134. {
  5135. }
  5136. namespace MD5Functions
  5137. {
  5138. void encode (void* const output, const void* const input, const int numBytes) throw()
  5139. {
  5140. for (int i = 0; i < (numBytes >> 2); ++i)
  5141. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5142. }
  5143. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5144. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5145. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5146. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5147. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5148. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5149. {
  5150. a += F (b, c, d) + x + ac;
  5151. a = rotateLeft (a, s) + b;
  5152. }
  5153. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5154. {
  5155. a += G (b, c, d) + x + ac;
  5156. a = rotateLeft (a, s) + b;
  5157. }
  5158. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5159. {
  5160. a += H (b, c, d) + x + ac;
  5161. a = rotateLeft (a, s) + b;
  5162. }
  5163. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5164. {
  5165. a += I (b, c, d) + x + ac;
  5166. a = rotateLeft (a, s) + b;
  5167. }
  5168. }
  5169. MD5::ProcessContext::ProcessContext()
  5170. {
  5171. state[0] = 0x67452301;
  5172. state[1] = 0xefcdab89;
  5173. state[2] = 0x98badcfe;
  5174. state[3] = 0x10325476;
  5175. count[0] = 0;
  5176. count[1] = 0;
  5177. }
  5178. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5179. {
  5180. int bufferPos = ((count[0] >> 3) & 0x3F);
  5181. count[0] += (uint32) (dataSize << 3);
  5182. if (count[0] < ((uint32) dataSize << 3))
  5183. count[1]++;
  5184. count[1] += (uint32) (dataSize >> 29);
  5185. const size_t spaceLeft = 64 - bufferPos;
  5186. size_t i = 0;
  5187. if (dataSize >= spaceLeft)
  5188. {
  5189. memcpy (buffer + bufferPos, data, spaceLeft);
  5190. transform (buffer);
  5191. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5192. transform (static_cast <const char*> (data) + i);
  5193. bufferPos = 0;
  5194. }
  5195. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5196. }
  5197. void MD5::ProcessContext::finish (void* const result)
  5198. {
  5199. unsigned char encodedLength[8];
  5200. MD5Functions::encode (encodedLength, count, 8);
  5201. // Pad out to 56 mod 64.
  5202. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5203. const int paddingLength = (index < 56) ? (56 - index)
  5204. : (120 - index);
  5205. uint8 paddingBuffer [64];
  5206. zeromem (paddingBuffer, paddingLength);
  5207. paddingBuffer [0] = 0x80;
  5208. processBlock (paddingBuffer, paddingLength);
  5209. processBlock (encodedLength, 8);
  5210. MD5Functions::encode (result, state, 16);
  5211. zerostruct (buffer);
  5212. }
  5213. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5214. {
  5215. using namespace MD5Functions;
  5216. uint32 a = state[0];
  5217. uint32 b = state[1];
  5218. uint32 c = state[2];
  5219. uint32 d = state[3];
  5220. uint32 x[16];
  5221. encode (x, bufferToTransform, 64);
  5222. enum Constants
  5223. {
  5224. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5225. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5226. };
  5227. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5228. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5229. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5230. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5231. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5232. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5233. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5234. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5235. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5236. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5237. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5238. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5239. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5240. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5241. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5242. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5243. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5244. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5245. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5246. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5247. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5248. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5249. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5250. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5251. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5252. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5253. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5254. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5255. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5256. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5257. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5258. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5259. state[0] += a;
  5260. state[1] += b;
  5261. state[2] += c;
  5262. state[3] += d;
  5263. zerostruct (x);
  5264. }
  5265. const MemoryBlock MD5::getRawChecksumData() const
  5266. {
  5267. return MemoryBlock (result, sizeof (result));
  5268. }
  5269. const String MD5::toHexString() const
  5270. {
  5271. return String::toHexString (result, sizeof (result), 0);
  5272. }
  5273. bool MD5::operator== (const MD5& other) const
  5274. {
  5275. return memcmp (result, other.result, sizeof (result)) == 0;
  5276. }
  5277. bool MD5::operator!= (const MD5& other) const
  5278. {
  5279. return ! operator== (other);
  5280. }
  5281. END_JUCE_NAMESPACE
  5282. /*** End of inlined file: juce_MD5.cpp ***/
  5283. /*** Start of inlined file: juce_Primes.cpp ***/
  5284. BEGIN_JUCE_NAMESPACE
  5285. namespace PrimesHelpers
  5286. {
  5287. void createSmallSieve (const int numBits, BigInteger& result)
  5288. {
  5289. result.setBit (numBits);
  5290. result.clearBit (numBits); // to enlarge the array
  5291. result.setBit (0);
  5292. int n = 2;
  5293. do
  5294. {
  5295. for (int i = n + n; i < numBits; i += n)
  5296. result.setBit (i);
  5297. n = result.findNextClearBit (n + 1);
  5298. }
  5299. while (n <= (numBits >> 1));
  5300. }
  5301. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5302. const BigInteger& smallSieve, const int smallSieveSize)
  5303. {
  5304. jassert (! base[0]); // must be even!
  5305. result.setBit (numBits);
  5306. result.clearBit (numBits); // to enlarge the array
  5307. int index = smallSieve.findNextClearBit (0);
  5308. do
  5309. {
  5310. const int prime = (index << 1) + 1;
  5311. BigInteger r (base), remainder;
  5312. r.divideBy (prime, remainder);
  5313. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5314. if (r.isZero())
  5315. i += prime;
  5316. if ((i & 1) == 0)
  5317. i += prime;
  5318. i = (i - 1) >> 1;
  5319. while (i < numBits)
  5320. {
  5321. result.setBit (i);
  5322. i += prime;
  5323. }
  5324. index = smallSieve.findNextClearBit (index + 1);
  5325. }
  5326. while (index < smallSieveSize);
  5327. }
  5328. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5329. const int numBits, BigInteger& result, const int certainty)
  5330. {
  5331. for (int i = 0; i < numBits; ++i)
  5332. {
  5333. if (! sieve[i])
  5334. {
  5335. result = base + (unsigned int) ((i << 1) + 1);
  5336. if (Primes::isProbablyPrime (result, certainty))
  5337. return true;
  5338. }
  5339. }
  5340. return false;
  5341. }
  5342. bool passesMillerRabin (const BigInteger& n, int iterations)
  5343. {
  5344. const BigInteger one (1), two (2);
  5345. const BigInteger nMinusOne (n - one);
  5346. BigInteger d (nMinusOne);
  5347. const int s = d.findNextSetBit (0);
  5348. d >>= s;
  5349. BigInteger smallPrimes;
  5350. int numBitsInSmallPrimes = 0;
  5351. for (;;)
  5352. {
  5353. numBitsInSmallPrimes += 256;
  5354. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5355. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5356. if (numPrimesFound > iterations + 1)
  5357. break;
  5358. }
  5359. int smallPrime = 2;
  5360. while (--iterations >= 0)
  5361. {
  5362. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5363. BigInteger r (smallPrime);
  5364. r.exponentModulo (d, n);
  5365. if (r != one && r != nMinusOne)
  5366. {
  5367. for (int j = 0; j < s; ++j)
  5368. {
  5369. r.exponentModulo (two, n);
  5370. if (r == nMinusOne)
  5371. break;
  5372. }
  5373. if (r != nMinusOne)
  5374. return false;
  5375. }
  5376. }
  5377. return true;
  5378. }
  5379. }
  5380. const BigInteger Primes::createProbablePrime (const int bitLength,
  5381. const int certainty,
  5382. const int* randomSeeds,
  5383. int numRandomSeeds)
  5384. {
  5385. using namespace PrimesHelpers;
  5386. int defaultSeeds [16];
  5387. if (numRandomSeeds <= 0)
  5388. {
  5389. randomSeeds = defaultSeeds;
  5390. numRandomSeeds = numElementsInArray (defaultSeeds);
  5391. Random r (0);
  5392. for (int j = 10; --j >= 0;)
  5393. {
  5394. r.setSeedRandomly();
  5395. for (int i = numRandomSeeds; --i >= 0;)
  5396. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5397. }
  5398. }
  5399. BigInteger smallSieve;
  5400. const int smallSieveSize = 15000;
  5401. createSmallSieve (smallSieveSize, smallSieve);
  5402. BigInteger p;
  5403. for (int i = numRandomSeeds; --i >= 0;)
  5404. {
  5405. BigInteger p2;
  5406. Random r (randomSeeds[i]);
  5407. r.fillBitsRandomly (p2, 0, bitLength);
  5408. p ^= p2;
  5409. }
  5410. p.setBit (bitLength - 1);
  5411. p.clearBit (0);
  5412. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5413. while (p.getHighestBit() < bitLength)
  5414. {
  5415. p += 2 * searchLen;
  5416. BigInteger sieve;
  5417. bigSieve (p, searchLen, sieve,
  5418. smallSieve, smallSieveSize);
  5419. BigInteger candidate;
  5420. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5421. return candidate;
  5422. }
  5423. jassertfalse;
  5424. return BigInteger();
  5425. }
  5426. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5427. {
  5428. using namespace PrimesHelpers;
  5429. if (! number[0])
  5430. return false;
  5431. if (number.getHighestBit() <= 10)
  5432. {
  5433. const int num = number.getBitRangeAsInt (0, 10);
  5434. for (int i = num / 2; --i > 1;)
  5435. if (num % i == 0)
  5436. return false;
  5437. return true;
  5438. }
  5439. else
  5440. {
  5441. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5442. return false;
  5443. return passesMillerRabin (number, certainty);
  5444. }
  5445. }
  5446. END_JUCE_NAMESPACE
  5447. /*** End of inlined file: juce_Primes.cpp ***/
  5448. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5449. BEGIN_JUCE_NAMESPACE
  5450. RSAKey::RSAKey()
  5451. {
  5452. }
  5453. RSAKey::RSAKey (const String& s)
  5454. {
  5455. if (s.containsChar (','))
  5456. {
  5457. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5458. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5459. }
  5460. else
  5461. {
  5462. // the string needs to be two hex numbers, comma-separated..
  5463. jassertfalse;
  5464. }
  5465. }
  5466. RSAKey::~RSAKey()
  5467. {
  5468. }
  5469. bool RSAKey::operator== (const RSAKey& other) const throw()
  5470. {
  5471. return part1 == other.part1 && part2 == other.part2;
  5472. }
  5473. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5474. {
  5475. return ! operator== (other);
  5476. }
  5477. const String RSAKey::toString() const
  5478. {
  5479. return part1.toString (16) + "," + part2.toString (16);
  5480. }
  5481. bool RSAKey::applyToValue (BigInteger& value) const
  5482. {
  5483. if (part1.isZero() || part2.isZero() || value <= 0)
  5484. {
  5485. jassertfalse; // using an uninitialised key
  5486. value.clear();
  5487. return false;
  5488. }
  5489. BigInteger result;
  5490. while (! value.isZero())
  5491. {
  5492. result *= part2;
  5493. BigInteger remainder;
  5494. value.divideBy (part2, remainder);
  5495. remainder.exponentModulo (part1, part2);
  5496. result += remainder;
  5497. }
  5498. value.swapWith (result);
  5499. return true;
  5500. }
  5501. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5502. {
  5503. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5504. // are fast to divide + multiply
  5505. for (int i = 2; i <= 65536; i *= 2)
  5506. {
  5507. const BigInteger e (1 + i);
  5508. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5509. return e;
  5510. }
  5511. BigInteger e (4);
  5512. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5513. ++e;
  5514. return e;
  5515. }
  5516. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5517. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5518. {
  5519. jassert (numBits > 16); // not much point using less than this..
  5520. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5521. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5522. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5523. const BigInteger n (p * q);
  5524. const BigInteger m (--p * --q);
  5525. const BigInteger e (findBestCommonDivisor (p, q));
  5526. BigInteger d (e);
  5527. d.inverseModulo (m);
  5528. publicKey.part1 = e;
  5529. publicKey.part2 = n;
  5530. privateKey.part1 = d;
  5531. privateKey.part2 = n;
  5532. }
  5533. END_JUCE_NAMESPACE
  5534. /*** End of inlined file: juce_RSAKey.cpp ***/
  5535. /*** Start of inlined file: juce_InputStream.cpp ***/
  5536. BEGIN_JUCE_NAMESPACE
  5537. char InputStream::readByte()
  5538. {
  5539. char temp = 0;
  5540. read (&temp, 1);
  5541. return temp;
  5542. }
  5543. bool InputStream::readBool()
  5544. {
  5545. return readByte() != 0;
  5546. }
  5547. short InputStream::readShort()
  5548. {
  5549. char temp[2];
  5550. if (read (temp, 2) == 2)
  5551. return (short) ByteOrder::littleEndianShort (temp);
  5552. return 0;
  5553. }
  5554. short InputStream::readShortBigEndian()
  5555. {
  5556. char temp[2];
  5557. if (read (temp, 2) == 2)
  5558. return (short) ByteOrder::bigEndianShort (temp);
  5559. return 0;
  5560. }
  5561. int InputStream::readInt()
  5562. {
  5563. char temp[4];
  5564. if (read (temp, 4) == 4)
  5565. return (int) ByteOrder::littleEndianInt (temp);
  5566. return 0;
  5567. }
  5568. int InputStream::readIntBigEndian()
  5569. {
  5570. char temp[4];
  5571. if (read (temp, 4) == 4)
  5572. return (int) ByteOrder::bigEndianInt (temp);
  5573. return 0;
  5574. }
  5575. int InputStream::readCompressedInt()
  5576. {
  5577. const unsigned char sizeByte = readByte();
  5578. if (sizeByte == 0)
  5579. return 0;
  5580. const int numBytes = (sizeByte & 0x7f);
  5581. if (numBytes > 4)
  5582. {
  5583. jassertfalse; // trying to read corrupt data - this method must only be used
  5584. // to read data that was written by OutputStream::writeCompressedInt()
  5585. return 0;
  5586. }
  5587. char bytes[4] = { 0, 0, 0, 0 };
  5588. if (read (bytes, numBytes) != numBytes)
  5589. return 0;
  5590. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5591. return (sizeByte >> 7) ? -num : num;
  5592. }
  5593. int64 InputStream::readInt64()
  5594. {
  5595. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5596. if (read (n.asBytes, 8) == 8)
  5597. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5598. return 0;
  5599. }
  5600. int64 InputStream::readInt64BigEndian()
  5601. {
  5602. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5603. if (read (n.asBytes, 8) == 8)
  5604. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5605. return 0;
  5606. }
  5607. float InputStream::readFloat()
  5608. {
  5609. // the union below relies on these types being the same size...
  5610. static_jassert (sizeof (int32) == sizeof (float));
  5611. union { int32 asInt; float asFloat; } n;
  5612. n.asInt = (int32) readInt();
  5613. return n.asFloat;
  5614. }
  5615. float InputStream::readFloatBigEndian()
  5616. {
  5617. union { int32 asInt; float asFloat; } n;
  5618. n.asInt = (int32) readIntBigEndian();
  5619. return n.asFloat;
  5620. }
  5621. double InputStream::readDouble()
  5622. {
  5623. union { int64 asInt; double asDouble; } n;
  5624. n.asInt = readInt64();
  5625. return n.asDouble;
  5626. }
  5627. double InputStream::readDoubleBigEndian()
  5628. {
  5629. union { int64 asInt; double asDouble; } n;
  5630. n.asInt = readInt64BigEndian();
  5631. return n.asDouble;
  5632. }
  5633. const String InputStream::readString()
  5634. {
  5635. MemoryBlock buffer (256);
  5636. char* data = static_cast<char*> (buffer.getData());
  5637. size_t i = 0;
  5638. while ((data[i] = readByte()) != 0)
  5639. {
  5640. if (++i >= buffer.getSize())
  5641. {
  5642. buffer.setSize (buffer.getSize() + 512);
  5643. data = static_cast<char*> (buffer.getData());
  5644. }
  5645. }
  5646. return String::fromUTF8 (data, (int) i);
  5647. }
  5648. const String InputStream::readNextLine()
  5649. {
  5650. MemoryBlock buffer (256);
  5651. char* data = static_cast<char*> (buffer.getData());
  5652. size_t i = 0;
  5653. while ((data[i] = readByte()) != 0)
  5654. {
  5655. if (data[i] == '\n')
  5656. break;
  5657. if (data[i] == '\r')
  5658. {
  5659. const int64 lastPos = getPosition();
  5660. if (readByte() != '\n')
  5661. setPosition (lastPos);
  5662. break;
  5663. }
  5664. if (++i >= buffer.getSize())
  5665. {
  5666. buffer.setSize (buffer.getSize() + 512);
  5667. data = static_cast<char*> (buffer.getData());
  5668. }
  5669. }
  5670. return String::fromUTF8 (data, (int) i);
  5671. }
  5672. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5673. {
  5674. MemoryOutputStream mo (block, true);
  5675. return mo.writeFromInputStream (*this, numBytes);
  5676. }
  5677. const String InputStream::readEntireStreamAsString()
  5678. {
  5679. MemoryOutputStream mo;
  5680. mo.writeFromInputStream (*this, -1);
  5681. return mo.toString();
  5682. }
  5683. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5684. {
  5685. if (numBytesToSkip > 0)
  5686. {
  5687. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5688. HeapBlock<char> temp (skipBufferSize);
  5689. while (numBytesToSkip > 0 && ! isExhausted())
  5690. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5691. }
  5692. }
  5693. END_JUCE_NAMESPACE
  5694. /*** End of inlined file: juce_InputStream.cpp ***/
  5695. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5696. BEGIN_JUCE_NAMESPACE
  5697. #if JUCE_DEBUG
  5698. static Array<void*, CriticalSection> activeStreams;
  5699. void juce_CheckForDanglingStreams()
  5700. {
  5701. /*
  5702. It's always a bad idea to leak any object, but if you're leaking output
  5703. streams, then there's a good chance that you're failing to flush a file
  5704. to disk properly, which could result in corrupted data and other similar
  5705. nastiness..
  5706. */
  5707. jassert (activeStreams.size() == 0);
  5708. };
  5709. #endif
  5710. OutputStream::OutputStream()
  5711. : newLineString (NewLine::getDefault())
  5712. {
  5713. #if JUCE_DEBUG
  5714. activeStreams.add (this);
  5715. #endif
  5716. }
  5717. OutputStream::~OutputStream()
  5718. {
  5719. #if JUCE_DEBUG
  5720. activeStreams.removeValue (this);
  5721. #endif
  5722. }
  5723. void OutputStream::writeBool (const bool b)
  5724. {
  5725. writeByte (b ? (char) 1
  5726. : (char) 0);
  5727. }
  5728. void OutputStream::writeByte (char byte)
  5729. {
  5730. write (&byte, 1);
  5731. }
  5732. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5733. {
  5734. while (--numTimesToRepeat >= 0)
  5735. writeByte (byte);
  5736. }
  5737. void OutputStream::writeShort (short value)
  5738. {
  5739. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5740. write (&v, 2);
  5741. }
  5742. void OutputStream::writeShortBigEndian (short value)
  5743. {
  5744. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5745. write (&v, 2);
  5746. }
  5747. void OutputStream::writeInt (int value)
  5748. {
  5749. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5750. write (&v, 4);
  5751. }
  5752. void OutputStream::writeIntBigEndian (int value)
  5753. {
  5754. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5755. write (&v, 4);
  5756. }
  5757. void OutputStream::writeCompressedInt (int value)
  5758. {
  5759. unsigned int un = (value < 0) ? (unsigned int) -value
  5760. : (unsigned int) value;
  5761. uint8 data[5];
  5762. int num = 0;
  5763. while (un > 0)
  5764. {
  5765. data[++num] = (uint8) un;
  5766. un >>= 8;
  5767. }
  5768. data[0] = (uint8) num;
  5769. if (value < 0)
  5770. data[0] |= 0x80;
  5771. write (data, num + 1);
  5772. }
  5773. void OutputStream::writeInt64 (int64 value)
  5774. {
  5775. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5776. write (&v, 8);
  5777. }
  5778. void OutputStream::writeInt64BigEndian (int64 value)
  5779. {
  5780. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5781. write (&v, 8);
  5782. }
  5783. void OutputStream::writeFloat (float value)
  5784. {
  5785. union { int asInt; float asFloat; } n;
  5786. n.asFloat = value;
  5787. writeInt (n.asInt);
  5788. }
  5789. void OutputStream::writeFloatBigEndian (float value)
  5790. {
  5791. union { int asInt; float asFloat; } n;
  5792. n.asFloat = value;
  5793. writeIntBigEndian (n.asInt);
  5794. }
  5795. void OutputStream::writeDouble (double value)
  5796. {
  5797. union { int64 asInt; double asDouble; } n;
  5798. n.asDouble = value;
  5799. writeInt64 (n.asInt);
  5800. }
  5801. void OutputStream::writeDoubleBigEndian (double value)
  5802. {
  5803. union { int64 asInt; double asDouble; } n;
  5804. n.asDouble = value;
  5805. writeInt64BigEndian (n.asInt);
  5806. }
  5807. void OutputStream::writeString (const String& text)
  5808. {
  5809. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5810. // if lots of large, persistent strings were to be written to streams).
  5811. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5812. HeapBlock<char> temp (numBytes);
  5813. text.copyToUTF8 (temp, numBytes);
  5814. write (temp, numBytes);
  5815. }
  5816. void OutputStream::writeText (const String& text, const bool asUTF16,
  5817. const bool writeUTF16ByteOrderMark)
  5818. {
  5819. if (asUTF16)
  5820. {
  5821. if (writeUTF16ByteOrderMark)
  5822. write ("\x0ff\x0fe", 2);
  5823. String::CharPointerType src (text.getCharPointer());
  5824. bool lastCharWasReturn = false;
  5825. for (;;)
  5826. {
  5827. const juce_wchar c = src.getAndAdvance();
  5828. if (c == 0)
  5829. break;
  5830. if (c == '\n' && ! lastCharWasReturn)
  5831. writeShort ((short) '\r');
  5832. lastCharWasReturn = (c == L'\r');
  5833. writeShort ((short) c);
  5834. }
  5835. }
  5836. else
  5837. {
  5838. const char* src = text.toUTF8();
  5839. const char* t = src;
  5840. for (;;)
  5841. {
  5842. if (*t == '\n')
  5843. {
  5844. if (t > src)
  5845. write (src, (int) (t - src));
  5846. write ("\r\n", 2);
  5847. src = t + 1;
  5848. }
  5849. else if (*t == '\r')
  5850. {
  5851. if (t[1] == '\n')
  5852. ++t;
  5853. }
  5854. else if (*t == 0)
  5855. {
  5856. if (t > src)
  5857. write (src, (int) (t - src));
  5858. break;
  5859. }
  5860. ++t;
  5861. }
  5862. }
  5863. }
  5864. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5865. {
  5866. if (numBytesToWrite < 0)
  5867. numBytesToWrite = std::numeric_limits<int64>::max();
  5868. int numWritten = 0;
  5869. while (numBytesToWrite > 0 && ! source.isExhausted())
  5870. {
  5871. char buffer [8192];
  5872. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5873. if (num <= 0)
  5874. break;
  5875. write (buffer, num);
  5876. numBytesToWrite -= num;
  5877. numWritten += num;
  5878. }
  5879. return numWritten;
  5880. }
  5881. void OutputStream::setNewLineString (const String& newLineString_)
  5882. {
  5883. newLineString = newLineString_;
  5884. }
  5885. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5886. {
  5887. return stream << String (number);
  5888. }
  5889. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5890. {
  5891. return stream << String (number);
  5892. }
  5893. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5894. {
  5895. stream.writeByte (character);
  5896. return stream;
  5897. }
  5898. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5899. {
  5900. stream.write (text, (int) strlen (text));
  5901. return stream;
  5902. }
  5903. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5904. {
  5905. stream.write (data.getData(), (int) data.getSize());
  5906. return stream;
  5907. }
  5908. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5909. {
  5910. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5911. if (in != 0)
  5912. stream.writeFromInputStream (*in, -1);
  5913. return stream;
  5914. }
  5915. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5916. {
  5917. return stream << stream.getNewLineString();
  5918. }
  5919. END_JUCE_NAMESPACE
  5920. /*** End of inlined file: juce_OutputStream.cpp ***/
  5921. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5922. BEGIN_JUCE_NAMESPACE
  5923. DirectoryIterator::DirectoryIterator (const File& directory,
  5924. bool isRecursive_,
  5925. const String& wildCard_,
  5926. const int whatToLookFor_)
  5927. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5928. wildCard (wildCard_),
  5929. path (File::addTrailingSeparator (directory.getFullPathName())),
  5930. index (-1),
  5931. totalNumFiles (-1),
  5932. whatToLookFor (whatToLookFor_),
  5933. isRecursive (isRecursive_),
  5934. hasBeenAdvanced (false)
  5935. {
  5936. // you have to specify the type of files you're looking for!
  5937. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5938. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5939. }
  5940. DirectoryIterator::~DirectoryIterator()
  5941. {
  5942. }
  5943. bool DirectoryIterator::next()
  5944. {
  5945. return next (0, 0, 0, 0, 0, 0);
  5946. }
  5947. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5948. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5949. {
  5950. hasBeenAdvanced = true;
  5951. if (subIterator != 0)
  5952. {
  5953. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5954. return true;
  5955. subIterator = 0;
  5956. }
  5957. String filename;
  5958. bool isDirectory, isHidden;
  5959. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5960. {
  5961. ++index;
  5962. if (! filename.containsOnly ("."))
  5963. {
  5964. const File fileFound (path + filename, 0);
  5965. bool matches = false;
  5966. if (isDirectory)
  5967. {
  5968. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5969. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5970. matches = (whatToLookFor & File::findDirectories) != 0;
  5971. }
  5972. else
  5973. {
  5974. matches = (whatToLookFor & File::findFiles) != 0;
  5975. }
  5976. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5977. if (matches && isRecursive)
  5978. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5979. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5980. matches = ! isHidden;
  5981. if (matches)
  5982. {
  5983. currentFile = fileFound;
  5984. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5985. if (isDirResult != 0) *isDirResult = isDirectory;
  5986. return true;
  5987. }
  5988. else if (subIterator != 0)
  5989. {
  5990. return next();
  5991. }
  5992. }
  5993. }
  5994. return false;
  5995. }
  5996. const File DirectoryIterator::getFile() const
  5997. {
  5998. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5999. return subIterator->getFile();
  6000. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  6001. jassert (hasBeenAdvanced);
  6002. return currentFile;
  6003. }
  6004. float DirectoryIterator::getEstimatedProgress() const
  6005. {
  6006. if (totalNumFiles < 0)
  6007. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  6008. if (totalNumFiles <= 0)
  6009. return 0.0f;
  6010. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  6011. : (float) index;
  6012. return detailedIndex / totalNumFiles;
  6013. }
  6014. END_JUCE_NAMESPACE
  6015. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  6016. /*** Start of inlined file: juce_File.cpp ***/
  6017. #if ! JUCE_WINDOWS
  6018. #include <pwd.h>
  6019. #endif
  6020. BEGIN_JUCE_NAMESPACE
  6021. File::File (const String& fullPathName)
  6022. : fullPath (parseAbsolutePath (fullPathName))
  6023. {
  6024. }
  6025. File::File (const String& path, int)
  6026. : fullPath (path)
  6027. {
  6028. }
  6029. const File File::createFileWithoutCheckingPath (const String& path)
  6030. {
  6031. return File (path, 0);
  6032. }
  6033. File::File (const File& other)
  6034. : fullPath (other.fullPath)
  6035. {
  6036. }
  6037. File& File::operator= (const String& newPath)
  6038. {
  6039. fullPath = parseAbsolutePath (newPath);
  6040. return *this;
  6041. }
  6042. File& File::operator= (const File& other)
  6043. {
  6044. fullPath = other.fullPath;
  6045. return *this;
  6046. }
  6047. const File File::nonexistent;
  6048. const String File::parseAbsolutePath (const String& p)
  6049. {
  6050. if (p.isEmpty())
  6051. return String::empty;
  6052. #if JUCE_WINDOWS
  6053. // Windows..
  6054. String path (p.replaceCharacter ('/', '\\'));
  6055. if (path.startsWithChar (File::separator))
  6056. {
  6057. if (path[1] != File::separator)
  6058. {
  6059. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6060. If you're trying to parse a string that may be either a relative path or an absolute path,
  6061. you MUST provide a context against which the partial path can be evaluated - you can do
  6062. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6063. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6064. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6065. */
  6066. jassertfalse;
  6067. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  6068. }
  6069. }
  6070. else if (! path.containsChar (':'))
  6071. {
  6072. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6073. If you're trying to parse a string that may be either a relative path or an absolute path,
  6074. you MUST provide a context against which the partial path can be evaluated - you can do
  6075. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6076. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6077. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6078. */
  6079. jassertfalse;
  6080. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6081. }
  6082. #else
  6083. // Mac or Linux..
  6084. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  6085. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  6086. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  6087. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  6088. String path (p);
  6089. if (path.startsWithChar ('~'))
  6090. {
  6091. if (path[1] == File::separator || path[1] == 0)
  6092. {
  6093. // expand a name of the form "~/abc"
  6094. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6095. + path.substring (1);
  6096. }
  6097. else
  6098. {
  6099. // expand a name of type "~dave/abc"
  6100. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6101. struct passwd* const pw = getpwnam (userName.toUTF8());
  6102. if (pw != 0)
  6103. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6104. }
  6105. }
  6106. else if (! path.startsWithChar (File::separator))
  6107. {
  6108. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6109. If you're trying to parse a string that may be either a relative path or an absolute path,
  6110. you MUST provide a context against which the partial path can be evaluated - you can do
  6111. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6112. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6113. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6114. */
  6115. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6116. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6117. }
  6118. #endif
  6119. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6120. path = path.dropLastCharacters (1);
  6121. return path;
  6122. }
  6123. const String File::addTrailingSeparator (const String& path)
  6124. {
  6125. return path.endsWithChar (File::separator) ? path
  6126. : path + File::separator;
  6127. }
  6128. #if JUCE_LINUX
  6129. #define NAMES_ARE_CASE_SENSITIVE 1
  6130. #endif
  6131. bool File::areFileNamesCaseSensitive()
  6132. {
  6133. #if NAMES_ARE_CASE_SENSITIVE
  6134. return true;
  6135. #else
  6136. return false;
  6137. #endif
  6138. }
  6139. bool File::operator== (const File& other) const
  6140. {
  6141. #if NAMES_ARE_CASE_SENSITIVE
  6142. return fullPath == other.fullPath;
  6143. #else
  6144. return fullPath.equalsIgnoreCase (other.fullPath);
  6145. #endif
  6146. }
  6147. bool File::operator!= (const File& other) const
  6148. {
  6149. return ! operator== (other);
  6150. }
  6151. bool File::operator< (const File& other) const
  6152. {
  6153. #if NAMES_ARE_CASE_SENSITIVE
  6154. return fullPath < other.fullPath;
  6155. #else
  6156. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6157. #endif
  6158. }
  6159. bool File::operator> (const File& other) const
  6160. {
  6161. #if NAMES_ARE_CASE_SENSITIVE
  6162. return fullPath > other.fullPath;
  6163. #else
  6164. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6165. #endif
  6166. }
  6167. bool File::setReadOnly (const bool shouldBeReadOnly,
  6168. const bool applyRecursively) const
  6169. {
  6170. bool worked = true;
  6171. if (applyRecursively && isDirectory())
  6172. {
  6173. Array <File> subFiles;
  6174. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6175. for (int i = subFiles.size(); --i >= 0;)
  6176. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6177. }
  6178. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6179. }
  6180. bool File::deleteRecursively() const
  6181. {
  6182. bool worked = true;
  6183. if (isDirectory())
  6184. {
  6185. Array<File> subFiles;
  6186. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6187. for (int i = subFiles.size(); --i >= 0;)
  6188. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6189. }
  6190. return deleteFile() && worked;
  6191. }
  6192. bool File::moveFileTo (const File& newFile) const
  6193. {
  6194. if (newFile.fullPath == fullPath)
  6195. return true;
  6196. #if ! NAMES_ARE_CASE_SENSITIVE
  6197. if (*this != newFile)
  6198. #endif
  6199. if (! newFile.deleteFile())
  6200. return false;
  6201. return moveInternal (newFile);
  6202. }
  6203. bool File::copyFileTo (const File& newFile) const
  6204. {
  6205. return (*this == newFile)
  6206. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6207. }
  6208. bool File::copyDirectoryTo (const File& newDirectory) const
  6209. {
  6210. if (isDirectory() && newDirectory.createDirectory())
  6211. {
  6212. Array<File> subFiles;
  6213. findChildFiles (subFiles, File::findFiles, false);
  6214. int i;
  6215. for (i = 0; i < subFiles.size(); ++i)
  6216. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6217. return false;
  6218. subFiles.clear();
  6219. findChildFiles (subFiles, File::findDirectories, false);
  6220. for (i = 0; i < subFiles.size(); ++i)
  6221. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6222. return false;
  6223. return true;
  6224. }
  6225. return false;
  6226. }
  6227. const String File::getPathUpToLastSlash() const
  6228. {
  6229. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6230. if (lastSlash > 0)
  6231. return fullPath.substring (0, lastSlash);
  6232. else if (lastSlash == 0)
  6233. return separatorString;
  6234. else
  6235. return fullPath;
  6236. }
  6237. const File File::getParentDirectory() const
  6238. {
  6239. return File (getPathUpToLastSlash(), (int) 0);
  6240. }
  6241. const String File::getFileName() const
  6242. {
  6243. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6244. }
  6245. int File::hashCode() const
  6246. {
  6247. return fullPath.hashCode();
  6248. }
  6249. int64 File::hashCode64() const
  6250. {
  6251. return fullPath.hashCode64();
  6252. }
  6253. const String File::getFileNameWithoutExtension() const
  6254. {
  6255. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6256. const int lastDot = fullPath.lastIndexOfChar ('.');
  6257. if (lastDot > lastSlash)
  6258. return fullPath.substring (lastSlash, lastDot);
  6259. else
  6260. return fullPath.substring (lastSlash);
  6261. }
  6262. bool File::isAChildOf (const File& potentialParent) const
  6263. {
  6264. if (potentialParent == File::nonexistent)
  6265. return false;
  6266. const String ourPath (getPathUpToLastSlash());
  6267. #if NAMES_ARE_CASE_SENSITIVE
  6268. if (potentialParent.fullPath == ourPath)
  6269. #else
  6270. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6271. #endif
  6272. {
  6273. return true;
  6274. }
  6275. else if (potentialParent.fullPath.length() >= ourPath.length())
  6276. {
  6277. return false;
  6278. }
  6279. else
  6280. {
  6281. return getParentDirectory().isAChildOf (potentialParent);
  6282. }
  6283. }
  6284. bool File::isAbsolutePath (const String& path)
  6285. {
  6286. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6287. #if JUCE_WINDOWS
  6288. || (path.isNotEmpty() && path[1] == ':');
  6289. #else
  6290. || path.startsWithChar ('~');
  6291. #endif
  6292. }
  6293. const File File::getChildFile (String relativePath) const
  6294. {
  6295. if (isAbsolutePath (relativePath))
  6296. {
  6297. // the path is really absolute..
  6298. return File (relativePath);
  6299. }
  6300. else
  6301. {
  6302. // it's relative, so remove any ../ or ./ bits at the start.
  6303. String path (fullPath);
  6304. if (relativePath[0] == '.')
  6305. {
  6306. #if JUCE_WINDOWS
  6307. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6308. #else
  6309. relativePath = relativePath.trimStart();
  6310. #endif
  6311. while (relativePath[0] == '.')
  6312. {
  6313. if (relativePath[1] == '.')
  6314. {
  6315. if (relativePath [2] == 0 || relativePath[2] == separator)
  6316. {
  6317. const int lastSlash = path.lastIndexOfChar (separator);
  6318. if (lastSlash >= 0)
  6319. path = path.substring (0, lastSlash);
  6320. relativePath = relativePath.substring (3);
  6321. }
  6322. else
  6323. {
  6324. break;
  6325. }
  6326. }
  6327. else if (relativePath[1] == separator)
  6328. {
  6329. relativePath = relativePath.substring (2);
  6330. }
  6331. else
  6332. {
  6333. break;
  6334. }
  6335. }
  6336. }
  6337. return File (addTrailingSeparator (path) + relativePath);
  6338. }
  6339. }
  6340. const File File::getSiblingFile (const String& fileName) const
  6341. {
  6342. return getParentDirectory().getChildFile (fileName);
  6343. }
  6344. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6345. {
  6346. if (bytes == 1)
  6347. {
  6348. return "1 byte";
  6349. }
  6350. else if (bytes < 1024)
  6351. {
  6352. return String ((int) bytes) + " bytes";
  6353. }
  6354. else if (bytes < 1024 * 1024)
  6355. {
  6356. return String (bytes / 1024.0, 1) + " KB";
  6357. }
  6358. else if (bytes < 1024 * 1024 * 1024)
  6359. {
  6360. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6361. }
  6362. else
  6363. {
  6364. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6365. }
  6366. }
  6367. bool File::create() const
  6368. {
  6369. if (exists())
  6370. return true;
  6371. {
  6372. const File parentDir (getParentDirectory());
  6373. if (parentDir == *this || ! parentDir.createDirectory())
  6374. return false;
  6375. FileOutputStream fo (*this, 8);
  6376. }
  6377. return exists();
  6378. }
  6379. bool File::createDirectory() const
  6380. {
  6381. if (! isDirectory())
  6382. {
  6383. const File parentDir (getParentDirectory());
  6384. if (parentDir == *this || ! parentDir.createDirectory())
  6385. return false;
  6386. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6387. return isDirectory();
  6388. }
  6389. return true;
  6390. }
  6391. const Time File::getCreationTime() const
  6392. {
  6393. int64 m, a, c;
  6394. getFileTimesInternal (m, a, c);
  6395. return Time (c);
  6396. }
  6397. const Time File::getLastModificationTime() const
  6398. {
  6399. int64 m, a, c;
  6400. getFileTimesInternal (m, a, c);
  6401. return Time (m);
  6402. }
  6403. const Time File::getLastAccessTime() const
  6404. {
  6405. int64 m, a, c;
  6406. getFileTimesInternal (m, a, c);
  6407. return Time (a);
  6408. }
  6409. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6410. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6411. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6412. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6413. {
  6414. if (! existsAsFile())
  6415. return false;
  6416. FileInputStream in (*this);
  6417. return getSize() == in.readIntoMemoryBlock (destBlock);
  6418. }
  6419. const String File::loadFileAsString() const
  6420. {
  6421. if (! existsAsFile())
  6422. return String::empty;
  6423. FileInputStream in (*this);
  6424. return in.readEntireStreamAsString();
  6425. }
  6426. int File::findChildFiles (Array<File>& results,
  6427. const int whatToLookFor,
  6428. const bool searchRecursively,
  6429. const String& wildCardPattern) const
  6430. {
  6431. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6432. int total = 0;
  6433. while (di.next())
  6434. {
  6435. results.add (di.getFile());
  6436. ++total;
  6437. }
  6438. return total;
  6439. }
  6440. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6441. {
  6442. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6443. int total = 0;
  6444. while (di.next())
  6445. ++total;
  6446. return total;
  6447. }
  6448. bool File::containsSubDirectories() const
  6449. {
  6450. if (isDirectory())
  6451. {
  6452. DirectoryIterator di (*this, false, "*", findDirectories);
  6453. return di.next();
  6454. }
  6455. return false;
  6456. }
  6457. const File File::getNonexistentChildFile (const String& prefix_,
  6458. const String& suffix,
  6459. bool putNumbersInBrackets) const
  6460. {
  6461. File f (getChildFile (prefix_ + suffix));
  6462. if (f.exists())
  6463. {
  6464. int num = 2;
  6465. String prefix (prefix_);
  6466. // remove any bracketed numbers that may already be on the end..
  6467. if (prefix.trim().endsWithChar (')'))
  6468. {
  6469. putNumbersInBrackets = true;
  6470. const int openBracks = prefix.lastIndexOfChar ('(');
  6471. const int closeBracks = prefix.lastIndexOfChar (')');
  6472. if (openBracks > 0
  6473. && closeBracks > openBracks
  6474. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6475. {
  6476. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6477. prefix = prefix.substring (0, openBracks);
  6478. }
  6479. }
  6480. // also use brackets if it ends in a digit.
  6481. putNumbersInBrackets = putNumbersInBrackets
  6482. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6483. do
  6484. {
  6485. if (putNumbersInBrackets)
  6486. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6487. else
  6488. f = getChildFile (prefix + String (num++) + suffix);
  6489. } while (f.exists());
  6490. }
  6491. return f;
  6492. }
  6493. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6494. {
  6495. if (exists())
  6496. {
  6497. return getParentDirectory()
  6498. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6499. getFileExtension(),
  6500. putNumbersInBrackets);
  6501. }
  6502. else
  6503. {
  6504. return *this;
  6505. }
  6506. }
  6507. const String File::getFileExtension() const
  6508. {
  6509. String ext;
  6510. if (! isDirectory())
  6511. {
  6512. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6513. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6514. ext = fullPath.substring (indexOfDot);
  6515. }
  6516. return ext;
  6517. }
  6518. bool File::hasFileExtension (const String& possibleSuffix) const
  6519. {
  6520. if (possibleSuffix.isEmpty())
  6521. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6522. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6523. if (semicolon >= 0)
  6524. {
  6525. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6526. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6527. }
  6528. else
  6529. {
  6530. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6531. {
  6532. if (possibleSuffix.startsWithChar ('.'))
  6533. return true;
  6534. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6535. if (dotPos >= 0)
  6536. return fullPath [dotPos] == '.';
  6537. }
  6538. }
  6539. return false;
  6540. }
  6541. const File File::withFileExtension (const String& newExtension) const
  6542. {
  6543. if (fullPath.isEmpty())
  6544. return File::nonexistent;
  6545. String filePart (getFileName());
  6546. int i = filePart.lastIndexOfChar ('.');
  6547. if (i >= 0)
  6548. filePart = filePart.substring (0, i);
  6549. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6550. filePart << '.';
  6551. return getSiblingFile (filePart + newExtension);
  6552. }
  6553. bool File::startAsProcess (const String& parameters) const
  6554. {
  6555. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6556. }
  6557. FileInputStream* File::createInputStream() const
  6558. {
  6559. if (existsAsFile())
  6560. return new FileInputStream (*this);
  6561. return 0;
  6562. }
  6563. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6564. {
  6565. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6566. if (out->failedToOpen())
  6567. return 0;
  6568. return out.release();
  6569. }
  6570. bool File::appendData (const void* const dataToAppend,
  6571. const int numberOfBytes) const
  6572. {
  6573. if (numberOfBytes > 0)
  6574. {
  6575. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6576. if (out == 0)
  6577. return false;
  6578. out->write (dataToAppend, numberOfBytes);
  6579. }
  6580. return true;
  6581. }
  6582. bool File::replaceWithData (const void* const dataToWrite,
  6583. const int numberOfBytes) const
  6584. {
  6585. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6586. if (numberOfBytes <= 0)
  6587. return deleteFile();
  6588. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6589. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6590. return tempFile.overwriteTargetFileWithTemporary();
  6591. }
  6592. bool File::appendText (const String& text,
  6593. const bool asUnicode,
  6594. const bool writeUnicodeHeaderBytes) const
  6595. {
  6596. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6597. if (out != 0)
  6598. {
  6599. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6600. return true;
  6601. }
  6602. return false;
  6603. }
  6604. bool File::replaceWithText (const String& textToWrite,
  6605. const bool asUnicode,
  6606. const bool writeUnicodeHeaderBytes) const
  6607. {
  6608. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6609. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6610. return tempFile.overwriteTargetFileWithTemporary();
  6611. }
  6612. bool File::hasIdenticalContentTo (const File& other) const
  6613. {
  6614. if (other == *this)
  6615. return true;
  6616. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6617. {
  6618. FileInputStream in1 (*this), in2 (other);
  6619. const int bufferSize = 4096;
  6620. HeapBlock <char> buffer1, buffer2;
  6621. buffer1.malloc (bufferSize);
  6622. buffer2.malloc (bufferSize);
  6623. for (;;)
  6624. {
  6625. const int num1 = in1.read (buffer1, bufferSize);
  6626. const int num2 = in2.read (buffer2, bufferSize);
  6627. if (num1 != num2)
  6628. break;
  6629. if (num1 <= 0)
  6630. return true;
  6631. if (memcmp (buffer1, buffer2, num1) != 0)
  6632. break;
  6633. }
  6634. }
  6635. return false;
  6636. }
  6637. const String File::createLegalPathName (const String& original)
  6638. {
  6639. String s (original);
  6640. String start;
  6641. if (s[1] == ':')
  6642. {
  6643. start = s.substring (0, 2);
  6644. s = s.substring (2);
  6645. }
  6646. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6647. .substring (0, 1024);
  6648. }
  6649. const String File::createLegalFileName (const String& original)
  6650. {
  6651. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6652. const int maxLength = 128; // only the length of the filename, not the whole path
  6653. const int len = s.length();
  6654. if (len > maxLength)
  6655. {
  6656. const int lastDot = s.lastIndexOfChar ('.');
  6657. if (lastDot > jmax (0, len - 12))
  6658. {
  6659. s = s.substring (0, maxLength - (len - lastDot))
  6660. + s.substring (lastDot);
  6661. }
  6662. else
  6663. {
  6664. s = s.substring (0, maxLength);
  6665. }
  6666. }
  6667. return s;
  6668. }
  6669. const String File::getRelativePathFrom (const File& dir) const
  6670. {
  6671. String thisPath (fullPath);
  6672. while (thisPath.endsWithChar (separator))
  6673. thisPath = thisPath.dropLastCharacters (1);
  6674. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6675. : dir.fullPath));
  6676. const int len = jmin (thisPath.length(), dirPath.length());
  6677. int commonBitLength = 0;
  6678. for (int i = 0; i < len; ++i)
  6679. {
  6680. #if NAMES_ARE_CASE_SENSITIVE
  6681. if (thisPath[i] != dirPath[i])
  6682. #else
  6683. if (CharacterFunctions::toLowerCase (thisPath[i])
  6684. != CharacterFunctions::toLowerCase (dirPath[i]))
  6685. #endif
  6686. {
  6687. break;
  6688. }
  6689. ++commonBitLength;
  6690. }
  6691. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6692. --commonBitLength;
  6693. // if the only common bit is the root, then just return the full path..
  6694. if (commonBitLength <= 0
  6695. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6696. return fullPath;
  6697. thisPath = thisPath.substring (commonBitLength);
  6698. dirPath = dirPath.substring (commonBitLength);
  6699. while (dirPath.isNotEmpty())
  6700. {
  6701. #if JUCE_WINDOWS
  6702. thisPath = "..\\" + thisPath;
  6703. #else
  6704. thisPath = "../" + thisPath;
  6705. #endif
  6706. const int sep = dirPath.indexOfChar (separator);
  6707. if (sep >= 0)
  6708. dirPath = dirPath.substring (sep + 1);
  6709. else
  6710. dirPath = String::empty;
  6711. }
  6712. return thisPath;
  6713. }
  6714. const File File::createTempFile (const String& fileNameEnding)
  6715. {
  6716. const File tempFile (getSpecialLocation (tempDirectory)
  6717. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6718. .withFileExtension (fileNameEnding));
  6719. if (tempFile.exists())
  6720. return createTempFile (fileNameEnding);
  6721. else
  6722. return tempFile;
  6723. }
  6724. #if JUCE_UNIT_TESTS
  6725. class FileTests : public UnitTest
  6726. {
  6727. public:
  6728. FileTests() : UnitTest ("Files") {}
  6729. void runTest()
  6730. {
  6731. beginTest ("Reading");
  6732. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6733. const File temp (File::getSpecialLocation (File::tempDirectory));
  6734. expect (! File::nonexistent.exists());
  6735. expect (home.isDirectory());
  6736. expect (home.exists());
  6737. expect (! home.existsAsFile());
  6738. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6739. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6740. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6741. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6742. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6743. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6744. expect (home.getBytesFreeOnVolume() > 0);
  6745. expect (! home.isHidden());
  6746. expect (home.isOnHardDisk());
  6747. expect (! home.isOnCDRomDrive());
  6748. expect (File::getCurrentWorkingDirectory().exists());
  6749. expect (home.setAsCurrentWorkingDirectory());
  6750. expect (File::getCurrentWorkingDirectory() == home);
  6751. {
  6752. Array<File> roots;
  6753. File::findFileSystemRoots (roots);
  6754. expect (roots.size() > 0);
  6755. int numRootsExisting = 0;
  6756. for (int i = 0; i < roots.size(); ++i)
  6757. if (roots[i].exists())
  6758. ++numRootsExisting;
  6759. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6760. expect (numRootsExisting > 0);
  6761. }
  6762. beginTest ("Writing");
  6763. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6764. expect (demoFolder.deleteRecursively());
  6765. expect (demoFolder.createDirectory());
  6766. expect (demoFolder.isDirectory());
  6767. expect (demoFolder.getParentDirectory() == temp);
  6768. expect (temp.isDirectory());
  6769. {
  6770. Array<File> files;
  6771. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6772. expect (files.contains (demoFolder));
  6773. }
  6774. {
  6775. Array<File> files;
  6776. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6777. expect (files.contains (demoFolder));
  6778. }
  6779. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6780. expect (tempFile.getFileExtension() == ".txt");
  6781. expect (tempFile.hasFileExtension (".txt"));
  6782. expect (tempFile.hasFileExtension ("txt"));
  6783. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6784. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6785. expect (tempFile.hasWriteAccess());
  6786. {
  6787. FileOutputStream fo (tempFile);
  6788. fo.write ("0123456789", 10);
  6789. }
  6790. expect (tempFile.exists());
  6791. expect (tempFile.getSize() == 10);
  6792. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6793. expect (tempFile.loadFileAsString() == "0123456789");
  6794. expect (! demoFolder.containsSubDirectories());
  6795. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  6796. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  6797. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6798. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6799. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6800. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6801. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6802. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6803. expect (demoFolder.containsSubDirectories());
  6804. expect (tempFile.hasWriteAccess());
  6805. tempFile.setReadOnly (true);
  6806. expect (! tempFile.hasWriteAccess());
  6807. tempFile.setReadOnly (false);
  6808. expect (tempFile.hasWriteAccess());
  6809. Time t (Time::getCurrentTime());
  6810. tempFile.setLastModificationTime (t);
  6811. Time t2 = tempFile.getLastModificationTime();
  6812. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6813. {
  6814. MemoryBlock mb;
  6815. tempFile.loadFileAsData (mb);
  6816. expect (mb.getSize() == 10);
  6817. expect (mb[0] == '0');
  6818. }
  6819. expect (tempFile.appendData ("abcdefghij", 10));
  6820. expect (tempFile.getSize() == 20);
  6821. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6822. expect (tempFile.getSize() == 10);
  6823. File tempFile2 (tempFile.getNonexistentSibling (false));
  6824. expect (tempFile.copyFileTo (tempFile2));
  6825. expect (tempFile2.exists());
  6826. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6827. expect (tempFile.deleteFile());
  6828. expect (! tempFile.exists());
  6829. expect (tempFile2.moveFileTo (tempFile));
  6830. expect (tempFile.exists());
  6831. expect (! tempFile2.exists());
  6832. expect (demoFolder.deleteRecursively());
  6833. expect (! demoFolder.exists());
  6834. }
  6835. };
  6836. static FileTests fileUnitTests;
  6837. #endif
  6838. END_JUCE_NAMESPACE
  6839. /*** End of inlined file: juce_File.cpp ***/
  6840. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6841. BEGIN_JUCE_NAMESPACE
  6842. int64 juce_fileSetPosition (void* handle, int64 pos);
  6843. FileInputStream::FileInputStream (const File& f)
  6844. : file (f),
  6845. fileHandle (0),
  6846. currentPosition (0),
  6847. totalSize (0),
  6848. needToSeek (true)
  6849. {
  6850. openHandle();
  6851. }
  6852. FileInputStream::~FileInputStream()
  6853. {
  6854. closeHandle();
  6855. }
  6856. int64 FileInputStream::getTotalLength()
  6857. {
  6858. return totalSize;
  6859. }
  6860. int FileInputStream::read (void* buffer, int bytesToRead)
  6861. {
  6862. if (needToSeek)
  6863. {
  6864. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6865. return 0;
  6866. needToSeek = false;
  6867. }
  6868. const size_t num = readInternal (buffer, bytesToRead);
  6869. currentPosition += num;
  6870. return (int) num;
  6871. }
  6872. bool FileInputStream::isExhausted()
  6873. {
  6874. return currentPosition >= totalSize;
  6875. }
  6876. int64 FileInputStream::getPosition()
  6877. {
  6878. return currentPosition;
  6879. }
  6880. bool FileInputStream::setPosition (int64 pos)
  6881. {
  6882. pos = jlimit ((int64) 0, totalSize, pos);
  6883. needToSeek |= (currentPosition != pos);
  6884. currentPosition = pos;
  6885. return true;
  6886. }
  6887. END_JUCE_NAMESPACE
  6888. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6889. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6890. BEGIN_JUCE_NAMESPACE
  6891. int64 juce_fileSetPosition (void* handle, int64 pos);
  6892. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6893. : file (f),
  6894. fileHandle (0),
  6895. currentPosition (0),
  6896. bufferSize (bufferSize_),
  6897. bytesInBuffer (0),
  6898. buffer (jmax (bufferSize_, 16))
  6899. {
  6900. openHandle();
  6901. }
  6902. FileOutputStream::~FileOutputStream()
  6903. {
  6904. flush();
  6905. closeHandle();
  6906. }
  6907. int64 FileOutputStream::getPosition()
  6908. {
  6909. return currentPosition;
  6910. }
  6911. bool FileOutputStream::setPosition (int64 newPosition)
  6912. {
  6913. if (newPosition != currentPosition)
  6914. {
  6915. flush();
  6916. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6917. }
  6918. return newPosition == currentPosition;
  6919. }
  6920. void FileOutputStream::flush()
  6921. {
  6922. if (bytesInBuffer > 0)
  6923. {
  6924. writeInternal (buffer, bytesInBuffer);
  6925. bytesInBuffer = 0;
  6926. }
  6927. flushInternal();
  6928. }
  6929. bool FileOutputStream::write (const void* const src, const int numBytes)
  6930. {
  6931. if (bytesInBuffer + numBytes < bufferSize)
  6932. {
  6933. memcpy (buffer + bytesInBuffer, src, numBytes);
  6934. bytesInBuffer += numBytes;
  6935. currentPosition += numBytes;
  6936. }
  6937. else
  6938. {
  6939. if (bytesInBuffer > 0)
  6940. {
  6941. // flush the reservoir
  6942. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6943. bytesInBuffer = 0;
  6944. if (! wroteOk)
  6945. return false;
  6946. }
  6947. if (numBytes < bufferSize)
  6948. {
  6949. memcpy (buffer + bytesInBuffer, src, numBytes);
  6950. bytesInBuffer += numBytes;
  6951. currentPosition += numBytes;
  6952. }
  6953. else
  6954. {
  6955. const int bytesWritten = writeInternal (src, numBytes);
  6956. if (bytesWritten < 0)
  6957. return false;
  6958. currentPosition += bytesWritten;
  6959. return bytesWritten == numBytes;
  6960. }
  6961. }
  6962. return true;
  6963. }
  6964. END_JUCE_NAMESPACE
  6965. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6966. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6967. BEGIN_JUCE_NAMESPACE
  6968. FileSearchPath::FileSearchPath()
  6969. {
  6970. }
  6971. FileSearchPath::FileSearchPath (const String& path)
  6972. {
  6973. init (path);
  6974. }
  6975. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6976. : directories (other.directories)
  6977. {
  6978. }
  6979. FileSearchPath::~FileSearchPath()
  6980. {
  6981. }
  6982. FileSearchPath& FileSearchPath::operator= (const String& path)
  6983. {
  6984. init (path);
  6985. return *this;
  6986. }
  6987. void FileSearchPath::init (const String& path)
  6988. {
  6989. directories.clear();
  6990. directories.addTokens (path, ";", "\"");
  6991. directories.trim();
  6992. directories.removeEmptyStrings();
  6993. for (int i = directories.size(); --i >= 0;)
  6994. directories.set (i, directories[i].unquoted());
  6995. }
  6996. int FileSearchPath::getNumPaths() const
  6997. {
  6998. return directories.size();
  6999. }
  7000. const File FileSearchPath::operator[] (const int index) const
  7001. {
  7002. return File (directories [index]);
  7003. }
  7004. const String FileSearchPath::toString() const
  7005. {
  7006. StringArray directories2 (directories);
  7007. for (int i = directories2.size(); --i >= 0;)
  7008. if (directories2[i].containsChar (';'))
  7009. directories2.set (i, directories2[i].quoted());
  7010. return directories2.joinIntoString (";");
  7011. }
  7012. void FileSearchPath::add (const File& dir, const int insertIndex)
  7013. {
  7014. directories.insert (insertIndex, dir.getFullPathName());
  7015. }
  7016. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  7017. {
  7018. for (int i = 0; i < directories.size(); ++i)
  7019. if (File (directories[i]) == dir)
  7020. return;
  7021. add (dir);
  7022. }
  7023. void FileSearchPath::remove (const int index)
  7024. {
  7025. directories.remove (index);
  7026. }
  7027. void FileSearchPath::addPath (const FileSearchPath& other)
  7028. {
  7029. for (int i = 0; i < other.getNumPaths(); ++i)
  7030. addIfNotAlreadyThere (other[i]);
  7031. }
  7032. void FileSearchPath::removeRedundantPaths()
  7033. {
  7034. for (int i = directories.size(); --i >= 0;)
  7035. {
  7036. const File d1 (directories[i]);
  7037. for (int j = directories.size(); --j >= 0;)
  7038. {
  7039. const File d2 (directories[j]);
  7040. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  7041. {
  7042. directories.remove (i);
  7043. break;
  7044. }
  7045. }
  7046. }
  7047. }
  7048. void FileSearchPath::removeNonExistentPaths()
  7049. {
  7050. for (int i = directories.size(); --i >= 0;)
  7051. if (! File (directories[i]).isDirectory())
  7052. directories.remove (i);
  7053. }
  7054. int FileSearchPath::findChildFiles (Array<File>& results,
  7055. const int whatToLookFor,
  7056. const bool searchRecursively,
  7057. const String& wildCardPattern) const
  7058. {
  7059. int total = 0;
  7060. for (int i = 0; i < directories.size(); ++i)
  7061. total += operator[] (i).findChildFiles (results,
  7062. whatToLookFor,
  7063. searchRecursively,
  7064. wildCardPattern);
  7065. return total;
  7066. }
  7067. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  7068. const bool checkRecursively) const
  7069. {
  7070. for (int i = directories.size(); --i >= 0;)
  7071. {
  7072. const File d (directories[i]);
  7073. if (checkRecursively)
  7074. {
  7075. if (fileToCheck.isAChildOf (d))
  7076. return true;
  7077. }
  7078. else
  7079. {
  7080. if (fileToCheck.getParentDirectory() == d)
  7081. return true;
  7082. }
  7083. }
  7084. return false;
  7085. }
  7086. END_JUCE_NAMESPACE
  7087. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7088. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7089. BEGIN_JUCE_NAMESPACE
  7090. NamedPipe::NamedPipe()
  7091. : internal (0)
  7092. {
  7093. }
  7094. NamedPipe::~NamedPipe()
  7095. {
  7096. close();
  7097. }
  7098. bool NamedPipe::openExisting (const String& pipeName)
  7099. {
  7100. currentPipeName = pipeName;
  7101. return openInternal (pipeName, false);
  7102. }
  7103. bool NamedPipe::createNewPipe (const String& pipeName)
  7104. {
  7105. currentPipeName = pipeName;
  7106. return openInternal (pipeName, true);
  7107. }
  7108. bool NamedPipe::isOpen() const
  7109. {
  7110. return internal != 0;
  7111. }
  7112. const String NamedPipe::getName() const
  7113. {
  7114. return currentPipeName;
  7115. }
  7116. // other methods for this class are implemented in the platform-specific files
  7117. END_JUCE_NAMESPACE
  7118. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7119. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7120. BEGIN_JUCE_NAMESPACE
  7121. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7122. {
  7123. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7124. "temp_" + String (Random::getSystemRandom().nextInt()),
  7125. suffix,
  7126. optionFlags);
  7127. }
  7128. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7129. : targetFile (targetFile_)
  7130. {
  7131. // If you use this constructor, you need to give it a valid target file!
  7132. jassert (targetFile != File::nonexistent);
  7133. createTempFile (targetFile.getParentDirectory(),
  7134. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7135. targetFile.getFileExtension(),
  7136. optionFlags);
  7137. }
  7138. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7139. const String& suffix, const int optionFlags)
  7140. {
  7141. if ((optionFlags & useHiddenFile) != 0)
  7142. name = "." + name;
  7143. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7144. }
  7145. TemporaryFile::~TemporaryFile()
  7146. {
  7147. if (! deleteTemporaryFile())
  7148. {
  7149. /* Failed to delete our temporary file! The most likely reason for this would be
  7150. that you've not closed an output stream that was being used to write to file.
  7151. If you find that something beyond your control is changing permissions on
  7152. your temporary files and preventing them from being deleted, you may want to
  7153. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7154. handle them appropriately.
  7155. */
  7156. jassertfalse;
  7157. }
  7158. }
  7159. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7160. {
  7161. // This method only works if you created this object with the constructor
  7162. // that takes a target file!
  7163. jassert (targetFile != File::nonexistent);
  7164. if (temporaryFile.exists())
  7165. {
  7166. // Have a few attempts at overwriting the file before giving up..
  7167. for (int i = 5; --i >= 0;)
  7168. {
  7169. if (temporaryFile.moveFileTo (targetFile))
  7170. return true;
  7171. Thread::sleep (100);
  7172. }
  7173. }
  7174. else
  7175. {
  7176. // There's no temporary file to use. If your write failed, you should
  7177. // probably check, and not bother calling this method.
  7178. jassertfalse;
  7179. }
  7180. return false;
  7181. }
  7182. bool TemporaryFile::deleteTemporaryFile() const
  7183. {
  7184. // Have a few attempts at deleting the file before giving up..
  7185. for (int i = 5; --i >= 0;)
  7186. {
  7187. if (temporaryFile.deleteFile())
  7188. return true;
  7189. Thread::sleep (50);
  7190. }
  7191. return false;
  7192. }
  7193. END_JUCE_NAMESPACE
  7194. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7195. /*** Start of inlined file: juce_Socket.cpp ***/
  7196. #if JUCE_WINDOWS
  7197. #include <winsock2.h>
  7198. #if JUCE_MSVC
  7199. #pragma warning (push)
  7200. #pragma warning (disable : 4127 4389 4018)
  7201. #endif
  7202. #else
  7203. #if JUCE_LINUX || JUCE_ANDROID
  7204. #include <sys/types.h>
  7205. #include <sys/socket.h>
  7206. #include <sys/errno.h>
  7207. #include <unistd.h>
  7208. #include <netinet/in.h>
  7209. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7210. #include <CoreServices/CoreServices.h>
  7211. #endif
  7212. #include <fcntl.h>
  7213. #include <netdb.h>
  7214. #include <arpa/inet.h>
  7215. #include <netinet/tcp.h>
  7216. #endif
  7217. BEGIN_JUCE_NAMESPACE
  7218. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7219. typedef socklen_t juce_socklen_t;
  7220. #else
  7221. typedef int juce_socklen_t;
  7222. #endif
  7223. #if JUCE_WINDOWS
  7224. namespace SocketHelpers
  7225. {
  7226. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7227. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7228. void initWin32Sockets()
  7229. {
  7230. static CriticalSection lock;
  7231. const ScopedLock sl (lock);
  7232. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7233. {
  7234. WSADATA wsaData;
  7235. const WORD wVersionRequested = MAKEWORD (1, 1);
  7236. WSAStartup (wVersionRequested, &wsaData);
  7237. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7238. }
  7239. }
  7240. }
  7241. void juce_shutdownWin32Sockets()
  7242. {
  7243. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7244. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7245. }
  7246. #endif
  7247. namespace SocketHelpers
  7248. {
  7249. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7250. {
  7251. const int sndBufSize = 65536;
  7252. const int rcvBufSize = 65536;
  7253. const int one = 1;
  7254. return handle > 0
  7255. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7256. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7257. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7258. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7259. }
  7260. bool bindSocketToPort (const int handle, const int port) throw()
  7261. {
  7262. if (handle <= 0 || port <= 0)
  7263. return false;
  7264. struct sockaddr_in servTmpAddr;
  7265. zerostruct (servTmpAddr);
  7266. servTmpAddr.sin_family = PF_INET;
  7267. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7268. servTmpAddr.sin_port = htons ((uint16) port);
  7269. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7270. }
  7271. int readSocket (const int handle,
  7272. void* const destBuffer, const int maxBytesToRead,
  7273. bool volatile& connected,
  7274. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7275. {
  7276. int bytesRead = 0;
  7277. while (bytesRead < maxBytesToRead)
  7278. {
  7279. int bytesThisTime;
  7280. #if JUCE_WINDOWS
  7281. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7282. #else
  7283. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7284. && errno == EINTR
  7285. && connected)
  7286. {
  7287. }
  7288. #endif
  7289. if (bytesThisTime <= 0 || ! connected)
  7290. {
  7291. if (bytesRead == 0)
  7292. bytesRead = -1;
  7293. break;
  7294. }
  7295. bytesRead += bytesThisTime;
  7296. if (! blockUntilSpecifiedAmountHasArrived)
  7297. break;
  7298. }
  7299. return bytesRead;
  7300. }
  7301. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7302. {
  7303. struct timeval timeout;
  7304. struct timeval* timeoutp;
  7305. if (timeoutMsecs >= 0)
  7306. {
  7307. timeout.tv_sec = timeoutMsecs / 1000;
  7308. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7309. timeoutp = &timeout;
  7310. }
  7311. else
  7312. {
  7313. timeoutp = 0;
  7314. }
  7315. fd_set rset, wset;
  7316. FD_ZERO (&rset);
  7317. FD_SET (handle, &rset);
  7318. FD_ZERO (&wset);
  7319. FD_SET (handle, &wset);
  7320. fd_set* const prset = forReading ? &rset : 0;
  7321. fd_set* const pwset = forReading ? 0 : &wset;
  7322. #if JUCE_WINDOWS
  7323. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7324. return -1;
  7325. #else
  7326. {
  7327. int result;
  7328. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7329. && errno == EINTR)
  7330. {
  7331. }
  7332. if (result < 0)
  7333. return -1;
  7334. }
  7335. #endif
  7336. {
  7337. int opt;
  7338. juce_socklen_t len = sizeof (opt);
  7339. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7340. || opt != 0)
  7341. return -1;
  7342. }
  7343. if ((forReading && FD_ISSET (handle, &rset))
  7344. || ((! forReading) && FD_ISSET (handle, &wset)))
  7345. return 1;
  7346. return 0;
  7347. }
  7348. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7349. {
  7350. #if JUCE_WINDOWS
  7351. u_long nonBlocking = shouldBlock ? 0 : 1;
  7352. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7353. return false;
  7354. #else
  7355. int socketFlags = fcntl (handle, F_GETFL, 0);
  7356. if (socketFlags == -1)
  7357. return false;
  7358. if (shouldBlock)
  7359. socketFlags &= ~O_NONBLOCK;
  7360. else
  7361. socketFlags |= O_NONBLOCK;
  7362. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7363. return false;
  7364. #endif
  7365. return true;
  7366. }
  7367. bool connectSocket (int volatile& handle,
  7368. const bool isDatagram,
  7369. void** serverAddress,
  7370. const String& hostName,
  7371. const int portNumber,
  7372. const int timeOutMillisecs) throw()
  7373. {
  7374. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7375. if (hostEnt == 0)
  7376. return false;
  7377. struct in_addr targetAddress;
  7378. memcpy (&targetAddress.s_addr,
  7379. *(hostEnt->h_addr_list),
  7380. sizeof (targetAddress.s_addr));
  7381. struct sockaddr_in servTmpAddr;
  7382. zerostruct (servTmpAddr);
  7383. servTmpAddr.sin_family = PF_INET;
  7384. servTmpAddr.sin_addr = targetAddress;
  7385. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7386. if (handle < 0)
  7387. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7388. if (handle < 0)
  7389. return false;
  7390. if (isDatagram)
  7391. {
  7392. *serverAddress = new struct sockaddr_in();
  7393. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7394. return true;
  7395. }
  7396. setSocketBlockingState (handle, false);
  7397. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7398. if (result < 0)
  7399. {
  7400. #if JUCE_WINDOWS
  7401. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7402. #else
  7403. if (errno == EINPROGRESS)
  7404. #endif
  7405. {
  7406. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7407. {
  7408. setSocketBlockingState (handle, true);
  7409. return false;
  7410. }
  7411. }
  7412. }
  7413. setSocketBlockingState (handle, true);
  7414. resetSocketOptions (handle, false, false);
  7415. return true;
  7416. }
  7417. }
  7418. StreamingSocket::StreamingSocket()
  7419. : portNumber (0),
  7420. handle (-1),
  7421. connected (false),
  7422. isListener (false)
  7423. {
  7424. #if JUCE_WINDOWS
  7425. SocketHelpers::initWin32Sockets();
  7426. #endif
  7427. }
  7428. StreamingSocket::StreamingSocket (const String& hostName_,
  7429. const int portNumber_,
  7430. const int handle_)
  7431. : hostName (hostName_),
  7432. portNumber (portNumber_),
  7433. handle (handle_),
  7434. connected (true),
  7435. isListener (false)
  7436. {
  7437. #if JUCE_WINDOWS
  7438. SocketHelpers::initWin32Sockets();
  7439. #endif
  7440. SocketHelpers::resetSocketOptions (handle_, false, false);
  7441. }
  7442. StreamingSocket::~StreamingSocket()
  7443. {
  7444. close();
  7445. }
  7446. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7447. {
  7448. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7449. : -1;
  7450. }
  7451. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7452. {
  7453. if (isListener || ! connected)
  7454. return -1;
  7455. #if JUCE_WINDOWS
  7456. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7457. #else
  7458. int result;
  7459. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7460. && errno == EINTR)
  7461. {
  7462. }
  7463. return result;
  7464. #endif
  7465. }
  7466. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7467. const int timeoutMsecs) const
  7468. {
  7469. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7470. : -1;
  7471. }
  7472. bool StreamingSocket::bindToPort (const int port)
  7473. {
  7474. return SocketHelpers::bindSocketToPort (handle, port);
  7475. }
  7476. bool StreamingSocket::connect (const String& remoteHostName,
  7477. const int remotePortNumber,
  7478. const int timeOutMillisecs)
  7479. {
  7480. if (isListener)
  7481. {
  7482. jassertfalse; // a listener socket can't connect to another one!
  7483. return false;
  7484. }
  7485. if (connected)
  7486. close();
  7487. hostName = remoteHostName;
  7488. portNumber = remotePortNumber;
  7489. isListener = false;
  7490. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7491. remotePortNumber, timeOutMillisecs);
  7492. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7493. {
  7494. close();
  7495. return false;
  7496. }
  7497. return true;
  7498. }
  7499. void StreamingSocket::close()
  7500. {
  7501. #if JUCE_WINDOWS
  7502. if (handle != SOCKET_ERROR || connected)
  7503. closesocket (handle);
  7504. connected = false;
  7505. #else
  7506. if (connected)
  7507. {
  7508. connected = false;
  7509. if (isListener)
  7510. {
  7511. // need to do this to interrupt the accept() function..
  7512. StreamingSocket temp;
  7513. temp.connect ("localhost", portNumber, 1000);
  7514. }
  7515. }
  7516. if (handle != -1)
  7517. ::close (handle);
  7518. #endif
  7519. hostName = String::empty;
  7520. portNumber = 0;
  7521. handle = -1;
  7522. isListener = false;
  7523. }
  7524. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7525. {
  7526. if (connected)
  7527. close();
  7528. hostName = "listener";
  7529. portNumber = newPortNumber;
  7530. isListener = true;
  7531. struct sockaddr_in servTmpAddr;
  7532. zerostruct (servTmpAddr);
  7533. servTmpAddr.sin_family = PF_INET;
  7534. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7535. if (localHostName.isNotEmpty())
  7536. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7537. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7538. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7539. if (handle < 0)
  7540. return false;
  7541. const int reuse = 1;
  7542. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7543. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7544. || listen (handle, SOMAXCONN) < 0)
  7545. {
  7546. close();
  7547. return false;
  7548. }
  7549. connected = true;
  7550. return true;
  7551. }
  7552. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7553. {
  7554. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7555. // prepare this socket as a listener.
  7556. if (connected && isListener)
  7557. {
  7558. struct sockaddr address;
  7559. juce_socklen_t len = sizeof (sockaddr);
  7560. const int newSocket = (int) accept (handle, &address, &len);
  7561. if (newSocket >= 0 && connected)
  7562. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7563. portNumber, newSocket);
  7564. }
  7565. return 0;
  7566. }
  7567. bool StreamingSocket::isLocal() const throw()
  7568. {
  7569. return hostName == "127.0.0.1";
  7570. }
  7571. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7572. : portNumber (0),
  7573. handle (-1),
  7574. connected (true),
  7575. allowBroadcast (allowBroadcast_),
  7576. serverAddress (0)
  7577. {
  7578. #if JUCE_WINDOWS
  7579. SocketHelpers::initWin32Sockets();
  7580. #endif
  7581. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7582. bindToPort (localPortNumber);
  7583. }
  7584. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7585. const int handle_, const int localPortNumber)
  7586. : hostName (hostName_),
  7587. portNumber (portNumber_),
  7588. handle (handle_),
  7589. connected (true),
  7590. allowBroadcast (false),
  7591. serverAddress (0)
  7592. {
  7593. #if JUCE_WINDOWS
  7594. SocketHelpers::initWin32Sockets();
  7595. #endif
  7596. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7597. bindToPort (localPortNumber);
  7598. }
  7599. DatagramSocket::~DatagramSocket()
  7600. {
  7601. close();
  7602. delete static_cast <struct sockaddr_in*> (serverAddress);
  7603. serverAddress = 0;
  7604. }
  7605. void DatagramSocket::close()
  7606. {
  7607. #if JUCE_WINDOWS
  7608. closesocket (handle);
  7609. connected = false;
  7610. #else
  7611. connected = false;
  7612. ::close (handle);
  7613. #endif
  7614. hostName = String::empty;
  7615. portNumber = 0;
  7616. handle = -1;
  7617. }
  7618. bool DatagramSocket::bindToPort (const int port)
  7619. {
  7620. return SocketHelpers::bindSocketToPort (handle, port);
  7621. }
  7622. bool DatagramSocket::connect (const String& remoteHostName,
  7623. const int remotePortNumber,
  7624. const int timeOutMillisecs)
  7625. {
  7626. if (connected)
  7627. close();
  7628. hostName = remoteHostName;
  7629. portNumber = remotePortNumber;
  7630. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7631. remoteHostName, remotePortNumber,
  7632. timeOutMillisecs);
  7633. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7634. {
  7635. close();
  7636. return false;
  7637. }
  7638. return true;
  7639. }
  7640. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7641. {
  7642. struct sockaddr address;
  7643. juce_socklen_t len = sizeof (sockaddr);
  7644. while (waitUntilReady (true, -1) == 1)
  7645. {
  7646. char buf[1];
  7647. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7648. {
  7649. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7650. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7651. -1, -1);
  7652. }
  7653. }
  7654. return 0;
  7655. }
  7656. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7657. const int timeoutMsecs) const
  7658. {
  7659. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7660. : -1;
  7661. }
  7662. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7663. {
  7664. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7665. : -1;
  7666. }
  7667. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7668. {
  7669. // You need to call connect() first to set the server address..
  7670. jassert (serverAddress != 0 && connected);
  7671. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7672. numBytesToWrite, 0,
  7673. (const struct sockaddr*) serverAddress,
  7674. sizeof (struct sockaddr_in))
  7675. : -1;
  7676. }
  7677. bool DatagramSocket::isLocal() const throw()
  7678. {
  7679. return hostName == "127.0.0.1";
  7680. }
  7681. #if JUCE_MSVC
  7682. #pragma warning (pop)
  7683. #endif
  7684. END_JUCE_NAMESPACE
  7685. /*** End of inlined file: juce_Socket.cpp ***/
  7686. /*** Start of inlined file: juce_URL.cpp ***/
  7687. BEGIN_JUCE_NAMESPACE
  7688. URL::URL()
  7689. {
  7690. }
  7691. URL::URL (const String& url_)
  7692. : url (url_)
  7693. {
  7694. int i = url.indexOfChar ('?');
  7695. if (i >= 0)
  7696. {
  7697. do
  7698. {
  7699. const int nextAmp = url.indexOfChar (i + 1, '&');
  7700. const int equalsPos = url.indexOfChar (i + 1, '=');
  7701. if (equalsPos > i + 1)
  7702. {
  7703. if (nextAmp < 0)
  7704. {
  7705. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7706. removeEscapeChars (url.substring (equalsPos + 1)));
  7707. }
  7708. else if (nextAmp > 0 && equalsPos < nextAmp)
  7709. {
  7710. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7711. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7712. }
  7713. }
  7714. i = nextAmp;
  7715. }
  7716. while (i >= 0);
  7717. url = url.upToFirstOccurrenceOf ("?", false, false);
  7718. }
  7719. }
  7720. URL::URL (const URL& other)
  7721. : url (other.url),
  7722. postData (other.postData),
  7723. parameters (other.parameters),
  7724. filesToUpload (other.filesToUpload),
  7725. mimeTypes (other.mimeTypes)
  7726. {
  7727. }
  7728. URL& URL::operator= (const URL& other)
  7729. {
  7730. url = other.url;
  7731. postData = other.postData;
  7732. parameters = other.parameters;
  7733. filesToUpload = other.filesToUpload;
  7734. mimeTypes = other.mimeTypes;
  7735. return *this;
  7736. }
  7737. URL::~URL()
  7738. {
  7739. }
  7740. namespace URLHelpers
  7741. {
  7742. const String getMangledParameters (const StringPairArray& parameters)
  7743. {
  7744. String p;
  7745. for (int i = 0; i < parameters.size(); ++i)
  7746. {
  7747. if (i > 0)
  7748. p << '&';
  7749. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7750. << '='
  7751. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7752. }
  7753. return p;
  7754. }
  7755. int findStartOfDomain (const String& url)
  7756. {
  7757. int i = 0;
  7758. while (CharacterFunctions::isLetterOrDigit (url[i])
  7759. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7760. ++i;
  7761. return url[i] == ':' ? i + 1 : 0;
  7762. }
  7763. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7764. {
  7765. MemoryOutputStream data (postData, false);
  7766. if (url.getFilesToUpload().size() > 0)
  7767. {
  7768. // need to upload some files, so do it as multi-part...
  7769. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7770. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7771. data << "--" << boundary;
  7772. int i;
  7773. for (i = 0; i < url.getParameters().size(); ++i)
  7774. {
  7775. data << "\r\nContent-Disposition: form-data; name=\""
  7776. << url.getParameters().getAllKeys() [i]
  7777. << "\"\r\n\r\n"
  7778. << url.getParameters().getAllValues() [i]
  7779. << "\r\n--"
  7780. << boundary;
  7781. }
  7782. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7783. {
  7784. const File file (url.getFilesToUpload().getAllValues() [i]);
  7785. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7786. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7787. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7788. const String mimeType (url.getMimeTypesOfUploadFiles()
  7789. .getValue (paramName, String::empty));
  7790. if (mimeType.isNotEmpty())
  7791. data << "Content-Type: " << mimeType << "\r\n";
  7792. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7793. << file << "\r\n--" << boundary;
  7794. }
  7795. data << "--\r\n";
  7796. data.flush();
  7797. }
  7798. else
  7799. {
  7800. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7801. data.flush();
  7802. // just a short text attachment, so use simple url encoding..
  7803. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7804. << (int) postData.getSize() << "\r\n";
  7805. }
  7806. }
  7807. }
  7808. const String URL::toString (const bool includeGetParameters) const
  7809. {
  7810. if (includeGetParameters && parameters.size() > 0)
  7811. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7812. else
  7813. return url;
  7814. }
  7815. bool URL::isWellFormed() const
  7816. {
  7817. //xxx TODO
  7818. return url.isNotEmpty();
  7819. }
  7820. const String URL::getDomain() const
  7821. {
  7822. int start = URLHelpers::findStartOfDomain (url);
  7823. while (url[start] == '/')
  7824. ++start;
  7825. const int end1 = url.indexOfChar (start, '/');
  7826. const int end2 = url.indexOfChar (start, ':');
  7827. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7828. : jmin (end1, end2);
  7829. return url.substring (start, end);
  7830. }
  7831. const String URL::getSubPath() const
  7832. {
  7833. int start = URLHelpers::findStartOfDomain (url);
  7834. while (url[start] == '/')
  7835. ++start;
  7836. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7837. return startOfPath <= 0 ? String::empty
  7838. : url.substring (startOfPath);
  7839. }
  7840. const String URL::getScheme() const
  7841. {
  7842. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7843. }
  7844. const URL URL::withNewSubPath (const String& newPath) const
  7845. {
  7846. int start = URLHelpers::findStartOfDomain (url);
  7847. while (url[start] == '/')
  7848. ++start;
  7849. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7850. URL u (*this);
  7851. if (startOfPath > 0)
  7852. u.url = url.substring (0, startOfPath);
  7853. if (! u.url.endsWithChar ('/'))
  7854. u.url << '/';
  7855. if (newPath.startsWithChar ('/'))
  7856. u.url << newPath.substring (1);
  7857. else
  7858. u.url << newPath;
  7859. return u;
  7860. }
  7861. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7862. {
  7863. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7864. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7865. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7866. return true;
  7867. if (possibleURL.containsChar ('@')
  7868. || possibleURL.containsChar (' '))
  7869. return false;
  7870. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7871. .fromLastOccurrenceOf (".", false, false));
  7872. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7873. }
  7874. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7875. {
  7876. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7877. return atSign > 0
  7878. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7879. && (! possibleEmailAddress.endsWithChar ('.'));
  7880. }
  7881. InputStream* URL::createInputStream (const bool usePostCommand,
  7882. OpenStreamProgressCallback* const progressCallback,
  7883. void* const progressCallbackContext,
  7884. const String& extraHeaders,
  7885. const int timeOutMs,
  7886. StringPairArray* const responseHeaders) const
  7887. {
  7888. String headers;
  7889. MemoryBlock headersAndPostData;
  7890. if (usePostCommand)
  7891. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7892. headers += extraHeaders;
  7893. if (! headers.endsWithChar ('\n'))
  7894. headers << "\r\n";
  7895. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7896. progressCallback, progressCallbackContext,
  7897. headers, timeOutMs, responseHeaders);
  7898. }
  7899. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7900. const bool usePostCommand) const
  7901. {
  7902. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7903. if (in != 0)
  7904. {
  7905. in->readIntoMemoryBlock (destData);
  7906. return true;
  7907. }
  7908. return false;
  7909. }
  7910. const String URL::readEntireTextStream (const bool usePostCommand) const
  7911. {
  7912. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7913. if (in != 0)
  7914. return in->readEntireStreamAsString();
  7915. return String::empty;
  7916. }
  7917. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7918. {
  7919. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7920. }
  7921. const URL URL::withParameter (const String& parameterName,
  7922. const String& parameterValue) const
  7923. {
  7924. URL u (*this);
  7925. u.parameters.set (parameterName, parameterValue);
  7926. return u;
  7927. }
  7928. const URL URL::withFileToUpload (const String& parameterName,
  7929. const File& fileToUpload,
  7930. const String& mimeType) const
  7931. {
  7932. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7933. URL u (*this);
  7934. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7935. u.mimeTypes.set (parameterName, mimeType);
  7936. return u;
  7937. }
  7938. const URL URL::withPOSTData (const String& postData_) const
  7939. {
  7940. URL u (*this);
  7941. u.postData = postData_;
  7942. return u;
  7943. }
  7944. const StringPairArray& URL::getParameters() const
  7945. {
  7946. return parameters;
  7947. }
  7948. const StringPairArray& URL::getFilesToUpload() const
  7949. {
  7950. return filesToUpload;
  7951. }
  7952. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7953. {
  7954. return mimeTypes;
  7955. }
  7956. const String URL::removeEscapeChars (const String& s)
  7957. {
  7958. String result (s.replaceCharacter ('+', ' '));
  7959. if (! result.containsChar ('%'))
  7960. return result;
  7961. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7962. // after all the replacements have been made, so that multi-byte chars are handled.
  7963. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7964. for (int i = 0; i < utf8.size(); ++i)
  7965. {
  7966. if (utf8.getUnchecked(i) == '%')
  7967. {
  7968. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7969. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7970. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7971. {
  7972. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7973. utf8.removeRange (i + 1, 2);
  7974. }
  7975. }
  7976. }
  7977. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7978. }
  7979. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7980. {
  7981. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7982. : ",$_-.*!'()");
  7983. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7984. for (int i = 0; i < utf8.size(); ++i)
  7985. {
  7986. const char c = utf8.getUnchecked(i);
  7987. if (! (CharacterFunctions::isLetterOrDigit (c)
  7988. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7989. {
  7990. if (c == ' ')
  7991. {
  7992. utf8.set (i, '+');
  7993. }
  7994. else
  7995. {
  7996. static const char* const hexDigits = "0123456789abcdef";
  7997. utf8.set (i, '%');
  7998. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7999. utf8.insert (++i, hexDigits [c & 15]);
  8000. }
  8001. }
  8002. }
  8003. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  8004. }
  8005. bool URL::launchInDefaultBrowser() const
  8006. {
  8007. String u (toString (true));
  8008. if (u.containsChar ('@') && ! u.containsChar (':'))
  8009. u = "mailto:" + u;
  8010. return PlatformUtilities::openDocument (u, String::empty);
  8011. }
  8012. END_JUCE_NAMESPACE
  8013. /*** End of inlined file: juce_URL.cpp ***/
  8014. /*** Start of inlined file: juce_MACAddress.cpp ***/
  8015. BEGIN_JUCE_NAMESPACE
  8016. MACAddress::MACAddress()
  8017. : asInt64 (0)
  8018. {
  8019. }
  8020. MACAddress::MACAddress (const MACAddress& other)
  8021. : asInt64 (other.asInt64)
  8022. {
  8023. }
  8024. MACAddress& MACAddress::operator= (const MACAddress& other)
  8025. {
  8026. asInt64 = other.asInt64;
  8027. return *this;
  8028. }
  8029. MACAddress::MACAddress (const uint8 bytes[6])
  8030. : asInt64 (0)
  8031. {
  8032. memcpy (asBytes, bytes, sizeof (asBytes));
  8033. }
  8034. const String MACAddress::toString() const
  8035. {
  8036. String s;
  8037. s.preallocateStorage (18);
  8038. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  8039. {
  8040. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  8041. if (i < numElementsInArray (asBytes) - 1)
  8042. s << '-';
  8043. }
  8044. return s;
  8045. }
  8046. int64 MACAddress::toInt64() const throw()
  8047. {
  8048. int64 n = 0;
  8049. for (int i = numElementsInArray (asBytes); --i >= 0;)
  8050. n = (n << 8) | asBytes[i];
  8051. return n;
  8052. }
  8053. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  8054. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  8055. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  8056. END_JUCE_NAMESPACE
  8057. /*** End of inlined file: juce_MACAddress.cpp ***/
  8058. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  8059. BEGIN_JUCE_NAMESPACE
  8060. namespace
  8061. {
  8062. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  8063. {
  8064. // You need to supply a real stream when creating a BufferedInputStream
  8065. jassert (source != 0);
  8066. requestedSize = jmax (256, requestedSize);
  8067. const int64 sourceSize = source->getTotalLength();
  8068. if (sourceSize >= 0 && sourceSize < requestedSize)
  8069. requestedSize = jmax (32, (int) sourceSize);
  8070. return requestedSize;
  8071. }
  8072. }
  8073. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  8074. const bool deleteSourceWhenDestroyed)
  8075. : source (sourceStream, deleteSourceWhenDestroyed),
  8076. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8077. position (sourceStream->getPosition()),
  8078. lastReadPos (0),
  8079. bufferStart (position),
  8080. bufferOverlap (128)
  8081. {
  8082. buffer.malloc (bufferSize);
  8083. }
  8084. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8085. : source (&sourceStream, false),
  8086. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8087. position (sourceStream.getPosition()),
  8088. lastReadPos (0),
  8089. bufferStart (position),
  8090. bufferOverlap (128)
  8091. {
  8092. buffer.malloc (bufferSize);
  8093. }
  8094. BufferedInputStream::~BufferedInputStream()
  8095. {
  8096. }
  8097. int64 BufferedInputStream::getTotalLength()
  8098. {
  8099. return source->getTotalLength();
  8100. }
  8101. int64 BufferedInputStream::getPosition()
  8102. {
  8103. return position;
  8104. }
  8105. bool BufferedInputStream::setPosition (int64 newPosition)
  8106. {
  8107. position = jmax ((int64) 0, newPosition);
  8108. return true;
  8109. }
  8110. bool BufferedInputStream::isExhausted()
  8111. {
  8112. return (position >= lastReadPos)
  8113. && source->isExhausted();
  8114. }
  8115. void BufferedInputStream::ensureBuffered()
  8116. {
  8117. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8118. if (position < bufferStart || position >= bufferEndOverlap)
  8119. {
  8120. int bytesRead;
  8121. if (position < lastReadPos
  8122. && position >= bufferEndOverlap
  8123. && position >= bufferStart)
  8124. {
  8125. const int bytesToKeep = (int) (lastReadPos - position);
  8126. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8127. bufferStart = position;
  8128. bytesRead = source->read (buffer + bytesToKeep,
  8129. bufferSize - bytesToKeep);
  8130. lastReadPos += bytesRead;
  8131. bytesRead += bytesToKeep;
  8132. }
  8133. else
  8134. {
  8135. bufferStart = position;
  8136. source->setPosition (bufferStart);
  8137. bytesRead = source->read (buffer, bufferSize);
  8138. lastReadPos = bufferStart + bytesRead;
  8139. }
  8140. while (bytesRead < bufferSize)
  8141. buffer [bytesRead++] = 0;
  8142. }
  8143. }
  8144. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8145. {
  8146. if (position >= bufferStart
  8147. && position + maxBytesToRead <= lastReadPos)
  8148. {
  8149. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8150. position += maxBytesToRead;
  8151. return maxBytesToRead;
  8152. }
  8153. else
  8154. {
  8155. if (position < bufferStart || position >= lastReadPos)
  8156. ensureBuffered();
  8157. int bytesRead = 0;
  8158. while (maxBytesToRead > 0)
  8159. {
  8160. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8161. if (bytesAvailable > 0)
  8162. {
  8163. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8164. maxBytesToRead -= bytesAvailable;
  8165. bytesRead += bytesAvailable;
  8166. position += bytesAvailable;
  8167. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8168. }
  8169. const int64 oldLastReadPos = lastReadPos;
  8170. ensureBuffered();
  8171. if (oldLastReadPos == lastReadPos)
  8172. break; // if ensureBuffered() failed to read any more data, bail out
  8173. if (isExhausted())
  8174. break;
  8175. }
  8176. return bytesRead;
  8177. }
  8178. }
  8179. const String BufferedInputStream::readString()
  8180. {
  8181. if (position >= bufferStart
  8182. && position < lastReadPos)
  8183. {
  8184. const int maxChars = (int) (lastReadPos - position);
  8185. const char* const src = buffer + (int) (position - bufferStart);
  8186. for (int i = 0; i < maxChars; ++i)
  8187. {
  8188. if (src[i] == 0)
  8189. {
  8190. position += i + 1;
  8191. return String::fromUTF8 (src, i);
  8192. }
  8193. }
  8194. }
  8195. return InputStream::readString();
  8196. }
  8197. END_JUCE_NAMESPACE
  8198. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8199. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8200. BEGIN_JUCE_NAMESPACE
  8201. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8202. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8203. {
  8204. }
  8205. FileInputSource::~FileInputSource()
  8206. {
  8207. }
  8208. InputStream* FileInputSource::createInputStream()
  8209. {
  8210. return file.createInputStream();
  8211. }
  8212. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8213. {
  8214. return file.getSiblingFile (relatedItemPath).createInputStream();
  8215. }
  8216. int64 FileInputSource::hashCode() const
  8217. {
  8218. int64 h = file.hashCode();
  8219. if (useFileTimeInHashGeneration)
  8220. h ^= file.getLastModificationTime().toMilliseconds();
  8221. return h;
  8222. }
  8223. END_JUCE_NAMESPACE
  8224. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8225. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8226. BEGIN_JUCE_NAMESPACE
  8227. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8228. const size_t sourceDataSize,
  8229. const bool keepInternalCopy)
  8230. : data (static_cast <const char*> (sourceData)),
  8231. dataSize (sourceDataSize),
  8232. position (0)
  8233. {
  8234. if (keepInternalCopy)
  8235. {
  8236. internalCopy.append (data, sourceDataSize);
  8237. data = static_cast <const char*> (internalCopy.getData());
  8238. }
  8239. }
  8240. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8241. const bool keepInternalCopy)
  8242. : data (static_cast <const char*> (sourceData.getData())),
  8243. dataSize (sourceData.getSize()),
  8244. position (0)
  8245. {
  8246. if (keepInternalCopy)
  8247. {
  8248. internalCopy = sourceData;
  8249. data = static_cast <const char*> (internalCopy.getData());
  8250. }
  8251. }
  8252. MemoryInputStream::~MemoryInputStream()
  8253. {
  8254. }
  8255. int64 MemoryInputStream::getTotalLength()
  8256. {
  8257. return dataSize;
  8258. }
  8259. int MemoryInputStream::read (void* const buffer, const int howMany)
  8260. {
  8261. jassert (howMany >= 0);
  8262. const int num = jmin (howMany, (int) (dataSize - position));
  8263. memcpy (buffer, data + position, num);
  8264. position += num;
  8265. return (int) num;
  8266. }
  8267. bool MemoryInputStream::isExhausted()
  8268. {
  8269. return (position >= dataSize);
  8270. }
  8271. bool MemoryInputStream::setPosition (const int64 pos)
  8272. {
  8273. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8274. return true;
  8275. }
  8276. int64 MemoryInputStream::getPosition()
  8277. {
  8278. return position;
  8279. }
  8280. #if JUCE_UNIT_TESTS
  8281. class MemoryStreamTests : public UnitTest
  8282. {
  8283. public:
  8284. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8285. void runTest()
  8286. {
  8287. beginTest ("Basics");
  8288. int randomInt = Random::getSystemRandom().nextInt();
  8289. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8290. double randomDouble = Random::getSystemRandom().nextDouble();
  8291. String randomString (createRandomWideCharString());
  8292. MemoryOutputStream mo;
  8293. mo.writeInt (randomInt);
  8294. mo.writeIntBigEndian (randomInt);
  8295. mo.writeCompressedInt (randomInt);
  8296. mo.writeString (randomString);
  8297. mo.writeInt64 (randomInt64);
  8298. mo.writeInt64BigEndian (randomInt64);
  8299. mo.writeDouble (randomDouble);
  8300. mo.writeDoubleBigEndian (randomDouble);
  8301. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8302. expect (mi.readInt() == randomInt);
  8303. expect (mi.readIntBigEndian() == randomInt);
  8304. expect (mi.readCompressedInt() == randomInt);
  8305. expectEquals (mi.readString(), randomString);
  8306. expect (mi.readInt64() == randomInt64);
  8307. expect (mi.readInt64BigEndian() == randomInt64);
  8308. expect (mi.readDouble() == randomDouble);
  8309. expect (mi.readDoubleBigEndian() == randomDouble);
  8310. }
  8311. static const String createRandomWideCharString()
  8312. {
  8313. juce_wchar buffer [50];
  8314. zerostruct (buffer);
  8315. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  8316. {
  8317. if (Random::getSystemRandom().nextBool())
  8318. {
  8319. do
  8320. {
  8321. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  8322. }
  8323. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  8324. }
  8325. else
  8326. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  8327. }
  8328. return buffer;
  8329. }
  8330. };
  8331. static MemoryStreamTests memoryInputStreamUnitTests;
  8332. #endif
  8333. END_JUCE_NAMESPACE
  8334. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8335. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8336. BEGIN_JUCE_NAMESPACE
  8337. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8338. : data (internalBlock),
  8339. position (0),
  8340. size (0)
  8341. {
  8342. internalBlock.setSize (initialSize, false);
  8343. }
  8344. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8345. const bool appendToExistingBlockContent)
  8346. : data (memoryBlockToWriteTo),
  8347. position (0),
  8348. size (0)
  8349. {
  8350. if (appendToExistingBlockContent)
  8351. position = size = memoryBlockToWriteTo.getSize();
  8352. }
  8353. MemoryOutputStream::~MemoryOutputStream()
  8354. {
  8355. flush();
  8356. }
  8357. void MemoryOutputStream::flush()
  8358. {
  8359. if (&data != &internalBlock)
  8360. data.setSize (size, false);
  8361. }
  8362. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8363. {
  8364. data.ensureSize (bytesToPreallocate + 1);
  8365. }
  8366. void MemoryOutputStream::reset() throw()
  8367. {
  8368. position = 0;
  8369. size = 0;
  8370. }
  8371. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8372. {
  8373. if (howMany > 0)
  8374. {
  8375. const size_t storageNeeded = position + howMany;
  8376. if (storageNeeded >= data.getSize())
  8377. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8378. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8379. position += howMany;
  8380. size = jmax (size, position);
  8381. }
  8382. return true;
  8383. }
  8384. const void* MemoryOutputStream::getData() const throw()
  8385. {
  8386. void* const d = data.getData();
  8387. if (data.getSize() > size)
  8388. static_cast <char*> (d) [size] = 0;
  8389. return d;
  8390. }
  8391. bool MemoryOutputStream::setPosition (int64 newPosition)
  8392. {
  8393. if (newPosition <= (int64) size)
  8394. {
  8395. // ok to seek backwards
  8396. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8397. return true;
  8398. }
  8399. else
  8400. {
  8401. // trying to make it bigger isn't a good thing to do..
  8402. return false;
  8403. }
  8404. }
  8405. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8406. {
  8407. // before writing from an input, see if we can preallocate to make it more efficient..
  8408. int64 availableData = source.getTotalLength() - source.getPosition();
  8409. if (availableData > 0)
  8410. {
  8411. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8412. availableData = maxNumBytesToWrite;
  8413. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8414. }
  8415. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8416. }
  8417. const String MemoryOutputStream::toUTF8() const
  8418. {
  8419. return String::fromUTF8 (static_cast <const char*> (getData()), getDataSize());
  8420. }
  8421. const String MemoryOutputStream::toString() const
  8422. {
  8423. return String::createStringFromData (getData(), (int) getDataSize());
  8424. }
  8425. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8426. {
  8427. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8428. return stream;
  8429. }
  8430. END_JUCE_NAMESPACE
  8431. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8432. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8433. BEGIN_JUCE_NAMESPACE
  8434. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8435. const int64 startPositionInSourceStream_,
  8436. const int64 lengthOfSourceStream_,
  8437. const bool deleteSourceWhenDestroyed)
  8438. : source (sourceStream, deleteSourceWhenDestroyed),
  8439. startPositionInSourceStream (startPositionInSourceStream_),
  8440. lengthOfSourceStream (lengthOfSourceStream_)
  8441. {
  8442. setPosition (0);
  8443. }
  8444. SubregionStream::~SubregionStream()
  8445. {
  8446. }
  8447. int64 SubregionStream::getTotalLength()
  8448. {
  8449. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8450. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8451. : srcLen;
  8452. }
  8453. int64 SubregionStream::getPosition()
  8454. {
  8455. return source->getPosition() - startPositionInSourceStream;
  8456. }
  8457. bool SubregionStream::setPosition (int64 newPosition)
  8458. {
  8459. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8460. }
  8461. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8462. {
  8463. if (lengthOfSourceStream < 0)
  8464. {
  8465. return source->read (destBuffer, maxBytesToRead);
  8466. }
  8467. else
  8468. {
  8469. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8470. if (maxBytesToRead <= 0)
  8471. return 0;
  8472. return source->read (destBuffer, maxBytesToRead);
  8473. }
  8474. }
  8475. bool SubregionStream::isExhausted()
  8476. {
  8477. if (lengthOfSourceStream >= 0)
  8478. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8479. else
  8480. return source->isExhausted();
  8481. }
  8482. END_JUCE_NAMESPACE
  8483. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8484. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8485. BEGIN_JUCE_NAMESPACE
  8486. PerformanceCounter::PerformanceCounter (const String& name_,
  8487. int runsPerPrintout,
  8488. const File& loggingFile)
  8489. : name (name_),
  8490. numRuns (0),
  8491. runsPerPrint (runsPerPrintout),
  8492. totalTime (0),
  8493. outputFile (loggingFile)
  8494. {
  8495. if (outputFile != File::nonexistent)
  8496. {
  8497. String s ("**** Counter for \"");
  8498. s << name_ << "\" started at: "
  8499. << Time::getCurrentTime().toString (true, true)
  8500. << newLine;
  8501. outputFile.appendText (s, false, false);
  8502. }
  8503. }
  8504. PerformanceCounter::~PerformanceCounter()
  8505. {
  8506. printStatistics();
  8507. }
  8508. void PerformanceCounter::start()
  8509. {
  8510. started = Time::getHighResolutionTicks();
  8511. }
  8512. void PerformanceCounter::stop()
  8513. {
  8514. const int64 now = Time::getHighResolutionTicks();
  8515. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8516. if (++numRuns == runsPerPrint)
  8517. printStatistics();
  8518. }
  8519. void PerformanceCounter::printStatistics()
  8520. {
  8521. if (numRuns > 0)
  8522. {
  8523. String s ("Performance count for \"");
  8524. s << name << "\" - average over " << numRuns << " run(s) = ";
  8525. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8526. if (micros > 10000)
  8527. s << (micros/1000) << " millisecs";
  8528. else
  8529. s << micros << " microsecs";
  8530. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8531. Logger::outputDebugString (s);
  8532. s << newLine;
  8533. if (outputFile != File::nonexistent)
  8534. outputFile.appendText (s, false, false);
  8535. numRuns = 0;
  8536. totalTime = 0;
  8537. }
  8538. }
  8539. END_JUCE_NAMESPACE
  8540. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8541. /*** Start of inlined file: juce_Uuid.cpp ***/
  8542. BEGIN_JUCE_NAMESPACE
  8543. Uuid::Uuid()
  8544. {
  8545. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8546. // to make it very very unlikely that two UUIDs will ever be the same..
  8547. static int64 macAddresses[2];
  8548. static bool hasCheckedMacAddresses = false;
  8549. if (! hasCheckedMacAddresses)
  8550. {
  8551. hasCheckedMacAddresses = true;
  8552. Array<MACAddress> result;
  8553. MACAddress::findAllAddresses (result);
  8554. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8555. macAddresses[i] = result[i].toInt64();
  8556. }
  8557. value.asInt64[0] = macAddresses[0];
  8558. value.asInt64[1] = macAddresses[1];
  8559. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8560. // whose seed will carry over between calls to this method.
  8561. Random r (macAddresses[0] ^ macAddresses[1]
  8562. ^ Random::getSystemRandom().nextInt64());
  8563. for (int i = 4; --i >= 0;)
  8564. {
  8565. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8566. value.asInt[i] ^= r.nextInt();
  8567. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8568. }
  8569. }
  8570. Uuid::~Uuid() throw()
  8571. {
  8572. }
  8573. Uuid::Uuid (const Uuid& other)
  8574. : value (other.value)
  8575. {
  8576. }
  8577. Uuid& Uuid::operator= (const Uuid& other)
  8578. {
  8579. value = other.value;
  8580. return *this;
  8581. }
  8582. bool Uuid::operator== (const Uuid& other) const
  8583. {
  8584. return value.asInt64[0] == other.value.asInt64[0]
  8585. && value.asInt64[1] == other.value.asInt64[1];
  8586. }
  8587. bool Uuid::operator!= (const Uuid& other) const
  8588. {
  8589. return ! operator== (other);
  8590. }
  8591. bool Uuid::isNull() const throw()
  8592. {
  8593. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8594. }
  8595. const String Uuid::toString() const
  8596. {
  8597. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8598. }
  8599. Uuid::Uuid (const String& uuidString)
  8600. {
  8601. operator= (uuidString);
  8602. }
  8603. Uuid& Uuid::operator= (const String& uuidString)
  8604. {
  8605. MemoryBlock mb;
  8606. mb.loadFromHexString (uuidString);
  8607. mb.ensureSize (sizeof (value.asBytes), true);
  8608. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8609. return *this;
  8610. }
  8611. Uuid::Uuid (const uint8* const rawData)
  8612. {
  8613. operator= (rawData);
  8614. }
  8615. Uuid& Uuid::operator= (const uint8* const rawData)
  8616. {
  8617. if (rawData != 0)
  8618. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8619. else
  8620. zeromem (value.asBytes, sizeof (value.asBytes));
  8621. return *this;
  8622. }
  8623. END_JUCE_NAMESPACE
  8624. /*** End of inlined file: juce_Uuid.cpp ***/
  8625. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8626. BEGIN_JUCE_NAMESPACE
  8627. class ZipFile::ZipEntryInfo
  8628. {
  8629. public:
  8630. ZipFile::ZipEntry entry;
  8631. int streamOffset;
  8632. int compressedSize;
  8633. bool compressed;
  8634. };
  8635. class ZipFile::ZipInputStream : public InputStream
  8636. {
  8637. public:
  8638. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8639. : file (file_),
  8640. zipEntryInfo (zei),
  8641. pos (0),
  8642. headerSize (0),
  8643. inputStream (0)
  8644. {
  8645. inputStream = file_.inputStream;
  8646. if (file_.inputSource != 0)
  8647. {
  8648. inputStream = streamToDelete = file.inputSource->createInputStream();
  8649. }
  8650. else
  8651. {
  8652. #if JUCE_DEBUG
  8653. file_.numOpenStreams++;
  8654. #endif
  8655. }
  8656. char buffer [30];
  8657. if (inputStream != 0
  8658. && inputStream->setPosition (zei.streamOffset)
  8659. && inputStream->read (buffer, 30) == 30
  8660. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8661. {
  8662. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8663. + ByteOrder::littleEndianShort (buffer + 28);
  8664. }
  8665. }
  8666. ~ZipInputStream()
  8667. {
  8668. #if JUCE_DEBUG
  8669. if (inputStream != 0 && inputStream == file.inputStream)
  8670. file.numOpenStreams--;
  8671. #endif
  8672. }
  8673. int64 getTotalLength()
  8674. {
  8675. return zipEntryInfo.compressedSize;
  8676. }
  8677. int read (void* buffer, int howMany)
  8678. {
  8679. if (headerSize <= 0)
  8680. return 0;
  8681. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8682. if (inputStream == 0)
  8683. return 0;
  8684. int num;
  8685. if (inputStream == file.inputStream)
  8686. {
  8687. const ScopedLock sl (file.lock);
  8688. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8689. num = inputStream->read (buffer, howMany);
  8690. }
  8691. else
  8692. {
  8693. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8694. num = inputStream->read (buffer, howMany);
  8695. }
  8696. pos += num;
  8697. return num;
  8698. }
  8699. bool isExhausted()
  8700. {
  8701. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8702. }
  8703. int64 getPosition()
  8704. {
  8705. return pos;
  8706. }
  8707. bool setPosition (int64 newPos)
  8708. {
  8709. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8710. return true;
  8711. }
  8712. private:
  8713. ZipFile& file;
  8714. ZipEntryInfo zipEntryInfo;
  8715. int64 pos;
  8716. int headerSize;
  8717. InputStream* inputStream;
  8718. ScopedPointer<InputStream> streamToDelete;
  8719. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8720. };
  8721. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8722. : inputStream (source_)
  8723. #if JUCE_DEBUG
  8724. , numOpenStreams (0)
  8725. #endif
  8726. {
  8727. if (deleteStreamWhenDestroyed)
  8728. streamToDelete = inputStream;
  8729. init();
  8730. }
  8731. ZipFile::ZipFile (const File& file)
  8732. : inputStream (0)
  8733. #if JUCE_DEBUG
  8734. , numOpenStreams (0)
  8735. #endif
  8736. {
  8737. inputSource = new FileInputSource (file);
  8738. init();
  8739. }
  8740. ZipFile::ZipFile (InputSource* const inputSource_)
  8741. : inputStream (0),
  8742. inputSource (inputSource_)
  8743. #if JUCE_DEBUG
  8744. , numOpenStreams (0)
  8745. #endif
  8746. {
  8747. init();
  8748. }
  8749. ZipFile::~ZipFile()
  8750. {
  8751. #if JUCE_DEBUG
  8752. entries.clear();
  8753. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8754. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8755. Streams can't be kept open after the file is deleted because they need to share the input
  8756. stream that the file uses to read itself.
  8757. */
  8758. jassert (numOpenStreams == 0);
  8759. #endif
  8760. }
  8761. int ZipFile::getNumEntries() const throw()
  8762. {
  8763. return entries.size();
  8764. }
  8765. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8766. {
  8767. ZipEntryInfo* const zei = entries [index];
  8768. return zei != 0 ? &(zei->entry) : 0;
  8769. }
  8770. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8771. {
  8772. for (int i = 0; i < entries.size(); ++i)
  8773. if (entries.getUnchecked (i)->entry.filename == fileName)
  8774. return i;
  8775. return -1;
  8776. }
  8777. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8778. {
  8779. return getEntry (getIndexOfFileName (fileName));
  8780. }
  8781. InputStream* ZipFile::createStreamForEntry (const int index)
  8782. {
  8783. ZipEntryInfo* const zei = entries[index];
  8784. InputStream* stream = 0;
  8785. if (zei != 0)
  8786. {
  8787. stream = new ZipInputStream (*this, *zei);
  8788. if (zei->compressed)
  8789. {
  8790. stream = new GZIPDecompressorInputStream (stream, true, true,
  8791. zei->entry.uncompressedSize);
  8792. // (much faster to unzip in big blocks using a buffer..)
  8793. stream = new BufferedInputStream (stream, 32768, true);
  8794. }
  8795. }
  8796. return stream;
  8797. }
  8798. class ZipFile::ZipFilenameComparator
  8799. {
  8800. public:
  8801. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8802. {
  8803. return first->entry.filename.compare (second->entry.filename);
  8804. }
  8805. };
  8806. void ZipFile::sortEntriesByFilename()
  8807. {
  8808. ZipFilenameComparator sorter;
  8809. entries.sort (sorter);
  8810. }
  8811. void ZipFile::init()
  8812. {
  8813. ScopedPointer <InputStream> toDelete;
  8814. InputStream* in = inputStream;
  8815. if (inputSource != 0)
  8816. {
  8817. in = inputSource->createInputStream();
  8818. toDelete = in;
  8819. }
  8820. if (in != 0)
  8821. {
  8822. int numEntries = 0;
  8823. int pos = findEndOfZipEntryTable (*in, numEntries);
  8824. if (pos >= 0 && pos < in->getTotalLength())
  8825. {
  8826. const int size = (int) (in->getTotalLength() - pos);
  8827. in->setPosition (pos);
  8828. MemoryBlock headerData;
  8829. if (in->readIntoMemoryBlock (headerData, size) == size)
  8830. {
  8831. pos = 0;
  8832. for (int i = 0; i < numEntries; ++i)
  8833. {
  8834. if (pos + 46 > size)
  8835. break;
  8836. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8837. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8838. if (pos + 46 + fileNameLen > size)
  8839. break;
  8840. ZipEntryInfo* const zei = new ZipEntryInfo();
  8841. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8842. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8843. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8844. const int year = 1980 + (date >> 9);
  8845. const int month = ((date >> 5) & 15) - 1;
  8846. const int day = date & 31;
  8847. const int hours = time >> 11;
  8848. const int minutes = (time >> 5) & 63;
  8849. const int seconds = (time & 31) << 1;
  8850. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8851. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8852. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8853. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8854. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8855. entries.add (zei);
  8856. pos += 46 + fileNameLen
  8857. + ByteOrder::littleEndianShort (buffer + 30)
  8858. + ByteOrder::littleEndianShort (buffer + 32);
  8859. }
  8860. }
  8861. }
  8862. }
  8863. }
  8864. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8865. {
  8866. BufferedInputStream in (input, 8192);
  8867. in.setPosition (in.getTotalLength());
  8868. int64 pos = in.getPosition();
  8869. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8870. char buffer [32];
  8871. zeromem (buffer, sizeof (buffer));
  8872. while (pos > lowestPos)
  8873. {
  8874. in.setPosition (pos - 22);
  8875. pos = in.getPosition();
  8876. memcpy (buffer + 22, buffer, 4);
  8877. if (in.read (buffer, 22) != 22)
  8878. return 0;
  8879. for (int i = 0; i < 22; ++i)
  8880. {
  8881. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8882. {
  8883. in.setPosition (pos + i);
  8884. in.read (buffer, 22);
  8885. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8886. return ByteOrder::littleEndianInt (buffer + 16);
  8887. }
  8888. }
  8889. }
  8890. return 0;
  8891. }
  8892. bool ZipFile::uncompressTo (const File& targetDirectory,
  8893. const bool shouldOverwriteFiles)
  8894. {
  8895. for (int i = 0; i < entries.size(); ++i)
  8896. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8897. return false;
  8898. return true;
  8899. }
  8900. bool ZipFile::uncompressEntry (const int index,
  8901. const File& targetDirectory,
  8902. bool shouldOverwriteFiles)
  8903. {
  8904. const ZipEntryInfo* zei = entries [index];
  8905. if (zei != 0)
  8906. {
  8907. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8908. if (zei->entry.filename.endsWithChar ('/'))
  8909. {
  8910. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8911. }
  8912. else
  8913. {
  8914. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8915. if (in != 0)
  8916. {
  8917. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8918. return false;
  8919. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8920. {
  8921. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8922. if (out != 0)
  8923. {
  8924. out->writeFromInputStream (*in, -1);
  8925. out = 0;
  8926. targetFile.setCreationTime (zei->entry.fileTime);
  8927. targetFile.setLastModificationTime (zei->entry.fileTime);
  8928. targetFile.setLastAccessTime (zei->entry.fileTime);
  8929. return true;
  8930. }
  8931. }
  8932. }
  8933. }
  8934. }
  8935. return false;
  8936. }
  8937. END_JUCE_NAMESPACE
  8938. /*** End of inlined file: juce_ZipFile.cpp ***/
  8939. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8940. #if JUCE_MSVC
  8941. #pragma warning (push)
  8942. #pragma warning (disable: 4514 4996)
  8943. #endif
  8944. #if ! JUCE_ANDROID
  8945. #include <cwctype>
  8946. #endif
  8947. #include <cctype>
  8948. #include <ctime>
  8949. BEGIN_JUCE_NAMESPACE
  8950. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8951. {
  8952. return towupper ((wchar_t) character);
  8953. }
  8954. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8955. {
  8956. return towlower ((wchar_t) character);
  8957. }
  8958. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8959. {
  8960. #if JUCE_WINDOWS
  8961. return iswupper ((wchar_t) character) != 0;
  8962. #else
  8963. return toLowerCase (character) != character;
  8964. #endif
  8965. }
  8966. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8967. {
  8968. #if JUCE_WINDOWS
  8969. return iswlower ((wchar_t) character) != 0;
  8970. #else
  8971. return toUpperCase (character) != character;
  8972. #endif
  8973. }
  8974. bool CharacterFunctions::isWhitespace (const char character) throw()
  8975. {
  8976. return character == ' ' || (character <= 13 && character >= 9);
  8977. }
  8978. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8979. {
  8980. return iswspace ((wchar_t) character) != 0;
  8981. }
  8982. bool CharacterFunctions::isDigit (const char character) throw()
  8983. {
  8984. return (character >= '0' && character <= '9');
  8985. }
  8986. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8987. {
  8988. return iswdigit ((wchar_t) character) != 0;
  8989. }
  8990. bool CharacterFunctions::isLetter (const char character) throw()
  8991. {
  8992. return (character >= 'a' && character <= 'z')
  8993. || (character >= 'A' && character <= 'Z');
  8994. }
  8995. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8996. {
  8997. return iswalpha ((wchar_t) character) != 0;
  8998. }
  8999. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9000. {
  9001. return (character >= 'a' && character <= 'z')
  9002. || (character >= 'A' && character <= 'Z')
  9003. || (character >= '0' && character <= '9');
  9004. }
  9005. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9006. {
  9007. return iswalnum ((wchar_t) character) != 0;
  9008. }
  9009. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9010. {
  9011. unsigned int d = digit - '0';
  9012. if (d < (unsigned int) 10)
  9013. return (int) d;
  9014. d += (unsigned int) ('0' - 'a');
  9015. if (d < (unsigned int) 6)
  9016. return (int) d + 10;
  9017. d += (unsigned int) ('a' - 'A');
  9018. if (d < (unsigned int) 6)
  9019. return (int) d + 10;
  9020. return -1;
  9021. }
  9022. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  9023. {
  9024. return (int) strftime (dest, maxChars, format, tm);
  9025. }
  9026. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  9027. {
  9028. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  9029. return (int) wcsftime (dest, maxChars, format, tm);
  9030. #else
  9031. HeapBlock <char> tempDest;
  9032. tempDest.calloc (maxChars + 2);
  9033. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  9034. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  9035. return result;
  9036. #endif
  9037. }
  9038. #if JUCE_MSVC
  9039. #pragma warning (pop)
  9040. #endif
  9041. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  9042. {
  9043. if (exponent == 0)
  9044. return value;
  9045. if (value == 0)
  9046. return 0;
  9047. const bool negative = (exponent < 0);
  9048. if (negative)
  9049. exponent = -exponent;
  9050. double result = 1.0, power = 10.0;
  9051. for (int bit = 1; exponent != 0; bit <<= 1)
  9052. {
  9053. if ((exponent & bit) != 0)
  9054. {
  9055. exponent ^= bit;
  9056. result *= power;
  9057. if (exponent == 0)
  9058. break;
  9059. }
  9060. power *= power;
  9061. }
  9062. return negative ? (value / result) : (value * result);
  9063. }
  9064. END_JUCE_NAMESPACE
  9065. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9066. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9067. BEGIN_JUCE_NAMESPACE
  9068. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9069. {
  9070. loadFromText (fileContents);
  9071. }
  9072. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9073. {
  9074. loadFromText (fileToLoad.loadFileAsString());
  9075. }
  9076. LocalisedStrings::~LocalisedStrings()
  9077. {
  9078. }
  9079. const String LocalisedStrings::translate (const String& text) const
  9080. {
  9081. return translations.getValue (text, text);
  9082. }
  9083. namespace
  9084. {
  9085. CriticalSection currentMappingsLock;
  9086. LocalisedStrings* currentMappings = 0;
  9087. int findCloseQuote (const String& text, int startPos)
  9088. {
  9089. juce_wchar lastChar = 0;
  9090. for (;;)
  9091. {
  9092. const juce_wchar c = text [startPos];
  9093. if (c == 0 || (c == '"' && lastChar != '\\'))
  9094. break;
  9095. lastChar = c;
  9096. ++startPos;
  9097. }
  9098. return startPos;
  9099. }
  9100. const String unescapeString (const String& s)
  9101. {
  9102. return s.replace ("\\\"", "\"")
  9103. .replace ("\\\'", "\'")
  9104. .replace ("\\t", "\t")
  9105. .replace ("\\r", "\r")
  9106. .replace ("\\n", "\n");
  9107. }
  9108. }
  9109. void LocalisedStrings::loadFromText (const String& fileContents)
  9110. {
  9111. StringArray lines;
  9112. lines.addLines (fileContents);
  9113. for (int i = 0; i < lines.size(); ++i)
  9114. {
  9115. String line (lines[i].trim());
  9116. if (line.startsWithChar ('"'))
  9117. {
  9118. int closeQuote = findCloseQuote (line, 1);
  9119. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9120. if (originalText.isNotEmpty())
  9121. {
  9122. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9123. closeQuote = findCloseQuote (line, openingQuote + 1);
  9124. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9125. if (newText.isNotEmpty())
  9126. translations.set (originalText, newText);
  9127. }
  9128. }
  9129. else if (line.startsWithIgnoreCase ("language:"))
  9130. {
  9131. languageName = line.substring (9).trim();
  9132. }
  9133. else if (line.startsWithIgnoreCase ("countries:"))
  9134. {
  9135. countryCodes.addTokens (line.substring (10).trim(), true);
  9136. countryCodes.trim();
  9137. countryCodes.removeEmptyStrings();
  9138. }
  9139. }
  9140. }
  9141. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9142. {
  9143. translations.setIgnoresCase (shouldIgnoreCase);
  9144. }
  9145. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9146. {
  9147. const ScopedLock sl (currentMappingsLock);
  9148. delete currentMappings;
  9149. currentMappings = newTranslations;
  9150. }
  9151. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9152. {
  9153. return currentMappings;
  9154. }
  9155. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9156. {
  9157. const ScopedLock sl (currentMappingsLock);
  9158. if (currentMappings != 0)
  9159. return currentMappings->translate (text);
  9160. return text;
  9161. }
  9162. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9163. {
  9164. return translateWithCurrentMappings (String (text));
  9165. }
  9166. END_JUCE_NAMESPACE
  9167. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9168. /*** Start of inlined file: juce_String.cpp ***/
  9169. #if JUCE_MSVC
  9170. #pragma warning (push)
  9171. #pragma warning (disable: 4514 4996)
  9172. #endif
  9173. #include <locale>
  9174. BEGIN_JUCE_NAMESPACE
  9175. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9176. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9177. #endif
  9178. #if JUCE_NATIVE_WCHAR_IS_UTF8
  9179. typedef CharPointer_UTF8 CharPointer_wchar_t;
  9180. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  9181. typedef CharPointer_UTF16 CharPointer_wchar_t;
  9182. #else
  9183. typedef CharPointer_UTF32 CharPointer_wchar_t;
  9184. #endif
  9185. NewLine newLine;
  9186. class StringHolder
  9187. {
  9188. public:
  9189. StringHolder()
  9190. : refCount (0x3fffffff), allocatedNumChars (0)
  9191. {
  9192. text[0] = 0;
  9193. }
  9194. typedef String::CharPointerType CharPointerType;
  9195. static const CharPointerType createUninitialised (const size_t numChars)
  9196. {
  9197. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9198. s->refCount.value = 0;
  9199. s->allocatedNumChars = numChars;
  9200. return CharPointerType (&(s->text[0]));
  9201. }
  9202. template <class CharPointer>
  9203. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9204. {
  9205. if (text.getAddress() == 0 || text.isEmpty())
  9206. return getEmpty();
  9207. const size_t numChars = text.length();
  9208. const CharPointerType dest (createUninitialised (numChars));
  9209. CharPointerType (dest).writeAll (text);
  9210. return dest;
  9211. }
  9212. template <class CharPointer>
  9213. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9214. {
  9215. if (text.getAddress() == 0 || text.isEmpty())
  9216. return getEmpty();
  9217. size_t numChars = text.lengthUpTo (maxChars);
  9218. if (numChars == 0)
  9219. return getEmpty();
  9220. const CharPointerType dest (createUninitialised (numChars));
  9221. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9222. return dest;
  9223. }
  9224. template <class CharPointer>
  9225. static const CharPointerType createFromCharPointer (const CharPointer& start, const CharPointer& end)
  9226. {
  9227. if (start.getAddress() == 0 || start.isEmpty())
  9228. return getEmpty();
  9229. size_t numChars = start.lengthUpTo (end);
  9230. if (numChars == 0)
  9231. return getEmpty();
  9232. const CharPointerType dest (createUninitialised (numChars));
  9233. CharPointerType (dest).writeWithCharLimit (start, (int) (numChars + 1));
  9234. return dest;
  9235. }
  9236. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9237. {
  9238. CharPointerType dest (createUninitialised (numChars));
  9239. copyChars (dest, CharPointerType (src), (int) numChars);
  9240. return dest;
  9241. }
  9242. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9243. {
  9244. const CharPointerType dest (createUninitialised (numChars));
  9245. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9246. return dest;
  9247. }
  9248. static inline const CharPointerType getEmpty() throw()
  9249. {
  9250. return CharPointerType (&(empty.text[0]));
  9251. }
  9252. static void retain (const CharPointerType& text) throw()
  9253. {
  9254. ++(bufferFromText (text)->refCount);
  9255. }
  9256. static inline void release (StringHolder* const b) throw()
  9257. {
  9258. if (--(b->refCount) == -1 && b != &empty)
  9259. delete[] reinterpret_cast <char*> (b);
  9260. }
  9261. static void release (const CharPointerType& text) throw()
  9262. {
  9263. release (bufferFromText (text));
  9264. }
  9265. static CharPointerType makeUnique (const CharPointerType& text)
  9266. {
  9267. StringHolder* const b = bufferFromText (text);
  9268. if (b->refCount.get() <= 0)
  9269. return text;
  9270. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9271. release (b);
  9272. return newText;
  9273. }
  9274. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9275. {
  9276. StringHolder* const b = bufferFromText (text);
  9277. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9278. return text;
  9279. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9280. copyChars (newText, text, b->allocatedNumChars);
  9281. release (b);
  9282. return newText;
  9283. }
  9284. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9285. {
  9286. return bufferFromText (text)->allocatedNumChars;
  9287. }
  9288. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9289. {
  9290. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9291. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9292. CharPointerType (dest + (int) numChars).writeNull();
  9293. }
  9294. Atomic<int> refCount;
  9295. size_t allocatedNumChars;
  9296. juce_wchar text[1];
  9297. static StringHolder empty;
  9298. private:
  9299. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9300. {
  9301. // (Can't use offsetof() here because of warnings about this not being a POD)
  9302. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9303. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9304. }
  9305. };
  9306. StringHolder StringHolder::empty;
  9307. const String String::empty;
  9308. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9309. {
  9310. if (numExtraChars > 0)
  9311. {
  9312. const int oldLen = length();
  9313. const int newTotalLen = oldLen + numExtraChars;
  9314. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9315. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9316. }
  9317. }
  9318. void String::preallocateStorage (const size_t numChars)
  9319. {
  9320. text = StringHolder::makeUniqueWithSize (text, numChars);
  9321. }
  9322. String::String() throw()
  9323. : text (StringHolder::getEmpty())
  9324. {
  9325. }
  9326. String::~String() throw()
  9327. {
  9328. StringHolder::release (text);
  9329. }
  9330. String::String (const String& other) throw()
  9331. : text (other.text)
  9332. {
  9333. StringHolder::retain (text);
  9334. }
  9335. void String::swapWith (String& other) throw()
  9336. {
  9337. swapVariables (text, other.text);
  9338. }
  9339. String& String::operator= (const String& other) throw()
  9340. {
  9341. StringHolder::retain (other.text);
  9342. StringHolder::release (text.atomicSwap (other.text));
  9343. return *this;
  9344. }
  9345. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9346. String::String (const Preallocation& preallocationSize)
  9347. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9348. {
  9349. }
  9350. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9351. : text (0)
  9352. {
  9353. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9354. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9355. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9356. }
  9357. String::String (const char* const t)
  9358. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  9359. {
  9360. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9361. that contains values greater than 127. These can NOT be correctly converted to unicode
  9362. because there's no way for the String class to know what encoding was used to
  9363. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9364. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9365. string to the String class - so for example if your source data is actually UTF-8,
  9366. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9367. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9368. you use UTF-8 with escape characters in your source code to represent extended characters,
  9369. because there's no other way to represent these strings in a way that isn't dependent on
  9370. the compiler, source code editor and platform.
  9371. */
  9372. jassert (t == 0 || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  9373. }
  9374. String::String (const char* const t, const size_t maxChars)
  9375. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  9376. {
  9377. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9378. that contains values greater than 127. These can NOT be correctly converted to unicode
  9379. because there's no way for the String class to know what encoding was used to
  9380. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9381. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9382. string to the String class - so for example if your source data is actually UTF-8,
  9383. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9384. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9385. you use UTF-8 with escape characters in your source code to represent extended characters,
  9386. because there's no other way to represent these strings in a way that isn't dependent on
  9387. the compiler, source code editor and platform.
  9388. */
  9389. jassert (t == 0 || CharPointer_ASCII::isValidString (t, (int) maxChars));
  9390. }
  9391. String::String (const juce_wchar* const t)
  9392. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9393. {
  9394. }
  9395. String::String (const juce_wchar* const t, const size_t maxChars)
  9396. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9397. {
  9398. }
  9399. String::String (const CharPointer_UTF8& t)
  9400. : text (StringHolder::createFromCharPointer (t))
  9401. {
  9402. }
  9403. String::String (const CharPointer_UTF16& t)
  9404. : text (StringHolder::createFromCharPointer (t))
  9405. {
  9406. }
  9407. String::String (const CharPointer_UTF32& t)
  9408. : text (StringHolder::createFromCharPointer (t))
  9409. {
  9410. }
  9411. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9412. : text (StringHolder::createFromCharPointer (t, maxChars))
  9413. {
  9414. }
  9415. String::String (const CharPointer_UTF32& start, const CharPointer_UTF32& end)
  9416. : text (StringHolder::createFromCharPointer (start, end))
  9417. {
  9418. }
  9419. String::String (const CharPointer_ASCII& t)
  9420. : text (StringHolder::createFromCharPointer (t))
  9421. {
  9422. }
  9423. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9424. String::String (const wchar_t* const t)
  9425. : text (StringHolder::createFromCharPointer
  9426. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t))))
  9427. {
  9428. }
  9429. String::String (const wchar_t* const t, size_t maxChars)
  9430. : text (StringHolder::createFromCharPointer
  9431. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t)), maxChars))
  9432. {
  9433. }
  9434. #endif
  9435. const String String::charToString (const juce_wchar character)
  9436. {
  9437. String result (Preallocation (1));
  9438. CharPointerType t (result.text);
  9439. t.write (character);
  9440. t.writeNull();
  9441. return result;
  9442. }
  9443. namespace NumberToStringConverters
  9444. {
  9445. // pass in a pointer to the END of a buffer..
  9446. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9447. {
  9448. *--t = 0;
  9449. int64 v = (n >= 0) ? n : -n;
  9450. do
  9451. {
  9452. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9453. v /= 10;
  9454. } while (v > 0);
  9455. if (n < 0)
  9456. *--t = '-';
  9457. return t;
  9458. }
  9459. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9460. {
  9461. *--t = 0;
  9462. do
  9463. {
  9464. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9465. v /= 10;
  9466. } while (v > 0);
  9467. return t;
  9468. }
  9469. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9470. {
  9471. if (n == (int) 0x80000000) // (would cause an overflow)
  9472. return numberToString (t, (int64) n);
  9473. *--t = 0;
  9474. int v = abs (n);
  9475. do
  9476. {
  9477. *--t = (juce_wchar) ('0' + (v % 10));
  9478. v /= 10;
  9479. } while (v > 0);
  9480. if (n < 0)
  9481. *--t = '-';
  9482. return t;
  9483. }
  9484. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9485. {
  9486. *--t = 0;
  9487. do
  9488. {
  9489. *--t = (juce_wchar) ('0' + (v % 10));
  9490. v /= 10;
  9491. } while (v > 0);
  9492. return t;
  9493. }
  9494. juce_wchar getDecimalPoint()
  9495. {
  9496. #if JUCE_VC7_OR_EARLIER
  9497. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9498. #else
  9499. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9500. #endif
  9501. return dp;
  9502. }
  9503. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9504. {
  9505. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9506. {
  9507. char* const end = buffer + numChars;
  9508. char* t = end;
  9509. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9510. *--t = (char) 0;
  9511. while (numDecPlaces >= 0 || v > 0)
  9512. {
  9513. if (numDecPlaces == 0)
  9514. *--t = (char) getDecimalPoint();
  9515. *--t = (char) ('0' + (v % 10));
  9516. v /= 10;
  9517. --numDecPlaces;
  9518. }
  9519. if (n < 0)
  9520. *--t = '-';
  9521. len = end - t - 1;
  9522. return t;
  9523. }
  9524. else
  9525. {
  9526. len = sprintf (buffer, "%.9g", n);
  9527. return buffer;
  9528. }
  9529. }
  9530. template <typename IntegerType>
  9531. const String::CharPointerType createFromInteger (const IntegerType number)
  9532. {
  9533. juce_wchar buffer [32];
  9534. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9535. juce_wchar* const start = numberToString (end, number);
  9536. return StringHolder::createFromFixedLength (start, end - start - 1);
  9537. }
  9538. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9539. {
  9540. char buffer [48];
  9541. size_t len;
  9542. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9543. return StringHolder::createFromFixedLength (start, len);
  9544. }
  9545. }
  9546. String::String (const int number)
  9547. : text (NumberToStringConverters::createFromInteger (number))
  9548. {
  9549. }
  9550. String::String (const unsigned int number)
  9551. : text (NumberToStringConverters::createFromInteger (number))
  9552. {
  9553. }
  9554. String::String (const short number)
  9555. : text (NumberToStringConverters::createFromInteger ((int) number))
  9556. {
  9557. }
  9558. String::String (const unsigned short number)
  9559. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9560. {
  9561. }
  9562. String::String (const int64 number)
  9563. : text (NumberToStringConverters::createFromInteger (number))
  9564. {
  9565. }
  9566. String::String (const uint64 number)
  9567. : text (NumberToStringConverters::createFromInteger (number))
  9568. {
  9569. }
  9570. String::String (const float number, const int numberOfDecimalPlaces)
  9571. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9572. {
  9573. }
  9574. String::String (const double number, const int numberOfDecimalPlaces)
  9575. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9576. {
  9577. }
  9578. int String::length() const throw()
  9579. {
  9580. return (int) text.length();
  9581. }
  9582. const juce_wchar String::operator[] (int index) const throw()
  9583. {
  9584. jassert (index == 0 || isPositiveAndNotGreaterThan (index, length()));
  9585. return text [index];
  9586. }
  9587. int String::hashCode() const throw()
  9588. {
  9589. CharPointerType t (text);
  9590. int result = 0;
  9591. while (! t.isEmpty())
  9592. result = 31 * result + t.getAndAdvance();
  9593. return result;
  9594. }
  9595. int64 String::hashCode64() const throw()
  9596. {
  9597. CharPointerType t (text);
  9598. int64 result = 0;
  9599. while (! t.isEmpty())
  9600. result = 101 * result + t.getAndAdvance();
  9601. return result;
  9602. }
  9603. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9604. {
  9605. return string1.compare (string2) == 0;
  9606. }
  9607. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9608. {
  9609. return string1.compare (string2) == 0;
  9610. }
  9611. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9612. {
  9613. return string1.compare (string2) == 0;
  9614. }
  9615. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9616. {
  9617. return string1.getCharPointer().compare (string2) == 0;
  9618. }
  9619. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9620. {
  9621. return string1.getCharPointer().compare (string2) == 0;
  9622. }
  9623. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9624. {
  9625. return string1.getCharPointer().compare (string2) == 0;
  9626. }
  9627. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9628. {
  9629. return string1.compare (string2) != 0;
  9630. }
  9631. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9632. {
  9633. return string1.compare (string2) != 0;
  9634. }
  9635. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9636. {
  9637. return string1.compare (string2) != 0;
  9638. }
  9639. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9640. {
  9641. return string1.getCharPointer().compare (string2) != 0;
  9642. }
  9643. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9644. {
  9645. return string1.getCharPointer().compare (string2) != 0;
  9646. }
  9647. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9648. {
  9649. return string1.getCharPointer().compare (string2) != 0;
  9650. }
  9651. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9652. {
  9653. return string1.compare (string2) > 0;
  9654. }
  9655. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9656. {
  9657. return string1.compare (string2) < 0;
  9658. }
  9659. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9660. {
  9661. return string1.compare (string2) >= 0;
  9662. }
  9663. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9664. {
  9665. return string1.compare (string2) <= 0;
  9666. }
  9667. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9668. {
  9669. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9670. : isEmpty();
  9671. }
  9672. bool String::equalsIgnoreCase (const char* t) const throw()
  9673. {
  9674. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9675. : isEmpty();
  9676. }
  9677. bool String::equalsIgnoreCase (const String& other) const throw()
  9678. {
  9679. return text == other.text
  9680. || text.compareIgnoreCase (other.text) == 0;
  9681. }
  9682. int String::compare (const String& other) const throw()
  9683. {
  9684. return (text == other.text) ? 0 : text.compare (other.text);
  9685. }
  9686. int String::compare (const char* other) const throw()
  9687. {
  9688. return text.compare (CharPointer_UTF8 (other));
  9689. }
  9690. int String::compare (const juce_wchar* other) const throw()
  9691. {
  9692. return text.compare (CharPointer_UTF32 (other));
  9693. }
  9694. int String::compareIgnoreCase (const String& other) const throw()
  9695. {
  9696. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9697. }
  9698. int String::compareLexicographically (const String& other) const throw()
  9699. {
  9700. CharPointerType s1 (text);
  9701. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9702. ++s1;
  9703. CharPointerType s2 (other.text);
  9704. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9705. ++s2;
  9706. return s1.compareIgnoreCase (s2);
  9707. }
  9708. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9709. {
  9710. appendCharPointer (textToAppend.text, maxCharsToTake);
  9711. }
  9712. String& String::operator+= (const juce_wchar* const t)
  9713. {
  9714. appendCharPointer (CharPointer_UTF32 (t));
  9715. return *this;
  9716. }
  9717. String& String::operator+= (const String& other)
  9718. {
  9719. if (isEmpty())
  9720. return operator= (other);
  9721. appendCharPointer (other.text);
  9722. return *this;
  9723. }
  9724. String& String::operator+= (const char ch)
  9725. {
  9726. return operator+= ((juce_wchar) ch);
  9727. }
  9728. String& String::operator+= (const juce_wchar ch)
  9729. {
  9730. const juce_wchar asString[] = { ch, 0 };
  9731. return operator+= (static_cast <const juce_wchar*> (asString));
  9732. }
  9733. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9734. String& String::operator+= (const wchar_t ch)
  9735. {
  9736. return operator+= ((juce_wchar) ch);
  9737. }
  9738. String& String::operator+= (const wchar_t* t)
  9739. {
  9740. return operator+= (String (t));
  9741. }
  9742. #endif
  9743. String& String::operator+= (const int number)
  9744. {
  9745. juce_wchar buffer [16];
  9746. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9747. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9748. appendFixedLength (start, (int) (end - start));
  9749. return *this;
  9750. }
  9751. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9752. {
  9753. String s (string1);
  9754. return s += string2;
  9755. }
  9756. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9757. {
  9758. String s (string1);
  9759. return s += string2;
  9760. }
  9761. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9762. {
  9763. return String::charToString (string1) + string2;
  9764. }
  9765. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9766. {
  9767. return String::charToString (string1) + string2;
  9768. }
  9769. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9770. {
  9771. return string1 += string2;
  9772. }
  9773. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9774. {
  9775. return string1 += string2;
  9776. }
  9777. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9778. {
  9779. return string1 += string2;
  9780. }
  9781. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9782. {
  9783. return string1 += string2;
  9784. }
  9785. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9786. {
  9787. return string1 += string2;
  9788. }
  9789. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9790. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9791. {
  9792. return string1 += string2;
  9793. }
  9794. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9795. {
  9796. string1.appendCharPointer (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (string2)));
  9797. return string1;
  9798. }
  9799. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9800. {
  9801. String s (string1);
  9802. return s += string2;
  9803. }
  9804. #endif
  9805. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9806. {
  9807. return string1 += characterToAppend;
  9808. }
  9809. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9810. {
  9811. return string1 += characterToAppend;
  9812. }
  9813. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9814. {
  9815. return string1 += string2;
  9816. }
  9817. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9818. {
  9819. return string1 += string2;
  9820. }
  9821. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9822. {
  9823. return string1 += string2;
  9824. }
  9825. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9826. {
  9827. return string1 += (int) number;
  9828. }
  9829. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9830. {
  9831. return string1 += number;
  9832. }
  9833. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9834. {
  9835. return string1 += (int) number;
  9836. }
  9837. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9838. {
  9839. return string1 += String (number);
  9840. }
  9841. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9842. {
  9843. return string1 += String (number);
  9844. }
  9845. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9846. {
  9847. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9848. // if lots of large, persistent strings were to be written to streams).
  9849. const int numBytes = text.getNumBytesAsUTF8();
  9850. HeapBlock<char> temp (numBytes + 1);
  9851. text.copyToUTF8 (temp, numBytes + 1);
  9852. stream.write (temp, numBytes);
  9853. return stream;
  9854. }
  9855. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9856. {
  9857. return string1 += NewLine::getDefault();
  9858. }
  9859. int String::indexOfChar (const juce_wchar character) const throw()
  9860. {
  9861. return text.indexOf (character);
  9862. }
  9863. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9864. {
  9865. for (int i = length(); --i >= 0;)
  9866. if (text[i] == character)
  9867. return i;
  9868. return -1;
  9869. }
  9870. int String::indexOf (const String& t) const throw()
  9871. {
  9872. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9873. }
  9874. int String::indexOfChar (const int startIndex,
  9875. const juce_wchar character) const throw()
  9876. {
  9877. const int i = (text + startIndex).indexOf (character);
  9878. return i < 0 ? -1 : (i + startIndex);
  9879. }
  9880. int String::indexOfAnyOf (const String& charactersToLookFor,
  9881. const int startIndex,
  9882. const bool ignoreCase) const throw()
  9883. {
  9884. if (startIndex > 0 && startIndex >= length())
  9885. return -1;
  9886. CharPointerType t (text);
  9887. int i = jmax (0, startIndex);
  9888. t += i;
  9889. while (! t.isEmpty())
  9890. {
  9891. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9892. return i;
  9893. ++i;
  9894. ++t;
  9895. }
  9896. return -1;
  9897. }
  9898. int String::indexOf (const int startIndex, const String& other) const throw()
  9899. {
  9900. if (startIndex > 0 && startIndex >= length())
  9901. return -1;
  9902. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9903. return i >= 0 ? i + startIndex : -1;
  9904. }
  9905. int String::indexOfIgnoreCase (const String& other) const throw()
  9906. {
  9907. if (other.isEmpty())
  9908. return 0;
  9909. const int len = other.length();
  9910. const int end = length() - len;
  9911. for (int i = 0; i <= end; ++i)
  9912. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9913. return i;
  9914. return -1;
  9915. }
  9916. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9917. {
  9918. if (other.isNotEmpty())
  9919. {
  9920. const int len = other.length();
  9921. const int end = length() - len;
  9922. for (int i = jmax (0, startIndex); i <= end; ++i)
  9923. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9924. return i;
  9925. }
  9926. return -1;
  9927. }
  9928. int String::lastIndexOf (const String& other) const throw()
  9929. {
  9930. if (other.isNotEmpty())
  9931. {
  9932. const int len = other.length();
  9933. int i = length() - len;
  9934. if (i >= 0)
  9935. {
  9936. CharPointerType n (text + i);
  9937. while (i >= 0)
  9938. {
  9939. if (n.compareUpTo (other.text, len) == 0)
  9940. return i;
  9941. --n;
  9942. --i;
  9943. }
  9944. }
  9945. }
  9946. return -1;
  9947. }
  9948. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9949. {
  9950. if (other.isNotEmpty())
  9951. {
  9952. const int len = other.length();
  9953. int i = length() - len;
  9954. if (i >= 0)
  9955. {
  9956. CharPointerType n (text + i);
  9957. while (i >= 0)
  9958. {
  9959. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9960. return i;
  9961. --n;
  9962. --i;
  9963. }
  9964. }
  9965. }
  9966. return -1;
  9967. }
  9968. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9969. {
  9970. for (int i = length(); --i >= 0;)
  9971. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9972. return i;
  9973. return -1;
  9974. }
  9975. bool String::contains (const String& other) const throw()
  9976. {
  9977. return indexOf (other) >= 0;
  9978. }
  9979. bool String::containsChar (const juce_wchar character) const throw()
  9980. {
  9981. return text.indexOf (character) >= 0;
  9982. }
  9983. bool String::containsIgnoreCase (const String& t) const throw()
  9984. {
  9985. return indexOfIgnoreCase (t) >= 0;
  9986. }
  9987. int String::indexOfWholeWord (const String& word) const throw()
  9988. {
  9989. if (word.isNotEmpty())
  9990. {
  9991. CharPointerType t (text);
  9992. const int wordLen = word.length();
  9993. const int end = (int) t.length() - wordLen;
  9994. for (int i = 0; i <= end; ++i)
  9995. {
  9996. if (t.compareUpTo (word.text, wordLen) == 0
  9997. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9998. && ! (t + wordLen).isLetterOrDigit())
  9999. return i;
  10000. ++t;
  10001. }
  10002. }
  10003. return -1;
  10004. }
  10005. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10006. {
  10007. if (word.isNotEmpty())
  10008. {
  10009. CharPointerType t (text);
  10010. const int wordLen = word.length();
  10011. const int end = (int) t.length() - wordLen;
  10012. for (int i = 0; i <= end; ++i)
  10013. {
  10014. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  10015. && (i == 0 || ! (t + -1).isLetterOrDigit())
  10016. && ! (t + wordLen).isLetterOrDigit())
  10017. return i;
  10018. ++t;
  10019. }
  10020. }
  10021. return -1;
  10022. }
  10023. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10024. {
  10025. return indexOfWholeWord (wordToLookFor) >= 0;
  10026. }
  10027. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10028. {
  10029. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10030. }
  10031. namespace WildCardHelpers
  10032. {
  10033. int indexOfMatch (const String::CharPointerType& wildcard,
  10034. String::CharPointerType test,
  10035. const bool ignoreCase) throw()
  10036. {
  10037. int start = 0;
  10038. while (! test.isEmpty())
  10039. {
  10040. String::CharPointerType t (test);
  10041. String::CharPointerType w (wildcard);
  10042. for (;;)
  10043. {
  10044. const juce_wchar wc = *w;
  10045. const juce_wchar tc = *t;
  10046. if (wc == tc
  10047. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  10048. || (wc == '?' && tc != 0))
  10049. {
  10050. if (wc == 0)
  10051. return start;
  10052. ++t;
  10053. ++w;
  10054. }
  10055. else
  10056. {
  10057. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  10058. return start;
  10059. break;
  10060. }
  10061. }
  10062. ++start;
  10063. ++test;
  10064. }
  10065. return -1;
  10066. }
  10067. }
  10068. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10069. {
  10070. CharPointerType w (wildcard.text);
  10071. CharPointerType t (text);
  10072. for (;;)
  10073. {
  10074. const juce_wchar wc = *w;
  10075. const juce_wchar tc = *t;
  10076. if (wc == tc
  10077. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  10078. || (wc == '?' && tc != 0))
  10079. {
  10080. if (wc == 0)
  10081. return true;
  10082. ++w;
  10083. ++t;
  10084. }
  10085. else
  10086. {
  10087. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  10088. }
  10089. }
  10090. }
  10091. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10092. {
  10093. if (numberOfTimesToRepeat <= 0)
  10094. return String::empty;
  10095. String result (Preallocation (stringToRepeat.length() * numberOfTimesToRepeat + 1));
  10096. CharPointerType n (result.text);
  10097. while (--numberOfTimesToRepeat >= 0)
  10098. n.writeAll (stringToRepeat.text);
  10099. return result;
  10100. }
  10101. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10102. {
  10103. jassert (padCharacter != 0);
  10104. const int len = length();
  10105. if (len >= minimumLength || padCharacter == 0)
  10106. return *this;
  10107. String result (Preallocation (minimumLength + 1));
  10108. CharPointerType n (result.text);
  10109. minimumLength -= len;
  10110. while (--minimumLength >= 0)
  10111. n.write (padCharacter);
  10112. StringHolder::copyChars (n, text, len);
  10113. return result;
  10114. }
  10115. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10116. {
  10117. jassert (padCharacter != 0);
  10118. const int len = length();
  10119. if (len >= minimumLength || padCharacter == 0)
  10120. return *this;
  10121. String result (*this, (size_t) minimumLength);
  10122. CharPointerType n (result.text + len);
  10123. minimumLength -= len;
  10124. while (--minimumLength >= 0)
  10125. n.write (padCharacter);
  10126. n.writeNull();
  10127. return result;
  10128. }
  10129. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10130. {
  10131. if (index < 0)
  10132. {
  10133. // a negative index to replace from?
  10134. jassertfalse;
  10135. index = 0;
  10136. }
  10137. if (numCharsToReplace < 0)
  10138. {
  10139. // replacing a negative number of characters?
  10140. numCharsToReplace = 0;
  10141. jassertfalse;
  10142. }
  10143. const int len = length();
  10144. if (index + numCharsToReplace > len)
  10145. {
  10146. if (index > len)
  10147. {
  10148. // replacing beyond the end of the string?
  10149. index = len;
  10150. jassertfalse;
  10151. }
  10152. numCharsToReplace = len - index;
  10153. }
  10154. const int newStringLen = stringToInsert.length();
  10155. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10156. if (newTotalLen <= 0)
  10157. return String::empty;
  10158. String result (Preallocation ((size_t) newTotalLen));
  10159. StringHolder::copyChars (result.text, text, index);
  10160. if (newStringLen > 0)
  10161. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10162. const int endStringLen = newTotalLen - (index + newStringLen);
  10163. if (endStringLen > 0)
  10164. StringHolder::copyChars (result.text + (index + newStringLen),
  10165. text + (index + numCharsToReplace),
  10166. endStringLen);
  10167. return result;
  10168. }
  10169. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10170. {
  10171. const int stringToReplaceLen = stringToReplace.length();
  10172. const int stringToInsertLen = stringToInsert.length();
  10173. int i = 0;
  10174. String result (*this);
  10175. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10176. : result.indexOf (i, stringToReplace))) >= 0)
  10177. {
  10178. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10179. i += stringToInsertLen;
  10180. }
  10181. return result;
  10182. }
  10183. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10184. {
  10185. const int index = indexOfChar (charToReplace);
  10186. if (index < 0)
  10187. return *this;
  10188. String result (*this, size_t());
  10189. CharPointerType t (result.text + index);
  10190. while (! t.isEmpty())
  10191. {
  10192. if (*t == charToReplace)
  10193. t.replaceChar (charToInsert);
  10194. ++t;
  10195. }
  10196. return result;
  10197. }
  10198. const String String::replaceCharacters (const String& charactersToReplace,
  10199. const String& charactersToInsertInstead) const
  10200. {
  10201. String result (*this, size_t());
  10202. CharPointerType t (result.text);
  10203. const int len2 = charactersToInsertInstead.length();
  10204. // the two strings passed in are supposed to be the same length!
  10205. jassert (len2 == charactersToReplace.length());
  10206. while (! t.isEmpty())
  10207. {
  10208. const int index = charactersToReplace.indexOfChar (*t);
  10209. if (isPositiveAndBelow (index, len2))
  10210. t.replaceChar (charactersToInsertInstead [index]);
  10211. ++t;
  10212. }
  10213. return result;
  10214. }
  10215. bool String::startsWith (const String& other) const throw()
  10216. {
  10217. return text.compareUpTo (other.text, other.length()) == 0;
  10218. }
  10219. bool String::startsWithIgnoreCase (const String& other) const throw()
  10220. {
  10221. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10222. }
  10223. bool String::startsWithChar (const juce_wchar character) const throw()
  10224. {
  10225. jassert (character != 0); // strings can't contain a null character!
  10226. return text[0] == character;
  10227. }
  10228. bool String::endsWithChar (const juce_wchar character) const throw()
  10229. {
  10230. jassert (character != 0); // strings can't contain a null character!
  10231. return text[0] != 0
  10232. && text [length() - 1] == character;
  10233. }
  10234. bool String::endsWith (const String& other) const throw()
  10235. {
  10236. const int thisLen = length();
  10237. const int otherLen = other.length();
  10238. return thisLen >= otherLen
  10239. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10240. }
  10241. bool String::endsWithIgnoreCase (const String& other) const throw()
  10242. {
  10243. const int thisLen = length();
  10244. const int otherLen = other.length();
  10245. return thisLen >= otherLen
  10246. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10247. }
  10248. const String String::toUpperCase() const
  10249. {
  10250. String result (Preallocation (this->length()));
  10251. CharPointerType dest (result.text);
  10252. CharPointerType src (text);
  10253. for (;;)
  10254. {
  10255. const juce_wchar c = src.toUpperCase();
  10256. dest.write (c);
  10257. if (c == 0)
  10258. break;
  10259. ++src;
  10260. }
  10261. return result;
  10262. }
  10263. const String String::toLowerCase() const
  10264. {
  10265. String result (Preallocation (this->length()));
  10266. CharPointerType dest (result.text);
  10267. CharPointerType src (text);
  10268. for (;;)
  10269. {
  10270. const juce_wchar c = src.toLowerCase();
  10271. dest.write (c);
  10272. if (c == 0)
  10273. break;
  10274. ++src;
  10275. }
  10276. return result;
  10277. }
  10278. juce_wchar String::getLastCharacter() const throw()
  10279. {
  10280. return isEmpty() ? juce_wchar() : text [length() - 1];
  10281. }
  10282. const String String::substring (int start, int end) const
  10283. {
  10284. if (start < 0)
  10285. start = 0;
  10286. else if (end <= start)
  10287. return empty;
  10288. int len = 0;
  10289. while (len <= end && text [len] != 0)
  10290. ++len;
  10291. if (end >= len)
  10292. {
  10293. if (start == 0)
  10294. return *this;
  10295. end = len;
  10296. }
  10297. return String (text + start, end - start);
  10298. }
  10299. const String String::substring (const int start) const
  10300. {
  10301. if (start <= 0)
  10302. return *this;
  10303. const int len = length();
  10304. if (start >= len)
  10305. return empty;
  10306. return String (text + start, len - start);
  10307. }
  10308. const String String::dropLastCharacters (const int numberToDrop) const
  10309. {
  10310. return String (text, jmax (0, length() - numberToDrop));
  10311. }
  10312. const String String::getLastCharacters (const int numCharacters) const
  10313. {
  10314. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10315. }
  10316. const String String::fromFirstOccurrenceOf (const String& sub,
  10317. const bool includeSubString,
  10318. const bool ignoreCase) const
  10319. {
  10320. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10321. : indexOf (sub);
  10322. if (i < 0)
  10323. return empty;
  10324. return substring (includeSubString ? i : i + sub.length());
  10325. }
  10326. const String String::fromLastOccurrenceOf (const String& sub,
  10327. const bool includeSubString,
  10328. const bool ignoreCase) const
  10329. {
  10330. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10331. : lastIndexOf (sub);
  10332. if (i < 0)
  10333. return *this;
  10334. return substring (includeSubString ? i : i + sub.length());
  10335. }
  10336. const String String::upToFirstOccurrenceOf (const String& sub,
  10337. const bool includeSubString,
  10338. const bool ignoreCase) const
  10339. {
  10340. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10341. : indexOf (sub);
  10342. if (i < 0)
  10343. return *this;
  10344. return substring (0, includeSubString ? i + sub.length() : i);
  10345. }
  10346. const String String::upToLastOccurrenceOf (const String& sub,
  10347. const bool includeSubString,
  10348. const bool ignoreCase) const
  10349. {
  10350. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10351. : lastIndexOf (sub);
  10352. if (i < 0)
  10353. return *this;
  10354. return substring (0, includeSubString ? i + sub.length() : i);
  10355. }
  10356. bool String::isQuotedString() const
  10357. {
  10358. const String trimmed (trimStart());
  10359. return trimmed[0] == '"'
  10360. || trimmed[0] == '\'';
  10361. }
  10362. const String String::unquoted() const
  10363. {
  10364. const int len = length();
  10365. if (len == 0)
  10366. return empty;
  10367. const juce_wchar lastChar = text [len - 1];
  10368. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  10369. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  10370. return substring (dropAtStart, len - dropAtEnd);
  10371. }
  10372. const String String::quoted (const juce_wchar quoteCharacter) const
  10373. {
  10374. if (isEmpty())
  10375. return charToString (quoteCharacter) + quoteCharacter;
  10376. String t (*this);
  10377. if (! t.startsWithChar (quoteCharacter))
  10378. t = charToString (quoteCharacter) + t;
  10379. if (! t.endsWithChar (quoteCharacter))
  10380. t += quoteCharacter;
  10381. return t;
  10382. }
  10383. static String::CharPointerType findTrimmedEnd (const String::CharPointerType& start, String::CharPointerType end)
  10384. {
  10385. while (end > start)
  10386. {
  10387. if (! (--end).isWhitespace())
  10388. {
  10389. ++end;
  10390. break;
  10391. }
  10392. }
  10393. return end;
  10394. }
  10395. const String String::trim() const
  10396. {
  10397. if (isNotEmpty())
  10398. {
  10399. CharPointerType start (text.findEndOfWhitespace());
  10400. const CharPointerType end (start.findTerminatingNull());
  10401. CharPointerType trimmedEnd (findTrimmedEnd (start, end));
  10402. if (trimmedEnd <= start)
  10403. return empty;
  10404. else if (text < start || trimmedEnd < end)
  10405. return String (start, trimmedEnd);
  10406. }
  10407. return *this;
  10408. }
  10409. const String String::trimStart() const
  10410. {
  10411. if (isNotEmpty())
  10412. {
  10413. const CharPointerType t (text.findEndOfWhitespace());
  10414. if (t != text)
  10415. return String (t);
  10416. }
  10417. return *this;
  10418. }
  10419. const String String::trimEnd() const
  10420. {
  10421. if (isNotEmpty())
  10422. {
  10423. const CharPointerType end (text.findTerminatingNull());
  10424. CharPointerType trimmedEnd (findTrimmedEnd (text, end));
  10425. if (trimmedEnd < end)
  10426. return String (text, trimmedEnd);
  10427. }
  10428. return *this;
  10429. }
  10430. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10431. {
  10432. CharPointerType t (text);
  10433. while (charactersToTrim.containsChar (*t))
  10434. ++t;
  10435. return t == text ? *this : String (t);
  10436. }
  10437. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10438. {
  10439. if (isNotEmpty())
  10440. {
  10441. const CharPointerType end (text.findTerminatingNull());
  10442. CharPointerType trimmedEnd (end);
  10443. while (trimmedEnd > text)
  10444. {
  10445. if (! charactersToTrim.containsChar (*--trimmedEnd))
  10446. {
  10447. ++trimmedEnd;
  10448. break;
  10449. }
  10450. }
  10451. if (trimmedEnd < end)
  10452. return String (text, trimmedEnd);
  10453. }
  10454. return *this;
  10455. }
  10456. const String String::retainCharacters (const String& charactersToRetain) const
  10457. {
  10458. if (isEmpty())
  10459. return empty;
  10460. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10461. CharPointerType dst (result.text);
  10462. CharPointerType src (text);
  10463. for (;;)
  10464. {
  10465. const juce_wchar c = src.getAndAdvance();
  10466. if (c == 0)
  10467. break;
  10468. if (charactersToRetain.containsChar (c))
  10469. dst.write (c);
  10470. }
  10471. dst.writeNull();
  10472. return result;
  10473. }
  10474. const String String::removeCharacters (const String& charactersToRemove) const
  10475. {
  10476. if (isEmpty())
  10477. return empty;
  10478. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10479. CharPointerType dst (result.text);
  10480. CharPointerType src (text);
  10481. for (;;)
  10482. {
  10483. const juce_wchar c = src.getAndAdvance();
  10484. if (c == 0)
  10485. break;
  10486. if (! charactersToRemove.containsChar (c))
  10487. dst.write (c);
  10488. }
  10489. dst.writeNull();
  10490. return result;
  10491. }
  10492. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10493. {
  10494. CharPointerType t (text);
  10495. while (! t.isEmpty())
  10496. {
  10497. if (! permittedCharacters.containsChar (*t))
  10498. return String (text, t);
  10499. ++t;
  10500. }
  10501. return *this;
  10502. }
  10503. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10504. {
  10505. CharPointerType t (text);
  10506. while (! t.isEmpty())
  10507. {
  10508. if (charactersToStopAt.containsChar (*t))
  10509. return String (text, t);
  10510. ++t;
  10511. }
  10512. return *this;
  10513. }
  10514. bool String::containsOnly (const String& chars) const throw()
  10515. {
  10516. CharPointerType t (text);
  10517. while (! t.isEmpty())
  10518. if (! chars.containsChar (t.getAndAdvance()))
  10519. return false;
  10520. return true;
  10521. }
  10522. bool String::containsAnyOf (const String& chars) const throw()
  10523. {
  10524. CharPointerType t (text);
  10525. while (! t.isEmpty())
  10526. if (chars.containsChar (t.getAndAdvance()))
  10527. return true;
  10528. return false;
  10529. }
  10530. bool String::containsNonWhitespaceChars() const throw()
  10531. {
  10532. CharPointerType t (text);
  10533. while (! t.isEmpty())
  10534. {
  10535. if (! t.isWhitespace())
  10536. return true;
  10537. ++t;
  10538. }
  10539. return false;
  10540. }
  10541. const String String::formatted (const juce_wchar* const pf, ... )
  10542. {
  10543. jassert (pf != 0);
  10544. va_list args;
  10545. va_start (args, pf);
  10546. size_t bufferSize = 256;
  10547. String result (Preallocation ((size_t) bufferSize));
  10548. result.text[0] = 0;
  10549. for (;;)
  10550. {
  10551. #if JUCE_LINUX && JUCE_64BIT
  10552. va_list tempArgs;
  10553. va_copy (tempArgs, args);
  10554. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10555. va_end (tempArgs);
  10556. #elif JUCE_WINDOWS
  10557. HeapBlock <wchar_t> temp (bufferSize);
  10558. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10559. if (num > 0)
  10560. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10561. #elif JUCE_ANDROID
  10562. HeapBlock <char> temp (bufferSize);
  10563. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10564. if (num > 0)
  10565. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10566. #else
  10567. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10568. #endif
  10569. if (num > 0)
  10570. return result;
  10571. bufferSize += 256;
  10572. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10573. break; // returns -1 because of an error rather than because it needs more space.
  10574. result.preallocateStorage (bufferSize);
  10575. }
  10576. return empty;
  10577. }
  10578. int String::getIntValue() const throw()
  10579. {
  10580. return text.getIntValue32();
  10581. }
  10582. int String::getTrailingIntValue() const throw()
  10583. {
  10584. int n = 0;
  10585. int mult = 1;
  10586. CharPointerType t (text.findTerminatingNull());
  10587. while ((--t).getAddress() >= text)
  10588. {
  10589. if (! t.isDigit())
  10590. {
  10591. if (*t == '-')
  10592. n = -n;
  10593. break;
  10594. }
  10595. n += mult * (*t - '0');
  10596. mult *= 10;
  10597. }
  10598. return n;
  10599. }
  10600. int64 String::getLargeIntValue() const throw()
  10601. {
  10602. return text.getIntValue64();
  10603. }
  10604. float String::getFloatValue() const throw()
  10605. {
  10606. return (float) getDoubleValue();
  10607. }
  10608. double String::getDoubleValue() const throw()
  10609. {
  10610. return text.getDoubleValue();
  10611. }
  10612. static const char* const hexDigits = "0123456789abcdef";
  10613. template <typename Type>
  10614. struct HexConverter
  10615. {
  10616. static const String hexToString (Type v)
  10617. {
  10618. juce_wchar buffer[32];
  10619. juce_wchar* const end = buffer + 32;
  10620. juce_wchar* t = end;
  10621. *--t = 0;
  10622. do
  10623. {
  10624. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10625. v >>= 4;
  10626. } while (v != 0);
  10627. return String (t, (int) (end - t) - 1);
  10628. }
  10629. static Type stringToHex (String::CharPointerType t) throw()
  10630. {
  10631. Type result = 0;
  10632. while (! t.isEmpty())
  10633. {
  10634. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10635. if (hexValue >= 0)
  10636. result = (result << 4) | hexValue;
  10637. }
  10638. return result;
  10639. }
  10640. };
  10641. const String String::toHexString (const int number)
  10642. {
  10643. return HexConverter <unsigned int>::hexToString ((unsigned int) number);
  10644. }
  10645. const String String::toHexString (const int64 number)
  10646. {
  10647. return HexConverter <uint64>::hexToString ((uint64) number);
  10648. }
  10649. const String String::toHexString (const short number)
  10650. {
  10651. return toHexString ((int) (unsigned short) number);
  10652. }
  10653. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10654. {
  10655. if (size <= 0)
  10656. return empty;
  10657. int numChars = (size * 2) + 2;
  10658. if (groupSize > 0)
  10659. numChars += size / groupSize;
  10660. String s (Preallocation ((size_t) numChars));
  10661. CharPointerType dest (s.text);
  10662. for (int i = 0; i < size; ++i)
  10663. {
  10664. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10665. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10666. ++data;
  10667. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10668. dest.write ((juce_wchar) ' ');
  10669. }
  10670. dest.writeNull();
  10671. return s;
  10672. }
  10673. int String::getHexValue32() const throw()
  10674. {
  10675. return HexConverter <int>::stringToHex (text);
  10676. }
  10677. int64 String::getHexValue64() const throw()
  10678. {
  10679. return HexConverter <int64>::stringToHex (text);
  10680. }
  10681. const String String::createStringFromData (const void* const data_, const int size)
  10682. {
  10683. const uint8* const data = static_cast <const uint8*> (data_);
  10684. if (size <= 0 || data == 0)
  10685. {
  10686. return empty;
  10687. }
  10688. else if (size == 1)
  10689. {
  10690. return charToString ((char) data[0]);
  10691. }
  10692. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1
  10693. && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10694. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1
  10695. && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10696. {
  10697. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10698. const int numChars = size / 2 - 1;
  10699. String result;
  10700. result.preallocateStorage (numChars + 2);
  10701. const uint16* const src = (const uint16*) (data + 2);
  10702. CharPointerType dst (result.getCharPointer());
  10703. if (bigEndian)
  10704. {
  10705. for (int i = 0; i < numChars; ++i)
  10706. dst.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  10707. }
  10708. else
  10709. {
  10710. for (int i = 0; i < numChars; ++i)
  10711. dst.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  10712. }
  10713. dst.writeNull();
  10714. return result;
  10715. }
  10716. else
  10717. {
  10718. if (size >= 3
  10719. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10720. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10721. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10722. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10723. return String::fromUTF8 ((const char*) data, size);
  10724. }
  10725. }
  10726. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10727. {
  10728. const int currentLen = length() + 1;
  10729. String& mutableThis = const_cast <String&> (*this);
  10730. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10731. return (mutableThis.text + currentLen).getAddress();
  10732. }
  10733. const CharPointer_UTF8 String::toUTF8() const
  10734. {
  10735. if (isEmpty())
  10736. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10737. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10738. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10739. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10740. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10741. #endif
  10742. CharPointer_UTF8 (extraSpace).writeAll (text);
  10743. return extraSpace;
  10744. }
  10745. CharPointer_UTF16 String::toUTF16() const
  10746. {
  10747. if (isEmpty())
  10748. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10749. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10750. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10751. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10752. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10753. #endif
  10754. CharPointer_UTF16 (extraSpace).writeAll (text);
  10755. return extraSpace;
  10756. }
  10757. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10758. {
  10759. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10760. if (buffer == 0)
  10761. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10762. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10763. }
  10764. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10765. {
  10766. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10767. if (buffer == 0)
  10768. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10769. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10770. }
  10771. int String::getNumBytesAsUTF8() const throw()
  10772. {
  10773. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10774. }
  10775. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10776. {
  10777. if (buffer == 0)
  10778. return empty;
  10779. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10780. : CharPointer_UTF8 (buffer).length());
  10781. String result (Preallocation (len + 1));
  10782. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10783. return result;
  10784. }
  10785. const char* String::toCString() const
  10786. {
  10787. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10788. if (isEmpty())
  10789. return reinterpret_cast <const char*> (text.getAddress());
  10790. const int len = getNumBytesAsCString();
  10791. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10792. wcstombs (extraSpace, text, len);
  10793. extraSpace [len] = 0;
  10794. return extraSpace;
  10795. #else
  10796. return toUTF8();
  10797. #endif
  10798. }
  10799. int String::getNumBytesAsCString() const throw()
  10800. {
  10801. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10802. return (int) wcstombs (0, text, 0);
  10803. #else
  10804. return getNumBytesAsUTF8();
  10805. #endif
  10806. }
  10807. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10808. {
  10809. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10810. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10811. if (destBuffer != 0 && numBytes >= 0)
  10812. destBuffer [numBytes] = 0;
  10813. return numBytes;
  10814. #else
  10815. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10816. #endif
  10817. }
  10818. #if JUCE_MSVC
  10819. #pragma warning (pop)
  10820. #endif
  10821. String::Concatenator::Concatenator (String& stringToAppendTo)
  10822. : result (stringToAppendTo),
  10823. nextIndex (stringToAppendTo.length())
  10824. {
  10825. }
  10826. String::Concatenator::~Concatenator()
  10827. {
  10828. }
  10829. void String::Concatenator::append (const String& s)
  10830. {
  10831. const int len = s.length();
  10832. if (len > 0)
  10833. {
  10834. result.preallocateStorage (nextIndex + len);
  10835. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10836. nextIndex += len;
  10837. }
  10838. }
  10839. #if JUCE_UNIT_TESTS
  10840. class StringTests : public UnitTest
  10841. {
  10842. public:
  10843. StringTests() : UnitTest ("String class") {}
  10844. template <class CharPointerType>
  10845. struct TestUTFConversion
  10846. {
  10847. static void test (UnitTest& test)
  10848. {
  10849. String s (createRandomWideCharString());
  10850. typename CharPointerType::CharType buffer [300];
  10851. memset (buffer, 0xff, sizeof (buffer));
  10852. CharPointerType (buffer).writeAll (s.toUTF32());
  10853. test.expectEquals (String (CharPointerType (buffer)), s);
  10854. memset (buffer, 0xff, sizeof (buffer));
  10855. CharPointerType (buffer).writeAll (s.toUTF16());
  10856. test.expectEquals (String (CharPointerType (buffer)), s);
  10857. memset (buffer, 0xff, sizeof (buffer));
  10858. CharPointerType (buffer).writeAll (s.toUTF8());
  10859. test.expectEquals (String (CharPointerType (buffer)), s);
  10860. }
  10861. };
  10862. static const String createRandomWideCharString()
  10863. {
  10864. juce_wchar buffer [50];
  10865. zerostruct (buffer);
  10866. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10867. {
  10868. if (Random::getSystemRandom().nextBool())
  10869. {
  10870. do
  10871. {
  10872. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10873. }
  10874. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  10875. }
  10876. else
  10877. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10878. }
  10879. return buffer;
  10880. }
  10881. void runTest()
  10882. {
  10883. {
  10884. beginTest ("Basics");
  10885. expect (String().length() == 0);
  10886. expect (String() == String::empty);
  10887. String s1, s2 ("abcd");
  10888. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10889. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10890. expect (s2.length() == 4);
  10891. s1 = "abcd";
  10892. expect (s2 == s1 && s1 == s2);
  10893. expect (s1 == "abcd" && s1 == L"abcd");
  10894. expect (String ("abcd") == String (L"abcd"));
  10895. expect (String ("abcdefg", 4) == L"abcd");
  10896. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10897. expect (String::charToString ('x') == "x");
  10898. expect (String::charToString (0) == String::empty);
  10899. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10900. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10901. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10902. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10903. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10904. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10905. expect (s1.indexOf (String::empty) == 0);
  10906. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10907. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10908. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10909. expect (s1.containsChar ('a'));
  10910. expect (! s1.containsChar ('x'));
  10911. expect (! s1.containsChar (0));
  10912. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10913. }
  10914. {
  10915. beginTest ("Operations");
  10916. String s ("012345678");
  10917. expect (s.hashCode() != 0);
  10918. expect (s.hashCode64() != 0);
  10919. expect (s.hashCode() != (s + s).hashCode());
  10920. expect (s.hashCode64() != (s + s).hashCode64());
  10921. expect (s.compare (String ("012345678")) == 0);
  10922. expect (s.compare (String ("012345679")) < 0);
  10923. expect (s.compare (String ("012345676")) > 0);
  10924. expect (s.substring (2, 3) == String::charToString (s[2]));
  10925. expect (s.substring (0, 1) == String::charToString (s[0]));
  10926. expect (s.getLastCharacter() == s [s.length() - 1]);
  10927. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10928. expect (s.substring (0, 3) == L"012");
  10929. expect (s.substring (0, 100) == s);
  10930. expect (s.substring (-1, 100) == s);
  10931. expect (s.substring (3) == "345678");
  10932. expect (s.indexOf (L"45") == 4);
  10933. expect (String ("444445").indexOf ("45") == 4);
  10934. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10935. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10936. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10937. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10938. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10939. expect (s.indexOfChar (L'4') == 4);
  10940. expect (s + s == "012345678012345678");
  10941. expect (s.startsWith (s));
  10942. expect (s.startsWith (s.substring (0, 4)));
  10943. expect (s.startsWith (s.dropLastCharacters (4)));
  10944. expect (s.endsWith (s.substring (5)));
  10945. expect (s.endsWith (s));
  10946. expect (s.contains (s.substring (3, 6)));
  10947. expect (s.contains (s.substring (3)));
  10948. expect (s.startsWithChar (s[0]));
  10949. expect (s.endsWithChar (s.getLastCharacter()));
  10950. expect (s [s.length()] == 0);
  10951. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10952. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10953. String s2 ("123");
  10954. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10955. s2 += "xyz";
  10956. expect (s2 == "1234567890xyz");
  10957. beginTest ("Numeric conversions");
  10958. expect (String::empty.getIntValue() == 0);
  10959. expect (String::empty.getDoubleValue() == 0.0);
  10960. expect (String::empty.getFloatValue() == 0.0f);
  10961. expect (s.getIntValue() == 12345678);
  10962. expect (s.getLargeIntValue() == (int64) 12345678);
  10963. expect (s.getDoubleValue() == 12345678.0);
  10964. expect (s.getFloatValue() == 12345678.0f);
  10965. expect (String (-1234).getIntValue() == -1234);
  10966. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10967. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10968. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10969. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10970. expect (s.getHexValue32() == 0x12345678);
  10971. expect (s.getHexValue64() == (int64) 0x12345678);
  10972. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10973. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10974. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10975. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10976. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10977. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10978. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10979. beginTest ("Subsections");
  10980. String s3;
  10981. s3 = "abcdeFGHIJ";
  10982. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10983. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10984. expect (s3.containsIgnoreCase (s3.substring (3)));
  10985. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10986. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10987. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10988. expect (s3.containsAnyOf (L"zzzFs"));
  10989. expect (s3.startsWith ("abcd"));
  10990. expect (s3.startsWithIgnoreCase (L"abCD"));
  10991. expect (s3.startsWith (String::empty));
  10992. expect (s3.startsWithChar ('a'));
  10993. expect (s3.endsWith (String ("HIJ")));
  10994. expect (s3.endsWithIgnoreCase (L"Hij"));
  10995. expect (s3.endsWith (String::empty));
  10996. expect (s3.endsWithChar (L'J'));
  10997. expect (s3.indexOf ("HIJ") == 7);
  10998. expect (s3.indexOf (L"HIJK") == -1);
  10999. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11000. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11001. String s4 (s3);
  11002. s4.append (String ("xyz123"), 3);
  11003. expect (s4 == s3 + "xyz");
  11004. expect (String (1234) < String (1235));
  11005. expect (String (1235) > String (1234));
  11006. expect (String (1234) >= String (1234));
  11007. expect (String (1234) <= String (1234));
  11008. expect (String (1235) >= String (1234));
  11009. expect (String (1234) <= String (1235));
  11010. String s5 ("word word2 word3");
  11011. expect (s5.containsWholeWord (String ("word2")));
  11012. expect (s5.indexOfWholeWord ("word2") == 5);
  11013. expect (s5.containsWholeWord (L"word"));
  11014. expect (s5.containsWholeWord ("word3"));
  11015. expect (s5.containsWholeWord (s5));
  11016. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11017. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11018. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11019. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11020. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11021. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11022. expect (s5.containsNonWhitespaceChars());
  11023. expect (s5.containsOnly ("ordw23 "));
  11024. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11025. expect (s5.matchesWildcard (L"wor*", false));
  11026. expect (s5.matchesWildcard ("wOr*", true));
  11027. expect (s5.matchesWildcard (L"*word3", true));
  11028. expect (s5.matchesWildcard ("*word?", true));
  11029. expect (s5.matchesWildcard (L"Word*3", true));
  11030. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  11031. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  11032. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  11033. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  11034. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  11035. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  11036. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  11037. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  11038. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  11039. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  11040. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  11041. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  11042. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11043. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  11044. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  11045. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  11046. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  11047. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  11048. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  11049. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  11050. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  11051. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  11052. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  11053. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  11054. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  11055. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  11056. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11057. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11058. expect (s5.replace ("Word", "", true) == " 2 3");
  11059. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  11060. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11061. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  11062. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11063. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  11064. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  11065. expect (s5.retainCharacters (String::empty).isEmpty());
  11066. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11067. expectEquals (s5.removeCharacters (String::empty), s5);
  11068. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11069. expect (String ("word").initialSectionContainingOnly ("word") == L"word");
  11070. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  11071. expectEquals (s5.initialSectionNotContaining (String (";[:'/")), s5);
  11072. expect (! s5.isQuotedString());
  11073. expect (s5.quoted().isQuotedString());
  11074. expect (! s5.quoted().unquoted().isQuotedString());
  11075. expect (! String ("x'").isQuotedString());
  11076. expect (String ("'x").isQuotedString());
  11077. String s6 (" \t xyz \t\r\n");
  11078. expectEquals (s6.trim(), String ("xyz"));
  11079. expect (s6.trim().trim() == "xyz");
  11080. expectEquals (s5.trim(), s5);
  11081. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  11082. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  11083. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  11084. expect (s6.trimStart() != s6.trimEnd());
  11085. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  11086. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11087. }
  11088. {
  11089. beginTest ("UTF conversions");
  11090. TestUTFConversion <CharPointer_UTF32>::test (*this);
  11091. TestUTFConversion <CharPointer_UTF8>::test (*this);
  11092. TestUTFConversion <CharPointer_UTF16>::test (*this);
  11093. }
  11094. {
  11095. beginTest ("StringArray");
  11096. StringArray s;
  11097. for (int i = 5; --i >= 0;)
  11098. s.add (String (i));
  11099. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11100. s.remove (2);
  11101. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11102. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11103. s.clear();
  11104. expectEquals (s.joinIntoString ("x"), String::empty);
  11105. }
  11106. }
  11107. };
  11108. static StringTests stringUnitTests;
  11109. #endif
  11110. END_JUCE_NAMESPACE
  11111. /*** End of inlined file: juce_String.cpp ***/
  11112. /*** Start of inlined file: juce_StringArray.cpp ***/
  11113. BEGIN_JUCE_NAMESPACE
  11114. StringArray::StringArray() throw()
  11115. {
  11116. }
  11117. StringArray::StringArray (const StringArray& other)
  11118. : strings (other.strings)
  11119. {
  11120. }
  11121. StringArray::StringArray (const String& firstValue)
  11122. {
  11123. strings.add (firstValue);
  11124. }
  11125. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11126. const int numberOfStrings)
  11127. {
  11128. for (int i = 0; i < numberOfStrings; ++i)
  11129. strings.add (initialStrings [i]);
  11130. }
  11131. StringArray::StringArray (const char* const* const initialStrings,
  11132. const int numberOfStrings)
  11133. {
  11134. for (int i = 0; i < numberOfStrings; ++i)
  11135. strings.add (initialStrings [i]);
  11136. }
  11137. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11138. {
  11139. int i = 0;
  11140. while (initialStrings[i] != 0)
  11141. strings.add (initialStrings [i++]);
  11142. }
  11143. StringArray::StringArray (const char* const* const initialStrings)
  11144. {
  11145. int i = 0;
  11146. while (initialStrings[i] != 0)
  11147. strings.add (initialStrings [i++]);
  11148. }
  11149. StringArray& StringArray::operator= (const StringArray& other)
  11150. {
  11151. strings = other.strings;
  11152. return *this;
  11153. }
  11154. StringArray::~StringArray()
  11155. {
  11156. }
  11157. bool StringArray::operator== (const StringArray& other) const throw()
  11158. {
  11159. if (other.size() != size())
  11160. return false;
  11161. for (int i = size(); --i >= 0;)
  11162. if (other.strings.getReference(i) != strings.getReference(i))
  11163. return false;
  11164. return true;
  11165. }
  11166. bool StringArray::operator!= (const StringArray& other) const throw()
  11167. {
  11168. return ! operator== (other);
  11169. }
  11170. void StringArray::clear()
  11171. {
  11172. strings.clear();
  11173. }
  11174. const String& StringArray::operator[] (const int index) const throw()
  11175. {
  11176. if (isPositiveAndBelow (index, strings.size()))
  11177. return strings.getReference (index);
  11178. return String::empty;
  11179. }
  11180. String& StringArray::getReference (const int index) throw()
  11181. {
  11182. jassert (isPositiveAndBelow (index, strings.size()));
  11183. return strings.getReference (index);
  11184. }
  11185. void StringArray::add (const String& newString)
  11186. {
  11187. strings.add (newString);
  11188. }
  11189. void StringArray::insert (const int index, const String& newString)
  11190. {
  11191. strings.insert (index, newString);
  11192. }
  11193. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11194. {
  11195. if (! contains (newString, ignoreCase))
  11196. add (newString);
  11197. }
  11198. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11199. {
  11200. if (startIndex < 0)
  11201. {
  11202. jassertfalse;
  11203. startIndex = 0;
  11204. }
  11205. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11206. numElementsToAdd = otherArray.size() - startIndex;
  11207. while (--numElementsToAdd >= 0)
  11208. strings.add (otherArray.strings.getReference (startIndex++));
  11209. }
  11210. void StringArray::set (const int index, const String& newString)
  11211. {
  11212. strings.set (index, newString);
  11213. }
  11214. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11215. {
  11216. if (ignoreCase)
  11217. {
  11218. for (int i = size(); --i >= 0;)
  11219. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11220. return true;
  11221. }
  11222. else
  11223. {
  11224. for (int i = size(); --i >= 0;)
  11225. if (stringToLookFor == strings.getReference(i))
  11226. return true;
  11227. }
  11228. return false;
  11229. }
  11230. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11231. {
  11232. if (i < 0)
  11233. i = 0;
  11234. const int numElements = size();
  11235. if (ignoreCase)
  11236. {
  11237. while (i < numElements)
  11238. {
  11239. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11240. return i;
  11241. ++i;
  11242. }
  11243. }
  11244. else
  11245. {
  11246. while (i < numElements)
  11247. {
  11248. if (stringToLookFor == strings.getReference (i))
  11249. return i;
  11250. ++i;
  11251. }
  11252. }
  11253. return -1;
  11254. }
  11255. void StringArray::remove (const int index)
  11256. {
  11257. strings.remove (index);
  11258. }
  11259. void StringArray::removeString (const String& stringToRemove,
  11260. const bool ignoreCase)
  11261. {
  11262. if (ignoreCase)
  11263. {
  11264. for (int i = size(); --i >= 0;)
  11265. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11266. strings.remove (i);
  11267. }
  11268. else
  11269. {
  11270. for (int i = size(); --i >= 0;)
  11271. if (stringToRemove == strings.getReference (i))
  11272. strings.remove (i);
  11273. }
  11274. }
  11275. void StringArray::removeRange (int startIndex, int numberToRemove)
  11276. {
  11277. strings.removeRange (startIndex, numberToRemove);
  11278. }
  11279. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11280. {
  11281. if (removeWhitespaceStrings)
  11282. {
  11283. for (int i = size(); --i >= 0;)
  11284. if (! strings.getReference(i).containsNonWhitespaceChars())
  11285. strings.remove (i);
  11286. }
  11287. else
  11288. {
  11289. for (int i = size(); --i >= 0;)
  11290. if (strings.getReference(i).isEmpty())
  11291. strings.remove (i);
  11292. }
  11293. }
  11294. void StringArray::trim()
  11295. {
  11296. for (int i = size(); --i >= 0;)
  11297. {
  11298. String& s = strings.getReference(i);
  11299. s = s.trim();
  11300. }
  11301. }
  11302. class InternalStringArrayComparator_CaseSensitive
  11303. {
  11304. public:
  11305. static int compareElements (String& first, String& second) { return first.compare (second); }
  11306. };
  11307. class InternalStringArrayComparator_CaseInsensitive
  11308. {
  11309. public:
  11310. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11311. };
  11312. void StringArray::sort (const bool ignoreCase)
  11313. {
  11314. if (ignoreCase)
  11315. {
  11316. InternalStringArrayComparator_CaseInsensitive comp;
  11317. strings.sort (comp);
  11318. }
  11319. else
  11320. {
  11321. InternalStringArrayComparator_CaseSensitive comp;
  11322. strings.sort (comp);
  11323. }
  11324. }
  11325. void StringArray::move (const int currentIndex, int newIndex) throw()
  11326. {
  11327. strings.move (currentIndex, newIndex);
  11328. }
  11329. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11330. {
  11331. const int last = (numberToJoin < 0) ? size()
  11332. : jmin (size(), start + numberToJoin);
  11333. if (start < 0)
  11334. start = 0;
  11335. if (start >= last)
  11336. return String::empty;
  11337. if (start == last - 1)
  11338. return strings.getReference (start);
  11339. const int separatorLen = separator.length();
  11340. int charsNeeded = separatorLen * (last - start - 1);
  11341. for (int i = start; i < last; ++i)
  11342. charsNeeded += strings.getReference(i).length();
  11343. String result;
  11344. result.preallocateStorage (charsNeeded);
  11345. String::CharPointerType dest (result.getCharPointer());
  11346. while (start < last)
  11347. {
  11348. const String& s = strings.getReference (start);
  11349. if (! s.isEmpty())
  11350. dest.writeAll (s.getCharPointer());
  11351. if (++start < last && separatorLen > 0)
  11352. dest.writeAll (separator.getCharPointer());
  11353. }
  11354. dest.writeNull();
  11355. return result;
  11356. }
  11357. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11358. {
  11359. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11360. }
  11361. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11362. {
  11363. int num = 0;
  11364. if (text.isNotEmpty())
  11365. {
  11366. bool insideQuotes = false;
  11367. juce_wchar currentQuoteChar = 0;
  11368. String::CharPointerType t (text.getCharPointer());
  11369. String::CharPointerType tokenStart (t);
  11370. int numChars = 0;
  11371. for (;;)
  11372. {
  11373. const juce_wchar c = t.getAndAdvance();
  11374. ++numChars;
  11375. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11376. if (! isBreak)
  11377. {
  11378. if (quoteCharacters.containsChar (c))
  11379. {
  11380. if (insideQuotes)
  11381. {
  11382. // only break out of quotes-mode if we find a matching quote to the
  11383. // one that we opened with..
  11384. if (currentQuoteChar == c)
  11385. insideQuotes = false;
  11386. }
  11387. else
  11388. {
  11389. insideQuotes = true;
  11390. currentQuoteChar = c;
  11391. }
  11392. }
  11393. }
  11394. else
  11395. {
  11396. add (String (tokenStart, numChars - 1));
  11397. ++num;
  11398. tokenStart = t;
  11399. numChars = 0;
  11400. }
  11401. if (c == 0)
  11402. break;
  11403. }
  11404. }
  11405. return num;
  11406. }
  11407. int StringArray::addLines (const String& sourceText)
  11408. {
  11409. int numLines = 0;
  11410. String::CharPointerType text (sourceText.getCharPointer());
  11411. bool finished = text.isEmpty();
  11412. while (! finished)
  11413. {
  11414. String::CharPointerType startOfLine (text);
  11415. int numChars = 0;
  11416. for (;;)
  11417. {
  11418. const juce_wchar c = text.getAndAdvance();
  11419. if (c == 0)
  11420. {
  11421. finished = true;
  11422. break;
  11423. }
  11424. if (c == '\n')
  11425. break;
  11426. if (c == '\r')
  11427. {
  11428. if (*text == '\n')
  11429. ++text;
  11430. break;
  11431. }
  11432. ++numChars;
  11433. }
  11434. add (String (startOfLine, numChars));
  11435. ++numLines;
  11436. }
  11437. return numLines;
  11438. }
  11439. void StringArray::removeDuplicates (const bool ignoreCase)
  11440. {
  11441. for (int i = 0; i < size() - 1; ++i)
  11442. {
  11443. const String s (strings.getReference(i));
  11444. int nextIndex = i + 1;
  11445. for (;;)
  11446. {
  11447. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11448. if (nextIndex < 0)
  11449. break;
  11450. strings.remove (nextIndex);
  11451. }
  11452. }
  11453. }
  11454. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11455. const bool appendNumberToFirstInstance,
  11456. CharPointer_UTF8 preNumberString,
  11457. CharPointer_UTF8 postNumberString)
  11458. {
  11459. CharPointer_UTF8 defaultPre (" ("), defaultPost (")");
  11460. if (preNumberString.getAddress() == 0)
  11461. preNumberString = defaultPre;
  11462. if (postNumberString.getAddress() == 0)
  11463. postNumberString = defaultPost;
  11464. for (int i = 0; i < size() - 1; ++i)
  11465. {
  11466. String& s = strings.getReference(i);
  11467. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11468. if (nextIndex >= 0)
  11469. {
  11470. const String original (s);
  11471. int number = 0;
  11472. if (appendNumberToFirstInstance)
  11473. s = original + String (preNumberString) + String (++number) + String (postNumberString);
  11474. else
  11475. ++number;
  11476. while (nextIndex >= 0)
  11477. {
  11478. set (nextIndex, (*this)[nextIndex] + String (preNumberString) + String (++number) + String (postNumberString));
  11479. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11480. }
  11481. }
  11482. }
  11483. }
  11484. void StringArray::minimiseStorageOverheads()
  11485. {
  11486. strings.minimiseStorageOverheads();
  11487. }
  11488. END_JUCE_NAMESPACE
  11489. /*** End of inlined file: juce_StringArray.cpp ***/
  11490. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11491. BEGIN_JUCE_NAMESPACE
  11492. StringPairArray::StringPairArray (const bool ignoreCase_)
  11493. : ignoreCase (ignoreCase_)
  11494. {
  11495. }
  11496. StringPairArray::StringPairArray (const StringPairArray& other)
  11497. : keys (other.keys),
  11498. values (other.values),
  11499. ignoreCase (other.ignoreCase)
  11500. {
  11501. }
  11502. StringPairArray::~StringPairArray()
  11503. {
  11504. }
  11505. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11506. {
  11507. keys = other.keys;
  11508. values = other.values;
  11509. return *this;
  11510. }
  11511. bool StringPairArray::operator== (const StringPairArray& other) const
  11512. {
  11513. for (int i = keys.size(); --i >= 0;)
  11514. if (other [keys[i]] != values[i])
  11515. return false;
  11516. return true;
  11517. }
  11518. bool StringPairArray::operator!= (const StringPairArray& other) const
  11519. {
  11520. return ! operator== (other);
  11521. }
  11522. const String& StringPairArray::operator[] (const String& key) const
  11523. {
  11524. return values [keys.indexOf (key, ignoreCase)];
  11525. }
  11526. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11527. {
  11528. const int i = keys.indexOf (key, ignoreCase);
  11529. if (i >= 0)
  11530. return values[i];
  11531. return defaultReturnValue;
  11532. }
  11533. void StringPairArray::set (const String& key, const String& value)
  11534. {
  11535. const int i = keys.indexOf (key, ignoreCase);
  11536. if (i >= 0)
  11537. {
  11538. values.set (i, value);
  11539. }
  11540. else
  11541. {
  11542. keys.add (key);
  11543. values.add (value);
  11544. }
  11545. }
  11546. void StringPairArray::addArray (const StringPairArray& other)
  11547. {
  11548. for (int i = 0; i < other.size(); ++i)
  11549. set (other.keys[i], other.values[i]);
  11550. }
  11551. void StringPairArray::clear()
  11552. {
  11553. keys.clear();
  11554. values.clear();
  11555. }
  11556. void StringPairArray::remove (const String& key)
  11557. {
  11558. remove (keys.indexOf (key, ignoreCase));
  11559. }
  11560. void StringPairArray::remove (const int index)
  11561. {
  11562. keys.remove (index);
  11563. values.remove (index);
  11564. }
  11565. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11566. {
  11567. ignoreCase = shouldIgnoreCase;
  11568. }
  11569. const String StringPairArray::getDescription() const
  11570. {
  11571. String s;
  11572. for (int i = 0; i < keys.size(); ++i)
  11573. {
  11574. s << keys[i] << " = " << values[i];
  11575. if (i < keys.size())
  11576. s << ", ";
  11577. }
  11578. return s;
  11579. }
  11580. void StringPairArray::minimiseStorageOverheads()
  11581. {
  11582. keys.minimiseStorageOverheads();
  11583. values.minimiseStorageOverheads();
  11584. }
  11585. END_JUCE_NAMESPACE
  11586. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11587. /*** Start of inlined file: juce_StringPool.cpp ***/
  11588. BEGIN_JUCE_NAMESPACE
  11589. StringPool::StringPool() throw() {}
  11590. StringPool::~StringPool() {}
  11591. namespace StringPoolHelpers
  11592. {
  11593. template <class StringType>
  11594. const String::CharPointerType getPooledStringFromArray (Array<String>& strings, StringType newString)
  11595. {
  11596. int start = 0;
  11597. int end = strings.size();
  11598. for (;;)
  11599. {
  11600. if (start >= end)
  11601. {
  11602. jassert (start <= end);
  11603. strings.insert (start, newString);
  11604. return strings.getReference (start).getCharPointer();
  11605. }
  11606. else
  11607. {
  11608. const String& startString = strings.getReference (start);
  11609. if (startString == newString)
  11610. return startString.getCharPointer();
  11611. const int halfway = (start + end) >> 1;
  11612. if (halfway == start)
  11613. {
  11614. if (startString.compare (newString) < 0)
  11615. ++start;
  11616. strings.insert (start, newString);
  11617. return strings.getReference (start).getCharPointer();
  11618. }
  11619. const int comp = strings.getReference (halfway).compare (newString);
  11620. if (comp == 0)
  11621. return strings.getReference (halfway).getCharPointer();
  11622. else if (comp < 0)
  11623. start = halfway;
  11624. else
  11625. end = halfway;
  11626. }
  11627. }
  11628. }
  11629. }
  11630. const String::CharPointerType StringPool::getPooledString (const String& s)
  11631. {
  11632. if (s.isEmpty())
  11633. return String::empty.getCharPointer();
  11634. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11635. }
  11636. const String::CharPointerType StringPool::getPooledString (const char* const s)
  11637. {
  11638. if (s == 0 || *s == 0)
  11639. return String::empty.getCharPointer();
  11640. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11641. }
  11642. const String::CharPointerType StringPool::getPooledString (const juce_wchar* const s)
  11643. {
  11644. if (s == 0 || *s == 0)
  11645. return String::empty.getCharPointer();
  11646. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11647. }
  11648. int StringPool::size() const throw()
  11649. {
  11650. return strings.size();
  11651. }
  11652. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11653. {
  11654. return strings [index].getCharPointer();
  11655. }
  11656. END_JUCE_NAMESPACE
  11657. /*** End of inlined file: juce_StringPool.cpp ***/
  11658. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11659. BEGIN_JUCE_NAMESPACE
  11660. XmlDocument::XmlDocument (const String& documentText)
  11661. : originalText (documentText),
  11662. input (0),
  11663. ignoreEmptyTextElements (true)
  11664. {
  11665. }
  11666. XmlDocument::XmlDocument (const File& file)
  11667. : input (0),
  11668. ignoreEmptyTextElements (true),
  11669. inputSource (new FileInputSource (file))
  11670. {
  11671. }
  11672. XmlDocument::~XmlDocument()
  11673. {
  11674. }
  11675. XmlElement* XmlDocument::parse (const File& file)
  11676. {
  11677. XmlDocument doc (file);
  11678. return doc.getDocumentElement();
  11679. }
  11680. XmlElement* XmlDocument::parse (const String& xmlData)
  11681. {
  11682. XmlDocument doc (xmlData);
  11683. return doc.getDocumentElement();
  11684. }
  11685. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11686. {
  11687. inputSource = newSource;
  11688. }
  11689. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11690. {
  11691. ignoreEmptyTextElements = shouldBeIgnored;
  11692. }
  11693. namespace XmlIdentifierChars
  11694. {
  11695. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11696. {
  11697. return CharacterFunctions::isLetterOrDigit (c)
  11698. || c == '_' || c == '-' || c == ':' || c == '.';
  11699. }
  11700. bool isIdentifierChar (const juce_wchar c) throw()
  11701. {
  11702. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11703. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11704. : isIdentifierCharSlow (c);
  11705. }
  11706. /*static void generateIdentifierCharConstants()
  11707. {
  11708. uint32 n[8];
  11709. zerostruct (n);
  11710. for (int i = 0; i < 256; ++i)
  11711. if (isIdentifierCharSlow (i))
  11712. n[i >> 5] |= (1 << (i & 31));
  11713. String s;
  11714. for (int i = 0; i < 8; ++i)
  11715. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11716. DBG (s);
  11717. }*/
  11718. }
  11719. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11720. {
  11721. String textToParse (originalText);
  11722. if (textToParse.isEmpty() && inputSource != 0)
  11723. {
  11724. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11725. if (in != 0)
  11726. {
  11727. MemoryOutputStream data;
  11728. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11729. textToParse = data.toString();
  11730. if (! onlyReadOuterDocumentElement)
  11731. originalText = textToParse;
  11732. }
  11733. }
  11734. input = textToParse.getCharPointer();
  11735. lastError = String::empty;
  11736. errorOccurred = false;
  11737. outOfData = false;
  11738. needToLoadDTD = true;
  11739. if (textToParse.isEmpty())
  11740. {
  11741. lastError = "not enough input";
  11742. }
  11743. else
  11744. {
  11745. skipHeader();
  11746. if (input.getAddress() != 0)
  11747. {
  11748. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11749. if (! errorOccurred)
  11750. return result.release();
  11751. }
  11752. else
  11753. {
  11754. lastError = "incorrect xml header";
  11755. }
  11756. }
  11757. return 0;
  11758. }
  11759. const String& XmlDocument::getLastParseError() const throw()
  11760. {
  11761. return lastError;
  11762. }
  11763. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11764. {
  11765. lastError = desc;
  11766. errorOccurred = ! carryOn;
  11767. }
  11768. const String XmlDocument::getFileContents (const String& filename) const
  11769. {
  11770. if (inputSource != 0)
  11771. {
  11772. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11773. if (in != 0)
  11774. return in->readEntireStreamAsString();
  11775. }
  11776. return String::empty;
  11777. }
  11778. juce_wchar XmlDocument::readNextChar() throw()
  11779. {
  11780. if (*input != 0)
  11781. return *input++;
  11782. outOfData = true;
  11783. return 0;
  11784. }
  11785. int XmlDocument::findNextTokenLength() throw()
  11786. {
  11787. int len = 0;
  11788. juce_wchar c = *input;
  11789. while (XmlIdentifierChars::isIdentifierChar (c))
  11790. c = input [++len];
  11791. return len;
  11792. }
  11793. void XmlDocument::skipHeader()
  11794. {
  11795. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11796. if (headerStart >= 0)
  11797. {
  11798. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11799. if (headerEnd < 0)
  11800. return;
  11801. #if JUCE_DEBUG
  11802. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11803. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11804. .fromFirstOccurrenceOf ("=", false, false)
  11805. .fromFirstOccurrenceOf ("\"", false, false)
  11806. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11807. /* If you load an XML document with a non-UTF encoding type, it may have been
  11808. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11809. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11810. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11811. read, use your own code to convert them to a unicode String, and pass that to the
  11812. XML parser.
  11813. */
  11814. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11815. #endif
  11816. input += headerEnd + 2;
  11817. }
  11818. skipNextWhiteSpace();
  11819. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11820. if (docTypeIndex < 0)
  11821. return;
  11822. input += docTypeIndex + 9;
  11823. const String::CharPointerType docType (input);
  11824. int n = 1;
  11825. while (n > 0)
  11826. {
  11827. const juce_wchar c = readNextChar();
  11828. if (outOfData)
  11829. return;
  11830. if (c == '<')
  11831. ++n;
  11832. else if (c == '>')
  11833. --n;
  11834. }
  11835. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11836. }
  11837. void XmlDocument::skipNextWhiteSpace()
  11838. {
  11839. for (;;)
  11840. {
  11841. juce_wchar c = *input;
  11842. while (CharacterFunctions::isWhitespace (c))
  11843. c = *++input;
  11844. if (c == 0)
  11845. {
  11846. outOfData = true;
  11847. break;
  11848. }
  11849. else if (c == '<')
  11850. {
  11851. if (input[1] == '!'
  11852. && input[2] == '-'
  11853. && input[3] == '-')
  11854. {
  11855. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11856. if (closeComment < 0)
  11857. {
  11858. outOfData = true;
  11859. break;
  11860. }
  11861. input += closeComment + 3;
  11862. continue;
  11863. }
  11864. else if (input[1] == '?')
  11865. {
  11866. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11867. if (closeBracket < 0)
  11868. {
  11869. outOfData = true;
  11870. break;
  11871. }
  11872. input += closeBracket + 2;
  11873. continue;
  11874. }
  11875. }
  11876. break;
  11877. }
  11878. }
  11879. void XmlDocument::readQuotedString (String& result)
  11880. {
  11881. const juce_wchar quote = readNextChar();
  11882. while (! outOfData)
  11883. {
  11884. const juce_wchar c = readNextChar();
  11885. if (c == quote)
  11886. break;
  11887. if (c == '&')
  11888. {
  11889. --input;
  11890. readEntity (result);
  11891. }
  11892. else
  11893. {
  11894. --input;
  11895. const String::CharPointerType start (input);
  11896. for (;;)
  11897. {
  11898. const juce_wchar character = *input;
  11899. if (character == quote)
  11900. {
  11901. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11902. ++input;
  11903. return;
  11904. }
  11905. else if (character == '&')
  11906. {
  11907. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11908. break;
  11909. }
  11910. else if (character == 0)
  11911. {
  11912. outOfData = true;
  11913. setLastError ("unmatched quotes", false);
  11914. break;
  11915. }
  11916. ++input;
  11917. }
  11918. }
  11919. }
  11920. }
  11921. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11922. {
  11923. XmlElement* node = 0;
  11924. skipNextWhiteSpace();
  11925. if (outOfData)
  11926. return 0;
  11927. const int openBracket = input.indexOf ((juce_wchar) '<');
  11928. if (openBracket >= 0)
  11929. {
  11930. input += openBracket + 1;
  11931. int tagLen = findNextTokenLength();
  11932. if (tagLen == 0)
  11933. {
  11934. // no tag name - but allow for a gap after the '<' before giving an error
  11935. skipNextWhiteSpace();
  11936. tagLen = findNextTokenLength();
  11937. if (tagLen == 0)
  11938. {
  11939. setLastError ("tag name missing", false);
  11940. return node;
  11941. }
  11942. }
  11943. node = new XmlElement (String (input.getAddress(), tagLen));
  11944. input += tagLen;
  11945. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11946. // look for attributes
  11947. for (;;)
  11948. {
  11949. skipNextWhiteSpace();
  11950. const juce_wchar c = *input;
  11951. // empty tag..
  11952. if (c == '/' && input[1] == '>')
  11953. {
  11954. input += 2;
  11955. break;
  11956. }
  11957. // parse the guts of the element..
  11958. if (c == '>')
  11959. {
  11960. ++input;
  11961. if (alsoParseSubElements)
  11962. readChildElements (node);
  11963. break;
  11964. }
  11965. // get an attribute..
  11966. if (XmlIdentifierChars::isIdentifierChar (c))
  11967. {
  11968. const int attNameLen = findNextTokenLength();
  11969. if (attNameLen > 0)
  11970. {
  11971. const String::CharPointerType attNameStart (input);
  11972. input += attNameLen;
  11973. skipNextWhiteSpace();
  11974. if (readNextChar() == '=')
  11975. {
  11976. skipNextWhiteSpace();
  11977. const juce_wchar nextChar = *input;
  11978. if (nextChar == '"' || nextChar == '\'')
  11979. {
  11980. XmlElement::XmlAttributeNode* const newAtt
  11981. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  11982. String::empty);
  11983. readQuotedString (newAtt->value);
  11984. attributeAppender.append (newAtt);
  11985. continue;
  11986. }
  11987. }
  11988. }
  11989. }
  11990. else
  11991. {
  11992. if (! outOfData)
  11993. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11994. }
  11995. break;
  11996. }
  11997. }
  11998. return node;
  11999. }
  12000. void XmlDocument::readChildElements (XmlElement* parent)
  12001. {
  12002. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  12003. for (;;)
  12004. {
  12005. const String::CharPointerType preWhitespaceInput (input);
  12006. skipNextWhiteSpace();
  12007. if (outOfData)
  12008. {
  12009. setLastError ("unmatched tags", false);
  12010. break;
  12011. }
  12012. if (*input == '<')
  12013. {
  12014. if (input[1] == '/')
  12015. {
  12016. // our close tag..
  12017. const int closeTag = input.indexOf ((juce_wchar) '>');
  12018. if (closeTag >= 0)
  12019. input += closeTag + 1;
  12020. break;
  12021. }
  12022. else if (input[1] == '!'
  12023. && input[2] == '['
  12024. && input[3] == 'C'
  12025. && input[4] == 'D'
  12026. && input[5] == 'A'
  12027. && input[6] == 'T'
  12028. && input[7] == 'A'
  12029. && input[8] == '[')
  12030. {
  12031. input += 9;
  12032. const String::CharPointerType inputStart (input);
  12033. int len = 0;
  12034. for (;;)
  12035. {
  12036. if (*input == 0)
  12037. {
  12038. setLastError ("unterminated CDATA section", false);
  12039. outOfData = true;
  12040. break;
  12041. }
  12042. else if (input[0] == ']'
  12043. && input[1] == ']'
  12044. && input[2] == '>')
  12045. {
  12046. input += 3;
  12047. break;
  12048. }
  12049. ++input;
  12050. ++len;
  12051. }
  12052. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  12053. }
  12054. else
  12055. {
  12056. // this is some other element, so parse and add it..
  12057. XmlElement* const n = readNextElement (true);
  12058. if (n != 0)
  12059. childAppender.append (n);
  12060. else
  12061. return;
  12062. }
  12063. }
  12064. else // must be a character block
  12065. {
  12066. input = preWhitespaceInput; // roll back to include the leading whitespace
  12067. String textElementContent;
  12068. for (;;)
  12069. {
  12070. const juce_wchar c = *input;
  12071. if (c == '<')
  12072. break;
  12073. if (c == 0)
  12074. {
  12075. setLastError ("unmatched tags", false);
  12076. outOfData = true;
  12077. return;
  12078. }
  12079. if (c == '&')
  12080. {
  12081. String entity;
  12082. readEntity (entity);
  12083. if (entity.startsWithChar ('<') && entity [1] != 0)
  12084. {
  12085. const String::CharPointerType oldInput (input);
  12086. const bool oldOutOfData = outOfData;
  12087. input = entity.getCharPointer();
  12088. outOfData = false;
  12089. for (;;)
  12090. {
  12091. XmlElement* const n = readNextElement (true);
  12092. if (n == 0)
  12093. break;
  12094. childAppender.append (n);
  12095. }
  12096. input = oldInput;
  12097. outOfData = oldOutOfData;
  12098. }
  12099. else
  12100. {
  12101. textElementContent += entity;
  12102. }
  12103. }
  12104. else
  12105. {
  12106. const String::CharPointerType start (input);
  12107. int len = 0;
  12108. for (;;)
  12109. {
  12110. const juce_wchar nextChar = *input;
  12111. if (nextChar == '<' || nextChar == '&')
  12112. {
  12113. break;
  12114. }
  12115. else if (nextChar == 0)
  12116. {
  12117. setLastError ("unmatched tags", false);
  12118. outOfData = true;
  12119. return;
  12120. }
  12121. ++input;
  12122. ++len;
  12123. }
  12124. textElementContent.appendCharPointer (start, len);
  12125. }
  12126. }
  12127. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12128. {
  12129. childAppender.append (XmlElement::createTextElement (textElementContent));
  12130. }
  12131. }
  12132. }
  12133. }
  12134. void XmlDocument::readEntity (String& result)
  12135. {
  12136. // skip over the ampersand
  12137. ++input;
  12138. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12139. {
  12140. input += 4;
  12141. result += '&';
  12142. }
  12143. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12144. {
  12145. input += 5;
  12146. result += '"';
  12147. }
  12148. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12149. {
  12150. input += 5;
  12151. result += '\'';
  12152. }
  12153. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12154. {
  12155. input += 3;
  12156. result += '<';
  12157. }
  12158. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12159. {
  12160. input += 3;
  12161. result += '>';
  12162. }
  12163. else if (*input == '#')
  12164. {
  12165. int charCode = 0;
  12166. ++input;
  12167. if (*input == 'x' || *input == 'X')
  12168. {
  12169. ++input;
  12170. int numChars = 0;
  12171. while (input[0] != ';')
  12172. {
  12173. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12174. if (hexValue < 0 || ++numChars > 8)
  12175. {
  12176. setLastError ("illegal escape sequence", true);
  12177. break;
  12178. }
  12179. charCode = (charCode << 4) | hexValue;
  12180. ++input;
  12181. }
  12182. ++input;
  12183. }
  12184. else if (input[0] >= '0' && input[0] <= '9')
  12185. {
  12186. int numChars = 0;
  12187. while (input[0] != ';')
  12188. {
  12189. if (++numChars > 12)
  12190. {
  12191. setLastError ("illegal escape sequence", true);
  12192. break;
  12193. }
  12194. charCode = charCode * 10 + (input[0] - '0');
  12195. ++input;
  12196. }
  12197. ++input;
  12198. }
  12199. else
  12200. {
  12201. setLastError ("illegal escape sequence", true);
  12202. result += '&';
  12203. return;
  12204. }
  12205. result << (juce_wchar) charCode;
  12206. }
  12207. else
  12208. {
  12209. const String::CharPointerType entityNameStart (input);
  12210. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12211. if (closingSemiColon < 0)
  12212. {
  12213. outOfData = true;
  12214. result += '&';
  12215. }
  12216. else
  12217. {
  12218. input += closingSemiColon + 1;
  12219. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12220. }
  12221. }
  12222. }
  12223. const String XmlDocument::expandEntity (const String& ent)
  12224. {
  12225. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12226. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12227. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12228. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12229. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12230. if (ent[0] == '#')
  12231. {
  12232. if (ent[1] == 'x' || ent[1] == 'X')
  12233. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12234. if (ent[1] >= '0' && ent[1] <= '9')
  12235. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12236. setLastError ("illegal escape sequence", false);
  12237. return String::charToString ('&');
  12238. }
  12239. return expandExternalEntity (ent);
  12240. }
  12241. const String XmlDocument::expandExternalEntity (const String& entity)
  12242. {
  12243. if (needToLoadDTD)
  12244. {
  12245. if (dtdText.isNotEmpty())
  12246. {
  12247. dtdText = dtdText.trimCharactersAtEnd (">");
  12248. tokenisedDTD.addTokens (dtdText, true);
  12249. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12250. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12251. {
  12252. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12253. tokenisedDTD.clear();
  12254. tokenisedDTD.addTokens (getFileContents (fn), true);
  12255. }
  12256. else
  12257. {
  12258. tokenisedDTD.clear();
  12259. const int openBracket = dtdText.indexOfChar ('[');
  12260. if (openBracket > 0)
  12261. {
  12262. const int closeBracket = dtdText.lastIndexOfChar (']');
  12263. if (closeBracket > openBracket)
  12264. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12265. closeBracket), true);
  12266. }
  12267. }
  12268. for (int i = tokenisedDTD.size(); --i >= 0;)
  12269. {
  12270. if (tokenisedDTD[i].startsWithChar ('%')
  12271. && tokenisedDTD[i].endsWithChar (';'))
  12272. {
  12273. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12274. StringArray newToks;
  12275. newToks.addTokens (parsed, true);
  12276. tokenisedDTD.remove (i);
  12277. for (int j = newToks.size(); --j >= 0;)
  12278. tokenisedDTD.insert (i, newToks[j]);
  12279. }
  12280. }
  12281. }
  12282. needToLoadDTD = false;
  12283. }
  12284. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12285. {
  12286. if (tokenisedDTD[i] == entity)
  12287. {
  12288. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12289. {
  12290. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12291. // check for sub-entities..
  12292. int ampersand = ent.indexOfChar ('&');
  12293. while (ampersand >= 0)
  12294. {
  12295. const int semiColon = ent.indexOf (i + 1, ";");
  12296. if (semiColon < 0)
  12297. {
  12298. setLastError ("entity without terminating semi-colon", false);
  12299. break;
  12300. }
  12301. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12302. ent = ent.substring (0, ampersand)
  12303. + resolved
  12304. + ent.substring (semiColon + 1);
  12305. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12306. }
  12307. return ent;
  12308. }
  12309. }
  12310. }
  12311. setLastError ("unknown entity", true);
  12312. return entity;
  12313. }
  12314. const String XmlDocument::getParameterEntity (const String& entity)
  12315. {
  12316. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12317. {
  12318. if (tokenisedDTD[i] == entity
  12319. && tokenisedDTD [i - 1] == "%"
  12320. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12321. {
  12322. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12323. if (ent.equalsIgnoreCase ("system"))
  12324. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12325. else
  12326. return ent.trim().unquoted();
  12327. }
  12328. }
  12329. return entity;
  12330. }
  12331. END_JUCE_NAMESPACE
  12332. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12333. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12334. BEGIN_JUCE_NAMESPACE
  12335. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12336. : name (other.name),
  12337. value (other.value)
  12338. {
  12339. }
  12340. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12341. : name (name_),
  12342. value (value_)
  12343. {
  12344. #if JUCE_DEBUG
  12345. // this checks whether the attribute name string contains any illegal characters..
  12346. for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
  12347. jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
  12348. #endif
  12349. }
  12350. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12351. {
  12352. return name.equalsIgnoreCase (nameToMatch);
  12353. }
  12354. XmlElement::XmlElement (const String& tagName_) throw()
  12355. : tagName (tagName_)
  12356. {
  12357. // the tag name mustn't be empty, or it'll look like a text element!
  12358. jassert (tagName_.containsNonWhitespaceChars())
  12359. // The tag can't contain spaces or other characters that would create invalid XML!
  12360. jassert (! tagName_.containsAnyOf (" <>/&"));
  12361. }
  12362. XmlElement::XmlElement (int /*dummy*/) throw()
  12363. {
  12364. }
  12365. XmlElement::XmlElement (const XmlElement& other)
  12366. : tagName (other.tagName)
  12367. {
  12368. copyChildrenAndAttributesFrom (other);
  12369. }
  12370. XmlElement& XmlElement::operator= (const XmlElement& other)
  12371. {
  12372. if (this != &other)
  12373. {
  12374. removeAllAttributes();
  12375. deleteAllChildElements();
  12376. tagName = other.tagName;
  12377. copyChildrenAndAttributesFrom (other);
  12378. }
  12379. return *this;
  12380. }
  12381. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12382. {
  12383. jassert (firstChildElement.get() == 0);
  12384. firstChildElement.addCopyOfList (other.firstChildElement);
  12385. jassert (attributes.get() == 0);
  12386. attributes.addCopyOfList (other.attributes);
  12387. }
  12388. XmlElement::~XmlElement() throw()
  12389. {
  12390. firstChildElement.deleteAll();
  12391. attributes.deleteAll();
  12392. }
  12393. namespace XmlOutputFunctions
  12394. {
  12395. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12396. {
  12397. if ((character >= 'a' && character <= 'z')
  12398. || (character >= 'A' && character <= 'Z')
  12399. || (character >= '0' && character <= '9'))
  12400. return true;
  12401. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12402. do
  12403. {
  12404. if (((juce_wchar) (uint8) *t) == character)
  12405. return true;
  12406. }
  12407. while (*++t != 0);
  12408. return false;
  12409. }
  12410. void generateLegalCharConstants()
  12411. {
  12412. uint8 n[32];
  12413. zerostruct (n);
  12414. for (int i = 0; i < 256; ++i)
  12415. if (isLegalXmlCharSlow (i))
  12416. n[i >> 3] |= (1 << (i & 7));
  12417. String s;
  12418. for (int i = 0; i < 32; ++i)
  12419. s << (int) n[i] << ", ";
  12420. DBG (s);
  12421. }*/
  12422. bool isLegalXmlChar (const uint32 c) throw()
  12423. {
  12424. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12425. return c < sizeof (legalChars) * 8
  12426. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12427. }
  12428. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12429. {
  12430. String::CharPointerType t (text.getCharPointer());
  12431. for (;;)
  12432. {
  12433. const uint32 character = (uint32) t.getAndAdvance();
  12434. if (character == 0)
  12435. break;
  12436. if (isLegalXmlChar (character))
  12437. {
  12438. outputStream << (char) character;
  12439. }
  12440. else
  12441. {
  12442. switch (character)
  12443. {
  12444. case '&': outputStream << "&amp;"; break;
  12445. case '"': outputStream << "&quot;"; break;
  12446. case '>': outputStream << "&gt;"; break;
  12447. case '<': outputStream << "&lt;"; break;
  12448. case '\n':
  12449. case '\r':
  12450. if (! changeNewLines)
  12451. {
  12452. outputStream << (char) character;
  12453. break;
  12454. }
  12455. // Note: deliberate fall-through here!
  12456. default:
  12457. outputStream << "&#" << ((int) character) << ';';
  12458. break;
  12459. }
  12460. }
  12461. }
  12462. }
  12463. void writeSpaces (OutputStream& out, int numSpaces)
  12464. {
  12465. if (numSpaces > 0)
  12466. {
  12467. const char blanks[] = " ";
  12468. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12469. while (numSpaces > blankSize)
  12470. {
  12471. out.write (blanks, blankSize);
  12472. numSpaces -= blankSize;
  12473. }
  12474. out.write (blanks, numSpaces);
  12475. }
  12476. }
  12477. }
  12478. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12479. const int indentationLevel,
  12480. const int lineWrapLength) const
  12481. {
  12482. using namespace XmlOutputFunctions;
  12483. writeSpaces (outputStream, indentationLevel);
  12484. if (! isTextElement())
  12485. {
  12486. outputStream.writeByte ('<');
  12487. outputStream << tagName;
  12488. {
  12489. const int attIndent = indentationLevel + tagName.length() + 1;
  12490. int lineLen = 0;
  12491. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12492. {
  12493. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12494. {
  12495. outputStream << newLine;
  12496. writeSpaces (outputStream, attIndent);
  12497. lineLen = 0;
  12498. }
  12499. const int64 startPos = outputStream.getPosition();
  12500. outputStream.writeByte (' ');
  12501. outputStream << att->name;
  12502. outputStream.write ("=\"", 2);
  12503. escapeIllegalXmlChars (outputStream, att->value, true);
  12504. outputStream.writeByte ('"');
  12505. lineLen += (int) (outputStream.getPosition() - startPos);
  12506. }
  12507. }
  12508. if (firstChildElement != 0)
  12509. {
  12510. outputStream.writeByte ('>');
  12511. XmlElement* child = firstChildElement;
  12512. bool lastWasTextNode = false;
  12513. while (child != 0)
  12514. {
  12515. if (child->isTextElement())
  12516. {
  12517. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12518. lastWasTextNode = true;
  12519. }
  12520. else
  12521. {
  12522. if (indentationLevel >= 0 && ! lastWasTextNode)
  12523. outputStream << newLine;
  12524. child->writeElementAsText (outputStream,
  12525. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12526. lastWasTextNode = false;
  12527. }
  12528. child = child->getNextElement();
  12529. }
  12530. if (indentationLevel >= 0 && ! lastWasTextNode)
  12531. {
  12532. outputStream << newLine;
  12533. writeSpaces (outputStream, indentationLevel);
  12534. }
  12535. outputStream.write ("</", 2);
  12536. outputStream << tagName;
  12537. outputStream.writeByte ('>');
  12538. }
  12539. else
  12540. {
  12541. outputStream.write ("/>", 2);
  12542. }
  12543. }
  12544. else
  12545. {
  12546. escapeIllegalXmlChars (outputStream, getText(), false);
  12547. }
  12548. }
  12549. const String XmlElement::createDocument (const String& dtdToUse,
  12550. const bool allOnOneLine,
  12551. const bool includeXmlHeader,
  12552. const String& encodingType,
  12553. const int lineWrapLength) const
  12554. {
  12555. MemoryOutputStream mem (2048);
  12556. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12557. return mem.toUTF8();
  12558. }
  12559. void XmlElement::writeToStream (OutputStream& output,
  12560. const String& dtdToUse,
  12561. const bool allOnOneLine,
  12562. const bool includeXmlHeader,
  12563. const String& encodingType,
  12564. const int lineWrapLength) const
  12565. {
  12566. using namespace XmlOutputFunctions;
  12567. if (includeXmlHeader)
  12568. {
  12569. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12570. if (allOnOneLine)
  12571. output.writeByte (' ');
  12572. else
  12573. output << newLine << newLine;
  12574. }
  12575. if (dtdToUse.isNotEmpty())
  12576. {
  12577. output << dtdToUse;
  12578. if (allOnOneLine)
  12579. output.writeByte (' ');
  12580. else
  12581. output << newLine;
  12582. }
  12583. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12584. if (! allOnOneLine)
  12585. output << newLine;
  12586. }
  12587. bool XmlElement::writeToFile (const File& file,
  12588. const String& dtdToUse,
  12589. const String& encodingType,
  12590. const int lineWrapLength) const
  12591. {
  12592. if (file.hasWriteAccess())
  12593. {
  12594. TemporaryFile tempFile (file);
  12595. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12596. if (out != 0)
  12597. {
  12598. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12599. out = 0;
  12600. return tempFile.overwriteTargetFileWithTemporary();
  12601. }
  12602. }
  12603. return false;
  12604. }
  12605. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12606. {
  12607. #if JUCE_DEBUG
  12608. // if debugging, check that the case is actually the same, because
  12609. // valid xml is case-sensitive, and although this lets it pass, it's
  12610. // better not to..
  12611. if (tagName.equalsIgnoreCase (tagNameWanted))
  12612. {
  12613. jassert (tagName == tagNameWanted);
  12614. return true;
  12615. }
  12616. else
  12617. {
  12618. return false;
  12619. }
  12620. #else
  12621. return tagName.equalsIgnoreCase (tagNameWanted);
  12622. #endif
  12623. }
  12624. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12625. {
  12626. XmlElement* e = nextListItem;
  12627. while (e != 0 && ! e->hasTagName (requiredTagName))
  12628. e = e->nextListItem;
  12629. return e;
  12630. }
  12631. int XmlElement::getNumAttributes() const throw()
  12632. {
  12633. return attributes.size();
  12634. }
  12635. const String& XmlElement::getAttributeName (const int index) const throw()
  12636. {
  12637. const XmlAttributeNode* const att = attributes [index];
  12638. return att != 0 ? att->name : String::empty;
  12639. }
  12640. const String& XmlElement::getAttributeValue (const int index) const throw()
  12641. {
  12642. const XmlAttributeNode* const att = attributes [index];
  12643. return att != 0 ? att->value : String::empty;
  12644. }
  12645. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12646. {
  12647. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12648. if (att->hasName (attributeName))
  12649. return true;
  12650. return false;
  12651. }
  12652. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12653. {
  12654. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12655. if (att->hasName (attributeName))
  12656. return att->value;
  12657. return String::empty;
  12658. }
  12659. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12660. {
  12661. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12662. if (att->hasName (attributeName))
  12663. return att->value;
  12664. return defaultReturnValue;
  12665. }
  12666. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12667. {
  12668. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12669. if (att->hasName (attributeName))
  12670. return att->value.getIntValue();
  12671. return defaultReturnValue;
  12672. }
  12673. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12674. {
  12675. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12676. if (att->hasName (attributeName))
  12677. return att->value.getDoubleValue();
  12678. return defaultReturnValue;
  12679. }
  12680. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12681. {
  12682. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12683. {
  12684. if (att->hasName (attributeName))
  12685. {
  12686. juce_wchar firstChar = att->value[0];
  12687. if (CharacterFunctions::isWhitespace (firstChar))
  12688. firstChar = att->value.trimStart() [0];
  12689. return firstChar == '1'
  12690. || firstChar == 't'
  12691. || firstChar == 'y'
  12692. || firstChar == 'T'
  12693. || firstChar == 'Y';
  12694. }
  12695. }
  12696. return defaultReturnValue;
  12697. }
  12698. bool XmlElement::compareAttribute (const String& attributeName,
  12699. const String& stringToCompareAgainst,
  12700. const bool ignoreCase) const throw()
  12701. {
  12702. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12703. if (att->hasName (attributeName))
  12704. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12705. : att->value == stringToCompareAgainst;
  12706. return false;
  12707. }
  12708. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12709. {
  12710. if (attributes == 0)
  12711. {
  12712. attributes = new XmlAttributeNode (attributeName, value);
  12713. }
  12714. else
  12715. {
  12716. XmlAttributeNode* att = attributes;
  12717. for (;;)
  12718. {
  12719. if (att->hasName (attributeName))
  12720. {
  12721. att->value = value;
  12722. break;
  12723. }
  12724. else if (att->nextListItem == 0)
  12725. {
  12726. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12727. break;
  12728. }
  12729. att = att->nextListItem;
  12730. }
  12731. }
  12732. }
  12733. void XmlElement::setAttribute (const String& attributeName, const int number)
  12734. {
  12735. setAttribute (attributeName, String (number));
  12736. }
  12737. void XmlElement::setAttribute (const String& attributeName, const double number)
  12738. {
  12739. setAttribute (attributeName, String (number));
  12740. }
  12741. void XmlElement::removeAttribute (const String& attributeName) throw()
  12742. {
  12743. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12744. while (att->get() != 0)
  12745. {
  12746. if (att->get()->hasName (attributeName))
  12747. {
  12748. delete att->removeNext();
  12749. break;
  12750. }
  12751. att = &(att->get()->nextListItem);
  12752. }
  12753. }
  12754. void XmlElement::removeAllAttributes() throw()
  12755. {
  12756. attributes.deleteAll();
  12757. }
  12758. int XmlElement::getNumChildElements() const throw()
  12759. {
  12760. return firstChildElement.size();
  12761. }
  12762. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12763. {
  12764. return firstChildElement [index].get();
  12765. }
  12766. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12767. {
  12768. XmlElement* child = firstChildElement;
  12769. while (child != 0)
  12770. {
  12771. if (child->hasTagName (childName))
  12772. break;
  12773. child = child->nextListItem;
  12774. }
  12775. return child;
  12776. }
  12777. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12778. {
  12779. if (newNode != 0)
  12780. firstChildElement.append (newNode);
  12781. }
  12782. void XmlElement::insertChildElement (XmlElement* const newNode,
  12783. int indexToInsertAt) throw()
  12784. {
  12785. if (newNode != 0)
  12786. {
  12787. removeChildElement (newNode, false);
  12788. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12789. }
  12790. }
  12791. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12792. {
  12793. XmlElement* const newElement = new XmlElement (childTagName);
  12794. addChildElement (newElement);
  12795. return newElement;
  12796. }
  12797. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12798. XmlElement* const newNode) throw()
  12799. {
  12800. if (newNode != 0)
  12801. {
  12802. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12803. if (p != 0)
  12804. {
  12805. if (currentChildElement != newNode)
  12806. delete p->replaceNext (newNode);
  12807. return true;
  12808. }
  12809. }
  12810. return false;
  12811. }
  12812. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12813. const bool shouldDeleteTheChild) throw()
  12814. {
  12815. if (childToRemove != 0)
  12816. {
  12817. firstChildElement.remove (childToRemove);
  12818. if (shouldDeleteTheChild)
  12819. delete childToRemove;
  12820. }
  12821. }
  12822. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12823. const bool ignoreOrderOfAttributes) const throw()
  12824. {
  12825. if (this != other)
  12826. {
  12827. if (other == 0 || tagName != other->tagName)
  12828. return false;
  12829. if (ignoreOrderOfAttributes)
  12830. {
  12831. int totalAtts = 0;
  12832. const XmlAttributeNode* att = attributes;
  12833. while (att != 0)
  12834. {
  12835. if (! other->compareAttribute (att->name, att->value))
  12836. return false;
  12837. att = att->nextListItem;
  12838. ++totalAtts;
  12839. }
  12840. if (totalAtts != other->getNumAttributes())
  12841. return false;
  12842. }
  12843. else
  12844. {
  12845. const XmlAttributeNode* thisAtt = attributes;
  12846. const XmlAttributeNode* otherAtt = other->attributes;
  12847. for (;;)
  12848. {
  12849. if (thisAtt == 0 || otherAtt == 0)
  12850. {
  12851. if (thisAtt == otherAtt) // both 0, so it's a match
  12852. break;
  12853. return false;
  12854. }
  12855. if (thisAtt->name != otherAtt->name
  12856. || thisAtt->value != otherAtt->value)
  12857. {
  12858. return false;
  12859. }
  12860. thisAtt = thisAtt->nextListItem;
  12861. otherAtt = otherAtt->nextListItem;
  12862. }
  12863. }
  12864. const XmlElement* thisChild = firstChildElement;
  12865. const XmlElement* otherChild = other->firstChildElement;
  12866. for (;;)
  12867. {
  12868. if (thisChild == 0 || otherChild == 0)
  12869. {
  12870. if (thisChild == otherChild) // both 0, so it's a match
  12871. break;
  12872. return false;
  12873. }
  12874. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12875. return false;
  12876. thisChild = thisChild->nextListItem;
  12877. otherChild = otherChild->nextListItem;
  12878. }
  12879. }
  12880. return true;
  12881. }
  12882. void XmlElement::deleteAllChildElements() throw()
  12883. {
  12884. firstChildElement.deleteAll();
  12885. }
  12886. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12887. {
  12888. XmlElement* child = firstChildElement;
  12889. while (child != 0)
  12890. {
  12891. XmlElement* const nextChild = child->nextListItem;
  12892. if (child->hasTagName (name))
  12893. removeChildElement (child, true);
  12894. child = nextChild;
  12895. }
  12896. }
  12897. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12898. {
  12899. return firstChildElement.contains (possibleChild);
  12900. }
  12901. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12902. {
  12903. if (this == elementToLookFor || elementToLookFor == 0)
  12904. return 0;
  12905. XmlElement* child = firstChildElement;
  12906. while (child != 0)
  12907. {
  12908. if (elementToLookFor == child)
  12909. return this;
  12910. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12911. if (found != 0)
  12912. return found;
  12913. child = child->nextListItem;
  12914. }
  12915. return 0;
  12916. }
  12917. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12918. {
  12919. firstChildElement.copyToArray (elems);
  12920. }
  12921. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12922. {
  12923. XmlElement* e = firstChildElement = elems[0];
  12924. for (int i = 1; i < num; ++i)
  12925. {
  12926. e->nextListItem = elems[i];
  12927. e = e->nextListItem;
  12928. }
  12929. e->nextListItem = 0;
  12930. }
  12931. bool XmlElement::isTextElement() const throw()
  12932. {
  12933. return tagName.isEmpty();
  12934. }
  12935. static const String juce_xmltextContentAttributeName ("text");
  12936. const String& XmlElement::getText() const throw()
  12937. {
  12938. jassert (isTextElement()); // you're trying to get the text from an element that
  12939. // isn't actually a text element.. If this contains text sub-nodes, you
  12940. // probably want to use getAllSubText instead.
  12941. return getStringAttribute (juce_xmltextContentAttributeName);
  12942. }
  12943. void XmlElement::setText (const String& newText)
  12944. {
  12945. if (isTextElement())
  12946. setAttribute (juce_xmltextContentAttributeName, newText);
  12947. else
  12948. jassertfalse; // you can only change the text in a text element, not a normal one.
  12949. }
  12950. const String XmlElement::getAllSubText() const
  12951. {
  12952. if (isTextElement())
  12953. return getText();
  12954. String result;
  12955. String::Concatenator concatenator (result);
  12956. const XmlElement* child = firstChildElement;
  12957. while (child != 0)
  12958. {
  12959. concatenator.append (child->getAllSubText());
  12960. child = child->nextListItem;
  12961. }
  12962. return result;
  12963. }
  12964. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12965. const String& defaultReturnValue) const
  12966. {
  12967. const XmlElement* const child = getChildByName (childTagName);
  12968. if (child != 0)
  12969. return child->getAllSubText();
  12970. return defaultReturnValue;
  12971. }
  12972. XmlElement* XmlElement::createTextElement (const String& text)
  12973. {
  12974. XmlElement* const e = new XmlElement ((int) 0);
  12975. e->setAttribute (juce_xmltextContentAttributeName, text);
  12976. return e;
  12977. }
  12978. void XmlElement::addTextElement (const String& text)
  12979. {
  12980. addChildElement (createTextElement (text));
  12981. }
  12982. void XmlElement::deleteAllTextElements() throw()
  12983. {
  12984. XmlElement* child = firstChildElement;
  12985. while (child != 0)
  12986. {
  12987. XmlElement* const next = child->nextListItem;
  12988. if (child->isTextElement())
  12989. removeChildElement (child, true);
  12990. child = next;
  12991. }
  12992. }
  12993. END_JUCE_NAMESPACE
  12994. /*** End of inlined file: juce_XmlElement.cpp ***/
  12995. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12996. BEGIN_JUCE_NAMESPACE
  12997. ReadWriteLock::ReadWriteLock() throw()
  12998. : numWaitingWriters (0),
  12999. numWriters (0),
  13000. writerThreadId (0)
  13001. {
  13002. }
  13003. ReadWriteLock::~ReadWriteLock() throw()
  13004. {
  13005. jassert (readerThreads.size() == 0);
  13006. jassert (numWriters == 0);
  13007. }
  13008. void ReadWriteLock::enterRead() const throw()
  13009. {
  13010. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13011. const ScopedLock sl (accessLock);
  13012. for (;;)
  13013. {
  13014. jassert (readerThreads.size() % 2 == 0);
  13015. int i;
  13016. for (i = 0; i < readerThreads.size(); i += 2)
  13017. if (readerThreads.getUnchecked(i) == threadId)
  13018. break;
  13019. if (i < readerThreads.size()
  13020. || numWriters + numWaitingWriters == 0
  13021. || (threadId == writerThreadId && numWriters > 0))
  13022. {
  13023. if (i < readerThreads.size())
  13024. {
  13025. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13026. }
  13027. else
  13028. {
  13029. readerThreads.add (threadId);
  13030. readerThreads.add ((Thread::ThreadID) 1);
  13031. }
  13032. return;
  13033. }
  13034. const ScopedUnlock ul (accessLock);
  13035. waitEvent.wait (100);
  13036. }
  13037. }
  13038. void ReadWriteLock::exitRead() const throw()
  13039. {
  13040. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13041. const ScopedLock sl (accessLock);
  13042. for (int i = 0; i < readerThreads.size(); i += 2)
  13043. {
  13044. if (readerThreads.getUnchecked(i) == threadId)
  13045. {
  13046. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13047. if (newCount == 0)
  13048. {
  13049. readerThreads.removeRange (i, 2);
  13050. waitEvent.signal();
  13051. }
  13052. else
  13053. {
  13054. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13055. }
  13056. return;
  13057. }
  13058. }
  13059. jassertfalse; // unlocking a lock that wasn't locked..
  13060. }
  13061. void ReadWriteLock::enterWrite() const throw()
  13062. {
  13063. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13064. const ScopedLock sl (accessLock);
  13065. for (;;)
  13066. {
  13067. if (readerThreads.size() + numWriters == 0
  13068. || threadId == writerThreadId
  13069. || (readerThreads.size() == 2
  13070. && readerThreads.getUnchecked(0) == threadId))
  13071. {
  13072. writerThreadId = threadId;
  13073. ++numWriters;
  13074. break;
  13075. }
  13076. ++numWaitingWriters;
  13077. accessLock.exit();
  13078. waitEvent.wait (100);
  13079. accessLock.enter();
  13080. --numWaitingWriters;
  13081. }
  13082. }
  13083. bool ReadWriteLock::tryEnterWrite() const throw()
  13084. {
  13085. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13086. const ScopedLock sl (accessLock);
  13087. if (readerThreads.size() + numWriters == 0
  13088. || threadId == writerThreadId
  13089. || (readerThreads.size() == 2
  13090. && readerThreads.getUnchecked(0) == threadId))
  13091. {
  13092. writerThreadId = threadId;
  13093. ++numWriters;
  13094. return true;
  13095. }
  13096. return false;
  13097. }
  13098. void ReadWriteLock::exitWrite() const throw()
  13099. {
  13100. const ScopedLock sl (accessLock);
  13101. // check this thread actually had the lock..
  13102. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13103. if (--numWriters == 0)
  13104. {
  13105. writerThreadId = 0;
  13106. waitEvent.signal();
  13107. }
  13108. }
  13109. END_JUCE_NAMESPACE
  13110. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13111. /*** Start of inlined file: juce_Thread.cpp ***/
  13112. BEGIN_JUCE_NAMESPACE
  13113. class RunningThreadsList
  13114. {
  13115. public:
  13116. RunningThreadsList()
  13117. {
  13118. }
  13119. void add (Thread* const thread)
  13120. {
  13121. const ScopedLock sl (lock);
  13122. jassert (! threads.contains (thread));
  13123. threads.add (thread);
  13124. }
  13125. void remove (Thread* const thread)
  13126. {
  13127. const ScopedLock sl (lock);
  13128. jassert (threads.contains (thread));
  13129. threads.removeValue (thread);
  13130. }
  13131. int size() const throw()
  13132. {
  13133. return threads.size();
  13134. }
  13135. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13136. {
  13137. const ScopedLock sl (lock);
  13138. for (int i = threads.size(); --i >= 0;)
  13139. {
  13140. Thread* const t = threads.getUnchecked(i);
  13141. if (t->getThreadId() == targetID)
  13142. return t;
  13143. }
  13144. return 0;
  13145. }
  13146. void stopAll (const int timeOutMilliseconds)
  13147. {
  13148. signalAllThreadsToStop();
  13149. for (;;)
  13150. {
  13151. Thread* firstThread = getFirstThread();
  13152. if (firstThread != 0)
  13153. firstThread->stopThread (timeOutMilliseconds);
  13154. else
  13155. break;
  13156. }
  13157. }
  13158. static RunningThreadsList& getInstance()
  13159. {
  13160. static RunningThreadsList runningThreads;
  13161. return runningThreads;
  13162. }
  13163. private:
  13164. Array<Thread*> threads;
  13165. CriticalSection lock;
  13166. void signalAllThreadsToStop()
  13167. {
  13168. const ScopedLock sl (lock);
  13169. for (int i = threads.size(); --i >= 0;)
  13170. threads.getUnchecked(i)->signalThreadShouldExit();
  13171. }
  13172. Thread* getFirstThread() const
  13173. {
  13174. const ScopedLock sl (lock);
  13175. return threads.getFirst();
  13176. }
  13177. };
  13178. void Thread::threadEntryPoint()
  13179. {
  13180. RunningThreadsList::getInstance().add (this);
  13181. JUCE_TRY
  13182. {
  13183. if (threadName_.isNotEmpty())
  13184. setCurrentThreadName (threadName_);
  13185. if (startSuspensionEvent_.wait (10000))
  13186. {
  13187. jassert (getCurrentThreadId() == threadId_);
  13188. if (affinityMask_ != 0)
  13189. setCurrentThreadAffinityMask (affinityMask_);
  13190. run();
  13191. }
  13192. }
  13193. JUCE_CATCH_ALL_ASSERT
  13194. RunningThreadsList::getInstance().remove (this);
  13195. closeThreadHandle();
  13196. }
  13197. // used to wrap the incoming call from the platform-specific code
  13198. void JUCE_API juce_threadEntryPoint (void* userData)
  13199. {
  13200. static_cast <Thread*> (userData)->threadEntryPoint();
  13201. }
  13202. Thread::Thread (const String& threadName)
  13203. : threadName_ (threadName),
  13204. threadHandle_ (0),
  13205. threadId_ (0),
  13206. threadPriority_ (5),
  13207. affinityMask_ (0),
  13208. threadShouldExit_ (false)
  13209. {
  13210. }
  13211. Thread::~Thread()
  13212. {
  13213. /* If your thread class's destructor has been called without first stopping the thread, that
  13214. means that this partially destructed object is still performing some work - and that's
  13215. probably a Bad Thing!
  13216. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13217. your subclass's destructor.
  13218. */
  13219. jassert (! isThreadRunning());
  13220. stopThread (100);
  13221. }
  13222. void Thread::startThread()
  13223. {
  13224. const ScopedLock sl (startStopLock);
  13225. threadShouldExit_ = false;
  13226. if (threadHandle_ == 0)
  13227. {
  13228. launchThread();
  13229. setThreadPriority (threadHandle_, threadPriority_);
  13230. startSuspensionEvent_.signal();
  13231. }
  13232. }
  13233. void Thread::startThread (const int priority)
  13234. {
  13235. const ScopedLock sl (startStopLock);
  13236. if (threadHandle_ == 0)
  13237. {
  13238. threadPriority_ = priority;
  13239. startThread();
  13240. }
  13241. else
  13242. {
  13243. setPriority (priority);
  13244. }
  13245. }
  13246. bool Thread::isThreadRunning() const
  13247. {
  13248. return threadHandle_ != 0;
  13249. }
  13250. void Thread::signalThreadShouldExit()
  13251. {
  13252. threadShouldExit_ = true;
  13253. }
  13254. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13255. {
  13256. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13257. jassert (getThreadId() != getCurrentThreadId());
  13258. const int sleepMsPerIteration = 5;
  13259. int count = timeOutMilliseconds / sleepMsPerIteration;
  13260. while (isThreadRunning())
  13261. {
  13262. if (timeOutMilliseconds > 0 && --count < 0)
  13263. return false;
  13264. sleep (sleepMsPerIteration);
  13265. }
  13266. return true;
  13267. }
  13268. void Thread::stopThread (const int timeOutMilliseconds)
  13269. {
  13270. // agh! You can't stop the thread that's calling this method! How on earth
  13271. // would that work??
  13272. jassert (getCurrentThreadId() != getThreadId());
  13273. const ScopedLock sl (startStopLock);
  13274. if (isThreadRunning())
  13275. {
  13276. signalThreadShouldExit();
  13277. notify();
  13278. if (timeOutMilliseconds != 0)
  13279. waitForThreadToExit (timeOutMilliseconds);
  13280. if (isThreadRunning())
  13281. {
  13282. // very bad karma if this point is reached, as there are bound to be
  13283. // locks and events left in silly states when a thread is killed by force..
  13284. jassertfalse;
  13285. Logger::writeToLog ("!! killing thread by force !!");
  13286. killThread();
  13287. RunningThreadsList::getInstance().remove (this);
  13288. threadHandle_ = 0;
  13289. threadId_ = 0;
  13290. }
  13291. }
  13292. }
  13293. bool Thread::setPriority (const int priority)
  13294. {
  13295. const ScopedLock sl (startStopLock);
  13296. if (setThreadPriority (threadHandle_, priority))
  13297. {
  13298. threadPriority_ = priority;
  13299. return true;
  13300. }
  13301. return false;
  13302. }
  13303. bool Thread::setCurrentThreadPriority (const int priority)
  13304. {
  13305. return setThreadPriority (0, priority);
  13306. }
  13307. void Thread::setAffinityMask (const uint32 affinityMask)
  13308. {
  13309. affinityMask_ = affinityMask;
  13310. }
  13311. bool Thread::wait (const int timeOutMilliseconds) const
  13312. {
  13313. return defaultEvent_.wait (timeOutMilliseconds);
  13314. }
  13315. void Thread::notify() const
  13316. {
  13317. defaultEvent_.signal();
  13318. }
  13319. int Thread::getNumRunningThreads()
  13320. {
  13321. return RunningThreadsList::getInstance().size();
  13322. }
  13323. Thread* Thread::getCurrentThread()
  13324. {
  13325. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13326. }
  13327. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13328. {
  13329. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13330. }
  13331. END_JUCE_NAMESPACE
  13332. /*** End of inlined file: juce_Thread.cpp ***/
  13333. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13334. BEGIN_JUCE_NAMESPACE
  13335. ThreadPoolJob::ThreadPoolJob (const String& name)
  13336. : jobName (name),
  13337. pool (0),
  13338. shouldStop (false),
  13339. isActive (false),
  13340. shouldBeDeleted (false)
  13341. {
  13342. }
  13343. ThreadPoolJob::~ThreadPoolJob()
  13344. {
  13345. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13346. // to remove it first!
  13347. jassert (pool == 0 || ! pool->contains (this));
  13348. }
  13349. const String ThreadPoolJob::getJobName() const
  13350. {
  13351. return jobName;
  13352. }
  13353. void ThreadPoolJob::setJobName (const String& newName)
  13354. {
  13355. jobName = newName;
  13356. }
  13357. void ThreadPoolJob::signalJobShouldExit()
  13358. {
  13359. shouldStop = true;
  13360. }
  13361. class ThreadPool::ThreadPoolThread : public Thread
  13362. {
  13363. public:
  13364. ThreadPoolThread (ThreadPool& pool_)
  13365. : Thread ("Pool"),
  13366. pool (pool_),
  13367. busy (false)
  13368. {
  13369. }
  13370. void run()
  13371. {
  13372. while (! threadShouldExit())
  13373. {
  13374. if (! pool.runNextJob())
  13375. wait (500);
  13376. }
  13377. }
  13378. private:
  13379. ThreadPool& pool;
  13380. bool volatile busy;
  13381. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13382. };
  13383. ThreadPool::ThreadPool (const int numThreads,
  13384. const bool startThreadsOnlyWhenNeeded,
  13385. const int stopThreadsWhenNotUsedTimeoutMs)
  13386. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13387. priority (5)
  13388. {
  13389. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13390. for (int i = jmax (1, numThreads); --i >= 0;)
  13391. threads.add (new ThreadPoolThread (*this));
  13392. if (! startThreadsOnlyWhenNeeded)
  13393. for (int i = threads.size(); --i >= 0;)
  13394. threads.getUnchecked(i)->startThread (priority);
  13395. }
  13396. ThreadPool::~ThreadPool()
  13397. {
  13398. removeAllJobs (true, 4000);
  13399. int i;
  13400. for (i = threads.size(); --i >= 0;)
  13401. threads.getUnchecked(i)->signalThreadShouldExit();
  13402. for (i = threads.size(); --i >= 0;)
  13403. threads.getUnchecked(i)->stopThread (500);
  13404. }
  13405. void ThreadPool::addJob (ThreadPoolJob* const job)
  13406. {
  13407. jassert (job != 0);
  13408. jassert (job->pool == 0);
  13409. if (job->pool == 0)
  13410. {
  13411. job->pool = this;
  13412. job->shouldStop = false;
  13413. job->isActive = false;
  13414. {
  13415. const ScopedLock sl (lock);
  13416. jobs.add (job);
  13417. int numRunning = 0;
  13418. for (int i = threads.size(); --i >= 0;)
  13419. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13420. ++numRunning;
  13421. if (numRunning < threads.size())
  13422. {
  13423. bool startedOne = false;
  13424. int n = 1000;
  13425. while (--n >= 0 && ! startedOne)
  13426. {
  13427. for (int i = threads.size(); --i >= 0;)
  13428. {
  13429. if (! threads.getUnchecked(i)->isThreadRunning())
  13430. {
  13431. threads.getUnchecked(i)->startThread (priority);
  13432. startedOne = true;
  13433. break;
  13434. }
  13435. }
  13436. if (! startedOne)
  13437. Thread::sleep (2);
  13438. }
  13439. }
  13440. }
  13441. for (int i = threads.size(); --i >= 0;)
  13442. threads.getUnchecked(i)->notify();
  13443. }
  13444. }
  13445. int ThreadPool::getNumJobs() const
  13446. {
  13447. return jobs.size();
  13448. }
  13449. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13450. {
  13451. const ScopedLock sl (lock);
  13452. return jobs [index];
  13453. }
  13454. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13455. {
  13456. const ScopedLock sl (lock);
  13457. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13458. }
  13459. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13460. {
  13461. const ScopedLock sl (lock);
  13462. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13463. }
  13464. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13465. const int timeOutMs) const
  13466. {
  13467. if (job != 0)
  13468. {
  13469. const uint32 start = Time::getMillisecondCounter();
  13470. while (contains (job))
  13471. {
  13472. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13473. return false;
  13474. jobFinishedSignal.wait (2);
  13475. }
  13476. }
  13477. return true;
  13478. }
  13479. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13480. const bool interruptIfRunning,
  13481. const int timeOutMs)
  13482. {
  13483. bool dontWait = true;
  13484. if (job != 0)
  13485. {
  13486. const ScopedLock sl (lock);
  13487. if (jobs.contains (job))
  13488. {
  13489. if (job->isActive)
  13490. {
  13491. if (interruptIfRunning)
  13492. job->signalJobShouldExit();
  13493. dontWait = false;
  13494. }
  13495. else
  13496. {
  13497. jobs.removeValue (job);
  13498. job->pool = 0;
  13499. }
  13500. }
  13501. }
  13502. return dontWait || waitForJobToFinish (job, timeOutMs);
  13503. }
  13504. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13505. const int timeOutMs,
  13506. const bool deleteInactiveJobs,
  13507. ThreadPool::JobSelector* selectedJobsToRemove)
  13508. {
  13509. Array <ThreadPoolJob*> jobsToWaitFor;
  13510. {
  13511. const ScopedLock sl (lock);
  13512. for (int i = jobs.size(); --i >= 0;)
  13513. {
  13514. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13515. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13516. {
  13517. if (job->isActive)
  13518. {
  13519. jobsToWaitFor.add (job);
  13520. if (interruptRunningJobs)
  13521. job->signalJobShouldExit();
  13522. }
  13523. else
  13524. {
  13525. jobs.remove (i);
  13526. if (deleteInactiveJobs)
  13527. delete job;
  13528. else
  13529. job->pool = 0;
  13530. }
  13531. }
  13532. }
  13533. }
  13534. const uint32 start = Time::getMillisecondCounter();
  13535. for (;;)
  13536. {
  13537. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13538. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13539. jobsToWaitFor.remove (i);
  13540. if (jobsToWaitFor.size() == 0)
  13541. break;
  13542. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13543. return false;
  13544. jobFinishedSignal.wait (20);
  13545. }
  13546. return true;
  13547. }
  13548. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13549. {
  13550. StringArray s;
  13551. const ScopedLock sl (lock);
  13552. for (int i = 0; i < jobs.size(); ++i)
  13553. {
  13554. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13555. if (job->isActive || ! onlyReturnActiveJobs)
  13556. s.add (job->getJobName());
  13557. }
  13558. return s;
  13559. }
  13560. bool ThreadPool::setThreadPriorities (const int newPriority)
  13561. {
  13562. bool ok = true;
  13563. if (priority != newPriority)
  13564. {
  13565. priority = newPriority;
  13566. for (int i = threads.size(); --i >= 0;)
  13567. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13568. ok = false;
  13569. }
  13570. return ok;
  13571. }
  13572. bool ThreadPool::runNextJob()
  13573. {
  13574. ThreadPoolJob* job = 0;
  13575. {
  13576. const ScopedLock sl (lock);
  13577. for (int i = 0; i < jobs.size(); ++i)
  13578. {
  13579. job = jobs[i];
  13580. if (job != 0 && ! (job->isActive || job->shouldStop))
  13581. break;
  13582. job = 0;
  13583. }
  13584. if (job != 0)
  13585. job->isActive = true;
  13586. }
  13587. if (job != 0)
  13588. {
  13589. JUCE_TRY
  13590. {
  13591. ThreadPoolJob::JobStatus result = job->runJob();
  13592. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13593. const ScopedLock sl (lock);
  13594. if (jobs.contains (job))
  13595. {
  13596. job->isActive = false;
  13597. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13598. {
  13599. job->pool = 0;
  13600. job->shouldStop = true;
  13601. jobs.removeValue (job);
  13602. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13603. delete job;
  13604. jobFinishedSignal.signal();
  13605. }
  13606. else
  13607. {
  13608. // move the job to the end of the queue if it wants another go
  13609. jobs.move (jobs.indexOf (job), -1);
  13610. }
  13611. }
  13612. }
  13613. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13614. catch (...)
  13615. {
  13616. const ScopedLock sl (lock);
  13617. jobs.removeValue (job);
  13618. }
  13619. #endif
  13620. }
  13621. else
  13622. {
  13623. if (threadStopTimeout > 0
  13624. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13625. {
  13626. const ScopedLock sl (lock);
  13627. if (jobs.size() == 0)
  13628. for (int i = threads.size(); --i >= 0;)
  13629. threads.getUnchecked(i)->signalThreadShouldExit();
  13630. }
  13631. else
  13632. {
  13633. return false;
  13634. }
  13635. }
  13636. return true;
  13637. }
  13638. END_JUCE_NAMESPACE
  13639. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13640. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13641. BEGIN_JUCE_NAMESPACE
  13642. TimeSliceThread::TimeSliceThread (const String& threadName)
  13643. : Thread (threadName),
  13644. clientBeingCalled (0)
  13645. {
  13646. }
  13647. TimeSliceThread::~TimeSliceThread()
  13648. {
  13649. stopThread (2000);
  13650. }
  13651. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13652. {
  13653. if (client != 0)
  13654. {
  13655. const ScopedLock sl (listLock);
  13656. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13657. clients.addIfNotAlreadyThere (client);
  13658. notify();
  13659. }
  13660. }
  13661. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13662. {
  13663. const ScopedLock sl1 (listLock);
  13664. // if there's a chance we're in the middle of calling this client, we need to
  13665. // also lock the outer lock..
  13666. if (clientBeingCalled == client)
  13667. {
  13668. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13669. const ScopedLock sl2 (callbackLock);
  13670. const ScopedLock sl3 (listLock);
  13671. clients.removeValue (client);
  13672. }
  13673. else
  13674. {
  13675. clients.removeValue (client);
  13676. }
  13677. }
  13678. int TimeSliceThread::getNumClients() const
  13679. {
  13680. return clients.size();
  13681. }
  13682. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13683. {
  13684. const ScopedLock sl (listLock);
  13685. return clients [i];
  13686. }
  13687. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13688. {
  13689. Time soonest;
  13690. TimeSliceClient* client = 0;
  13691. for (int i = clients.size(); --i >= 0;)
  13692. {
  13693. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13694. if (client == 0 || c->nextCallTime < soonest)
  13695. {
  13696. client = c;
  13697. soonest = c->nextCallTime;
  13698. }
  13699. }
  13700. return client;
  13701. }
  13702. void TimeSliceThread::run()
  13703. {
  13704. int index = 0;
  13705. while (! threadShouldExit())
  13706. {
  13707. int timeToWait = 500;
  13708. {
  13709. Time nextClientTime;
  13710. {
  13711. const ScopedLock sl2 (listLock);
  13712. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13713. TimeSliceClient* const firstClient = getNextClient (index);
  13714. if (firstClient != 0)
  13715. nextClientTime = firstClient->nextCallTime;
  13716. }
  13717. const Time now (Time::getCurrentTime());
  13718. if (nextClientTime > now)
  13719. {
  13720. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13721. }
  13722. else
  13723. {
  13724. timeToWait = index == 0 ? 1 : 0;
  13725. const ScopedLock sl (callbackLock);
  13726. {
  13727. const ScopedLock sl2 (listLock);
  13728. clientBeingCalled = getNextClient (index);
  13729. }
  13730. if (clientBeingCalled != 0)
  13731. {
  13732. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13733. const ScopedLock sl2 (listLock);
  13734. if (msUntilNextCall >= 0)
  13735. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13736. else
  13737. clients.removeValue (clientBeingCalled);
  13738. clientBeingCalled = 0;
  13739. }
  13740. }
  13741. }
  13742. if (timeToWait > 0)
  13743. wait (timeToWait);
  13744. }
  13745. }
  13746. END_JUCE_NAMESPACE
  13747. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13748. #endif
  13749. #if JUCE_BUILD_MISC
  13750. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13751. BEGIN_JUCE_NAMESPACE
  13752. class ValueTree::SetPropertyAction : public UndoableAction
  13753. {
  13754. public:
  13755. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13756. const var& newValue_, const var& oldValue_,
  13757. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13758. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13759. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13760. {
  13761. }
  13762. bool perform()
  13763. {
  13764. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13765. if (isDeletingProperty)
  13766. target->removeProperty (name, 0);
  13767. else
  13768. target->setProperty (name, newValue, 0);
  13769. return true;
  13770. }
  13771. bool undo()
  13772. {
  13773. if (isAddingNewProperty)
  13774. target->removeProperty (name, 0);
  13775. else
  13776. target->setProperty (name, oldValue, 0);
  13777. return true;
  13778. }
  13779. int getSizeInUnits()
  13780. {
  13781. return (int) sizeof (*this); //xxx should be more accurate
  13782. }
  13783. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13784. {
  13785. if (! (isAddingNewProperty || isDeletingProperty))
  13786. {
  13787. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13788. if (next != 0 && next->target == target && next->name == name
  13789. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13790. {
  13791. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13792. }
  13793. }
  13794. return 0;
  13795. }
  13796. private:
  13797. const SharedObjectPtr target;
  13798. const Identifier name;
  13799. const var newValue;
  13800. var oldValue;
  13801. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13802. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13803. };
  13804. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13805. {
  13806. public:
  13807. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13808. const SharedObjectPtr& newChild_)
  13809. : target (target_),
  13810. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13811. childIndex (childIndex_),
  13812. isDeleting (newChild_ == 0)
  13813. {
  13814. jassert (child != 0);
  13815. }
  13816. bool perform()
  13817. {
  13818. if (isDeleting)
  13819. target->removeChild (childIndex, 0);
  13820. else
  13821. target->addChild (child, childIndex, 0);
  13822. return true;
  13823. }
  13824. bool undo()
  13825. {
  13826. if (isDeleting)
  13827. {
  13828. target->addChild (child, childIndex, 0);
  13829. }
  13830. else
  13831. {
  13832. // If you hit this, it seems that your object's state is getting confused - probably
  13833. // because you've interleaved some undoable and non-undoable operations?
  13834. jassert (childIndex < target->children.size());
  13835. target->removeChild (childIndex, 0);
  13836. }
  13837. return true;
  13838. }
  13839. int getSizeInUnits()
  13840. {
  13841. return (int) sizeof (*this); //xxx should be more accurate
  13842. }
  13843. private:
  13844. const SharedObjectPtr target, child;
  13845. const int childIndex;
  13846. const bool isDeleting;
  13847. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13848. };
  13849. class ValueTree::MoveChildAction : public UndoableAction
  13850. {
  13851. public:
  13852. MoveChildAction (const SharedObjectPtr& parent_,
  13853. const int startIndex_, const int endIndex_)
  13854. : parent (parent_),
  13855. startIndex (startIndex_),
  13856. endIndex (endIndex_)
  13857. {
  13858. }
  13859. bool perform()
  13860. {
  13861. parent->moveChild (startIndex, endIndex, 0);
  13862. return true;
  13863. }
  13864. bool undo()
  13865. {
  13866. parent->moveChild (endIndex, startIndex, 0);
  13867. return true;
  13868. }
  13869. int getSizeInUnits()
  13870. {
  13871. return (int) sizeof (*this); //xxx should be more accurate
  13872. }
  13873. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13874. {
  13875. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13876. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13877. return new MoveChildAction (parent, startIndex, next->endIndex);
  13878. return 0;
  13879. }
  13880. private:
  13881. const SharedObjectPtr parent;
  13882. const int startIndex, endIndex;
  13883. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  13884. };
  13885. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13886. : type (type_), parent (0)
  13887. {
  13888. }
  13889. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13890. : type (other.type), properties (other.properties), parent (0)
  13891. {
  13892. for (int i = 0; i < other.children.size(); ++i)
  13893. {
  13894. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13895. child->parent = this;
  13896. children.add (child);
  13897. }
  13898. }
  13899. ValueTree::SharedObject::~SharedObject()
  13900. {
  13901. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13902. for (int i = children.size(); --i >= 0;)
  13903. {
  13904. const SharedObjectPtr c (children.getUnchecked(i));
  13905. c->parent = 0;
  13906. children.remove (i);
  13907. c->sendParentChangeMessage();
  13908. }
  13909. }
  13910. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13911. {
  13912. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13913. {
  13914. ValueTree* const v = valueTreesWithListeners[i];
  13915. if (v != 0)
  13916. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13917. }
  13918. }
  13919. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13920. {
  13921. ValueTree tree (this);
  13922. ValueTree::SharedObject* t = this;
  13923. while (t != 0)
  13924. {
  13925. t->sendPropertyChangeMessage (tree, property);
  13926. t = t->parent;
  13927. }
  13928. }
  13929. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree& tree, ValueTree& child)
  13930. {
  13931. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13932. {
  13933. ValueTree* const v = valueTreesWithListeners[i];
  13934. if (v != 0)
  13935. v->listeners.call (&ValueTree::Listener::valueTreeChildAdded, tree, child);
  13936. }
  13937. }
  13938. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree child)
  13939. {
  13940. ValueTree tree (this);
  13941. ValueTree::SharedObject* t = this;
  13942. while (t != 0)
  13943. {
  13944. t->sendChildAddedMessage (tree, child);
  13945. t = t->parent;
  13946. }
  13947. }
  13948. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree& tree, ValueTree& child)
  13949. {
  13950. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13951. {
  13952. ValueTree* const v = valueTreesWithListeners[i];
  13953. if (v != 0)
  13954. v->listeners.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child);
  13955. }
  13956. }
  13957. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree child)
  13958. {
  13959. ValueTree tree (this);
  13960. ValueTree::SharedObject* t = this;
  13961. while (t != 0)
  13962. {
  13963. t->sendChildRemovedMessage (tree, child);
  13964. t = t->parent;
  13965. }
  13966. }
  13967. void ValueTree::SharedObject::sendChildOrderChangedMessage (ValueTree& tree)
  13968. {
  13969. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13970. {
  13971. ValueTree* const v = valueTreesWithListeners[i];
  13972. if (v != 0)
  13973. v->listeners.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree);
  13974. }
  13975. }
  13976. void ValueTree::SharedObject::sendChildOrderChangedMessage()
  13977. {
  13978. ValueTree tree (this);
  13979. ValueTree::SharedObject* t = this;
  13980. while (t != 0)
  13981. {
  13982. t->sendChildOrderChangedMessage (tree);
  13983. t = t->parent;
  13984. }
  13985. }
  13986. void ValueTree::SharedObject::sendParentChangeMessage()
  13987. {
  13988. ValueTree tree (this);
  13989. int i;
  13990. for (i = children.size(); --i >= 0;)
  13991. {
  13992. SharedObject* const t = children[i];
  13993. if (t != 0)
  13994. t->sendParentChangeMessage();
  13995. }
  13996. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13997. {
  13998. ValueTree* const v = valueTreesWithListeners[i];
  13999. if (v != 0)
  14000. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14001. }
  14002. }
  14003. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14004. {
  14005. return properties [name];
  14006. }
  14007. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14008. {
  14009. return properties.getWithDefault (name, defaultReturnValue);
  14010. }
  14011. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14012. {
  14013. if (undoManager == 0)
  14014. {
  14015. if (properties.set (name, newValue))
  14016. sendPropertyChangeMessage (name);
  14017. }
  14018. else
  14019. {
  14020. var* const existingValue = properties.getVarPointer (name);
  14021. if (existingValue != 0)
  14022. {
  14023. if (*existingValue != newValue)
  14024. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14025. }
  14026. else
  14027. {
  14028. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14029. }
  14030. }
  14031. }
  14032. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14033. {
  14034. return properties.contains (name);
  14035. }
  14036. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14037. {
  14038. if (undoManager == 0)
  14039. {
  14040. if (properties.remove (name))
  14041. sendPropertyChangeMessage (name);
  14042. }
  14043. else
  14044. {
  14045. if (properties.contains (name))
  14046. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14047. }
  14048. }
  14049. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14050. {
  14051. if (undoManager == 0)
  14052. {
  14053. while (properties.size() > 0)
  14054. {
  14055. const Identifier name (properties.getName (properties.size() - 1));
  14056. properties.remove (name);
  14057. sendPropertyChangeMessage (name);
  14058. }
  14059. }
  14060. else
  14061. {
  14062. for (int i = properties.size(); --i >= 0;)
  14063. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14064. }
  14065. }
  14066. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14067. {
  14068. for (int i = 0; i < children.size(); ++i)
  14069. if (children.getUnchecked(i)->type == typeToMatch)
  14070. return ValueTree (children.getUnchecked(i).getObject());
  14071. return ValueTree::invalid;
  14072. }
  14073. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14074. {
  14075. for (int i = 0; i < children.size(); ++i)
  14076. if (children.getUnchecked(i)->type == typeToMatch)
  14077. return ValueTree (children.getUnchecked(i).getObject());
  14078. SharedObject* const newObject = new SharedObject (typeToMatch);
  14079. addChild (newObject, -1, undoManager);
  14080. return ValueTree (newObject);
  14081. }
  14082. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14083. {
  14084. for (int i = 0; i < children.size(); ++i)
  14085. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14086. return ValueTree (children.getUnchecked(i).getObject());
  14087. return ValueTree::invalid;
  14088. }
  14089. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14090. {
  14091. const SharedObject* p = parent;
  14092. while (p != 0)
  14093. {
  14094. if (p == possibleParent)
  14095. return true;
  14096. p = p->parent;
  14097. }
  14098. return false;
  14099. }
  14100. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14101. {
  14102. return children.indexOf (child.object);
  14103. }
  14104. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14105. {
  14106. if (child != 0 && child->parent != this)
  14107. {
  14108. if (child != this && ! isAChildOf (child))
  14109. {
  14110. // You should always make sure that a child is removed from its previous parent before
  14111. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14112. // undomanager should be used when removing it from its current parent..
  14113. jassert (child->parent == 0);
  14114. if (child->parent != 0)
  14115. {
  14116. jassert (child->parent->children.indexOf (child) >= 0);
  14117. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14118. }
  14119. if (undoManager == 0)
  14120. {
  14121. children.insert (index, child);
  14122. child->parent = this;
  14123. sendChildAddedMessage (ValueTree (child));
  14124. child->sendParentChangeMessage();
  14125. }
  14126. else
  14127. {
  14128. if (index < 0)
  14129. index = children.size();
  14130. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14131. }
  14132. }
  14133. else
  14134. {
  14135. // You're attempting to create a recursive loop! A node
  14136. // can't be a child of one of its own children!
  14137. jassertfalse;
  14138. }
  14139. }
  14140. }
  14141. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14142. {
  14143. const SharedObjectPtr child (children [childIndex]);
  14144. if (child != 0)
  14145. {
  14146. if (undoManager == 0)
  14147. {
  14148. children.remove (childIndex);
  14149. child->parent = 0;
  14150. sendChildRemovedMessage (ValueTree (child));
  14151. child->sendParentChangeMessage();
  14152. }
  14153. else
  14154. {
  14155. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14156. }
  14157. }
  14158. }
  14159. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14160. {
  14161. while (children.size() > 0)
  14162. removeChild (children.size() - 1, undoManager);
  14163. }
  14164. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14165. {
  14166. // The source index must be a valid index!
  14167. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14168. if (currentIndex != newIndex
  14169. && isPositiveAndBelow (currentIndex, children.size()))
  14170. {
  14171. if (undoManager == 0)
  14172. {
  14173. children.move (currentIndex, newIndex);
  14174. sendChildOrderChangedMessage();
  14175. }
  14176. else
  14177. {
  14178. if (! isPositiveAndBelow (newIndex, children.size()))
  14179. newIndex = children.size() - 1;
  14180. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14181. }
  14182. }
  14183. }
  14184. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14185. {
  14186. jassert (newOrder.size() == children.size());
  14187. if (undoManager == 0)
  14188. {
  14189. children = newOrder;
  14190. sendChildOrderChangedMessage();
  14191. }
  14192. else
  14193. {
  14194. for (int i = 0; i < children.size(); ++i)
  14195. {
  14196. const SharedObjectPtr child (newOrder.getUnchecked(i));
  14197. if (children.getUnchecked(i) != child)
  14198. {
  14199. const int oldIndex = children.indexOf (child);
  14200. jassert (oldIndex >= 0);
  14201. moveChild (oldIndex, i, undoManager);
  14202. }
  14203. }
  14204. }
  14205. }
  14206. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14207. {
  14208. if (type != other.type
  14209. || properties.size() != other.properties.size()
  14210. || children.size() != other.children.size()
  14211. || properties != other.properties)
  14212. return false;
  14213. for (int i = 0; i < children.size(); ++i)
  14214. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14215. return false;
  14216. return true;
  14217. }
  14218. ValueTree::ValueTree() throw()
  14219. : object (0)
  14220. {
  14221. }
  14222. const ValueTree ValueTree::invalid;
  14223. ValueTree::ValueTree (const Identifier& type_)
  14224. : object (new ValueTree::SharedObject (type_))
  14225. {
  14226. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14227. }
  14228. ValueTree::ValueTree (SharedObject* const object_)
  14229. : object (object_)
  14230. {
  14231. }
  14232. ValueTree::ValueTree (const ValueTree& other)
  14233. : object (other.object)
  14234. {
  14235. }
  14236. ValueTree& ValueTree::operator= (const ValueTree& other)
  14237. {
  14238. if (listeners.size() > 0)
  14239. {
  14240. if (object != 0)
  14241. object->valueTreesWithListeners.removeValue (this);
  14242. if (other.object != 0)
  14243. other.object->valueTreesWithListeners.add (this);
  14244. }
  14245. object = other.object;
  14246. return *this;
  14247. }
  14248. ValueTree::~ValueTree()
  14249. {
  14250. if (listeners.size() > 0 && object != 0)
  14251. object->valueTreesWithListeners.removeValue (this);
  14252. }
  14253. bool ValueTree::operator== (const ValueTree& other) const throw()
  14254. {
  14255. return object == other.object;
  14256. }
  14257. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14258. {
  14259. return object != other.object;
  14260. }
  14261. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14262. {
  14263. return object == other.object
  14264. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14265. }
  14266. ValueTree ValueTree::createCopy() const
  14267. {
  14268. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14269. }
  14270. bool ValueTree::hasType (const Identifier& typeName) const
  14271. {
  14272. return object != 0 && object->type == typeName;
  14273. }
  14274. const Identifier ValueTree::getType() const
  14275. {
  14276. return object != 0 ? object->type : Identifier();
  14277. }
  14278. ValueTree ValueTree::getParent() const
  14279. {
  14280. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14281. }
  14282. ValueTree ValueTree::getSibling (const int delta) const
  14283. {
  14284. if (object == 0 || object->parent == 0)
  14285. return invalid;
  14286. const int index = object->parent->indexOf (*this) + delta;
  14287. return ValueTree (object->parent->children [index].getObject());
  14288. }
  14289. const var& ValueTree::operator[] (const Identifier& name) const
  14290. {
  14291. return object == 0 ? var::null : object->getProperty (name);
  14292. }
  14293. const var& ValueTree::getProperty (const Identifier& name) const
  14294. {
  14295. return object == 0 ? var::null : object->getProperty (name);
  14296. }
  14297. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14298. {
  14299. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14300. }
  14301. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14302. {
  14303. jassert (name.toString().isNotEmpty());
  14304. if (object != 0 && name.toString().isNotEmpty())
  14305. object->setProperty (name, newValue, undoManager);
  14306. }
  14307. bool ValueTree::hasProperty (const Identifier& name) const
  14308. {
  14309. return object != 0 && object->hasProperty (name);
  14310. }
  14311. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14312. {
  14313. if (object != 0)
  14314. object->removeProperty (name, undoManager);
  14315. }
  14316. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14317. {
  14318. if (object != 0)
  14319. object->removeAllProperties (undoManager);
  14320. }
  14321. int ValueTree::getNumProperties() const
  14322. {
  14323. return object == 0 ? 0 : object->properties.size();
  14324. }
  14325. const Identifier ValueTree::getPropertyName (const int index) const
  14326. {
  14327. return object == 0 ? Identifier()
  14328. : object->properties.getName (index);
  14329. }
  14330. class ValueTreePropertyValueSource : public Value::ValueSource,
  14331. public ValueTree::Listener
  14332. {
  14333. public:
  14334. ValueTreePropertyValueSource (const ValueTree& tree_,
  14335. const Identifier& property_,
  14336. UndoManager* const undoManager_)
  14337. : tree (tree_),
  14338. property (property_),
  14339. undoManager (undoManager_)
  14340. {
  14341. tree.addListener (this);
  14342. }
  14343. ~ValueTreePropertyValueSource()
  14344. {
  14345. tree.removeListener (this);
  14346. }
  14347. const var getValue() const
  14348. {
  14349. return tree [property];
  14350. }
  14351. void setValue (const var& newValue)
  14352. {
  14353. tree.setProperty (property, newValue, undoManager);
  14354. }
  14355. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14356. {
  14357. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14358. sendChangeMessage (false);
  14359. }
  14360. void valueTreeChildAdded (ValueTree&, ValueTree&) {}
  14361. void valueTreeChildRemoved (ValueTree&, ValueTree&) {}
  14362. void valueTreeChildOrderChanged (ValueTree&) {}
  14363. void valueTreeParentChanged (ValueTree&) {}
  14364. private:
  14365. ValueTree tree;
  14366. const Identifier property;
  14367. UndoManager* const undoManager;
  14368. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14369. };
  14370. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14371. {
  14372. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14373. }
  14374. int ValueTree::getNumChildren() const
  14375. {
  14376. return object == 0 ? 0 : object->children.size();
  14377. }
  14378. ValueTree ValueTree::getChild (int index) const
  14379. {
  14380. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14381. }
  14382. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14383. {
  14384. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14385. }
  14386. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14387. {
  14388. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14389. }
  14390. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14391. {
  14392. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14393. }
  14394. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14395. {
  14396. return object != 0 && object->isAChildOf (possibleParent.object);
  14397. }
  14398. int ValueTree::indexOf (const ValueTree& child) const
  14399. {
  14400. return object != 0 ? object->indexOf (child) : -1;
  14401. }
  14402. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14403. {
  14404. if (object != 0)
  14405. object->addChild (child.object, index, undoManager);
  14406. }
  14407. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14408. {
  14409. if (object != 0)
  14410. object->removeChild (childIndex, undoManager);
  14411. }
  14412. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14413. {
  14414. if (object != 0)
  14415. object->removeChild (object->children.indexOf (child.object), undoManager);
  14416. }
  14417. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14418. {
  14419. if (object != 0)
  14420. object->removeAllChildren (undoManager);
  14421. }
  14422. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14423. {
  14424. if (object != 0)
  14425. object->moveChild (currentIndex, newIndex, undoManager);
  14426. }
  14427. void ValueTree::addListener (Listener* listener)
  14428. {
  14429. if (listener != 0)
  14430. {
  14431. if (listeners.size() == 0 && object != 0)
  14432. object->valueTreesWithListeners.add (this);
  14433. listeners.add (listener);
  14434. }
  14435. }
  14436. void ValueTree::removeListener (Listener* listener)
  14437. {
  14438. listeners.remove (listener);
  14439. if (listeners.size() == 0 && object != 0)
  14440. object->valueTreesWithListeners.removeValue (this);
  14441. }
  14442. XmlElement* ValueTree::SharedObject::createXml() const
  14443. {
  14444. XmlElement* const xml = new XmlElement (type.toString());
  14445. properties.copyToXmlAttributes (*xml);
  14446. for (int i = 0; i < children.size(); ++i)
  14447. xml->addChildElement (children.getUnchecked(i)->createXml());
  14448. return xml;
  14449. }
  14450. XmlElement* ValueTree::createXml() const
  14451. {
  14452. return object != 0 ? object->createXml() : 0;
  14453. }
  14454. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14455. {
  14456. ValueTree v (xml.getTagName());
  14457. v.object->properties.setFromXmlAttributes (xml);
  14458. forEachXmlChildElement (xml, e)
  14459. v.addChild (fromXml (*e), -1, 0);
  14460. return v;
  14461. }
  14462. void ValueTree::writeToStream (OutputStream& output)
  14463. {
  14464. output.writeString (getType().toString());
  14465. const int numProps = getNumProperties();
  14466. output.writeCompressedInt (numProps);
  14467. int i;
  14468. for (i = 0; i < numProps; ++i)
  14469. {
  14470. const Identifier name (getPropertyName(i));
  14471. output.writeString (name.toString());
  14472. getProperty(name).writeToStream (output);
  14473. }
  14474. const int numChildren = getNumChildren();
  14475. output.writeCompressedInt (numChildren);
  14476. for (i = 0; i < numChildren; ++i)
  14477. getChild (i).writeToStream (output);
  14478. }
  14479. ValueTree ValueTree::readFromStream (InputStream& input)
  14480. {
  14481. const String type (input.readString());
  14482. if (type.isEmpty())
  14483. return ValueTree::invalid;
  14484. ValueTree v (type);
  14485. const int numProps = input.readCompressedInt();
  14486. if (numProps < 0)
  14487. {
  14488. jassertfalse; // trying to read corrupted data!
  14489. return v;
  14490. }
  14491. int i;
  14492. for (i = 0; i < numProps; ++i)
  14493. {
  14494. const String name (input.readString());
  14495. jassert (name.isNotEmpty());
  14496. const var value (var::readFromStream (input));
  14497. v.object->properties.set (name, value);
  14498. }
  14499. const int numChildren = input.readCompressedInt();
  14500. for (i = 0; i < numChildren; ++i)
  14501. {
  14502. ValueTree child (readFromStream (input));
  14503. v.object->children.add (child.object);
  14504. child.object->parent = v.object;
  14505. }
  14506. return v;
  14507. }
  14508. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14509. {
  14510. MemoryInputStream in (data, numBytes, false);
  14511. return readFromStream (in);
  14512. }
  14513. END_JUCE_NAMESPACE
  14514. /*** End of inlined file: juce_ValueTree.cpp ***/
  14515. /*** Start of inlined file: juce_Value.cpp ***/
  14516. BEGIN_JUCE_NAMESPACE
  14517. Value::ValueSource::ValueSource()
  14518. {
  14519. }
  14520. Value::ValueSource::~ValueSource()
  14521. {
  14522. }
  14523. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14524. {
  14525. if (synchronous)
  14526. {
  14527. for (int i = valuesWithListeners.size(); --i >= 0;)
  14528. {
  14529. Value* const v = valuesWithListeners[i];
  14530. if (v != 0)
  14531. v->callListeners();
  14532. }
  14533. }
  14534. else
  14535. {
  14536. triggerAsyncUpdate();
  14537. }
  14538. }
  14539. void Value::ValueSource::handleAsyncUpdate()
  14540. {
  14541. sendChangeMessage (true);
  14542. }
  14543. class SimpleValueSource : public Value::ValueSource
  14544. {
  14545. public:
  14546. SimpleValueSource()
  14547. {
  14548. }
  14549. SimpleValueSource (const var& initialValue)
  14550. : value (initialValue)
  14551. {
  14552. }
  14553. const var getValue() const
  14554. {
  14555. return value;
  14556. }
  14557. void setValue (const var& newValue)
  14558. {
  14559. if (! newValue.equalsWithSameType (value))
  14560. {
  14561. value = newValue;
  14562. sendChangeMessage (false);
  14563. }
  14564. }
  14565. private:
  14566. var value;
  14567. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14568. };
  14569. Value::Value()
  14570. : value (new SimpleValueSource())
  14571. {
  14572. }
  14573. Value::Value (ValueSource* const value_)
  14574. : value (value_)
  14575. {
  14576. jassert (value_ != 0);
  14577. }
  14578. Value::Value (const var& initialValue)
  14579. : value (new SimpleValueSource (initialValue))
  14580. {
  14581. }
  14582. Value::Value (const Value& other)
  14583. : value (other.value)
  14584. {
  14585. }
  14586. Value& Value::operator= (const Value& other)
  14587. {
  14588. value = other.value;
  14589. return *this;
  14590. }
  14591. Value::~Value()
  14592. {
  14593. if (listeners.size() > 0)
  14594. value->valuesWithListeners.removeValue (this);
  14595. }
  14596. const var Value::getValue() const
  14597. {
  14598. return value->getValue();
  14599. }
  14600. Value::operator const var() const
  14601. {
  14602. return getValue();
  14603. }
  14604. void Value::setValue (const var& newValue)
  14605. {
  14606. value->setValue (newValue);
  14607. }
  14608. const String Value::toString() const
  14609. {
  14610. return value->getValue().toString();
  14611. }
  14612. Value& Value::operator= (const var& newValue)
  14613. {
  14614. value->setValue (newValue);
  14615. return *this;
  14616. }
  14617. void Value::referTo (const Value& valueToReferTo)
  14618. {
  14619. if (valueToReferTo.value != value)
  14620. {
  14621. if (listeners.size() > 0)
  14622. {
  14623. value->valuesWithListeners.removeValue (this);
  14624. valueToReferTo.value->valuesWithListeners.add (this);
  14625. }
  14626. value = valueToReferTo.value;
  14627. callListeners();
  14628. }
  14629. }
  14630. bool Value::refersToSameSourceAs (const Value& other) const
  14631. {
  14632. return value == other.value;
  14633. }
  14634. bool Value::operator== (const Value& other) const
  14635. {
  14636. return value == other.value || value->getValue() == other.getValue();
  14637. }
  14638. bool Value::operator!= (const Value& other) const
  14639. {
  14640. return value != other.value && value->getValue() != other.getValue();
  14641. }
  14642. void Value::addListener (ValueListener* const listener)
  14643. {
  14644. if (listener != 0)
  14645. {
  14646. if (listeners.size() == 0)
  14647. value->valuesWithListeners.add (this);
  14648. listeners.add (listener);
  14649. }
  14650. }
  14651. void Value::removeListener (ValueListener* const listener)
  14652. {
  14653. listeners.remove (listener);
  14654. if (listeners.size() == 0)
  14655. value->valuesWithListeners.removeValue (this);
  14656. }
  14657. void Value::callListeners()
  14658. {
  14659. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14660. listeners.call (&ValueListener::valueChanged, v);
  14661. }
  14662. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14663. {
  14664. return stream << value.toString();
  14665. }
  14666. END_JUCE_NAMESPACE
  14667. /*** End of inlined file: juce_Value.cpp ***/
  14668. /*** Start of inlined file: juce_Application.cpp ***/
  14669. BEGIN_JUCE_NAMESPACE
  14670. #if JUCE_MAC
  14671. extern void juce_initialiseMacMainMenu();
  14672. #endif
  14673. JUCEApplication::JUCEApplication()
  14674. : appReturnValue (0),
  14675. stillInitialising (true)
  14676. {
  14677. jassert (isStandaloneApp() && appInstance == 0);
  14678. appInstance = this;
  14679. }
  14680. JUCEApplication::~JUCEApplication()
  14681. {
  14682. if (appLock != 0)
  14683. {
  14684. appLock->exit();
  14685. appLock = 0;
  14686. }
  14687. jassert (appInstance == this);
  14688. appInstance = 0;
  14689. }
  14690. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14691. JUCEApplication* JUCEApplication::appInstance = 0;
  14692. bool JUCEApplication::moreThanOneInstanceAllowed()
  14693. {
  14694. return true;
  14695. }
  14696. void JUCEApplication::anotherInstanceStarted (const String&)
  14697. {
  14698. }
  14699. void JUCEApplication::systemRequestedQuit()
  14700. {
  14701. quit();
  14702. }
  14703. void JUCEApplication::quit()
  14704. {
  14705. MessageManager::getInstance()->stopDispatchLoop();
  14706. }
  14707. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14708. {
  14709. appReturnValue = newReturnValue;
  14710. }
  14711. void JUCEApplication::actionListenerCallback (const String& message)
  14712. {
  14713. if (message.startsWith (getApplicationName() + "/"))
  14714. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14715. }
  14716. void JUCEApplication::unhandledException (const std::exception*,
  14717. const String&,
  14718. const int)
  14719. {
  14720. jassertfalse;
  14721. }
  14722. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14723. const char* const sourceFile,
  14724. const int lineNumber)
  14725. {
  14726. if (appInstance != 0)
  14727. appInstance->unhandledException (e, sourceFile, lineNumber);
  14728. }
  14729. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14730. {
  14731. return 0;
  14732. }
  14733. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14734. {
  14735. commands.add (StandardApplicationCommandIDs::quit);
  14736. }
  14737. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14738. {
  14739. if (commandID == StandardApplicationCommandIDs::quit)
  14740. {
  14741. result.setInfo (TRANS("Quit"),
  14742. TRANS("Quits the application"),
  14743. "Application",
  14744. 0);
  14745. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14746. }
  14747. }
  14748. bool JUCEApplication::perform (const InvocationInfo& info)
  14749. {
  14750. if (info.commandID == StandardApplicationCommandIDs::quit)
  14751. {
  14752. systemRequestedQuit();
  14753. return true;
  14754. }
  14755. return false;
  14756. }
  14757. bool JUCEApplication::initialiseApp (const String& commandLine)
  14758. {
  14759. commandLineParameters = commandLine.trim();
  14760. #if ! JUCE_IOS
  14761. jassert (appLock == 0); // initialiseApp must only be called once!
  14762. if (! moreThanOneInstanceAllowed())
  14763. {
  14764. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14765. if (! appLock->enter(0))
  14766. {
  14767. appLock = 0;
  14768. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14769. DBG ("Another instance is running - quitting...");
  14770. return false;
  14771. }
  14772. }
  14773. #endif
  14774. // let the app do its setting-up..
  14775. initialise (commandLineParameters);
  14776. #if JUCE_MAC
  14777. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14778. #endif
  14779. // register for broadcast new app messages
  14780. MessageManager::getInstance()->registerBroadcastListener (this);
  14781. stillInitialising = false;
  14782. return true;
  14783. }
  14784. int JUCEApplication::shutdownApp()
  14785. {
  14786. jassert (appInstance == this);
  14787. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14788. JUCE_TRY
  14789. {
  14790. // give the app a chance to clean up..
  14791. shutdown();
  14792. }
  14793. JUCE_CATCH_EXCEPTION
  14794. return getApplicationReturnValue();
  14795. }
  14796. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14797. void JUCEApplication::appWillTerminateByForce()
  14798. {
  14799. {
  14800. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14801. if (app != 0)
  14802. app->shutdownApp();
  14803. }
  14804. shutdownJuce_GUI();
  14805. }
  14806. #if ! JUCE_ANDROID
  14807. int JUCEApplication::main (const String& commandLine)
  14808. {
  14809. ScopedJuceInitialiser_GUI libraryInitialiser;
  14810. jassert (createInstance != 0);
  14811. int returnCode = 0;
  14812. {
  14813. const ScopedPointer<JUCEApplication> app (createInstance());
  14814. if (! app->initialiseApp (commandLine))
  14815. return 0;
  14816. JUCE_TRY
  14817. {
  14818. // loop until a quit message is received..
  14819. MessageManager::getInstance()->runDispatchLoop();
  14820. }
  14821. JUCE_CATCH_EXCEPTION
  14822. returnCode = app->shutdownApp();
  14823. }
  14824. return returnCode;
  14825. }
  14826. #if JUCE_IOS
  14827. extern int juce_iOSMain (int argc, const char* argv[]);
  14828. #endif
  14829. #if ! JUCE_WINDOWS
  14830. extern const char* juce_Argv0;
  14831. #endif
  14832. int JUCEApplication::main (int argc, const char* argv[])
  14833. {
  14834. JUCE_AUTORELEASEPOOL
  14835. #if ! JUCE_WINDOWS
  14836. jassert (createInstance != 0);
  14837. juce_Argv0 = argv[0];
  14838. #endif
  14839. #if JUCE_IOS
  14840. return juce_iOSMain (argc, argv);
  14841. #else
  14842. String cmd;
  14843. for (int i = 1; i < argc; ++i)
  14844. cmd << argv[i] << ' ';
  14845. return JUCEApplication::main (cmd);
  14846. #endif
  14847. }
  14848. #endif
  14849. END_JUCE_NAMESPACE
  14850. /*** End of inlined file: juce_Application.cpp ***/
  14851. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14852. BEGIN_JUCE_NAMESPACE
  14853. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14854. : commandID (commandID_),
  14855. flags (0)
  14856. {
  14857. }
  14858. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14859. const String& description_,
  14860. const String& categoryName_,
  14861. const int flags_) throw()
  14862. {
  14863. shortName = shortName_;
  14864. description = description_;
  14865. categoryName = categoryName_;
  14866. flags = flags_;
  14867. }
  14868. void ApplicationCommandInfo::setActive (const bool b) throw()
  14869. {
  14870. if (b)
  14871. flags &= ~isDisabled;
  14872. else
  14873. flags |= isDisabled;
  14874. }
  14875. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14876. {
  14877. if (b)
  14878. flags |= isTicked;
  14879. else
  14880. flags &= ~isTicked;
  14881. }
  14882. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14883. {
  14884. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14885. }
  14886. END_JUCE_NAMESPACE
  14887. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14888. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14889. BEGIN_JUCE_NAMESPACE
  14890. ApplicationCommandManager::ApplicationCommandManager()
  14891. : firstTarget (0)
  14892. {
  14893. keyMappings = new KeyPressMappingSet (this);
  14894. Desktop::getInstance().addFocusChangeListener (this);
  14895. }
  14896. ApplicationCommandManager::~ApplicationCommandManager()
  14897. {
  14898. Desktop::getInstance().removeFocusChangeListener (this);
  14899. keyMappings = 0;
  14900. }
  14901. void ApplicationCommandManager::clearCommands()
  14902. {
  14903. commands.clear();
  14904. keyMappings->clearAllKeyPresses();
  14905. triggerAsyncUpdate();
  14906. }
  14907. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14908. {
  14909. // zero isn't a valid command ID!
  14910. jassert (newCommand.commandID != 0);
  14911. // the name isn't optional!
  14912. jassert (newCommand.shortName.isNotEmpty());
  14913. if (getCommandForID (newCommand.commandID) == 0)
  14914. {
  14915. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14916. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14917. commands.add (newInfo);
  14918. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14919. triggerAsyncUpdate();
  14920. }
  14921. else
  14922. {
  14923. // trying to re-register the same command with different parameters?
  14924. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14925. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14926. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14927. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14928. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14929. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14930. }
  14931. }
  14932. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14933. {
  14934. if (target != 0)
  14935. {
  14936. Array <CommandID> commandIDs;
  14937. target->getAllCommands (commandIDs);
  14938. for (int i = 0; i < commandIDs.size(); ++i)
  14939. {
  14940. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14941. target->getCommandInfo (info.commandID, info);
  14942. registerCommand (info);
  14943. }
  14944. }
  14945. }
  14946. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14947. {
  14948. for (int i = commands.size(); --i >= 0;)
  14949. {
  14950. if (commands.getUnchecked (i)->commandID == commandID)
  14951. {
  14952. commands.remove (i);
  14953. triggerAsyncUpdate();
  14954. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14955. for (int j = keys.size(); --j >= 0;)
  14956. keyMappings->removeKeyPress (keys.getReference (j));
  14957. }
  14958. }
  14959. }
  14960. void ApplicationCommandManager::commandStatusChanged()
  14961. {
  14962. triggerAsyncUpdate();
  14963. }
  14964. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14965. {
  14966. for (int i = commands.size(); --i >= 0;)
  14967. if (commands.getUnchecked(i)->commandID == commandID)
  14968. return commands.getUnchecked(i);
  14969. return 0;
  14970. }
  14971. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14972. {
  14973. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14974. return (ci != 0) ? ci->shortName : String::empty;
  14975. }
  14976. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14977. {
  14978. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14979. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14980. : String::empty;
  14981. }
  14982. const StringArray ApplicationCommandManager::getCommandCategories() const
  14983. {
  14984. StringArray s;
  14985. for (int i = 0; i < commands.size(); ++i)
  14986. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14987. return s;
  14988. }
  14989. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  14990. {
  14991. Array <CommandID> results;
  14992. for (int i = 0; i < commands.size(); ++i)
  14993. if (commands.getUnchecked(i)->categoryName == categoryName)
  14994. results.add (commands.getUnchecked(i)->commandID);
  14995. return results;
  14996. }
  14997. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14998. {
  14999. ApplicationCommandTarget::InvocationInfo info (commandID);
  15000. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15001. return invoke (info, asynchronously);
  15002. }
  15003. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15004. {
  15005. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15006. // manager first..
  15007. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15008. ApplicationCommandInfo commandInfo (0);
  15009. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15010. if (target == 0)
  15011. return false;
  15012. ApplicationCommandTarget::InvocationInfo info (info_);
  15013. info.commandFlags = commandInfo.flags;
  15014. sendListenerInvokeCallback (info);
  15015. const bool ok = target->invoke (info, asynchronously);
  15016. commandStatusChanged();
  15017. return ok;
  15018. }
  15019. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15020. {
  15021. return firstTarget != 0 ? firstTarget
  15022. : findDefaultComponentTarget();
  15023. }
  15024. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15025. {
  15026. firstTarget = newTarget;
  15027. }
  15028. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15029. ApplicationCommandInfo& upToDateInfo)
  15030. {
  15031. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15032. if (target == 0)
  15033. target = JUCEApplication::getInstance();
  15034. if (target != 0)
  15035. target = target->getTargetForCommand (commandID);
  15036. if (target != 0)
  15037. target->getCommandInfo (commandID, upToDateInfo);
  15038. return target;
  15039. }
  15040. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15041. {
  15042. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15043. if (target == 0 && c != 0)
  15044. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15045. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15046. return target;
  15047. }
  15048. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15049. {
  15050. Component* c = Component::getCurrentlyFocusedComponent();
  15051. if (c == 0)
  15052. {
  15053. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15054. if (activeWindow != 0)
  15055. {
  15056. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15057. if (c == 0)
  15058. c = activeWindow;
  15059. }
  15060. }
  15061. if (c == 0 && Process::isForegroundProcess())
  15062. {
  15063. // getting a bit desperate now - try all desktop comps..
  15064. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15065. {
  15066. ApplicationCommandTarget* const target
  15067. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15068. ->getPeer()->getLastFocusedSubcomponent());
  15069. if (target != 0)
  15070. return target;
  15071. }
  15072. }
  15073. if (c != 0)
  15074. {
  15075. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15076. // if we're focused on a ResizableWindow, chances are that it's the content
  15077. // component that really should get the event. And if not, the event will
  15078. // still be passed up to the top level window anyway, so let's send it to the
  15079. // content comp.
  15080. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15081. c = resizableWindow->getContentComponent();
  15082. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15083. if (target != 0)
  15084. return target;
  15085. }
  15086. return JUCEApplication::getInstance();
  15087. }
  15088. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15089. {
  15090. listeners.add (listener);
  15091. }
  15092. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15093. {
  15094. listeners.remove (listener);
  15095. }
  15096. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15097. {
  15098. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15099. }
  15100. void ApplicationCommandManager::handleAsyncUpdate()
  15101. {
  15102. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15103. }
  15104. void ApplicationCommandManager::globalFocusChanged (Component*)
  15105. {
  15106. commandStatusChanged();
  15107. }
  15108. END_JUCE_NAMESPACE
  15109. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15110. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15111. BEGIN_JUCE_NAMESPACE
  15112. ApplicationCommandTarget::ApplicationCommandTarget()
  15113. {
  15114. }
  15115. ApplicationCommandTarget::~ApplicationCommandTarget()
  15116. {
  15117. messageInvoker = 0;
  15118. }
  15119. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15120. {
  15121. if (isCommandActive (info.commandID))
  15122. {
  15123. if (async)
  15124. {
  15125. if (messageInvoker == 0)
  15126. messageInvoker = new CommandTargetMessageInvoker (this);
  15127. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15128. return true;
  15129. }
  15130. else
  15131. {
  15132. const bool success = perform (info);
  15133. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15134. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15135. // returns the command's info.
  15136. return success;
  15137. }
  15138. }
  15139. return false;
  15140. }
  15141. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15142. {
  15143. Component* c = dynamic_cast <Component*> (this);
  15144. if (c != 0)
  15145. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15146. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15147. return 0;
  15148. }
  15149. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15150. {
  15151. ApplicationCommandTarget* target = this;
  15152. int depth = 0;
  15153. while (target != 0)
  15154. {
  15155. Array <CommandID> commandIDs;
  15156. target->getAllCommands (commandIDs);
  15157. if (commandIDs.contains (commandID))
  15158. return target;
  15159. target = target->getNextCommandTarget();
  15160. ++depth;
  15161. jassert (depth < 100); // could be a recursive command chain??
  15162. jassert (target != this); // definitely a recursive command chain!
  15163. if (depth > 100 || target == this)
  15164. break;
  15165. }
  15166. if (target == 0)
  15167. {
  15168. target = JUCEApplication::getInstance();
  15169. if (target != 0)
  15170. {
  15171. Array <CommandID> commandIDs;
  15172. target->getAllCommands (commandIDs);
  15173. if (commandIDs.contains (commandID))
  15174. return target;
  15175. }
  15176. }
  15177. return 0;
  15178. }
  15179. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15180. {
  15181. ApplicationCommandInfo info (commandID);
  15182. info.flags = ApplicationCommandInfo::isDisabled;
  15183. getCommandInfo (commandID, info);
  15184. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15185. }
  15186. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15187. {
  15188. ApplicationCommandTarget* target = this;
  15189. int depth = 0;
  15190. while (target != 0)
  15191. {
  15192. if (target->tryToInvoke (info, async))
  15193. return true;
  15194. target = target->getNextCommandTarget();
  15195. ++depth;
  15196. jassert (depth < 100); // could be a recursive command chain??
  15197. jassert (target != this); // definitely a recursive command chain!
  15198. if (depth > 100 || target == this)
  15199. break;
  15200. }
  15201. if (target == 0)
  15202. {
  15203. target = JUCEApplication::getInstance();
  15204. if (target != 0)
  15205. return target->tryToInvoke (info, async);
  15206. }
  15207. return false;
  15208. }
  15209. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15210. {
  15211. ApplicationCommandTarget::InvocationInfo info (commandID);
  15212. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15213. return invoke (info, asynchronously);
  15214. }
  15215. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15216. : commandID (commandID_),
  15217. commandFlags (0),
  15218. invocationMethod (direct),
  15219. originatingComponent (0),
  15220. isKeyDown (false),
  15221. millisecsSinceKeyPressed (0)
  15222. {
  15223. }
  15224. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15225. : owner (owner_)
  15226. {
  15227. }
  15228. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15229. {
  15230. }
  15231. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15232. {
  15233. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15234. owner->tryToInvoke (*info, false);
  15235. }
  15236. END_JUCE_NAMESPACE
  15237. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15238. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15239. BEGIN_JUCE_NAMESPACE
  15240. juce_ImplementSingleton (ApplicationProperties)
  15241. ApplicationProperties::ApplicationProperties()
  15242. : msBeforeSaving (3000),
  15243. options (PropertiesFile::storeAsBinary),
  15244. commonSettingsAreReadOnly (0),
  15245. processLock (0)
  15246. {
  15247. }
  15248. ApplicationProperties::~ApplicationProperties()
  15249. {
  15250. closeFiles();
  15251. clearSingletonInstance();
  15252. }
  15253. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15254. const String& fileNameSuffix,
  15255. const String& folderName_,
  15256. const int millisecondsBeforeSaving,
  15257. const int propertiesFileOptions,
  15258. InterProcessLock* processLock_)
  15259. {
  15260. appName = applicationName;
  15261. fileSuffix = fileNameSuffix;
  15262. folderName = folderName_;
  15263. msBeforeSaving = millisecondsBeforeSaving;
  15264. options = propertiesFileOptions;
  15265. processLock = processLock_;
  15266. }
  15267. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15268. const bool testCommonSettings,
  15269. const bool showWarningDialogOnFailure)
  15270. {
  15271. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15272. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15273. if (! (userOk && commonOk))
  15274. {
  15275. if (showWarningDialogOnFailure)
  15276. {
  15277. String filenames;
  15278. if (userProps != 0 && ! userOk)
  15279. filenames << '\n' << userProps->getFile().getFullPathName();
  15280. if (commonProps != 0 && ! commonOk)
  15281. filenames << '\n' << commonProps->getFile().getFullPathName();
  15282. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  15283. appName + TRANS(" - Unable to save settings"),
  15284. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15285. + appName + TRANS(" needs to be able to write to the following files:\n")
  15286. + filenames
  15287. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15288. }
  15289. return false;
  15290. }
  15291. return true;
  15292. }
  15293. void ApplicationProperties::openFiles()
  15294. {
  15295. // You need to call setStorageParameters() before trying to get hold of the
  15296. // properties!
  15297. jassert (appName.isNotEmpty());
  15298. if (appName.isNotEmpty())
  15299. {
  15300. if (userProps == 0)
  15301. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15302. false, msBeforeSaving, options, processLock);
  15303. if (commonProps == 0)
  15304. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15305. true, msBeforeSaving, options, processLock);
  15306. userProps->setFallbackPropertySet (commonProps);
  15307. }
  15308. }
  15309. PropertiesFile* ApplicationProperties::getUserSettings()
  15310. {
  15311. if (userProps == 0)
  15312. openFiles();
  15313. return userProps;
  15314. }
  15315. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15316. {
  15317. if (commonProps == 0)
  15318. openFiles();
  15319. if (returnUserPropsIfReadOnly)
  15320. {
  15321. if (commonSettingsAreReadOnly == 0)
  15322. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15323. if (commonSettingsAreReadOnly > 0)
  15324. return userProps;
  15325. }
  15326. return commonProps;
  15327. }
  15328. bool ApplicationProperties::saveIfNeeded()
  15329. {
  15330. return (userProps == 0 || userProps->saveIfNeeded())
  15331. && (commonProps == 0 || commonProps->saveIfNeeded());
  15332. }
  15333. void ApplicationProperties::closeFiles()
  15334. {
  15335. userProps = 0;
  15336. commonProps = 0;
  15337. }
  15338. END_JUCE_NAMESPACE
  15339. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15340. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15341. BEGIN_JUCE_NAMESPACE
  15342. namespace PropertyFileConstants
  15343. {
  15344. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15345. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15346. static const char* const fileTag = "PROPERTIES";
  15347. static const char* const valueTag = "VALUE";
  15348. static const char* const nameAttribute = "name";
  15349. static const char* const valueAttribute = "val";
  15350. }
  15351. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15352. const int options_, InterProcessLock* const processLock_)
  15353. : PropertySet (ignoreCaseOfKeyNames),
  15354. file (f),
  15355. timerInterval (millisecondsBeforeSaving),
  15356. options (options_),
  15357. loadedOk (false),
  15358. needsWriting (false),
  15359. processLock (processLock_)
  15360. {
  15361. // You need to correctly specify just one storage format for the file
  15362. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15363. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15364. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15365. ProcessScopedLock pl (createProcessLock());
  15366. if (pl != 0 && ! pl->isLocked())
  15367. return; // locking failure..
  15368. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15369. if (fileStream != 0)
  15370. {
  15371. int magicNumber = fileStream->readInt();
  15372. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15373. {
  15374. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15375. magicNumber = PropertyFileConstants::magicNumber;
  15376. }
  15377. if (magicNumber == PropertyFileConstants::magicNumber)
  15378. {
  15379. loadedOk = true;
  15380. BufferedInputStream in (fileStream.release(), 2048, true);
  15381. int numValues = in.readInt();
  15382. while (--numValues >= 0 && ! in.isExhausted())
  15383. {
  15384. const String key (in.readString());
  15385. const String value (in.readString());
  15386. jassert (key.isNotEmpty());
  15387. if (key.isNotEmpty())
  15388. getAllProperties().set (key, value);
  15389. }
  15390. }
  15391. else
  15392. {
  15393. // Not a binary props file - let's see if it's XML..
  15394. fileStream = 0;
  15395. XmlDocument parser (f);
  15396. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15397. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15398. {
  15399. doc = parser.getDocumentElement();
  15400. if (doc != 0)
  15401. {
  15402. loadedOk = true;
  15403. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15404. {
  15405. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15406. if (name.isNotEmpty())
  15407. {
  15408. getAllProperties().set (name,
  15409. e->getFirstChildElement() != 0
  15410. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15411. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15412. }
  15413. }
  15414. }
  15415. else
  15416. {
  15417. // must be a pretty broken XML file we're trying to parse here,
  15418. // or a sign that this object needs an InterProcessLock,
  15419. // or just a failure reading the file. This last reason is why
  15420. // we don't jassertfalse here.
  15421. }
  15422. }
  15423. }
  15424. }
  15425. else
  15426. {
  15427. loadedOk = ! f.exists();
  15428. }
  15429. }
  15430. PropertiesFile::~PropertiesFile()
  15431. {
  15432. if (! saveIfNeeded())
  15433. jassertfalse;
  15434. }
  15435. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15436. {
  15437. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15438. }
  15439. bool PropertiesFile::saveIfNeeded()
  15440. {
  15441. const ScopedLock sl (getLock());
  15442. return (! needsWriting) || save();
  15443. }
  15444. bool PropertiesFile::needsToBeSaved() const
  15445. {
  15446. const ScopedLock sl (getLock());
  15447. return needsWriting;
  15448. }
  15449. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15450. {
  15451. const ScopedLock sl (getLock());
  15452. needsWriting = needsToBeSaved_;
  15453. }
  15454. bool PropertiesFile::save()
  15455. {
  15456. const ScopedLock sl (getLock());
  15457. stopTimer();
  15458. if (file == File::nonexistent
  15459. || file.isDirectory()
  15460. || ! file.getParentDirectory().createDirectory())
  15461. return false;
  15462. if ((options & storeAsXML) != 0)
  15463. {
  15464. XmlElement doc (PropertyFileConstants::fileTag);
  15465. for (int i = 0; i < getAllProperties().size(); ++i)
  15466. {
  15467. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15468. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15469. // if the value seems to contain xml, store it as such..
  15470. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15471. if (childElement != 0)
  15472. e->addChildElement (childElement);
  15473. else
  15474. e->setAttribute (PropertyFileConstants::valueAttribute,
  15475. getAllProperties().getAllValues() [i]);
  15476. }
  15477. ProcessScopedLock pl (createProcessLock());
  15478. if (pl != 0 && ! pl->isLocked())
  15479. return false; // locking failure..
  15480. if (doc.writeToFile (file, String::empty))
  15481. {
  15482. needsWriting = false;
  15483. return true;
  15484. }
  15485. }
  15486. else
  15487. {
  15488. ProcessScopedLock pl (createProcessLock());
  15489. if (pl != 0 && ! pl->isLocked())
  15490. return false; // locking failure..
  15491. TemporaryFile tempFile (file);
  15492. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15493. if (out != 0)
  15494. {
  15495. if ((options & storeAsCompressedBinary) != 0)
  15496. {
  15497. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15498. out->flush();
  15499. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15500. }
  15501. else
  15502. {
  15503. // have you set up the storage option flags correctly?
  15504. jassert ((options & storeAsBinary) != 0);
  15505. out->writeInt (PropertyFileConstants::magicNumber);
  15506. }
  15507. const int numProperties = getAllProperties().size();
  15508. out->writeInt (numProperties);
  15509. for (int i = 0; i < numProperties; ++i)
  15510. {
  15511. out->writeString (getAllProperties().getAllKeys() [i]);
  15512. out->writeString (getAllProperties().getAllValues() [i]);
  15513. }
  15514. out = 0;
  15515. if (tempFile.overwriteTargetFileWithTemporary())
  15516. {
  15517. needsWriting = false;
  15518. return true;
  15519. }
  15520. }
  15521. }
  15522. return false;
  15523. }
  15524. void PropertiesFile::timerCallback()
  15525. {
  15526. saveIfNeeded();
  15527. }
  15528. void PropertiesFile::propertyChanged()
  15529. {
  15530. sendChangeMessage();
  15531. needsWriting = true;
  15532. if (timerInterval > 0)
  15533. startTimer (timerInterval);
  15534. else if (timerInterval == 0)
  15535. saveIfNeeded();
  15536. }
  15537. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15538. const String& fileNameSuffix,
  15539. const String& folderName,
  15540. const bool commonToAllUsers)
  15541. {
  15542. // mustn't have illegal characters in this name..
  15543. jassert (applicationName == File::createLegalFileName (applicationName));
  15544. #if JUCE_MAC || JUCE_IOS
  15545. File dir (commonToAllUsers ? "/Library/Preferences"
  15546. : "~/Library/Preferences");
  15547. if (folderName.isNotEmpty())
  15548. dir = dir.getChildFile (folderName);
  15549. #elif JUCE_LINUX || JUCE_ANDROID
  15550. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15551. + (folderName.isNotEmpty() ? folderName
  15552. : ("." + applicationName)));
  15553. #elif JUCE_WINDOWS
  15554. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15555. : File::userApplicationDataDirectory));
  15556. if (dir == File::nonexistent)
  15557. return File::nonexistent;
  15558. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15559. : applicationName);
  15560. #endif
  15561. return dir.getChildFile (applicationName)
  15562. .withFileExtension (fileNameSuffix);
  15563. }
  15564. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15565. const String& fileNameSuffix,
  15566. const String& folderName,
  15567. const bool commonToAllUsers,
  15568. const int millisecondsBeforeSaving,
  15569. const int propertiesFileOptions,
  15570. InterProcessLock* processLock_)
  15571. {
  15572. const File file (getDefaultAppSettingsFile (applicationName,
  15573. fileNameSuffix,
  15574. folderName,
  15575. commonToAllUsers));
  15576. jassert (file != File::nonexistent);
  15577. if (file == File::nonexistent)
  15578. return 0;
  15579. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15580. }
  15581. END_JUCE_NAMESPACE
  15582. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15583. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15584. BEGIN_JUCE_NAMESPACE
  15585. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15586. const String& fileWildcard_,
  15587. const String& openFileDialogTitle_,
  15588. const String& saveFileDialogTitle_)
  15589. : changedSinceSave (false),
  15590. fileExtension (fileExtension_),
  15591. fileWildcard (fileWildcard_),
  15592. openFileDialogTitle (openFileDialogTitle_),
  15593. saveFileDialogTitle (saveFileDialogTitle_)
  15594. {
  15595. }
  15596. FileBasedDocument::~FileBasedDocument()
  15597. {
  15598. }
  15599. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15600. {
  15601. if (changedSinceSave != hasChanged)
  15602. {
  15603. changedSinceSave = hasChanged;
  15604. sendChangeMessage();
  15605. }
  15606. }
  15607. void FileBasedDocument::changed()
  15608. {
  15609. changedSinceSave = true;
  15610. sendChangeMessage();
  15611. }
  15612. void FileBasedDocument::setFile (const File& newFile)
  15613. {
  15614. if (documentFile != newFile)
  15615. {
  15616. documentFile = newFile;
  15617. changed();
  15618. }
  15619. }
  15620. #if JUCE_MODAL_LOOPS_PERMITTED
  15621. bool FileBasedDocument::loadFrom (const File& newFile,
  15622. const bool showMessageOnFailure)
  15623. {
  15624. MouseCursor::showWaitCursor();
  15625. const File oldFile (documentFile);
  15626. documentFile = newFile;
  15627. String error;
  15628. if (newFile.existsAsFile())
  15629. {
  15630. error = loadDocument (newFile);
  15631. if (error.isEmpty())
  15632. {
  15633. setChangedFlag (false);
  15634. MouseCursor::hideWaitCursor();
  15635. setLastDocumentOpened (newFile);
  15636. return true;
  15637. }
  15638. }
  15639. else
  15640. {
  15641. error = "The file doesn't exist";
  15642. }
  15643. documentFile = oldFile;
  15644. MouseCursor::hideWaitCursor();
  15645. if (showMessageOnFailure)
  15646. {
  15647. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15648. TRANS("Failed to open file..."),
  15649. TRANS("There was an error while trying to load the file:\n\n")
  15650. + newFile.getFullPathName()
  15651. + "\n\n"
  15652. + error);
  15653. }
  15654. return false;
  15655. }
  15656. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15657. {
  15658. FileChooser fc (openFileDialogTitle,
  15659. getLastDocumentOpened(),
  15660. fileWildcard);
  15661. if (fc.browseForFileToOpen())
  15662. return loadFrom (fc.getResult(), showMessageOnFailure);
  15663. return false;
  15664. }
  15665. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15666. const bool showMessageOnFailure)
  15667. {
  15668. return saveAs (documentFile,
  15669. false,
  15670. askUserForFileIfNotSpecified,
  15671. showMessageOnFailure);
  15672. }
  15673. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15674. const bool warnAboutOverwritingExistingFiles,
  15675. const bool askUserForFileIfNotSpecified,
  15676. const bool showMessageOnFailure)
  15677. {
  15678. if (newFile == File::nonexistent)
  15679. {
  15680. if (askUserForFileIfNotSpecified)
  15681. {
  15682. return saveAsInteractive (true);
  15683. }
  15684. else
  15685. {
  15686. // can't save to an unspecified file
  15687. jassertfalse;
  15688. return failedToWriteToFile;
  15689. }
  15690. }
  15691. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15692. {
  15693. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15694. TRANS("File already exists"),
  15695. TRANS("There's already a file called:\n\n")
  15696. + newFile.getFullPathName()
  15697. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15698. TRANS("overwrite"),
  15699. TRANS("cancel")))
  15700. {
  15701. return userCancelledSave;
  15702. }
  15703. }
  15704. MouseCursor::showWaitCursor();
  15705. const File oldFile (documentFile);
  15706. documentFile = newFile;
  15707. String error (saveDocument (newFile));
  15708. if (error.isEmpty())
  15709. {
  15710. setChangedFlag (false);
  15711. MouseCursor::hideWaitCursor();
  15712. return savedOk;
  15713. }
  15714. documentFile = oldFile;
  15715. MouseCursor::hideWaitCursor();
  15716. if (showMessageOnFailure)
  15717. {
  15718. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15719. TRANS("Error writing to file..."),
  15720. TRANS("An error occurred while trying to save \"")
  15721. + getDocumentTitle()
  15722. + TRANS("\" to the file:\n\n")
  15723. + newFile.getFullPathName()
  15724. + "\n\n"
  15725. + error);
  15726. }
  15727. return failedToWriteToFile;
  15728. }
  15729. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15730. {
  15731. if (! hasChangedSinceSaved())
  15732. return savedOk;
  15733. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15734. TRANS("Closing document..."),
  15735. TRANS("Do you want to save the changes to \"")
  15736. + getDocumentTitle() + "\"?",
  15737. TRANS("save"),
  15738. TRANS("discard changes"),
  15739. TRANS("cancel"));
  15740. if (r == 1)
  15741. {
  15742. // save changes
  15743. return save (true, true);
  15744. }
  15745. else if (r == 2)
  15746. {
  15747. // discard changes
  15748. return savedOk;
  15749. }
  15750. return userCancelledSave;
  15751. }
  15752. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15753. {
  15754. File f;
  15755. if (documentFile.existsAsFile())
  15756. f = documentFile;
  15757. else
  15758. f = getLastDocumentOpened();
  15759. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15760. if (legalFilename.isEmpty())
  15761. legalFilename = "unnamed";
  15762. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15763. f = f.getSiblingFile (legalFilename);
  15764. else
  15765. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15766. f = f.withFileExtension (fileExtension)
  15767. .getNonexistentSibling (true);
  15768. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15769. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15770. {
  15771. File chosen (fc.getResult());
  15772. if (chosen.getFileExtension().isEmpty())
  15773. {
  15774. chosen = chosen.withFileExtension (fileExtension);
  15775. if (chosen.exists())
  15776. {
  15777. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15778. TRANS("File already exists"),
  15779. TRANS("There's already a file called:")
  15780. + "\n\n" + chosen.getFullPathName()
  15781. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15782. TRANS("overwrite"),
  15783. TRANS("cancel")))
  15784. {
  15785. return userCancelledSave;
  15786. }
  15787. }
  15788. }
  15789. setLastDocumentOpened (chosen);
  15790. return saveAs (chosen, false, false, true);
  15791. }
  15792. return userCancelledSave;
  15793. }
  15794. #endif
  15795. END_JUCE_NAMESPACE
  15796. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15797. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15798. BEGIN_JUCE_NAMESPACE
  15799. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15800. : maxNumberOfItems (10)
  15801. {
  15802. }
  15803. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15804. {
  15805. }
  15806. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15807. {
  15808. maxNumberOfItems = jmax (1, newMaxNumber);
  15809. while (getNumFiles() > maxNumberOfItems)
  15810. files.remove (getNumFiles() - 1);
  15811. }
  15812. int RecentlyOpenedFilesList::getNumFiles() const
  15813. {
  15814. return files.size();
  15815. }
  15816. const File RecentlyOpenedFilesList::getFile (const int index) const
  15817. {
  15818. return File (files [index]);
  15819. }
  15820. void RecentlyOpenedFilesList::clear()
  15821. {
  15822. files.clear();
  15823. }
  15824. void RecentlyOpenedFilesList::addFile (const File& file)
  15825. {
  15826. const String path (file.getFullPathName());
  15827. files.removeString (path, true);
  15828. files.insert (0, path);
  15829. setMaxNumberOfItems (maxNumberOfItems);
  15830. }
  15831. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15832. {
  15833. for (int i = getNumFiles(); --i >= 0;)
  15834. if (! getFile(i).exists())
  15835. files.remove (i);
  15836. }
  15837. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15838. const int baseItemId,
  15839. const bool showFullPaths,
  15840. const bool dontAddNonExistentFiles,
  15841. const File** filesToAvoid)
  15842. {
  15843. int num = 0;
  15844. for (int i = 0; i < getNumFiles(); ++i)
  15845. {
  15846. const File f (getFile(i));
  15847. if ((! dontAddNonExistentFiles) || f.exists())
  15848. {
  15849. bool needsAvoiding = false;
  15850. if (filesToAvoid != 0)
  15851. {
  15852. const File** avoid = filesToAvoid;
  15853. while (*avoid != 0)
  15854. {
  15855. if (f == **avoid)
  15856. {
  15857. needsAvoiding = true;
  15858. break;
  15859. }
  15860. ++avoid;
  15861. }
  15862. }
  15863. if (! needsAvoiding)
  15864. {
  15865. menuToAddTo.addItem (baseItemId + i,
  15866. showFullPaths ? f.getFullPathName()
  15867. : f.getFileName());
  15868. ++num;
  15869. }
  15870. }
  15871. }
  15872. return num;
  15873. }
  15874. const String RecentlyOpenedFilesList::toString() const
  15875. {
  15876. return files.joinIntoString ("\n");
  15877. }
  15878. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15879. {
  15880. clear();
  15881. files.addLines (stringifiedVersion);
  15882. setMaxNumberOfItems (maxNumberOfItems);
  15883. }
  15884. END_JUCE_NAMESPACE
  15885. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15886. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15887. BEGIN_JUCE_NAMESPACE
  15888. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15889. const int minimumTransactions)
  15890. : totalUnitsStored (0),
  15891. nextIndex (0),
  15892. newTransaction (true),
  15893. reentrancyCheck (false)
  15894. {
  15895. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15896. minimumTransactions);
  15897. }
  15898. UndoManager::~UndoManager()
  15899. {
  15900. clearUndoHistory();
  15901. }
  15902. void UndoManager::clearUndoHistory()
  15903. {
  15904. transactions.clear();
  15905. transactionNames.clear();
  15906. totalUnitsStored = 0;
  15907. nextIndex = 0;
  15908. sendChangeMessage();
  15909. }
  15910. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15911. {
  15912. return totalUnitsStored;
  15913. }
  15914. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15915. const int minimumTransactions)
  15916. {
  15917. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15918. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15919. }
  15920. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15921. {
  15922. if (command_ != 0)
  15923. {
  15924. ScopedPointer<UndoableAction> command (command_);
  15925. if (actionName.isNotEmpty())
  15926. currentTransactionName = actionName;
  15927. if (reentrancyCheck)
  15928. {
  15929. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15930. // undo() methods, or else these actions won't actually get done.
  15931. return false;
  15932. }
  15933. else if (command->perform())
  15934. {
  15935. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15936. if (commandSet != 0 && ! newTransaction)
  15937. {
  15938. UndoableAction* lastAction = commandSet->getLast();
  15939. if (lastAction != 0)
  15940. {
  15941. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15942. if (coalescedAction != 0)
  15943. {
  15944. command = coalescedAction;
  15945. totalUnitsStored -= lastAction->getSizeInUnits();
  15946. commandSet->removeLast();
  15947. }
  15948. }
  15949. }
  15950. else
  15951. {
  15952. commandSet = new OwnedArray<UndoableAction>();
  15953. transactions.insert (nextIndex, commandSet);
  15954. transactionNames.insert (nextIndex, currentTransactionName);
  15955. ++nextIndex;
  15956. }
  15957. totalUnitsStored += command->getSizeInUnits();
  15958. commandSet->add (command.release());
  15959. newTransaction = false;
  15960. while (nextIndex < transactions.size())
  15961. {
  15962. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15963. for (int i = lastSet->size(); --i >= 0;)
  15964. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15965. transactions.removeLast();
  15966. transactionNames.remove (transactionNames.size() - 1);
  15967. }
  15968. while (nextIndex > 0
  15969. && totalUnitsStored > maxNumUnitsToKeep
  15970. && transactions.size() > minimumTransactionsToKeep)
  15971. {
  15972. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15973. for (int i = firstSet->size(); --i >= 0;)
  15974. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15975. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15976. transactions.remove (0);
  15977. transactionNames.remove (0);
  15978. --nextIndex;
  15979. }
  15980. sendChangeMessage();
  15981. return true;
  15982. }
  15983. }
  15984. return false;
  15985. }
  15986. void UndoManager::beginNewTransaction (const String& actionName)
  15987. {
  15988. newTransaction = true;
  15989. currentTransactionName = actionName;
  15990. }
  15991. void UndoManager::setCurrentTransactionName (const String& newName)
  15992. {
  15993. currentTransactionName = newName;
  15994. }
  15995. bool UndoManager::canUndo() const
  15996. {
  15997. return nextIndex > 0;
  15998. }
  15999. bool UndoManager::canRedo() const
  16000. {
  16001. return nextIndex < transactions.size();
  16002. }
  16003. const String UndoManager::getUndoDescription() const
  16004. {
  16005. return transactionNames [nextIndex - 1];
  16006. }
  16007. const String UndoManager::getRedoDescription() const
  16008. {
  16009. return transactionNames [nextIndex];
  16010. }
  16011. bool UndoManager::undo()
  16012. {
  16013. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16014. if (commandSet == 0)
  16015. return false;
  16016. bool failed = false;
  16017. {
  16018. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16019. for (int i = commandSet->size(); --i >= 0;)
  16020. {
  16021. if (! commandSet->getUnchecked(i)->undo())
  16022. {
  16023. jassertfalse;
  16024. failed = true;
  16025. break;
  16026. }
  16027. }
  16028. }
  16029. if (failed)
  16030. clearUndoHistory();
  16031. else
  16032. --nextIndex;
  16033. beginNewTransaction();
  16034. sendChangeMessage();
  16035. return true;
  16036. }
  16037. bool UndoManager::redo()
  16038. {
  16039. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16040. if (commandSet == 0)
  16041. return false;
  16042. bool failed = false;
  16043. {
  16044. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16045. for (int i = 0; i < commandSet->size(); ++i)
  16046. {
  16047. if (! commandSet->getUnchecked(i)->perform())
  16048. {
  16049. jassertfalse;
  16050. failed = true;
  16051. break;
  16052. }
  16053. }
  16054. }
  16055. if (failed)
  16056. clearUndoHistory();
  16057. else
  16058. ++nextIndex;
  16059. beginNewTransaction();
  16060. sendChangeMessage();
  16061. return true;
  16062. }
  16063. bool UndoManager::undoCurrentTransactionOnly()
  16064. {
  16065. return newTransaction ? false : undo();
  16066. }
  16067. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16068. {
  16069. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16070. if (commandSet != 0 && ! newTransaction)
  16071. {
  16072. for (int i = 0; i < commandSet->size(); ++i)
  16073. actionsFound.add (commandSet->getUnchecked(i));
  16074. }
  16075. }
  16076. int UndoManager::getNumActionsInCurrentTransaction() const
  16077. {
  16078. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16079. if (commandSet != 0 && ! newTransaction)
  16080. return commandSet->size();
  16081. return 0;
  16082. }
  16083. END_JUCE_NAMESPACE
  16084. /*** End of inlined file: juce_UndoManager.cpp ***/
  16085. /*** Start of inlined file: juce_UnitTest.cpp ***/
  16086. BEGIN_JUCE_NAMESPACE
  16087. UnitTest::UnitTest (const String& name_)
  16088. : name (name_), runner (0)
  16089. {
  16090. getAllTests().add (this);
  16091. }
  16092. UnitTest::~UnitTest()
  16093. {
  16094. getAllTests().removeValue (this);
  16095. }
  16096. Array<UnitTest*>& UnitTest::getAllTests()
  16097. {
  16098. static Array<UnitTest*> tests;
  16099. return tests;
  16100. }
  16101. void UnitTest::initialise() {}
  16102. void UnitTest::shutdown() {}
  16103. void UnitTest::performTest (UnitTestRunner* const runner_)
  16104. {
  16105. jassert (runner_ != 0);
  16106. runner = runner_;
  16107. initialise();
  16108. runTest();
  16109. shutdown();
  16110. }
  16111. void UnitTest::logMessage (const String& message)
  16112. {
  16113. runner->logMessage (message);
  16114. }
  16115. void UnitTest::beginTest (const String& testName)
  16116. {
  16117. runner->beginNewTest (this, testName);
  16118. }
  16119. void UnitTest::expect (const bool result, const String& failureMessage)
  16120. {
  16121. if (result)
  16122. runner->addPass();
  16123. else
  16124. runner->addFail (failureMessage);
  16125. }
  16126. UnitTestRunner::UnitTestRunner()
  16127. : currentTest (0), assertOnFailure (false)
  16128. {
  16129. }
  16130. UnitTestRunner::~UnitTestRunner()
  16131. {
  16132. }
  16133. int UnitTestRunner::getNumResults() const throw()
  16134. {
  16135. return results.size();
  16136. }
  16137. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  16138. {
  16139. return results [index];
  16140. }
  16141. void UnitTestRunner::resultsUpdated()
  16142. {
  16143. }
  16144. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  16145. {
  16146. results.clear();
  16147. assertOnFailure = assertOnFailure_;
  16148. resultsUpdated();
  16149. for (int i = 0; i < tests.size(); ++i)
  16150. {
  16151. try
  16152. {
  16153. tests.getUnchecked(i)->performTest (this);
  16154. }
  16155. catch (...)
  16156. {
  16157. addFail ("An unhandled exception was thrown!");
  16158. }
  16159. }
  16160. endTest();
  16161. }
  16162. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  16163. {
  16164. runTests (UnitTest::getAllTests(), assertOnFailure_);
  16165. }
  16166. void UnitTestRunner::logMessage (const String& message)
  16167. {
  16168. Logger::writeToLog (message);
  16169. }
  16170. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  16171. {
  16172. endTest();
  16173. currentTest = test;
  16174. TestResult* const r = new TestResult();
  16175. r->unitTestName = test->getName();
  16176. r->subcategoryName = subCategory;
  16177. r->passes = 0;
  16178. r->failures = 0;
  16179. results.add (r);
  16180. logMessage ("-----------------------------------------------------------------");
  16181. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  16182. resultsUpdated();
  16183. }
  16184. void UnitTestRunner::endTest()
  16185. {
  16186. if (results.size() > 0)
  16187. {
  16188. TestResult* const r = results.getLast();
  16189. if (r->failures > 0)
  16190. {
  16191. String m ("FAILED!! ");
  16192. m << r->failures << (r->failures == 1 ? " test" : " tests")
  16193. << " failed, out of a total of " << (r->passes + r->failures);
  16194. logMessage (String::empty);
  16195. logMessage (m);
  16196. logMessage (String::empty);
  16197. }
  16198. else
  16199. {
  16200. logMessage ("All tests completed successfully");
  16201. }
  16202. }
  16203. }
  16204. void UnitTestRunner::addPass()
  16205. {
  16206. {
  16207. const ScopedLock sl (results.getLock());
  16208. TestResult* const r = results.getLast();
  16209. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  16210. r->passes++;
  16211. String message ("Test ");
  16212. message << (r->failures + r->passes) << " passed";
  16213. logMessage (message);
  16214. }
  16215. resultsUpdated();
  16216. }
  16217. void UnitTestRunner::addFail (const String& failureMessage)
  16218. {
  16219. {
  16220. const ScopedLock sl (results.getLock());
  16221. TestResult* const r = results.getLast();
  16222. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  16223. r->failures++;
  16224. String message ("!!! Test ");
  16225. message << (r->failures + r->passes) << " failed";
  16226. if (failureMessage.isNotEmpty())
  16227. message << ": " << failureMessage;
  16228. r->messages.add (message);
  16229. logMessage (message);
  16230. }
  16231. resultsUpdated();
  16232. if (assertOnFailure) { jassertfalse }
  16233. }
  16234. END_JUCE_NAMESPACE
  16235. /*** End of inlined file: juce_UnitTest.cpp ***/
  16236. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  16237. BEGIN_JUCE_NAMESPACE
  16238. DeletedAtShutdown::DeletedAtShutdown()
  16239. {
  16240. const ScopedLock sl (getLock());
  16241. getObjects().add (this);
  16242. }
  16243. DeletedAtShutdown::~DeletedAtShutdown()
  16244. {
  16245. const ScopedLock sl (getLock());
  16246. getObjects().removeValue (this);
  16247. }
  16248. void DeletedAtShutdown::deleteAll()
  16249. {
  16250. // make a local copy of the array, so it can't get into a loop if something
  16251. // creates another DeletedAtShutdown object during its destructor.
  16252. Array <DeletedAtShutdown*> localCopy;
  16253. {
  16254. const ScopedLock sl (getLock());
  16255. localCopy = getObjects();
  16256. }
  16257. for (int i = localCopy.size(); --i >= 0;)
  16258. {
  16259. JUCE_TRY
  16260. {
  16261. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  16262. // double-check that it's not already been deleted during another object's destructor.
  16263. {
  16264. const ScopedLock sl (getLock());
  16265. if (! getObjects().contains (deletee))
  16266. deletee = 0;
  16267. }
  16268. delete deletee;
  16269. }
  16270. JUCE_CATCH_EXCEPTION
  16271. }
  16272. // if no objects got re-created during shutdown, this should have been emptied by their
  16273. // destructors
  16274. jassert (getObjects().size() == 0);
  16275. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  16276. }
  16277. CriticalSection& DeletedAtShutdown::getLock()
  16278. {
  16279. static CriticalSection lock;
  16280. return lock;
  16281. }
  16282. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  16283. {
  16284. static Array <DeletedAtShutdown*> objects;
  16285. return objects;
  16286. }
  16287. END_JUCE_NAMESPACE
  16288. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  16289. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16290. BEGIN_JUCE_NAMESPACE
  16291. static const char* const aiffFormatName = "AIFF file";
  16292. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16293. class AiffAudioFormatReader : public AudioFormatReader
  16294. {
  16295. public:
  16296. int bytesPerFrame;
  16297. int64 dataChunkStart;
  16298. bool littleEndian;
  16299. AiffAudioFormatReader (InputStream* in)
  16300. : AudioFormatReader (in, TRANS (aiffFormatName))
  16301. {
  16302. if (input->readInt() == chunkName ("FORM"))
  16303. {
  16304. const int len = input->readIntBigEndian();
  16305. const int64 end = input->getPosition() + len;
  16306. const int nextType = input->readInt();
  16307. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16308. {
  16309. bool hasGotVer = false;
  16310. bool hasGotData = false;
  16311. bool hasGotType = false;
  16312. while (input->getPosition() < end)
  16313. {
  16314. const int type = input->readInt();
  16315. const uint32 length = (uint32) input->readIntBigEndian();
  16316. const int64 chunkEnd = input->getPosition() + length;
  16317. if (type == chunkName ("FVER"))
  16318. {
  16319. hasGotVer = true;
  16320. const int ver = input->readIntBigEndian();
  16321. if (ver != 0 && ver != (int) 0xa2805140)
  16322. break;
  16323. }
  16324. else if (type == chunkName ("COMM"))
  16325. {
  16326. hasGotType = true;
  16327. numChannels = (unsigned int) input->readShortBigEndian();
  16328. lengthInSamples = input->readIntBigEndian();
  16329. bitsPerSample = input->readShortBigEndian();
  16330. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16331. unsigned char sampleRateBytes[10];
  16332. input->read (sampleRateBytes, 10);
  16333. const int byte0 = sampleRateBytes[0];
  16334. if ((byte0 & 0x80) != 0
  16335. || byte0 <= 0x3F || byte0 > 0x40
  16336. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16337. break;
  16338. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16339. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16340. sampleRate = (int) sampRate;
  16341. if (length <= 18)
  16342. {
  16343. // some types don't have a chunk large enough to include a compression
  16344. // type, so assume it's just big-endian pcm
  16345. littleEndian = false;
  16346. }
  16347. else
  16348. {
  16349. const int compType = input->readInt();
  16350. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16351. {
  16352. littleEndian = false;
  16353. }
  16354. else if (compType == chunkName ("sowt"))
  16355. {
  16356. littleEndian = true;
  16357. }
  16358. else
  16359. {
  16360. sampleRate = 0;
  16361. break;
  16362. }
  16363. }
  16364. }
  16365. else if (type == chunkName ("SSND"))
  16366. {
  16367. hasGotData = true;
  16368. const int offset = input->readIntBigEndian();
  16369. dataChunkStart = input->getPosition() + 4 + offset;
  16370. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16371. }
  16372. else if ((hasGotVer && hasGotData && hasGotType)
  16373. || chunkEnd < input->getPosition()
  16374. || input->isExhausted())
  16375. {
  16376. break;
  16377. }
  16378. input->setPosition (chunkEnd);
  16379. }
  16380. }
  16381. }
  16382. }
  16383. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16384. int64 startSampleInFile, int numSamples)
  16385. {
  16386. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16387. if (samplesAvailable < numSamples)
  16388. {
  16389. for (int i = numDestChannels; --i >= 0;)
  16390. if (destSamples[i] != 0)
  16391. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16392. numSamples = (int) samplesAvailable;
  16393. }
  16394. if (numSamples <= 0)
  16395. return true;
  16396. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16397. while (numSamples > 0)
  16398. {
  16399. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16400. char tempBuffer [tempBufSize];
  16401. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16402. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16403. if (bytesRead < numThisTime * bytesPerFrame)
  16404. {
  16405. jassert (bytesRead >= 0);
  16406. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16407. }
  16408. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16409. if (littleEndian)
  16410. {
  16411. switch (bitsPerSample)
  16412. {
  16413. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16414. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16415. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16416. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16417. default: jassertfalse; break;
  16418. }
  16419. }
  16420. else
  16421. {
  16422. switch (bitsPerSample)
  16423. {
  16424. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16425. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16426. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16427. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16428. default: jassertfalse; break;
  16429. }
  16430. }
  16431. startOffsetInDestBuffer += numThisTime;
  16432. numSamples -= numThisTime;
  16433. }
  16434. return true;
  16435. }
  16436. private:
  16437. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16439. };
  16440. class AiffAudioFormatWriter : public AudioFormatWriter
  16441. {
  16442. public:
  16443. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16444. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16445. lengthInSamples (0),
  16446. bytesWritten (0),
  16447. writeFailed (false)
  16448. {
  16449. headerPosition = out->getPosition();
  16450. writeHeader();
  16451. }
  16452. ~AiffAudioFormatWriter()
  16453. {
  16454. if ((bytesWritten & 1) != 0)
  16455. output->writeByte (0);
  16456. writeHeader();
  16457. }
  16458. bool write (const int** data, int numSamples)
  16459. {
  16460. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16461. if (writeFailed)
  16462. return false;
  16463. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16464. tempBlock.ensureSize (bytes, false);
  16465. switch (bitsPerSample)
  16466. {
  16467. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16468. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16469. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16470. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16471. default: jassertfalse; break;
  16472. }
  16473. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16474. || ! output->write (tempBlock.getData(), bytes))
  16475. {
  16476. // failed to write to disk, so let's try writing the header.
  16477. // If it's just run out of disk space, then if it does manage
  16478. // to write the header, we'll still have a useable file..
  16479. writeHeader();
  16480. writeFailed = true;
  16481. return false;
  16482. }
  16483. else
  16484. {
  16485. bytesWritten += bytes;
  16486. lengthInSamples += numSamples;
  16487. return true;
  16488. }
  16489. }
  16490. private:
  16491. MemoryBlock tempBlock;
  16492. uint32 lengthInSamples, bytesWritten;
  16493. int64 headerPosition;
  16494. bool writeFailed;
  16495. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16496. void writeHeader()
  16497. {
  16498. const bool couldSeekOk = output->setPosition (headerPosition);
  16499. (void) couldSeekOk;
  16500. // if this fails, you've given it an output stream that can't seek! It needs
  16501. // to be able to seek back to write the header
  16502. jassert (couldSeekOk);
  16503. const int headerLen = 54;
  16504. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16505. audioBytes += (audioBytes & 1);
  16506. output->writeInt (chunkName ("FORM"));
  16507. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16508. output->writeInt (chunkName ("AIFF"));
  16509. output->writeInt (chunkName ("COMM"));
  16510. output->writeIntBigEndian (18);
  16511. output->writeShortBigEndian ((short) numChannels);
  16512. output->writeIntBigEndian (lengthInSamples);
  16513. output->writeShortBigEndian ((short) bitsPerSample);
  16514. uint8 sampleRateBytes[10];
  16515. zeromem (sampleRateBytes, 10);
  16516. if (sampleRate <= 1)
  16517. {
  16518. sampleRateBytes[0] = 0x3f;
  16519. sampleRateBytes[1] = 0xff;
  16520. sampleRateBytes[2] = 0x80;
  16521. }
  16522. else
  16523. {
  16524. int mask = 0x40000000;
  16525. sampleRateBytes[0] = 0x40;
  16526. if (sampleRate >= mask)
  16527. {
  16528. jassertfalse;
  16529. sampleRateBytes[1] = 0x1d;
  16530. }
  16531. else
  16532. {
  16533. int n = (int) sampleRate;
  16534. int i;
  16535. for (i = 0; i <= 32 ; ++i)
  16536. {
  16537. if ((n & mask) != 0)
  16538. break;
  16539. mask >>= 1;
  16540. }
  16541. n = n << (i + 1);
  16542. sampleRateBytes[1] = (uint8) (29 - i);
  16543. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16544. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16545. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16546. sampleRateBytes[5] = (uint8) (n & 0xff);
  16547. }
  16548. }
  16549. output->write (sampleRateBytes, 10);
  16550. output->writeInt (chunkName ("SSND"));
  16551. output->writeIntBigEndian (audioBytes + 8);
  16552. output->writeInt (0);
  16553. output->writeInt (0);
  16554. jassert (output->getPosition() == headerLen);
  16555. }
  16556. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16557. };
  16558. AiffAudioFormat::AiffAudioFormat()
  16559. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16560. {
  16561. }
  16562. AiffAudioFormat::~AiffAudioFormat()
  16563. {
  16564. }
  16565. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16566. {
  16567. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16568. return Array <int> (rates);
  16569. }
  16570. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16571. {
  16572. const int depths[] = { 8, 16, 24, 0 };
  16573. return Array <int> (depths);
  16574. }
  16575. bool AiffAudioFormat::canDoStereo() { return true; }
  16576. bool AiffAudioFormat::canDoMono() { return true; }
  16577. #if JUCE_MAC
  16578. bool AiffAudioFormat::canHandleFile (const File& f)
  16579. {
  16580. if (AudioFormat::canHandleFile (f))
  16581. return true;
  16582. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16583. return type == 'AIFF' || type == 'AIFC'
  16584. || type == 'aiff' || type == 'aifc';
  16585. }
  16586. #endif
  16587. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16588. {
  16589. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16590. if (w->sampleRate > 0)
  16591. return w.release();
  16592. if (! deleteStreamIfOpeningFails)
  16593. w->input = 0;
  16594. return 0;
  16595. }
  16596. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16597. double sampleRate,
  16598. unsigned int numberOfChannels,
  16599. int bitsPerSample,
  16600. const StringPairArray& /*metadataValues*/,
  16601. int /*qualityOptionIndex*/)
  16602. {
  16603. if (getPossibleBitDepths().contains (bitsPerSample))
  16604. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16605. return 0;
  16606. }
  16607. END_JUCE_NAMESPACE
  16608. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16609. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16610. BEGIN_JUCE_NAMESPACE
  16611. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16612. : formatName (name),
  16613. fileExtensions (extensions)
  16614. {
  16615. }
  16616. AudioFormat::~AudioFormat()
  16617. {
  16618. }
  16619. bool AudioFormat::canHandleFile (const File& f)
  16620. {
  16621. for (int i = 0; i < fileExtensions.size(); ++i)
  16622. if (f.hasFileExtension (fileExtensions[i]))
  16623. return true;
  16624. return false;
  16625. }
  16626. const String& AudioFormat::getFormatName() const { return formatName; }
  16627. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16628. bool AudioFormat::isCompressed() { return false; }
  16629. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16630. END_JUCE_NAMESPACE
  16631. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16632. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16633. BEGIN_JUCE_NAMESPACE
  16634. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16635. const String& formatName_)
  16636. : sampleRate (0),
  16637. bitsPerSample (0),
  16638. lengthInSamples (0),
  16639. numChannels (0),
  16640. usesFloatingPointData (false),
  16641. input (in),
  16642. formatName (formatName_)
  16643. {
  16644. }
  16645. AudioFormatReader::~AudioFormatReader()
  16646. {
  16647. delete input;
  16648. }
  16649. bool AudioFormatReader::read (int* const* destSamples,
  16650. int numDestChannels,
  16651. int64 startSampleInSource,
  16652. int numSamplesToRead,
  16653. const bool fillLeftoverChannelsWithCopies)
  16654. {
  16655. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16656. int startOffsetInDestBuffer = 0;
  16657. if (startSampleInSource < 0)
  16658. {
  16659. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16660. for (int i = numDestChannels; --i >= 0;)
  16661. if (destSamples[i] != 0)
  16662. zeromem (destSamples[i], sizeof (int) * silence);
  16663. startOffsetInDestBuffer += silence;
  16664. numSamplesToRead -= silence;
  16665. startSampleInSource = 0;
  16666. }
  16667. if (numSamplesToRead <= 0)
  16668. return true;
  16669. if (! readSamples (const_cast<int**> (destSamples),
  16670. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16671. startSampleInSource, numSamplesToRead))
  16672. return false;
  16673. if (numDestChannels > (int) numChannels)
  16674. {
  16675. if (fillLeftoverChannelsWithCopies)
  16676. {
  16677. int* lastFullChannel = destSamples[0];
  16678. for (int i = (int) numChannels; --i > 0;)
  16679. {
  16680. if (destSamples[i] != 0)
  16681. {
  16682. lastFullChannel = destSamples[i];
  16683. break;
  16684. }
  16685. }
  16686. if (lastFullChannel != 0)
  16687. for (int i = numChannels; i < numDestChannels; ++i)
  16688. if (destSamples[i] != 0)
  16689. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16690. }
  16691. else
  16692. {
  16693. for (int i = numChannels; i < numDestChannels; ++i)
  16694. if (destSamples[i] != 0)
  16695. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16696. }
  16697. }
  16698. return true;
  16699. }
  16700. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16701. int64 numSamples,
  16702. float& lowestLeft, float& highestLeft,
  16703. float& lowestRight, float& highestRight)
  16704. {
  16705. if (numSamples <= 0)
  16706. {
  16707. lowestLeft = 0;
  16708. lowestRight = 0;
  16709. highestLeft = 0;
  16710. highestRight = 0;
  16711. return;
  16712. }
  16713. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16714. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16715. int* tempBuffer[3];
  16716. tempBuffer[0] = tempSpace.getData();
  16717. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16718. tempBuffer[2] = 0;
  16719. if (usesFloatingPointData)
  16720. {
  16721. float lmin = 1.0e6f;
  16722. float lmax = -lmin;
  16723. float rmin = lmin;
  16724. float rmax = lmax;
  16725. while (numSamples > 0)
  16726. {
  16727. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16728. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16729. numSamples -= numToDo;
  16730. startSampleInFile += numToDo;
  16731. float bufMin, bufMax;
  16732. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16733. lmin = jmin (lmin, bufMin);
  16734. lmax = jmax (lmax, bufMax);
  16735. if (numChannels > 1)
  16736. {
  16737. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16738. rmin = jmin (rmin, bufMin);
  16739. rmax = jmax (rmax, bufMax);
  16740. }
  16741. }
  16742. if (numChannels <= 1)
  16743. {
  16744. rmax = lmax;
  16745. rmin = lmin;
  16746. }
  16747. lowestLeft = lmin;
  16748. highestLeft = lmax;
  16749. lowestRight = rmin;
  16750. highestRight = rmax;
  16751. }
  16752. else
  16753. {
  16754. int lmax = std::numeric_limits<int>::min();
  16755. int lmin = std::numeric_limits<int>::max();
  16756. int rmax = std::numeric_limits<int>::min();
  16757. int rmin = std::numeric_limits<int>::max();
  16758. while (numSamples > 0)
  16759. {
  16760. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16761. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16762. break;
  16763. numSamples -= numToDo;
  16764. startSampleInFile += numToDo;
  16765. for (int j = numChannels; --j >= 0;)
  16766. {
  16767. int bufMin, bufMax;
  16768. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16769. if (j == 0)
  16770. {
  16771. lmax = jmax (lmax, bufMax);
  16772. lmin = jmin (lmin, bufMin);
  16773. }
  16774. else
  16775. {
  16776. rmax = jmax (rmax, bufMax);
  16777. rmin = jmin (rmin, bufMin);
  16778. }
  16779. }
  16780. }
  16781. if (numChannels <= 1)
  16782. {
  16783. rmax = lmax;
  16784. rmin = lmin;
  16785. }
  16786. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16787. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16788. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16789. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16790. }
  16791. }
  16792. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16793. int64 numSamplesToSearch,
  16794. const double magnitudeRangeMinimum,
  16795. const double magnitudeRangeMaximum,
  16796. const int minimumConsecutiveSamples)
  16797. {
  16798. if (numSamplesToSearch == 0)
  16799. return -1;
  16800. const int bufferSize = 4096;
  16801. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16802. int* tempBuffer[3];
  16803. tempBuffer[0] = tempSpace.getData();
  16804. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16805. tempBuffer[2] = 0;
  16806. int consecutive = 0;
  16807. int64 firstMatchPos = -1;
  16808. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16809. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16810. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16811. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16812. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16813. while (numSamplesToSearch != 0)
  16814. {
  16815. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16816. int64 bufferStart = startSample;
  16817. if (numSamplesToSearch < 0)
  16818. bufferStart -= numThisTime;
  16819. if (bufferStart >= (int) lengthInSamples)
  16820. break;
  16821. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16822. int num = numThisTime;
  16823. while (--num >= 0)
  16824. {
  16825. if (numSamplesToSearch < 0)
  16826. --startSample;
  16827. bool matches = false;
  16828. const int index = (int) (startSample - bufferStart);
  16829. if (usesFloatingPointData)
  16830. {
  16831. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16832. if (sample1 >= magnitudeRangeMinimum
  16833. && sample1 <= magnitudeRangeMaximum)
  16834. {
  16835. matches = true;
  16836. }
  16837. else if (numChannels > 1)
  16838. {
  16839. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16840. matches = (sample2 >= magnitudeRangeMinimum
  16841. && sample2 <= magnitudeRangeMaximum);
  16842. }
  16843. }
  16844. else
  16845. {
  16846. const int sample1 = abs (tempBuffer[0] [index]);
  16847. if (sample1 >= intMagnitudeRangeMinimum
  16848. && sample1 <= intMagnitudeRangeMaximum)
  16849. {
  16850. matches = true;
  16851. }
  16852. else if (numChannels > 1)
  16853. {
  16854. const int sample2 = abs (tempBuffer[1][index]);
  16855. matches = (sample2 >= intMagnitudeRangeMinimum
  16856. && sample2 <= intMagnitudeRangeMaximum);
  16857. }
  16858. }
  16859. if (matches)
  16860. {
  16861. if (firstMatchPos < 0)
  16862. firstMatchPos = startSample;
  16863. if (++consecutive >= minimumConsecutiveSamples)
  16864. {
  16865. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16866. return -1;
  16867. return firstMatchPos;
  16868. }
  16869. }
  16870. else
  16871. {
  16872. consecutive = 0;
  16873. firstMatchPos = -1;
  16874. }
  16875. if (numSamplesToSearch > 0)
  16876. ++startSample;
  16877. }
  16878. if (numSamplesToSearch > 0)
  16879. numSamplesToSearch -= numThisTime;
  16880. else
  16881. numSamplesToSearch += numThisTime;
  16882. }
  16883. return -1;
  16884. }
  16885. END_JUCE_NAMESPACE
  16886. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16887. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16888. BEGIN_JUCE_NAMESPACE
  16889. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16890. const String& formatName_,
  16891. const double rate,
  16892. const unsigned int numChannels_,
  16893. const unsigned int bitsPerSample_)
  16894. : sampleRate (rate),
  16895. numChannels (numChannels_),
  16896. bitsPerSample (bitsPerSample_),
  16897. usesFloatingPointData (false),
  16898. output (out),
  16899. formatName (formatName_)
  16900. {
  16901. }
  16902. AudioFormatWriter::~AudioFormatWriter()
  16903. {
  16904. delete output;
  16905. }
  16906. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16907. int64 startSample,
  16908. int64 numSamplesToRead)
  16909. {
  16910. const int bufferSize = 16384;
  16911. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16912. int* buffers [128];
  16913. zerostruct (buffers);
  16914. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16915. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16916. if (numSamplesToRead < 0)
  16917. numSamplesToRead = reader.lengthInSamples;
  16918. while (numSamplesToRead > 0)
  16919. {
  16920. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16921. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16922. return false;
  16923. if (reader.usesFloatingPointData != isFloatingPoint())
  16924. {
  16925. int** bufferChan = buffers;
  16926. while (*bufferChan != 0)
  16927. {
  16928. int* b = *bufferChan++;
  16929. if (isFloatingPoint())
  16930. {
  16931. // int -> float
  16932. const double factor = 1.0 / std::numeric_limits<int>::max();
  16933. for (int i = 0; i < numToDo; ++i)
  16934. ((float*) b)[i] = (float) (factor * b[i]);
  16935. }
  16936. else
  16937. {
  16938. // float -> int
  16939. for (int i = 0; i < numToDo; ++i)
  16940. {
  16941. const double samp = *(const float*) b;
  16942. if (samp <= -1.0)
  16943. *b++ = std::numeric_limits<int>::min();
  16944. else if (samp >= 1.0)
  16945. *b++ = std::numeric_limits<int>::max();
  16946. else
  16947. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16948. }
  16949. }
  16950. }
  16951. }
  16952. if (! write (const_cast<const int**> (buffers), numToDo))
  16953. return false;
  16954. numSamplesToRead -= numToDo;
  16955. startSample += numToDo;
  16956. }
  16957. return true;
  16958. }
  16959. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16960. {
  16961. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16962. while (numSamplesToRead > 0)
  16963. {
  16964. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16965. AudioSourceChannelInfo info;
  16966. info.buffer = &tempBuffer;
  16967. info.startSample = 0;
  16968. info.numSamples = numToDo;
  16969. info.clearActiveBufferRegion();
  16970. source.getNextAudioBlock (info);
  16971. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16972. return false;
  16973. numSamplesToRead -= numToDo;
  16974. }
  16975. return true;
  16976. }
  16977. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16978. {
  16979. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16980. if (numSamples <= 0)
  16981. return true;
  16982. HeapBlock<int> tempBuffer;
  16983. HeapBlock<int*> chans (numChannels + 1);
  16984. chans [numChannels] = 0;
  16985. if (isFloatingPoint())
  16986. {
  16987. for (int i = numChannels; --i >= 0;)
  16988. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  16989. }
  16990. else
  16991. {
  16992. tempBuffer.malloc (numSamples * numChannels);
  16993. for (unsigned int i = 0; i < numChannels; ++i)
  16994. {
  16995. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  16996. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  16997. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  16998. SourceSampleType sourceData (source.getSampleData (i, startSample));
  16999. destData.convertSamples (sourceData, numSamples);
  17000. }
  17001. }
  17002. return write ((const int**) chans.getData(), numSamples);
  17003. }
  17004. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17005. public AbstractFifo
  17006. {
  17007. public:
  17008. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  17009. : AbstractFifo (bufferSize_),
  17010. buffer (numChannels, bufferSize_),
  17011. timeSliceThread (timeSliceThread_),
  17012. writer (writer_),
  17013. thumbnailToUpdate (0),
  17014. samplesWritten (0),
  17015. isRunning (true)
  17016. {
  17017. timeSliceThread.addTimeSliceClient (this);
  17018. }
  17019. ~Buffer()
  17020. {
  17021. isRunning = false;
  17022. timeSliceThread.removeTimeSliceClient (this);
  17023. while (useTimeSlice() == 0)
  17024. {}
  17025. }
  17026. bool write (const float** data, int numSamples)
  17027. {
  17028. if (numSamples <= 0 || ! isRunning)
  17029. return true;
  17030. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17031. int start1, size1, start2, size2;
  17032. prepareToWrite (numSamples, start1, size1, start2, size2);
  17033. if (size1 + size2 < numSamples)
  17034. return false;
  17035. for (int i = buffer.getNumChannels(); --i >= 0;)
  17036. {
  17037. buffer.copyFrom (i, start1, data[i], size1);
  17038. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17039. }
  17040. finishedWrite (size1 + size2);
  17041. timeSliceThread.notify();
  17042. return true;
  17043. }
  17044. int useTimeSlice()
  17045. {
  17046. const int numToDo = getTotalSize() / 4;
  17047. int start1, size1, start2, size2;
  17048. prepareToRead (numToDo, start1, size1, start2, size2);
  17049. if (size1 <= 0)
  17050. return 10;
  17051. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17052. const ScopedLock sl (thumbnailLock);
  17053. if (thumbnailToUpdate != 0)
  17054. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17055. samplesWritten += size1;
  17056. if (size2 > 0)
  17057. {
  17058. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17059. if (thumbnailToUpdate != 0)
  17060. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17061. samplesWritten += size2;
  17062. }
  17063. finishedRead (size1 + size2);
  17064. return 0;
  17065. }
  17066. void setThumbnail (AudioThumbnail* thumb)
  17067. {
  17068. if (thumb != 0)
  17069. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17070. const ScopedLock sl (thumbnailLock);
  17071. thumbnailToUpdate = thumb;
  17072. samplesWritten = 0;
  17073. }
  17074. private:
  17075. AudioSampleBuffer buffer;
  17076. TimeSliceThread& timeSliceThread;
  17077. ScopedPointer<AudioFormatWriter> writer;
  17078. CriticalSection thumbnailLock;
  17079. AudioThumbnail* thumbnailToUpdate;
  17080. int64 samplesWritten;
  17081. volatile bool isRunning;
  17082. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17083. };
  17084. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17085. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17086. {
  17087. }
  17088. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17089. {
  17090. }
  17091. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17092. {
  17093. return buffer->write (data, numSamples);
  17094. }
  17095. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17096. {
  17097. buffer->setThumbnail (thumb);
  17098. }
  17099. END_JUCE_NAMESPACE
  17100. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17101. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17102. BEGIN_JUCE_NAMESPACE
  17103. AudioFormatManager::AudioFormatManager()
  17104. : defaultFormatIndex (0)
  17105. {
  17106. }
  17107. AudioFormatManager::~AudioFormatManager()
  17108. {
  17109. }
  17110. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17111. {
  17112. jassert (newFormat != 0);
  17113. if (newFormat != 0)
  17114. {
  17115. #if JUCE_DEBUG
  17116. for (int i = getNumKnownFormats(); --i >= 0;)
  17117. {
  17118. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17119. {
  17120. jassertfalse; // trying to add the same format twice!
  17121. }
  17122. }
  17123. #endif
  17124. if (makeThisTheDefaultFormat)
  17125. defaultFormatIndex = getNumKnownFormats();
  17126. knownFormats.add (newFormat);
  17127. }
  17128. }
  17129. void AudioFormatManager::registerBasicFormats()
  17130. {
  17131. #if JUCE_MAC
  17132. registerFormat (new AiffAudioFormat(), true);
  17133. registerFormat (new WavAudioFormat(), false);
  17134. #else
  17135. registerFormat (new WavAudioFormat(), true);
  17136. registerFormat (new AiffAudioFormat(), false);
  17137. #endif
  17138. #if JUCE_USE_FLAC
  17139. registerFormat (new FlacAudioFormat(), false);
  17140. #endif
  17141. #if JUCE_USE_OGGVORBIS
  17142. registerFormat (new OggVorbisAudioFormat(), false);
  17143. #endif
  17144. }
  17145. void AudioFormatManager::clearFormats()
  17146. {
  17147. knownFormats.clear();
  17148. defaultFormatIndex = 0;
  17149. }
  17150. int AudioFormatManager::getNumKnownFormats() const
  17151. {
  17152. return knownFormats.size();
  17153. }
  17154. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17155. {
  17156. return knownFormats [index];
  17157. }
  17158. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17159. {
  17160. return getKnownFormat (defaultFormatIndex);
  17161. }
  17162. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17163. {
  17164. String e (fileExtension);
  17165. if (! e.startsWithChar ('.'))
  17166. e = "." + e;
  17167. for (int i = 0; i < getNumKnownFormats(); ++i)
  17168. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17169. return getKnownFormat(i);
  17170. return 0;
  17171. }
  17172. const String AudioFormatManager::getWildcardForAllFormats() const
  17173. {
  17174. StringArray allExtensions;
  17175. int i;
  17176. for (i = 0; i < getNumKnownFormats(); ++i)
  17177. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17178. allExtensions.trim();
  17179. allExtensions.removeEmptyStrings();
  17180. String s;
  17181. for (i = 0; i < allExtensions.size(); ++i)
  17182. {
  17183. s << '*';
  17184. if (! allExtensions[i].startsWithChar ('.'))
  17185. s << '.';
  17186. s << allExtensions[i];
  17187. if (i < allExtensions.size() - 1)
  17188. s << ';';
  17189. }
  17190. return s;
  17191. }
  17192. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17193. {
  17194. // you need to actually register some formats before the manager can
  17195. // use them to open a file!
  17196. jassert (getNumKnownFormats() > 0);
  17197. for (int i = 0; i < getNumKnownFormats(); ++i)
  17198. {
  17199. AudioFormat* const af = getKnownFormat(i);
  17200. if (af->canHandleFile (file))
  17201. {
  17202. InputStream* const in = file.createInputStream();
  17203. if (in != 0)
  17204. {
  17205. AudioFormatReader* const r = af->createReaderFor (in, true);
  17206. if (r != 0)
  17207. return r;
  17208. }
  17209. }
  17210. }
  17211. return 0;
  17212. }
  17213. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17214. {
  17215. // you need to actually register some formats before the manager can
  17216. // use them to open a file!
  17217. jassert (getNumKnownFormats() > 0);
  17218. ScopedPointer <InputStream> in (audioFileStream);
  17219. if (in != 0)
  17220. {
  17221. const int64 originalStreamPos = in->getPosition();
  17222. for (int i = 0; i < getNumKnownFormats(); ++i)
  17223. {
  17224. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17225. if (r != 0)
  17226. {
  17227. in.release();
  17228. return r;
  17229. }
  17230. in->setPosition (originalStreamPos);
  17231. // the stream that is passed-in must be capable of being repositioned so
  17232. // that all the formats can have a go at opening it.
  17233. jassert (in->getPosition() == originalStreamPos);
  17234. }
  17235. }
  17236. return 0;
  17237. }
  17238. END_JUCE_NAMESPACE
  17239. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17240. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17241. BEGIN_JUCE_NAMESPACE
  17242. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17243. const int64 startSample_,
  17244. const int64 length_,
  17245. const bool deleteSourceWhenDeleted_)
  17246. : AudioFormatReader (0, source_->getFormatName()),
  17247. source (source_),
  17248. startSample (startSample_),
  17249. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17250. {
  17251. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17252. sampleRate = source->sampleRate;
  17253. bitsPerSample = source->bitsPerSample;
  17254. lengthInSamples = length;
  17255. numChannels = source->numChannels;
  17256. usesFloatingPointData = source->usesFloatingPointData;
  17257. }
  17258. AudioSubsectionReader::~AudioSubsectionReader()
  17259. {
  17260. if (deleteSourceWhenDeleted)
  17261. delete source;
  17262. }
  17263. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17264. int64 startSampleInFile, int numSamples)
  17265. {
  17266. if (startSampleInFile + numSamples > length)
  17267. {
  17268. for (int i = numDestChannels; --i >= 0;)
  17269. if (destSamples[i] != 0)
  17270. zeromem (destSamples[i], sizeof (int) * numSamples);
  17271. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17272. if (numSamples <= 0)
  17273. return true;
  17274. }
  17275. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17276. startSampleInFile + startSample, numSamples);
  17277. }
  17278. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17279. int64 numSamples,
  17280. float& lowestLeft,
  17281. float& highestLeft,
  17282. float& lowestRight,
  17283. float& highestRight)
  17284. {
  17285. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17286. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17287. source->readMaxLevels (startSampleInFile + startSample,
  17288. numSamples,
  17289. lowestLeft,
  17290. highestLeft,
  17291. lowestRight,
  17292. highestRight);
  17293. }
  17294. END_JUCE_NAMESPACE
  17295. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17296. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17297. BEGIN_JUCE_NAMESPACE
  17298. struct AudioThumbnail::MinMaxValue
  17299. {
  17300. char minValue;
  17301. char maxValue;
  17302. MinMaxValue() : minValue (0), maxValue (0)
  17303. {
  17304. }
  17305. inline void set (const char newMin, const char newMax) throw()
  17306. {
  17307. minValue = newMin;
  17308. maxValue = newMax;
  17309. }
  17310. inline void setFloat (const float newMin, const float newMax) throw()
  17311. {
  17312. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17313. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17314. if (maxValue == minValue)
  17315. maxValue = (char) jmin (127, maxValue + 1);
  17316. }
  17317. inline bool isNonZero() const throw()
  17318. {
  17319. return maxValue > minValue;
  17320. }
  17321. inline int getPeak() const throw()
  17322. {
  17323. return jmax (std::abs ((int) minValue),
  17324. std::abs ((int) maxValue));
  17325. }
  17326. inline void read (InputStream& input)
  17327. {
  17328. minValue = input.readByte();
  17329. maxValue = input.readByte();
  17330. }
  17331. inline void write (OutputStream& output)
  17332. {
  17333. output.writeByte (minValue);
  17334. output.writeByte (maxValue);
  17335. }
  17336. };
  17337. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17338. {
  17339. public:
  17340. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17341. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17342. hashCode (hash), owner (owner_), reader (newReader)
  17343. {
  17344. }
  17345. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17346. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17347. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17348. {
  17349. }
  17350. ~LevelDataSource()
  17351. {
  17352. owner.cache.removeTimeSliceClient (this);
  17353. }
  17354. enum { timeBeforeDeletingReader = 1000 };
  17355. void initialise (int64 numSamplesFinished_)
  17356. {
  17357. const ScopedLock sl (readerLock);
  17358. numSamplesFinished = numSamplesFinished_;
  17359. createReader();
  17360. if (reader != 0)
  17361. {
  17362. lengthInSamples = reader->lengthInSamples;
  17363. numChannels = reader->numChannels;
  17364. sampleRate = reader->sampleRate;
  17365. if (lengthInSamples <= 0 || isFullyLoaded())
  17366. reader = 0;
  17367. else
  17368. owner.cache.addTimeSliceClient (this);
  17369. }
  17370. }
  17371. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17372. {
  17373. const ScopedLock sl (readerLock);
  17374. if (reader == 0)
  17375. {
  17376. createReader();
  17377. if (reader != 0)
  17378. owner.cache.addTimeSliceClient (this);
  17379. }
  17380. if (reader != 0)
  17381. {
  17382. float l[4] = { 0 };
  17383. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17384. levels.clearQuick();
  17385. levels.addArray ((const float*) l, 4);
  17386. }
  17387. }
  17388. void releaseResources()
  17389. {
  17390. const ScopedLock sl (readerLock);
  17391. reader = 0;
  17392. }
  17393. int useTimeSlice()
  17394. {
  17395. if (isFullyLoaded())
  17396. {
  17397. if (reader != 0 && source != 0)
  17398. releaseResources();
  17399. return -1;
  17400. }
  17401. bool justFinished = false;
  17402. {
  17403. const ScopedLock sl (readerLock);
  17404. createReader();
  17405. if (reader != 0)
  17406. {
  17407. if (! readNextBlock())
  17408. return 0;
  17409. justFinished = true;
  17410. }
  17411. }
  17412. if (justFinished)
  17413. owner.cache.storeThumb (owner, hashCode);
  17414. return timeBeforeDeletingReader;
  17415. }
  17416. bool isFullyLoaded() const throw()
  17417. {
  17418. return numSamplesFinished >= lengthInSamples;
  17419. }
  17420. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17421. {
  17422. return (int) (originalSample / owner.samplesPerThumbSample);
  17423. }
  17424. int64 lengthInSamples, numSamplesFinished;
  17425. double sampleRate;
  17426. int numChannels;
  17427. int64 hashCode;
  17428. private:
  17429. AudioThumbnail& owner;
  17430. ScopedPointer <InputSource> source;
  17431. ScopedPointer <AudioFormatReader> reader;
  17432. CriticalSection readerLock;
  17433. void createReader()
  17434. {
  17435. if (reader == 0 && source != 0)
  17436. {
  17437. InputStream* audioFileStream = source->createInputStream();
  17438. if (audioFileStream != 0)
  17439. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17440. }
  17441. }
  17442. bool readNextBlock()
  17443. {
  17444. jassert (reader != 0);
  17445. if (! isFullyLoaded())
  17446. {
  17447. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17448. if (numToDo > 0)
  17449. {
  17450. int64 startSample = numSamplesFinished;
  17451. const int firstThumbIndex = sampleToThumbSample (startSample);
  17452. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17453. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17454. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17455. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17456. for (int i = 0; i < numThumbSamps; ++i)
  17457. {
  17458. float lowestLeft, highestLeft, lowestRight, highestRight;
  17459. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17460. lowestLeft, highestLeft, lowestRight, highestRight);
  17461. levels[0][i].setFloat (lowestLeft, highestLeft);
  17462. levels[1][i].setFloat (lowestRight, highestRight);
  17463. }
  17464. {
  17465. const ScopedUnlock su (readerLock);
  17466. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17467. }
  17468. numSamplesFinished += numToDo;
  17469. }
  17470. }
  17471. return isFullyLoaded();
  17472. }
  17473. };
  17474. class AudioThumbnail::ThumbData
  17475. {
  17476. public:
  17477. ThumbData (const int numThumbSamples)
  17478. : peakLevel (-1)
  17479. {
  17480. ensureSize (numThumbSamples);
  17481. }
  17482. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17483. {
  17484. jassert (thumbSampleIndex < data.size());
  17485. return data.getRawDataPointer() + thumbSampleIndex;
  17486. }
  17487. int getSize() const throw()
  17488. {
  17489. return data.size();
  17490. }
  17491. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17492. {
  17493. if (startSample >= 0)
  17494. {
  17495. endSample = jmin (endSample, data.size() - 1);
  17496. char mx = -128;
  17497. char mn = 127;
  17498. while (startSample <= endSample)
  17499. {
  17500. const MinMaxValue& v = data.getReference (startSample);
  17501. if (v.minValue < mn) mn = v.minValue;
  17502. if (v.maxValue > mx) mx = v.maxValue;
  17503. ++startSample;
  17504. }
  17505. if (mn <= mx)
  17506. {
  17507. result.set (mn, mx);
  17508. return;
  17509. }
  17510. }
  17511. result.set (1, 0);
  17512. }
  17513. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17514. {
  17515. resetPeak();
  17516. if (startIndex + numValues > data.size())
  17517. ensureSize (startIndex + numValues);
  17518. MinMaxValue* const dest = getData (startIndex);
  17519. for (int i = 0; i < numValues; ++i)
  17520. dest[i] = source[i];
  17521. }
  17522. void resetPeak()
  17523. {
  17524. peakLevel = -1;
  17525. }
  17526. int getPeak()
  17527. {
  17528. if (peakLevel < 0)
  17529. {
  17530. for (int i = 0; i < data.size(); ++i)
  17531. {
  17532. const int peak = data[i].getPeak();
  17533. if (peak > peakLevel)
  17534. peakLevel = peak;
  17535. }
  17536. }
  17537. return peakLevel;
  17538. }
  17539. private:
  17540. Array <MinMaxValue> data;
  17541. int peakLevel;
  17542. void ensureSize (const int thumbSamples)
  17543. {
  17544. const int extraNeeded = thumbSamples - data.size();
  17545. if (extraNeeded > 0)
  17546. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17547. }
  17548. };
  17549. class AudioThumbnail::CachedWindow
  17550. {
  17551. public:
  17552. CachedWindow()
  17553. : cachedStart (0), cachedTimePerPixel (0),
  17554. numChannelsCached (0), numSamplesCached (0),
  17555. cacheNeedsRefilling (true)
  17556. {
  17557. }
  17558. void invalidate()
  17559. {
  17560. cacheNeedsRefilling = true;
  17561. }
  17562. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17563. const double startTime, const double endTime,
  17564. const int channelNum, const float verticalZoomFactor,
  17565. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17566. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17567. {
  17568. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17569. numChannels, samplesPerThumbSample, levelData, channels);
  17570. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17571. {
  17572. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17573. if (! clip.isEmpty())
  17574. {
  17575. const float topY = (float) area.getY();
  17576. const float bottomY = (float) area.getBottom();
  17577. const float midY = (topY + bottomY) * 0.5f;
  17578. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17579. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17580. int x = clip.getX();
  17581. for (int w = clip.getWidth(); --w >= 0;)
  17582. {
  17583. if (cacheData->isNonZero())
  17584. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17585. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17586. ++x;
  17587. ++cacheData;
  17588. }
  17589. }
  17590. }
  17591. }
  17592. private:
  17593. Array <MinMaxValue> data;
  17594. double cachedStart, cachedTimePerPixel;
  17595. int numChannelsCached, numSamplesCached;
  17596. bool cacheNeedsRefilling;
  17597. void refillCache (const int numSamples, double startTime, const double endTime,
  17598. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17599. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17600. {
  17601. const double timePerPixel = (endTime - startTime) / numSamples;
  17602. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17603. {
  17604. invalidate();
  17605. return;
  17606. }
  17607. if (numSamples == numSamplesCached
  17608. && numChannelsCached == numChannels
  17609. && startTime == cachedStart
  17610. && timePerPixel == cachedTimePerPixel
  17611. && ! cacheNeedsRefilling)
  17612. {
  17613. return;
  17614. }
  17615. numSamplesCached = numSamples;
  17616. numChannelsCached = numChannels;
  17617. cachedStart = startTime;
  17618. cachedTimePerPixel = timePerPixel;
  17619. cacheNeedsRefilling = false;
  17620. ensureSize (numSamples);
  17621. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17622. {
  17623. int sample = roundToInt (startTime * sampleRate);
  17624. Array<float> levels;
  17625. int i;
  17626. for (i = 0; i < numSamples; ++i)
  17627. {
  17628. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17629. if (sample >= 0)
  17630. {
  17631. if (sample >= levelData->lengthInSamples)
  17632. break;
  17633. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17634. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17635. for (int chan = 0; chan < numChans; ++chan)
  17636. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17637. levels.getUnchecked (chan * 2 + 1));
  17638. }
  17639. startTime += timePerPixel;
  17640. sample = nextSample;
  17641. }
  17642. numSamplesCached = i;
  17643. }
  17644. else
  17645. {
  17646. jassert (channels.size() == numChannelsCached);
  17647. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17648. {
  17649. ThumbData* channelData = channels.getUnchecked (channelNum);
  17650. MinMaxValue* cacheData = getData (channelNum, 0);
  17651. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17652. startTime = cachedStart;
  17653. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17654. for (int i = numSamples; --i >= 0;)
  17655. {
  17656. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17657. channelData->getMinMax (sample, nextSample, *cacheData);
  17658. ++cacheData;
  17659. startTime += timePerPixel;
  17660. sample = nextSample;
  17661. }
  17662. }
  17663. }
  17664. }
  17665. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17666. {
  17667. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17668. return data.getRawDataPointer() + channelNum * numSamplesCached
  17669. + cacheIndex;
  17670. }
  17671. void ensureSize (const int numSamples)
  17672. {
  17673. const int itemsRequired = numSamples * numChannelsCached;
  17674. if (data.size() < itemsRequired)
  17675. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17676. }
  17677. };
  17678. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17679. AudioFormatManager& formatManagerToUse_,
  17680. AudioThumbnailCache& cacheToUse)
  17681. : formatManagerToUse (formatManagerToUse_),
  17682. cache (cacheToUse),
  17683. window (new CachedWindow()),
  17684. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17685. totalSamples (0),
  17686. numChannels (0),
  17687. sampleRate (0)
  17688. {
  17689. }
  17690. AudioThumbnail::~AudioThumbnail()
  17691. {
  17692. clear();
  17693. }
  17694. void AudioThumbnail::clear()
  17695. {
  17696. source = 0;
  17697. const ScopedLock sl (lock);
  17698. window->invalidate();
  17699. channels.clear();
  17700. totalSamples = numSamplesFinished = 0;
  17701. numChannels = 0;
  17702. sampleRate = 0;
  17703. sendChangeMessage();
  17704. }
  17705. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17706. {
  17707. clear();
  17708. numChannels = newNumChannels;
  17709. sampleRate = newSampleRate;
  17710. totalSamples = totalSamplesInSource;
  17711. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17712. }
  17713. void AudioThumbnail::createChannels (const int length)
  17714. {
  17715. while (channels.size() < numChannels)
  17716. channels.add (new ThumbData (length));
  17717. }
  17718. void AudioThumbnail::loadFrom (InputStream& input)
  17719. {
  17720. clear();
  17721. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17722. return;
  17723. samplesPerThumbSample = input.readInt();
  17724. totalSamples = input.readInt64(); // Total number of source samples.
  17725. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17726. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17727. numChannels = input.readInt(); // Number of audio channels.
  17728. sampleRate = input.readInt(); // Source sample rate.
  17729. input.skipNextBytes (16); // reserved area
  17730. createChannels (numThumbnailSamples);
  17731. for (int i = 0; i < numThumbnailSamples; ++i)
  17732. for (int chan = 0; chan < numChannels; ++chan)
  17733. channels.getUnchecked(chan)->getData(i)->read (input);
  17734. }
  17735. void AudioThumbnail::saveTo (OutputStream& output) const
  17736. {
  17737. const ScopedLock sl (lock);
  17738. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17739. output.write ("jatm", 4);
  17740. output.writeInt (samplesPerThumbSample);
  17741. output.writeInt64 (totalSamples);
  17742. output.writeInt64 (numSamplesFinished);
  17743. output.writeInt (numThumbnailSamples);
  17744. output.writeInt (numChannels);
  17745. output.writeInt ((int) sampleRate);
  17746. output.writeInt64 (0);
  17747. output.writeInt64 (0);
  17748. for (int i = 0; i < numThumbnailSamples; ++i)
  17749. for (int chan = 0; chan < numChannels; ++chan)
  17750. channels.getUnchecked(chan)->getData(i)->write (output);
  17751. }
  17752. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17753. {
  17754. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17755. numSamplesFinished = 0;
  17756. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17757. {
  17758. source = newSource; // (make sure this isn't done before loadThumb is called)
  17759. source->lengthInSamples = totalSamples;
  17760. source->sampleRate = sampleRate;
  17761. source->numChannels = numChannels;
  17762. source->numSamplesFinished = numSamplesFinished;
  17763. }
  17764. else
  17765. {
  17766. source = newSource; // (make sure this isn't done before loadThumb is called)
  17767. const ScopedLock sl (lock);
  17768. source->initialise (numSamplesFinished);
  17769. totalSamples = source->lengthInSamples;
  17770. sampleRate = source->sampleRate;
  17771. numChannels = source->numChannels;
  17772. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17773. }
  17774. return sampleRate > 0 && totalSamples > 0;
  17775. }
  17776. bool AudioThumbnail::setSource (InputSource* const newSource)
  17777. {
  17778. clear();
  17779. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17780. }
  17781. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17782. {
  17783. clear();
  17784. if (newReader != 0)
  17785. setDataSource (new LevelDataSource (*this, newReader, hash));
  17786. }
  17787. int64 AudioThumbnail::getHashCode() const
  17788. {
  17789. return source == 0 ? 0 : source->hashCode;
  17790. }
  17791. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17792. int startOffsetInBuffer, int numSamples)
  17793. {
  17794. jassert (startSample >= 0);
  17795. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17796. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17797. const int numToDo = lastThumbIndex - firstThumbIndex;
  17798. if (numToDo > 0)
  17799. {
  17800. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17801. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17802. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17803. for (int chan = 0; chan < numChans; ++chan)
  17804. {
  17805. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17806. MinMaxValue* const dest = thumbData + numToDo * chan;
  17807. thumbChannels [chan] = dest;
  17808. for (int i = 0; i < numToDo; ++i)
  17809. {
  17810. float low, high;
  17811. const int start = i * samplesPerThumbSample;
  17812. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17813. dest[i].setFloat (low, high);
  17814. }
  17815. }
  17816. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17817. }
  17818. }
  17819. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17820. {
  17821. const ScopedLock sl (lock);
  17822. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17823. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17824. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17825. totalSamples = jmax (numSamplesFinished, totalSamples);
  17826. window->invalidate();
  17827. sendChangeMessage();
  17828. }
  17829. int AudioThumbnail::getNumChannels() const throw()
  17830. {
  17831. return numChannels;
  17832. }
  17833. double AudioThumbnail::getTotalLength() const throw()
  17834. {
  17835. return totalSamples / sampleRate;
  17836. }
  17837. bool AudioThumbnail::isFullyLoaded() const throw()
  17838. {
  17839. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17840. }
  17841. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17842. {
  17843. return numSamplesFinished;
  17844. }
  17845. float AudioThumbnail::getApproximatePeak() const
  17846. {
  17847. int peak = 0;
  17848. for (int i = channels.size(); --i >= 0;)
  17849. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17850. return jlimit (0, 127, peak) / 127.0f;
  17851. }
  17852. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17853. double endTime, int channelNum, float verticalZoomFactor)
  17854. {
  17855. const ScopedLock sl (lock);
  17856. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17857. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17858. }
  17859. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17860. double endTimeSeconds, float verticalZoomFactor)
  17861. {
  17862. for (int i = 0; i < numChannels; ++i)
  17863. {
  17864. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17865. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17866. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17867. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17868. }
  17869. }
  17870. END_JUCE_NAMESPACE
  17871. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17872. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17873. BEGIN_JUCE_NAMESPACE
  17874. struct ThumbnailCacheEntry
  17875. {
  17876. int64 hash;
  17877. uint32 lastUsed;
  17878. MemoryBlock data;
  17879. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17880. };
  17881. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17882. : TimeSliceThread ("thumb cache"),
  17883. maxNumThumbsToStore (maxNumThumbsToStore_)
  17884. {
  17885. startThread (2);
  17886. }
  17887. AudioThumbnailCache::~AudioThumbnailCache()
  17888. {
  17889. }
  17890. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17891. {
  17892. for (int i = thumbs.size(); --i >= 0;)
  17893. if (thumbs.getUnchecked(i)->hash == hash)
  17894. return thumbs.getUnchecked(i);
  17895. return 0;
  17896. }
  17897. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17898. {
  17899. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17900. if (te != 0)
  17901. {
  17902. te->lastUsed = Time::getMillisecondCounter();
  17903. MemoryInputStream in (te->data, false);
  17904. thumb.loadFrom (in);
  17905. return true;
  17906. }
  17907. return false;
  17908. }
  17909. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17910. const int64 hashCode)
  17911. {
  17912. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17913. if (te == 0)
  17914. {
  17915. te = new ThumbnailCacheEntry();
  17916. te->hash = hashCode;
  17917. if (thumbs.size() < maxNumThumbsToStore)
  17918. {
  17919. thumbs.add (te);
  17920. }
  17921. else
  17922. {
  17923. int oldest = 0;
  17924. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17925. for (int i = thumbs.size(); --i >= 0;)
  17926. {
  17927. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17928. {
  17929. oldest = i;
  17930. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17931. }
  17932. }
  17933. thumbs.set (oldest, te);
  17934. }
  17935. }
  17936. te->lastUsed = Time::getMillisecondCounter();
  17937. MemoryOutputStream out (te->data, false);
  17938. thumb.saveTo (out);
  17939. }
  17940. void AudioThumbnailCache::clear()
  17941. {
  17942. thumbs.clear();
  17943. }
  17944. END_JUCE_NAMESPACE
  17945. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17946. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17947. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17948. #if ! JUCE_WINDOWS
  17949. #include <QuickTime/Movies.h>
  17950. #include <QuickTime/QTML.h>
  17951. #include <QuickTime/QuickTimeComponents.h>
  17952. #include <QuickTime/MediaHandlers.h>
  17953. #include <QuickTime/ImageCodec.h>
  17954. #else
  17955. #if JUCE_MSVC
  17956. #pragma warning (push)
  17957. #pragma warning (disable : 4100)
  17958. #endif
  17959. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17960. add its header directory to your include path.
  17961. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17962. flag in juce_Config.h
  17963. */
  17964. #include <Movies.h>
  17965. #include <QTML.h>
  17966. #include <QuickTimeComponents.h>
  17967. #include <MediaHandlers.h>
  17968. #include <ImageCodec.h>
  17969. #if JUCE_MSVC
  17970. #pragma warning (pop)
  17971. #endif
  17972. #endif
  17973. BEGIN_JUCE_NAMESPACE
  17974. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17975. static const char* const quickTimeFormatName = "QuickTime file";
  17976. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17977. class QTAudioReader : public AudioFormatReader
  17978. {
  17979. public:
  17980. QTAudioReader (InputStream* const input_, const int trackNum_)
  17981. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17982. ok (false),
  17983. movie (0),
  17984. trackNum (trackNum_),
  17985. lastSampleRead (0),
  17986. lastThreadId (0),
  17987. extractor (0),
  17988. dataHandle (0)
  17989. {
  17990. JUCE_AUTORELEASEPOOL
  17991. bufferList.calloc (256, 1);
  17992. #if JUCE_WINDOWS
  17993. if (InitializeQTML (0) != noErr)
  17994. return;
  17995. #endif
  17996. if (EnterMovies() != noErr)
  17997. return;
  17998. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17999. if (! opened)
  18000. return;
  18001. {
  18002. const int numTracks = GetMovieTrackCount (movie);
  18003. int trackCount = 0;
  18004. for (int i = 1; i <= numTracks; ++i)
  18005. {
  18006. track = GetMovieIndTrack (movie, i);
  18007. media = GetTrackMedia (track);
  18008. OSType mediaType;
  18009. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18010. if (mediaType == SoundMediaType
  18011. && trackCount++ == trackNum_)
  18012. {
  18013. ok = true;
  18014. break;
  18015. }
  18016. }
  18017. }
  18018. if (! ok)
  18019. return;
  18020. ok = false;
  18021. lengthInSamples = GetMediaDecodeDuration (media);
  18022. usesFloatingPointData = false;
  18023. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18024. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18025. / GetMediaTimeScale (media);
  18026. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18027. unsigned long output_layout_size;
  18028. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18029. kQTPropertyClass_MovieAudioExtraction_Audio,
  18030. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18031. 0, &output_layout_size, 0);
  18032. if (err != noErr)
  18033. return;
  18034. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18035. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18036. err = MovieAudioExtractionGetProperty (extractor,
  18037. kQTPropertyClass_MovieAudioExtraction_Audio,
  18038. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18039. output_layout_size, qt_audio_channel_layout, 0);
  18040. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18041. err = MovieAudioExtractionSetProperty (extractor,
  18042. kQTPropertyClass_MovieAudioExtraction_Audio,
  18043. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18044. output_layout_size,
  18045. qt_audio_channel_layout);
  18046. err = MovieAudioExtractionGetProperty (extractor,
  18047. kQTPropertyClass_MovieAudioExtraction_Audio,
  18048. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18049. sizeof (inputStreamDesc),
  18050. &inputStreamDesc, 0);
  18051. if (err != noErr)
  18052. return;
  18053. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18054. | kAudioFormatFlagIsPacked
  18055. | kAudioFormatFlagsNativeEndian;
  18056. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18057. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18058. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18059. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18060. err = MovieAudioExtractionSetProperty (extractor,
  18061. kQTPropertyClass_MovieAudioExtraction_Audio,
  18062. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18063. sizeof (inputStreamDesc),
  18064. &inputStreamDesc);
  18065. if (err != noErr)
  18066. return;
  18067. Boolean allChannelsDiscrete = false;
  18068. err = MovieAudioExtractionSetProperty (extractor,
  18069. kQTPropertyClass_MovieAudioExtraction_Movie,
  18070. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18071. sizeof (allChannelsDiscrete),
  18072. &allChannelsDiscrete);
  18073. if (err != noErr)
  18074. return;
  18075. bufferList->mNumberBuffers = 1;
  18076. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18077. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18078. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18079. bufferList->mBuffers[0].mData = dataBuffer;
  18080. sampleRate = inputStreamDesc.mSampleRate;
  18081. bitsPerSample = 16;
  18082. numChannels = inputStreamDesc.mChannelsPerFrame;
  18083. detachThread();
  18084. ok = true;
  18085. }
  18086. ~QTAudioReader()
  18087. {
  18088. JUCE_AUTORELEASEPOOL
  18089. checkThreadIsAttached();
  18090. if (dataHandle != 0)
  18091. DisposeHandle (dataHandle);
  18092. if (extractor != 0)
  18093. {
  18094. MovieAudioExtractionEnd (extractor);
  18095. extractor = 0;
  18096. }
  18097. DisposeMovie (movie);
  18098. #if JUCE_MAC
  18099. ExitMoviesOnThread ();
  18100. #endif
  18101. }
  18102. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18103. int64 startSampleInFile, int numSamples)
  18104. {
  18105. JUCE_AUTORELEASEPOOL
  18106. checkThreadIsAttached();
  18107. bool ok = true;
  18108. while (numSamples > 0)
  18109. {
  18110. if (lastSampleRead != startSampleInFile)
  18111. {
  18112. TimeRecord time;
  18113. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18114. time.base = 0;
  18115. time.value.hi = 0;
  18116. time.value.lo = (UInt32) startSampleInFile;
  18117. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18118. kQTPropertyClass_MovieAudioExtraction_Movie,
  18119. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18120. sizeof (time), &time);
  18121. if (err != noErr)
  18122. {
  18123. ok = false;
  18124. break;
  18125. }
  18126. }
  18127. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18128. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18129. UInt32 outFlags = 0;
  18130. UInt32 actualNumFrames = framesToDo;
  18131. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18132. if (err != noErr)
  18133. {
  18134. ok = false;
  18135. break;
  18136. }
  18137. lastSampleRead = startSampleInFile + actualNumFrames;
  18138. const int samplesReceived = actualNumFrames;
  18139. for (int j = numDestChannels; --j >= 0;)
  18140. {
  18141. if (destSamples[j] != 0)
  18142. {
  18143. const short* src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18144. for (int i = 0; i < samplesReceived; ++i)
  18145. {
  18146. destSamples[j][startOffsetInDestBuffer + i] = (*src << 16);
  18147. src += numChannels;
  18148. }
  18149. }
  18150. }
  18151. startOffsetInDestBuffer += samplesReceived;
  18152. startSampleInFile += samplesReceived;
  18153. numSamples -= samplesReceived;
  18154. if (((outFlags & kQTMovieAudioExtractionComplete) != 0 || samplesReceived == 0) && numSamples > 0)
  18155. {
  18156. for (int j = numDestChannels; --j >= 0;)
  18157. if (destSamples[j] != 0)
  18158. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18159. break;
  18160. }
  18161. }
  18162. detachThread();
  18163. return ok;
  18164. }
  18165. bool ok;
  18166. private:
  18167. Movie movie;
  18168. Media media;
  18169. Track track;
  18170. const int trackNum;
  18171. double trackUnitsPerFrame;
  18172. int samplesPerFrame;
  18173. int64 lastSampleRead;
  18174. Thread::ThreadID lastThreadId;
  18175. MovieAudioExtractionRef extractor;
  18176. AudioStreamBasicDescription inputStreamDesc;
  18177. HeapBlock <AudioBufferList> bufferList;
  18178. HeapBlock <char> dataBuffer;
  18179. Handle dataHandle;
  18180. void checkThreadIsAttached()
  18181. {
  18182. #if JUCE_MAC
  18183. if (Thread::getCurrentThreadId() != lastThreadId)
  18184. EnterMoviesOnThread (0);
  18185. AttachMovieToCurrentThread (movie);
  18186. #endif
  18187. }
  18188. void detachThread()
  18189. {
  18190. #if JUCE_MAC
  18191. DetachMovieFromCurrentThread (movie);
  18192. #endif
  18193. }
  18194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18195. };
  18196. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18197. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18198. {
  18199. }
  18200. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18201. {
  18202. }
  18203. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18204. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18205. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18206. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18207. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18208. const bool deleteStreamIfOpeningFails)
  18209. {
  18210. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18211. if (r->ok)
  18212. return r.release();
  18213. if (! deleteStreamIfOpeningFails)
  18214. r->input = 0;
  18215. return 0;
  18216. }
  18217. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18218. double /*sampleRateToUse*/,
  18219. unsigned int /*numberOfChannels*/,
  18220. int /*bitsPerSample*/,
  18221. const StringPairArray& /*metadataValues*/,
  18222. int /*qualityOptionIndex*/)
  18223. {
  18224. jassertfalse; // not yet implemented!
  18225. return 0;
  18226. }
  18227. END_JUCE_NAMESPACE
  18228. #endif
  18229. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18230. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18231. BEGIN_JUCE_NAMESPACE
  18232. static const char* const wavFormatName = "WAV file";
  18233. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18234. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18235. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18236. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18237. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18238. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18239. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18240. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18241. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18242. const String& originator,
  18243. const String& originatorRef,
  18244. const Time& date,
  18245. const int64 timeReferenceSamples,
  18246. const String& codingHistory)
  18247. {
  18248. StringPairArray m;
  18249. m.set (bwavDescription, description);
  18250. m.set (bwavOriginator, originator);
  18251. m.set (bwavOriginatorRef, originatorRef);
  18252. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18253. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18254. m.set (bwavTimeReference, String (timeReferenceSamples));
  18255. m.set (bwavCodingHistory, codingHistory);
  18256. return m;
  18257. }
  18258. namespace WavFileHelpers
  18259. {
  18260. #if JUCE_MSVC
  18261. #pragma pack (push, 1)
  18262. #define PACKED
  18263. #elif JUCE_GCC
  18264. #define PACKED __attribute__((packed))
  18265. #else
  18266. #define PACKED
  18267. #endif
  18268. struct BWAVChunk
  18269. {
  18270. char description [256];
  18271. char originator [32];
  18272. char originatorRef [32];
  18273. char originationDate [10];
  18274. char originationTime [8];
  18275. uint32 timeRefLow;
  18276. uint32 timeRefHigh;
  18277. uint16 version;
  18278. uint8 umid[64];
  18279. uint8 reserved[190];
  18280. char codingHistory[1];
  18281. void copyTo (StringPairArray& values) const
  18282. {
  18283. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18284. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18285. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18286. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18287. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18288. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18289. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18290. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18291. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18292. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18293. }
  18294. static MemoryBlock createFrom (const StringPairArray& values)
  18295. {
  18296. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18297. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18298. data.fillWith (0);
  18299. BWAVChunk* b = (BWAVChunk*) data.getData();
  18300. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18301. // as they get called in the right order..
  18302. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18303. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18304. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18305. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18306. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18307. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18308. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18309. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18310. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18311. if (b->description[0] != 0
  18312. || b->originator[0] != 0
  18313. || b->originationDate[0] != 0
  18314. || b->originationTime[0] != 0
  18315. || b->codingHistory[0] != 0
  18316. || time != 0)
  18317. {
  18318. return data;
  18319. }
  18320. return MemoryBlock();
  18321. }
  18322. } PACKED;
  18323. struct SMPLChunk
  18324. {
  18325. struct SampleLoop
  18326. {
  18327. uint32 identifier;
  18328. uint32 type;
  18329. uint32 start;
  18330. uint32 end;
  18331. uint32 fraction;
  18332. uint32 playCount;
  18333. } PACKED;
  18334. uint32 manufacturer;
  18335. uint32 product;
  18336. uint32 samplePeriod;
  18337. uint32 midiUnityNote;
  18338. uint32 midiPitchFraction;
  18339. uint32 smpteFormat;
  18340. uint32 smpteOffset;
  18341. uint32 numSampleLoops;
  18342. uint32 samplerData;
  18343. SampleLoop loops[1];
  18344. void copyTo (StringPairArray& values, const int totalSize) const
  18345. {
  18346. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18347. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18348. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18349. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18350. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18351. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18352. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18353. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18354. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18355. for (uint32 i = 0; i < numSampleLoops; ++i)
  18356. {
  18357. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18358. break;
  18359. const String prefix ("Loop" + String(i));
  18360. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18361. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18362. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18363. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18364. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18365. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18366. }
  18367. }
  18368. static MemoryBlock createFrom (const StringPairArray& values)
  18369. {
  18370. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18371. if (numLoops <= 0)
  18372. return MemoryBlock();
  18373. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18374. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18375. data.fillWith (0);
  18376. SMPLChunk* s = (SMPLChunk*) data.getData();
  18377. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18378. // as they get called in the right order..
  18379. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18380. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18381. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18382. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18383. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18384. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18385. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18386. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18387. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18388. for (int i = 0; i < numLoops; ++i)
  18389. {
  18390. const String prefix ("Loop" + String(i));
  18391. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18392. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18393. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18394. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18395. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18396. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18397. }
  18398. return data;
  18399. }
  18400. } PACKED;
  18401. struct ExtensibleWavSubFormat
  18402. {
  18403. uint32 data1;
  18404. uint16 data2;
  18405. uint16 data3;
  18406. uint8 data4[8];
  18407. } PACKED;
  18408. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18409. {
  18410. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18411. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18412. uint32 dataSizeLow; // low 4 byte size of data chunk
  18413. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18414. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18415. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18416. uint32 tableLength; // number of valid entries in array 'table'
  18417. } PACKED;
  18418. #if JUCE_MSVC
  18419. #pragma pack (pop)
  18420. #endif
  18421. #undef PACKED
  18422. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18423. }
  18424. class WavAudioFormatReader : public AudioFormatReader
  18425. {
  18426. public:
  18427. WavAudioFormatReader (InputStream* const in)
  18428. : AudioFormatReader (in, TRANS (wavFormatName)),
  18429. bwavChunkStart (0),
  18430. bwavSize (0),
  18431. dataLength (0),
  18432. isRF64 (false)
  18433. {
  18434. using namespace WavFileHelpers;
  18435. uint64 len = 0;
  18436. int64 end = 0;
  18437. bool hasGotType = false;
  18438. bool hasGotData = false;
  18439. const int firstChunkType = input->readInt();
  18440. if (firstChunkType == chunkName ("RF64"))
  18441. {
  18442. input->skipNextBytes (4); // size is -1 for RF64
  18443. isRF64 = true;
  18444. }
  18445. else if (firstChunkType == chunkName ("RIFF"))
  18446. {
  18447. len = (uint64) input->readInt();
  18448. end = input->getPosition() + len;
  18449. }
  18450. else
  18451. {
  18452. return;
  18453. }
  18454. const int64 startOfRIFFChunk = input->getPosition();
  18455. if (input->readInt() == chunkName ("WAVE"))
  18456. {
  18457. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18458. {
  18459. uint32 length = (uint32) input->readInt();
  18460. if (length < 28)
  18461. {
  18462. return;
  18463. }
  18464. else
  18465. {
  18466. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18467. len = input->readInt64();
  18468. end = startOfRIFFChunk + len;
  18469. dataLength = input->readInt64();
  18470. input->setPosition (chunkEnd);
  18471. }
  18472. }
  18473. while (input->getPosition() < end && ! input->isExhausted())
  18474. {
  18475. const int chunkType = input->readInt();
  18476. uint32 length = (uint32) input->readInt();
  18477. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18478. if (chunkType == chunkName ("fmt "))
  18479. {
  18480. // read the format chunk
  18481. const unsigned short format = input->readShort();
  18482. const short numChans = input->readShort();
  18483. sampleRate = input->readInt();
  18484. const int bytesPerSec = input->readInt();
  18485. numChannels = numChans;
  18486. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18487. bitsPerSample = 8 * bytesPerFrame / numChans;
  18488. if (format == 3)
  18489. {
  18490. usesFloatingPointData = true;
  18491. }
  18492. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18493. {
  18494. if (length < 40) // too short
  18495. {
  18496. bytesPerFrame = 0;
  18497. }
  18498. else
  18499. {
  18500. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18501. ExtensibleWavSubFormat subFormat;
  18502. subFormat.data1 = input->readInt();
  18503. subFormat.data2 = input->readShort();
  18504. subFormat.data3 = input->readShort();
  18505. input->read (subFormat.data4, sizeof (subFormat.data4));
  18506. const ExtensibleWavSubFormat pcmFormat
  18507. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18508. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18509. {
  18510. const ExtensibleWavSubFormat ambisonicFormat
  18511. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18512. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18513. bytesPerFrame = 0;
  18514. }
  18515. }
  18516. }
  18517. else if (format != 1)
  18518. {
  18519. bytesPerFrame = 0;
  18520. }
  18521. hasGotType = true;
  18522. }
  18523. else if (chunkType == chunkName ("data"))
  18524. {
  18525. // get the data chunk's position
  18526. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18527. dataLength = length;
  18528. dataChunkStart = input->getPosition();
  18529. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18530. hasGotData = true;
  18531. }
  18532. else if (chunkType == chunkName ("bext"))
  18533. {
  18534. bwavChunkStart = input->getPosition();
  18535. bwavSize = length;
  18536. // Broadcast-wav extension chunk..
  18537. HeapBlock <BWAVChunk> bwav;
  18538. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18539. input->read (bwav, length);
  18540. bwav->copyTo (metadataValues);
  18541. }
  18542. else if (chunkType == chunkName ("smpl"))
  18543. {
  18544. HeapBlock <SMPLChunk> smpl;
  18545. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18546. input->read (smpl, length);
  18547. smpl->copyTo (metadataValues, length);
  18548. }
  18549. else if (chunkEnd <= input->getPosition())
  18550. {
  18551. break;
  18552. }
  18553. input->setPosition (chunkEnd);
  18554. }
  18555. }
  18556. }
  18557. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18558. int64 startSampleInFile, int numSamples)
  18559. {
  18560. jassert (destSamples != 0);
  18561. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18562. if (samplesAvailable < numSamples)
  18563. {
  18564. for (int i = numDestChannels; --i >= 0;)
  18565. if (destSamples[i] != 0)
  18566. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18567. numSamples = (int) samplesAvailable;
  18568. }
  18569. if (numSamples <= 0)
  18570. return true;
  18571. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18572. while (numSamples > 0)
  18573. {
  18574. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18575. char tempBuffer [tempBufSize];
  18576. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18577. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18578. if (bytesRead < numThisTime * bytesPerFrame)
  18579. {
  18580. jassert (bytesRead >= 0);
  18581. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18582. }
  18583. switch (bitsPerSample)
  18584. {
  18585. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18586. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18587. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18588. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18589. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18590. default: jassertfalse; break;
  18591. }
  18592. startOffsetInDestBuffer += numThisTime;
  18593. numSamples -= numThisTime;
  18594. }
  18595. return true;
  18596. }
  18597. int64 bwavChunkStart, bwavSize;
  18598. private:
  18599. ScopedPointer<AudioData::Converter> converter;
  18600. int bytesPerFrame;
  18601. int64 dataChunkStart, dataLength;
  18602. bool isRF64;
  18603. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18604. };
  18605. class WavAudioFormatWriter : public AudioFormatWriter
  18606. {
  18607. public:
  18608. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18609. const unsigned int numChannels_, const int bits,
  18610. const StringPairArray& metadataValues)
  18611. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18612. lengthInSamples (0),
  18613. bytesWritten (0),
  18614. writeFailed (false)
  18615. {
  18616. using namespace WavFileHelpers;
  18617. if (metadataValues.size() > 0)
  18618. {
  18619. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18620. smplChunk = SMPLChunk::createFrom (metadataValues);
  18621. }
  18622. headerPosition = out->getPosition();
  18623. writeHeader();
  18624. }
  18625. ~WavAudioFormatWriter()
  18626. {
  18627. if ((bytesWritten & 1) != 0) // pad to an even length
  18628. {
  18629. ++bytesWritten;
  18630. output->writeByte (0);
  18631. }
  18632. writeHeader();
  18633. }
  18634. bool write (const int** data, int numSamples)
  18635. {
  18636. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18637. if (writeFailed)
  18638. return false;
  18639. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18640. tempBlock.ensureSize (bytes, false);
  18641. switch (bitsPerSample)
  18642. {
  18643. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18644. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18645. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18646. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18647. default: jassertfalse; break;
  18648. }
  18649. if (! output->write (tempBlock.getData(), bytes))
  18650. {
  18651. // failed to write to disk, so let's try writing the header.
  18652. // If it's just run out of disk space, then if it does manage
  18653. // to write the header, we'll still have a useable file..
  18654. writeHeader();
  18655. writeFailed = true;
  18656. return false;
  18657. }
  18658. else
  18659. {
  18660. bytesWritten += bytes;
  18661. lengthInSamples += numSamples;
  18662. return true;
  18663. }
  18664. }
  18665. private:
  18666. ScopedPointer<AudioData::Converter> converter;
  18667. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18668. uint64 lengthInSamples, bytesWritten;
  18669. int64 headerPosition;
  18670. bool writeFailed;
  18671. static int getChannelMask (const int numChannels) throw()
  18672. {
  18673. switch (numChannels)
  18674. {
  18675. case 1: return 0;
  18676. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18677. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18678. 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
  18679. default: break;
  18680. }
  18681. return 0;
  18682. }
  18683. void writeHeader()
  18684. {
  18685. using namespace WavFileHelpers;
  18686. const bool seekedOk = output->setPosition (headerPosition);
  18687. (void) seekedOk;
  18688. // if this fails, you've given it an output stream that can't seek! It needs
  18689. // to be able to seek back to write the header
  18690. jassert (seekedOk);
  18691. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18692. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18693. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  18694. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  18695. + 8 + audioDataSize + (audioDataSize & 1)
  18696. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18697. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18698. + (8 + 28); // (ds64 chunk)
  18699. riffChunkSize += (riffChunkSize & 0x1);
  18700. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18701. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18702. output->writeInt (chunkName ("WAVE"));
  18703. if (! isRF64)
  18704. {
  18705. output->writeInt (chunkName ("JUNK"));
  18706. output->writeInt (28 + 24);
  18707. output->writeRepeatedByte (0, 28 /* ds64 */ + 24 /* extra waveformatex */);
  18708. }
  18709. else
  18710. {
  18711. // write ds64 chunk
  18712. output->writeInt (chunkName ("ds64"));
  18713. output->writeInt (28); // chunk size for uncompressed data (no table)
  18714. output->writeInt64 (riffChunkSize);
  18715. output->writeInt64 (audioDataSize);
  18716. output->writeRepeatedByte (0, 12);
  18717. }
  18718. output->writeInt (chunkName ("fmt "));
  18719. if (isRF64)
  18720. {
  18721. output->writeInt (40); // chunk size
  18722. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18723. }
  18724. else
  18725. {
  18726. output->writeInt (16); // chunk size
  18727. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  18728. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18729. }
  18730. output->writeShort ((short) numChannels);
  18731. output->writeInt ((int) sampleRate);
  18732. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18733. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18734. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18735. if (isRF64)
  18736. {
  18737. output->writeShort (22); // cbSize (size of the extension)
  18738. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18739. output->writeInt (getChannelMask (numChannels));
  18740. const ExtensibleWavSubFormat pcmFormat
  18741. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18742. const ExtensibleWavSubFormat IEEEFloatFormat
  18743. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18744. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18745. output->writeInt ((int) subFormat.data1);
  18746. output->writeShort ((short) subFormat.data2);
  18747. output->writeShort ((short) subFormat.data3);
  18748. output->write (subFormat.data4, sizeof (subFormat.data4));
  18749. }
  18750. if (bwavChunk.getSize() > 0)
  18751. {
  18752. output->writeInt (chunkName ("bext"));
  18753. output->writeInt ((int) bwavChunk.getSize());
  18754. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18755. }
  18756. if (smplChunk.getSize() > 0)
  18757. {
  18758. output->writeInt (chunkName ("smpl"));
  18759. output->writeInt ((int) smplChunk.getSize());
  18760. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18761. }
  18762. output->writeInt (chunkName ("data"));
  18763. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18764. usesFloatingPointData = (bitsPerSample == 32);
  18765. }
  18766. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18767. };
  18768. WavAudioFormat::WavAudioFormat()
  18769. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18770. {
  18771. }
  18772. WavAudioFormat::~WavAudioFormat()
  18773. {
  18774. }
  18775. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18776. {
  18777. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18778. return Array <int> (rates);
  18779. }
  18780. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18781. {
  18782. const int depths[] = { 8, 16, 24, 32, 0 };
  18783. return Array <int> (depths);
  18784. }
  18785. bool WavAudioFormat::canDoStereo() { return true; }
  18786. bool WavAudioFormat::canDoMono() { return true; }
  18787. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18788. const bool deleteStreamIfOpeningFails)
  18789. {
  18790. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18791. if (r->sampleRate > 0)
  18792. return r.release();
  18793. if (! deleteStreamIfOpeningFails)
  18794. r->input = 0;
  18795. return 0;
  18796. }
  18797. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18798. unsigned int numChannels, int bitsPerSample,
  18799. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18800. {
  18801. if (getPossibleBitDepths().contains (bitsPerSample))
  18802. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18803. return 0;
  18804. }
  18805. namespace WavFileHelpers
  18806. {
  18807. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18808. {
  18809. TemporaryFile tempFile (file);
  18810. WavAudioFormat wav;
  18811. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18812. if (reader != 0)
  18813. {
  18814. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18815. if (outStream != 0)
  18816. {
  18817. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18818. reader->numChannels, reader->bitsPerSample,
  18819. metadata, 0));
  18820. if (writer != 0)
  18821. {
  18822. outStream.release();
  18823. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18824. writer = 0;
  18825. reader = 0;
  18826. return ok && tempFile.overwriteTargetFileWithTemporary();
  18827. }
  18828. }
  18829. }
  18830. return false;
  18831. }
  18832. }
  18833. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18834. {
  18835. using namespace WavFileHelpers;
  18836. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18837. if (reader != 0)
  18838. {
  18839. const int64 bwavPos = reader->bwavChunkStart;
  18840. const int64 bwavSize = reader->bwavSize;
  18841. reader = 0;
  18842. if (bwavSize > 0)
  18843. {
  18844. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18845. if (chunk.getSize() <= (size_t) bwavSize)
  18846. {
  18847. // the new one will fit in the space available, so write it directly..
  18848. const int64 oldSize = wavFile.getSize();
  18849. {
  18850. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18851. out->setPosition (bwavPos);
  18852. out->write (chunk.getData(), (int) chunk.getSize());
  18853. out->setPosition (oldSize);
  18854. }
  18855. jassert (wavFile.getSize() == oldSize);
  18856. return true;
  18857. }
  18858. }
  18859. }
  18860. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18861. }
  18862. END_JUCE_NAMESPACE
  18863. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18864. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18865. #if JUCE_USE_CDREADER
  18866. BEGIN_JUCE_NAMESPACE
  18867. int AudioCDReader::getNumTracks() const
  18868. {
  18869. return trackStartSamples.size() - 1;
  18870. }
  18871. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18872. {
  18873. return trackStartSamples [trackNum];
  18874. }
  18875. const Array<int>& AudioCDReader::getTrackOffsets() const
  18876. {
  18877. return trackStartSamples;
  18878. }
  18879. int AudioCDReader::getCDDBId()
  18880. {
  18881. int checksum = 0;
  18882. const int numTracks = getNumTracks();
  18883. for (int i = 0; i < numTracks; ++i)
  18884. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18885. checksum += offset % 10;
  18886. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18887. // CCLLLLTT: checksum, length, tracks
  18888. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18889. }
  18890. END_JUCE_NAMESPACE
  18891. #endif
  18892. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18893. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18894. BEGIN_JUCE_NAMESPACE
  18895. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18896. const bool deleteReaderWhenThisIsDeleted)
  18897. : reader (reader_),
  18898. deleteReader (deleteReaderWhenThisIsDeleted),
  18899. nextPlayPos (0),
  18900. looping (false)
  18901. {
  18902. jassert (reader != 0);
  18903. }
  18904. AudioFormatReaderSource::~AudioFormatReaderSource()
  18905. {
  18906. releaseResources();
  18907. if (deleteReader)
  18908. delete reader;
  18909. }
  18910. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18911. {
  18912. nextPlayPos = newPosition;
  18913. }
  18914. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18915. {
  18916. looping = shouldLoop;
  18917. }
  18918. int64 AudioFormatReaderSource::getNextReadPosition() const
  18919. {
  18920. return looping ? nextPlayPos % reader->lengthInSamples
  18921. : nextPlayPos;
  18922. }
  18923. int64 AudioFormatReaderSource::getTotalLength() const
  18924. {
  18925. return reader->lengthInSamples;
  18926. }
  18927. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18928. double /*sampleRate*/)
  18929. {
  18930. }
  18931. void AudioFormatReaderSource::releaseResources()
  18932. {
  18933. }
  18934. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18935. {
  18936. if (info.numSamples > 0)
  18937. {
  18938. const int64 start = nextPlayPos;
  18939. if (looping)
  18940. {
  18941. const int newStart = start % (int) reader->lengthInSamples;
  18942. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18943. if (newEnd > newStart)
  18944. {
  18945. info.buffer->readFromAudioReader (reader,
  18946. info.startSample,
  18947. newEnd - newStart,
  18948. newStart,
  18949. true, true);
  18950. }
  18951. else
  18952. {
  18953. const int endSamps = (int) reader->lengthInSamples - newStart;
  18954. info.buffer->readFromAudioReader (reader,
  18955. info.startSample,
  18956. endSamps,
  18957. newStart,
  18958. true, true);
  18959. info.buffer->readFromAudioReader (reader,
  18960. info.startSample + endSamps,
  18961. newEnd,
  18962. 0,
  18963. true, true);
  18964. }
  18965. nextPlayPos = newEnd;
  18966. }
  18967. else
  18968. {
  18969. info.buffer->readFromAudioReader (reader,
  18970. info.startSample,
  18971. info.numSamples,
  18972. start,
  18973. true, true);
  18974. nextPlayPos += info.numSamples;
  18975. }
  18976. }
  18977. }
  18978. END_JUCE_NAMESPACE
  18979. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18980. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18981. BEGIN_JUCE_NAMESPACE
  18982. AudioSourcePlayer::AudioSourcePlayer()
  18983. : source (0),
  18984. sampleRate (0),
  18985. bufferSize (0),
  18986. tempBuffer (2, 8),
  18987. lastGain (1.0f),
  18988. gain (1.0f)
  18989. {
  18990. }
  18991. AudioSourcePlayer::~AudioSourcePlayer()
  18992. {
  18993. setSource (0);
  18994. }
  18995. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18996. {
  18997. if (source != newSource)
  18998. {
  18999. AudioSource* const oldSource = source;
  19000. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19001. newSource->prepareToPlay (bufferSize, sampleRate);
  19002. {
  19003. const ScopedLock sl (readLock);
  19004. source = newSource;
  19005. }
  19006. if (oldSource != 0)
  19007. oldSource->releaseResources();
  19008. }
  19009. }
  19010. void AudioSourcePlayer::setGain (const float newGain) throw()
  19011. {
  19012. gain = newGain;
  19013. }
  19014. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19015. int totalNumInputChannels,
  19016. float** outputChannelData,
  19017. int totalNumOutputChannels,
  19018. int numSamples)
  19019. {
  19020. // these should have been prepared by audioDeviceAboutToStart()...
  19021. jassert (sampleRate > 0 && bufferSize > 0);
  19022. const ScopedLock sl (readLock);
  19023. if (source != 0)
  19024. {
  19025. AudioSourceChannelInfo info;
  19026. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19027. // messy stuff needed to compact the channels down into an array
  19028. // of non-zero pointers..
  19029. for (i = 0; i < totalNumInputChannels; ++i)
  19030. {
  19031. if (inputChannelData[i] != 0)
  19032. {
  19033. inputChans [numInputs++] = inputChannelData[i];
  19034. if (numInputs >= numElementsInArray (inputChans))
  19035. break;
  19036. }
  19037. }
  19038. for (i = 0; i < totalNumOutputChannels; ++i)
  19039. {
  19040. if (outputChannelData[i] != 0)
  19041. {
  19042. outputChans [numOutputs++] = outputChannelData[i];
  19043. if (numOutputs >= numElementsInArray (outputChans))
  19044. break;
  19045. }
  19046. }
  19047. if (numInputs > numOutputs)
  19048. {
  19049. // if there aren't enough output channels for the number of
  19050. // inputs, we need to create some temporary extra ones (can't
  19051. // use the input data in case it gets written to)
  19052. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19053. false, false, true);
  19054. for (i = 0; i < numOutputs; ++i)
  19055. {
  19056. channels[numActiveChans] = outputChans[i];
  19057. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19058. ++numActiveChans;
  19059. }
  19060. for (i = numOutputs; i < numInputs; ++i)
  19061. {
  19062. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19063. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19064. ++numActiveChans;
  19065. }
  19066. }
  19067. else
  19068. {
  19069. for (i = 0; i < numInputs; ++i)
  19070. {
  19071. channels[numActiveChans] = outputChans[i];
  19072. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19073. ++numActiveChans;
  19074. }
  19075. for (i = numInputs; i < numOutputs; ++i)
  19076. {
  19077. channels[numActiveChans] = outputChans[i];
  19078. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19079. ++numActiveChans;
  19080. }
  19081. }
  19082. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19083. info.buffer = &buffer;
  19084. info.startSample = 0;
  19085. info.numSamples = numSamples;
  19086. source->getNextAudioBlock (info);
  19087. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19088. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19089. lastGain = gain;
  19090. }
  19091. else
  19092. {
  19093. for (int i = 0; i < totalNumOutputChannels; ++i)
  19094. if (outputChannelData[i] != 0)
  19095. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19096. }
  19097. }
  19098. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19099. {
  19100. sampleRate = device->getCurrentSampleRate();
  19101. bufferSize = device->getCurrentBufferSizeSamples();
  19102. zeromem (channels, sizeof (channels));
  19103. if (source != 0)
  19104. source->prepareToPlay (bufferSize, sampleRate);
  19105. }
  19106. void AudioSourcePlayer::audioDeviceStopped()
  19107. {
  19108. if (source != 0)
  19109. source->releaseResources();
  19110. sampleRate = 0.0;
  19111. bufferSize = 0;
  19112. tempBuffer.setSize (2, 8);
  19113. }
  19114. END_JUCE_NAMESPACE
  19115. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19116. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19117. BEGIN_JUCE_NAMESPACE
  19118. AudioTransportSource::AudioTransportSource()
  19119. : source (0),
  19120. resamplerSource (0),
  19121. bufferingSource (0),
  19122. positionableSource (0),
  19123. masterSource (0),
  19124. gain (1.0f),
  19125. lastGain (1.0f),
  19126. playing (false),
  19127. stopped (true),
  19128. sampleRate (44100.0),
  19129. sourceSampleRate (0.0),
  19130. blockSize (128),
  19131. readAheadBufferSize (0),
  19132. isPrepared (false),
  19133. inputStreamEOF (false)
  19134. {
  19135. }
  19136. AudioTransportSource::~AudioTransportSource()
  19137. {
  19138. setSource (0);
  19139. releaseResources();
  19140. }
  19141. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19142. int readAheadBufferSize_,
  19143. double sourceSampleRateToCorrectFor,
  19144. int maxNumChannels)
  19145. {
  19146. if (source == newSource)
  19147. {
  19148. if (source == 0)
  19149. return;
  19150. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19151. }
  19152. readAheadBufferSize = readAheadBufferSize_;
  19153. sourceSampleRate = sourceSampleRateToCorrectFor;
  19154. ResamplingAudioSource* newResamplerSource = 0;
  19155. BufferingAudioSource* newBufferingSource = 0;
  19156. PositionableAudioSource* newPositionableSource = 0;
  19157. AudioSource* newMasterSource = 0;
  19158. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19159. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19160. AudioSource* oldMasterSource = masterSource;
  19161. if (newSource != 0)
  19162. {
  19163. newPositionableSource = newSource;
  19164. if (readAheadBufferSize_ > 0)
  19165. newPositionableSource = newBufferingSource
  19166. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19167. newPositionableSource->setNextReadPosition (0);
  19168. if (sourceSampleRateToCorrectFor > 0)
  19169. newMasterSource = newResamplerSource
  19170. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19171. else
  19172. newMasterSource = newPositionableSource;
  19173. if (isPrepared)
  19174. {
  19175. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19176. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19177. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19178. }
  19179. }
  19180. {
  19181. const ScopedLock sl (callbackLock);
  19182. source = newSource;
  19183. resamplerSource = newResamplerSource;
  19184. bufferingSource = newBufferingSource;
  19185. masterSource = newMasterSource;
  19186. positionableSource = newPositionableSource;
  19187. playing = false;
  19188. }
  19189. if (oldMasterSource != 0)
  19190. oldMasterSource->releaseResources();
  19191. }
  19192. void AudioTransportSource::start()
  19193. {
  19194. if ((! playing) && masterSource != 0)
  19195. {
  19196. {
  19197. const ScopedLock sl (callbackLock);
  19198. playing = true;
  19199. stopped = false;
  19200. inputStreamEOF = false;
  19201. }
  19202. sendChangeMessage();
  19203. }
  19204. }
  19205. void AudioTransportSource::stop()
  19206. {
  19207. if (playing)
  19208. {
  19209. {
  19210. const ScopedLock sl (callbackLock);
  19211. playing = false;
  19212. }
  19213. int n = 500;
  19214. while (--n >= 0 && ! stopped)
  19215. Thread::sleep (2);
  19216. sendChangeMessage();
  19217. }
  19218. }
  19219. void AudioTransportSource::setPosition (double newPosition)
  19220. {
  19221. if (sampleRate > 0.0)
  19222. setNextReadPosition ((int64) (newPosition * sampleRate));
  19223. }
  19224. double AudioTransportSource::getCurrentPosition() const
  19225. {
  19226. if (sampleRate > 0.0)
  19227. return getNextReadPosition() / sampleRate;
  19228. else
  19229. return 0.0;
  19230. }
  19231. double AudioTransportSource::getLengthInSeconds() const
  19232. {
  19233. return getTotalLength() / sampleRate;
  19234. }
  19235. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19236. {
  19237. if (positionableSource != 0)
  19238. {
  19239. if (sampleRate > 0 && sourceSampleRate > 0)
  19240. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19241. positionableSource->setNextReadPosition (newPosition);
  19242. }
  19243. }
  19244. int64 AudioTransportSource::getNextReadPosition() const
  19245. {
  19246. if (positionableSource != 0)
  19247. {
  19248. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19249. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19250. }
  19251. return 0;
  19252. }
  19253. int64 AudioTransportSource::getTotalLength() const
  19254. {
  19255. const ScopedLock sl (callbackLock);
  19256. if (positionableSource != 0)
  19257. {
  19258. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19259. return (int64) (positionableSource->getTotalLength() * ratio);
  19260. }
  19261. return 0;
  19262. }
  19263. bool AudioTransportSource::isLooping() const
  19264. {
  19265. const ScopedLock sl (callbackLock);
  19266. return positionableSource != 0
  19267. && positionableSource->isLooping();
  19268. }
  19269. void AudioTransportSource::setGain (const float newGain) throw()
  19270. {
  19271. gain = newGain;
  19272. }
  19273. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19274. double sampleRate_)
  19275. {
  19276. const ScopedLock sl (callbackLock);
  19277. sampleRate = sampleRate_;
  19278. blockSize = samplesPerBlockExpected;
  19279. if (masterSource != 0)
  19280. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19281. if (resamplerSource != 0 && sourceSampleRate > 0)
  19282. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19283. isPrepared = true;
  19284. }
  19285. void AudioTransportSource::releaseResources()
  19286. {
  19287. const ScopedLock sl (callbackLock);
  19288. if (masterSource != 0)
  19289. masterSource->releaseResources();
  19290. isPrepared = false;
  19291. }
  19292. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19293. {
  19294. const ScopedLock sl (callbackLock);
  19295. inputStreamEOF = false;
  19296. if (masterSource != 0 && ! stopped)
  19297. {
  19298. masterSource->getNextAudioBlock (info);
  19299. if (! playing)
  19300. {
  19301. // just stopped playing, so fade out the last block..
  19302. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19303. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19304. if (info.numSamples > 256)
  19305. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19306. }
  19307. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19308. && ! positionableSource->isLooping())
  19309. {
  19310. playing = false;
  19311. inputStreamEOF = true;
  19312. sendChangeMessage();
  19313. }
  19314. stopped = ! playing;
  19315. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19316. {
  19317. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19318. lastGain, gain);
  19319. }
  19320. }
  19321. else
  19322. {
  19323. info.clearActiveBufferRegion();
  19324. stopped = true;
  19325. }
  19326. lastGain = gain;
  19327. }
  19328. END_JUCE_NAMESPACE
  19329. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19330. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19331. BEGIN_JUCE_NAMESPACE
  19332. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19333. public Thread,
  19334. private Timer
  19335. {
  19336. public:
  19337. SharedBufferingAudioSourceThread()
  19338. : Thread ("Audio Buffer")
  19339. {
  19340. }
  19341. ~SharedBufferingAudioSourceThread()
  19342. {
  19343. stopThread (10000);
  19344. clearSingletonInstance();
  19345. }
  19346. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19347. void addSource (BufferingAudioSource* source)
  19348. {
  19349. const ScopedLock sl (lock);
  19350. if (! sources.contains (source))
  19351. {
  19352. sources.add (source);
  19353. startThread();
  19354. stopTimer();
  19355. }
  19356. notify();
  19357. }
  19358. void removeSource (BufferingAudioSource* source)
  19359. {
  19360. const ScopedLock sl (lock);
  19361. sources.removeValue (source);
  19362. if (sources.size() == 0)
  19363. startTimer (5000);
  19364. }
  19365. private:
  19366. Array <BufferingAudioSource*> sources;
  19367. CriticalSection lock;
  19368. void run()
  19369. {
  19370. while (! threadShouldExit())
  19371. {
  19372. bool busy = false;
  19373. for (int i = sources.size(); --i >= 0;)
  19374. {
  19375. if (threadShouldExit())
  19376. return;
  19377. const ScopedLock sl (lock);
  19378. BufferingAudioSource* const b = sources[i];
  19379. if (b != 0 && b->readNextBufferChunk())
  19380. busy = true;
  19381. }
  19382. if (! busy)
  19383. wait (500);
  19384. }
  19385. }
  19386. void timerCallback()
  19387. {
  19388. stopTimer();
  19389. if (sources.size() == 0)
  19390. deleteInstance();
  19391. }
  19392. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19393. };
  19394. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19395. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19396. const bool deleteSourceWhenDeleted_,
  19397. int numberOfSamplesToBuffer_)
  19398. : source (source_),
  19399. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19400. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19401. buffer (2, 0),
  19402. bufferValidStart (0),
  19403. bufferValidEnd (0),
  19404. nextPlayPos (0),
  19405. wasSourceLooping (false)
  19406. {
  19407. jassert (source_ != 0);
  19408. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19409. // not using a larger buffer..
  19410. }
  19411. BufferingAudioSource::~BufferingAudioSource()
  19412. {
  19413. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19414. if (thread != 0)
  19415. thread->removeSource (this);
  19416. if (deleteSourceWhenDeleted)
  19417. delete source;
  19418. }
  19419. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19420. {
  19421. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19422. sampleRate = sampleRate_;
  19423. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19424. buffer.clear();
  19425. bufferValidStart = 0;
  19426. bufferValidEnd = 0;
  19427. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19428. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19429. buffer.getNumSamples() / 2))
  19430. {
  19431. SharedBufferingAudioSourceThread::getInstance()->notify();
  19432. Thread::sleep (5);
  19433. }
  19434. }
  19435. void BufferingAudioSource::releaseResources()
  19436. {
  19437. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19438. if (thread != 0)
  19439. thread->removeSource (this);
  19440. buffer.setSize (2, 0);
  19441. source->releaseResources();
  19442. }
  19443. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19444. {
  19445. const ScopedLock sl (bufferStartPosLock);
  19446. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19447. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19448. if (validStart == validEnd)
  19449. {
  19450. // total cache miss
  19451. info.clearActiveBufferRegion();
  19452. }
  19453. else
  19454. {
  19455. if (validStart > 0)
  19456. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19457. if (validEnd < info.numSamples)
  19458. info.buffer->clear (info.startSample + validEnd,
  19459. info.numSamples - validEnd); // partial cache miss at end
  19460. if (validStart < validEnd)
  19461. {
  19462. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19463. {
  19464. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19465. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19466. if (startBufferIndex < endBufferIndex)
  19467. {
  19468. info.buffer->copyFrom (chan, info.startSample + validStart,
  19469. buffer,
  19470. chan, startBufferIndex,
  19471. validEnd - validStart);
  19472. }
  19473. else
  19474. {
  19475. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19476. info.buffer->copyFrom (chan, info.startSample + validStart,
  19477. buffer,
  19478. chan, startBufferIndex,
  19479. initialSize);
  19480. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19481. buffer,
  19482. chan, 0,
  19483. (validEnd - validStart) - initialSize);
  19484. }
  19485. }
  19486. }
  19487. nextPlayPos += info.numSamples;
  19488. if (source->isLooping() && nextPlayPos > 0)
  19489. nextPlayPos %= source->getTotalLength();
  19490. }
  19491. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19492. if (thread != 0)
  19493. thread->notify();
  19494. }
  19495. int64 BufferingAudioSource::getNextReadPosition() const
  19496. {
  19497. return (source->isLooping() && nextPlayPos > 0)
  19498. ? nextPlayPos % source->getTotalLength()
  19499. : nextPlayPos;
  19500. }
  19501. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19502. {
  19503. const ScopedLock sl (bufferStartPosLock);
  19504. nextPlayPos = newPosition;
  19505. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19506. if (thread != 0)
  19507. thread->notify();
  19508. }
  19509. bool BufferingAudioSource::readNextBufferChunk()
  19510. {
  19511. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19512. {
  19513. const ScopedLock sl (bufferStartPosLock);
  19514. if (wasSourceLooping != isLooping())
  19515. {
  19516. wasSourceLooping = isLooping();
  19517. bufferValidStart = 0;
  19518. bufferValidEnd = 0;
  19519. }
  19520. newBVS = jmax ((int64) 0, nextPlayPos);
  19521. newBVE = newBVS + buffer.getNumSamples() - 4;
  19522. sectionToReadStart = 0;
  19523. sectionToReadEnd = 0;
  19524. const int maxChunkSize = 2048;
  19525. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19526. {
  19527. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19528. sectionToReadStart = newBVS;
  19529. sectionToReadEnd = newBVE;
  19530. bufferValidStart = 0;
  19531. bufferValidEnd = 0;
  19532. }
  19533. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19534. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19535. {
  19536. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19537. sectionToReadStart = bufferValidEnd;
  19538. sectionToReadEnd = newBVE;
  19539. bufferValidStart = newBVS;
  19540. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19541. }
  19542. }
  19543. if (sectionToReadStart != sectionToReadEnd)
  19544. {
  19545. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19546. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19547. if (bufferIndexStart < bufferIndexEnd)
  19548. {
  19549. readBufferSection (sectionToReadStart,
  19550. (int) (sectionToReadEnd - sectionToReadStart),
  19551. bufferIndexStart);
  19552. }
  19553. else
  19554. {
  19555. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19556. readBufferSection (sectionToReadStart,
  19557. initialSize,
  19558. bufferIndexStart);
  19559. readBufferSection (sectionToReadStart + initialSize,
  19560. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19561. 0);
  19562. }
  19563. const ScopedLock sl2 (bufferStartPosLock);
  19564. bufferValidStart = newBVS;
  19565. bufferValidEnd = newBVE;
  19566. return true;
  19567. }
  19568. else
  19569. {
  19570. return false;
  19571. }
  19572. }
  19573. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19574. {
  19575. if (source->getNextReadPosition() != start)
  19576. source->setNextReadPosition (start);
  19577. AudioSourceChannelInfo info;
  19578. info.buffer = &buffer;
  19579. info.startSample = bufferOffset;
  19580. info.numSamples = length;
  19581. source->getNextAudioBlock (info);
  19582. }
  19583. END_JUCE_NAMESPACE
  19584. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19585. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19586. BEGIN_JUCE_NAMESPACE
  19587. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19588. const bool deleteSourceWhenDeleted_)
  19589. : requiredNumberOfChannels (2),
  19590. source (source_),
  19591. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19592. buffer (2, 16)
  19593. {
  19594. remappedInfo.buffer = &buffer;
  19595. remappedInfo.startSample = 0;
  19596. }
  19597. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19598. {
  19599. if (deleteSourceWhenDeleted)
  19600. delete source;
  19601. }
  19602. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19603. {
  19604. const ScopedLock sl (lock);
  19605. requiredNumberOfChannels = requiredNumberOfChannels_;
  19606. }
  19607. void ChannelRemappingAudioSource::clearAllMappings()
  19608. {
  19609. const ScopedLock sl (lock);
  19610. remappedInputs.clear();
  19611. remappedOutputs.clear();
  19612. }
  19613. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19614. {
  19615. const ScopedLock sl (lock);
  19616. while (remappedInputs.size() < destIndex)
  19617. remappedInputs.add (-1);
  19618. remappedInputs.set (destIndex, sourceIndex);
  19619. }
  19620. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19621. {
  19622. const ScopedLock sl (lock);
  19623. while (remappedOutputs.size() < sourceIndex)
  19624. remappedOutputs.add (-1);
  19625. remappedOutputs.set (sourceIndex, destIndex);
  19626. }
  19627. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19628. {
  19629. const ScopedLock sl (lock);
  19630. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19631. return remappedInputs.getUnchecked (inputChannelIndex);
  19632. return -1;
  19633. }
  19634. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19635. {
  19636. const ScopedLock sl (lock);
  19637. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19638. return remappedOutputs .getUnchecked (outputChannelIndex);
  19639. return -1;
  19640. }
  19641. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19642. {
  19643. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19644. }
  19645. void ChannelRemappingAudioSource::releaseResources()
  19646. {
  19647. source->releaseResources();
  19648. }
  19649. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19650. {
  19651. const ScopedLock sl (lock);
  19652. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19653. const int numChans = bufferToFill.buffer->getNumChannels();
  19654. int i;
  19655. for (i = 0; i < buffer.getNumChannels(); ++i)
  19656. {
  19657. const int remappedChan = getRemappedInputChannel (i);
  19658. if (remappedChan >= 0 && remappedChan < numChans)
  19659. {
  19660. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19661. remappedChan,
  19662. bufferToFill.startSample,
  19663. bufferToFill.numSamples);
  19664. }
  19665. else
  19666. {
  19667. buffer.clear (i, 0, bufferToFill.numSamples);
  19668. }
  19669. }
  19670. remappedInfo.numSamples = bufferToFill.numSamples;
  19671. source->getNextAudioBlock (remappedInfo);
  19672. bufferToFill.clearActiveBufferRegion();
  19673. for (i = 0; i < requiredNumberOfChannels; ++i)
  19674. {
  19675. const int remappedChan = getRemappedOutputChannel (i);
  19676. if (remappedChan >= 0 && remappedChan < numChans)
  19677. {
  19678. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19679. buffer, i, 0, bufferToFill.numSamples);
  19680. }
  19681. }
  19682. }
  19683. XmlElement* ChannelRemappingAudioSource::createXml() const
  19684. {
  19685. XmlElement* e = new XmlElement ("MAPPINGS");
  19686. String ins, outs;
  19687. int i;
  19688. const ScopedLock sl (lock);
  19689. for (i = 0; i < remappedInputs.size(); ++i)
  19690. ins << remappedInputs.getUnchecked(i) << ' ';
  19691. for (i = 0; i < remappedOutputs.size(); ++i)
  19692. outs << remappedOutputs.getUnchecked(i) << ' ';
  19693. e->setAttribute ("inputs", ins.trimEnd());
  19694. e->setAttribute ("outputs", outs.trimEnd());
  19695. return e;
  19696. }
  19697. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19698. {
  19699. if (e.hasTagName ("MAPPINGS"))
  19700. {
  19701. const ScopedLock sl (lock);
  19702. clearAllMappings();
  19703. StringArray ins, outs;
  19704. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19705. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19706. int i;
  19707. for (i = 0; i < ins.size(); ++i)
  19708. remappedInputs.add (ins[i].getIntValue());
  19709. for (i = 0; i < outs.size(); ++i)
  19710. remappedOutputs.add (outs[i].getIntValue());
  19711. }
  19712. }
  19713. END_JUCE_NAMESPACE
  19714. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19715. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19716. BEGIN_JUCE_NAMESPACE
  19717. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19718. const bool deleteInputWhenDeleted_)
  19719. : input (inputSource),
  19720. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19721. {
  19722. jassert (inputSource != 0);
  19723. for (int i = 2; --i >= 0;)
  19724. iirFilters.add (new IIRFilter());
  19725. }
  19726. IIRFilterAudioSource::~IIRFilterAudioSource()
  19727. {
  19728. if (deleteInputWhenDeleted)
  19729. delete input;
  19730. }
  19731. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19732. {
  19733. for (int i = iirFilters.size(); --i >= 0;)
  19734. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19735. }
  19736. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19737. {
  19738. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19739. for (int i = iirFilters.size(); --i >= 0;)
  19740. iirFilters.getUnchecked(i)->reset();
  19741. }
  19742. void IIRFilterAudioSource::releaseResources()
  19743. {
  19744. input->releaseResources();
  19745. }
  19746. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19747. {
  19748. input->getNextAudioBlock (bufferToFill);
  19749. const int numChannels = bufferToFill.buffer->getNumChannels();
  19750. while (numChannels > iirFilters.size())
  19751. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19752. for (int i = 0; i < numChannels; ++i)
  19753. iirFilters.getUnchecked(i)
  19754. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19755. bufferToFill.numSamples);
  19756. }
  19757. END_JUCE_NAMESPACE
  19758. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19759. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19760. BEGIN_JUCE_NAMESPACE
  19761. MixerAudioSource::MixerAudioSource()
  19762. : tempBuffer (2, 0),
  19763. currentSampleRate (0.0),
  19764. bufferSizeExpected (0)
  19765. {
  19766. }
  19767. MixerAudioSource::~MixerAudioSource()
  19768. {
  19769. removeAllInputs();
  19770. }
  19771. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19772. {
  19773. if (input != 0 && ! inputs.contains (input))
  19774. {
  19775. double localRate;
  19776. int localBufferSize;
  19777. {
  19778. const ScopedLock sl (lock);
  19779. localRate = currentSampleRate;
  19780. localBufferSize = bufferSizeExpected;
  19781. }
  19782. if (localRate > 0.0)
  19783. input->prepareToPlay (localBufferSize, localRate);
  19784. const ScopedLock sl (lock);
  19785. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19786. inputs.add (input);
  19787. }
  19788. }
  19789. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19790. {
  19791. if (input != 0)
  19792. {
  19793. int index;
  19794. {
  19795. const ScopedLock sl (lock);
  19796. index = inputs.indexOf (input);
  19797. if (index >= 0)
  19798. {
  19799. inputsToDelete.shiftBits (index, 1);
  19800. inputs.remove (index);
  19801. }
  19802. }
  19803. if (index >= 0)
  19804. {
  19805. input->releaseResources();
  19806. if (deleteInput)
  19807. delete input;
  19808. }
  19809. }
  19810. }
  19811. void MixerAudioSource::removeAllInputs()
  19812. {
  19813. OwnedArray<AudioSource> toDelete;
  19814. {
  19815. const ScopedLock sl (lock);
  19816. for (int i = inputs.size(); --i >= 0;)
  19817. if (inputsToDelete[i])
  19818. toDelete.add (inputs.getUnchecked(i));
  19819. }
  19820. }
  19821. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19822. {
  19823. tempBuffer.setSize (2, samplesPerBlockExpected);
  19824. const ScopedLock sl (lock);
  19825. currentSampleRate = sampleRate;
  19826. bufferSizeExpected = samplesPerBlockExpected;
  19827. for (int i = inputs.size(); --i >= 0;)
  19828. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19829. }
  19830. void MixerAudioSource::releaseResources()
  19831. {
  19832. const ScopedLock sl (lock);
  19833. for (int i = inputs.size(); --i >= 0;)
  19834. inputs.getUnchecked(i)->releaseResources();
  19835. tempBuffer.setSize (2, 0);
  19836. currentSampleRate = 0;
  19837. bufferSizeExpected = 0;
  19838. }
  19839. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19840. {
  19841. const ScopedLock sl (lock);
  19842. if (inputs.size() > 0)
  19843. {
  19844. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19845. if (inputs.size() > 1)
  19846. {
  19847. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19848. info.buffer->getNumSamples());
  19849. AudioSourceChannelInfo info2;
  19850. info2.buffer = &tempBuffer;
  19851. info2.numSamples = info.numSamples;
  19852. info2.startSample = 0;
  19853. for (int i = 1; i < inputs.size(); ++i)
  19854. {
  19855. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19856. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19857. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19858. }
  19859. }
  19860. }
  19861. else
  19862. {
  19863. info.clearActiveBufferRegion();
  19864. }
  19865. }
  19866. END_JUCE_NAMESPACE
  19867. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19868. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19869. BEGIN_JUCE_NAMESPACE
  19870. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19871. const bool deleteInputWhenDeleted_,
  19872. const int numChannels_)
  19873. : input (inputSource),
  19874. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19875. ratio (1.0),
  19876. lastRatio (1.0),
  19877. buffer (numChannels_, 0),
  19878. sampsInBuffer (0),
  19879. numChannels (numChannels_)
  19880. {
  19881. jassert (input != 0);
  19882. }
  19883. ResamplingAudioSource::~ResamplingAudioSource()
  19884. {
  19885. if (deleteInputWhenDeleted)
  19886. delete input;
  19887. }
  19888. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19889. {
  19890. jassert (samplesInPerOutputSample > 0);
  19891. const ScopedLock sl (ratioLock);
  19892. ratio = jmax (0.0, samplesInPerOutputSample);
  19893. }
  19894. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19895. double sampleRate)
  19896. {
  19897. const ScopedLock sl (ratioLock);
  19898. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19899. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19900. buffer.clear();
  19901. sampsInBuffer = 0;
  19902. bufferPos = 0;
  19903. subSampleOffset = 0.0;
  19904. filterStates.calloc (numChannels);
  19905. srcBuffers.calloc (numChannels);
  19906. destBuffers.calloc (numChannels);
  19907. createLowPass (ratio);
  19908. resetFilters();
  19909. }
  19910. void ResamplingAudioSource::releaseResources()
  19911. {
  19912. input->releaseResources();
  19913. buffer.setSize (numChannels, 0);
  19914. }
  19915. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19916. {
  19917. double localRatio;
  19918. {
  19919. const ScopedLock sl (ratioLock);
  19920. localRatio = ratio;
  19921. }
  19922. if (lastRatio != localRatio)
  19923. {
  19924. createLowPass (localRatio);
  19925. lastRatio = localRatio;
  19926. }
  19927. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19928. int bufferSize = buffer.getNumSamples();
  19929. if (bufferSize < sampsNeeded + 8)
  19930. {
  19931. bufferPos %= bufferSize;
  19932. bufferSize = sampsNeeded + 32;
  19933. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19934. }
  19935. bufferPos %= bufferSize;
  19936. int endOfBufferPos = bufferPos + sampsInBuffer;
  19937. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19938. while (sampsNeeded > sampsInBuffer)
  19939. {
  19940. endOfBufferPos %= bufferSize;
  19941. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19942. bufferSize - endOfBufferPos);
  19943. AudioSourceChannelInfo readInfo;
  19944. readInfo.buffer = &buffer;
  19945. readInfo.numSamples = numToDo;
  19946. readInfo.startSample = endOfBufferPos;
  19947. input->getNextAudioBlock (readInfo);
  19948. if (localRatio > 1.0001)
  19949. {
  19950. // for down-sampling, pre-apply the filter..
  19951. for (int i = channelsToProcess; --i >= 0;)
  19952. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19953. }
  19954. sampsInBuffer += numToDo;
  19955. endOfBufferPos += numToDo;
  19956. }
  19957. for (int channel = 0; channel < channelsToProcess; ++channel)
  19958. {
  19959. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19960. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19961. }
  19962. int nextPos = (bufferPos + 1) % bufferSize;
  19963. for (int m = info.numSamples; --m >= 0;)
  19964. {
  19965. const float alpha = (float) subSampleOffset;
  19966. const float invAlpha = 1.0f - alpha;
  19967. for (int channel = 0; channel < channelsToProcess; ++channel)
  19968. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19969. subSampleOffset += localRatio;
  19970. jassert (sampsInBuffer > 0);
  19971. while (subSampleOffset >= 1.0)
  19972. {
  19973. if (++bufferPos >= bufferSize)
  19974. bufferPos = 0;
  19975. --sampsInBuffer;
  19976. nextPos = (bufferPos + 1) % bufferSize;
  19977. subSampleOffset -= 1.0;
  19978. }
  19979. }
  19980. if (localRatio < 0.9999)
  19981. {
  19982. // for up-sampling, apply the filter after transposing..
  19983. for (int i = channelsToProcess; --i >= 0;)
  19984. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19985. }
  19986. else if (localRatio <= 1.0001)
  19987. {
  19988. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19989. for (int i = channelsToProcess; --i >= 0;)
  19990. {
  19991. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19992. FilterState& fs = filterStates[i];
  19993. if (info.numSamples > 1)
  19994. {
  19995. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19996. }
  19997. else
  19998. {
  19999. fs.y2 = fs.y1;
  20000. fs.x2 = fs.x1;
  20001. }
  20002. fs.y1 = fs.x1 = *endOfBuffer;
  20003. }
  20004. }
  20005. jassert (sampsInBuffer >= 0);
  20006. }
  20007. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20008. {
  20009. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20010. : 0.5 * frequencyRatio;
  20011. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20012. const double nSquared = n * n;
  20013. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20014. setFilterCoefficients (c1,
  20015. c1 * 2.0f,
  20016. c1,
  20017. 1.0,
  20018. c1 * 2.0 * (1.0 - nSquared),
  20019. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20020. }
  20021. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20022. {
  20023. const double a = 1.0 / c4;
  20024. c1 *= a;
  20025. c2 *= a;
  20026. c3 *= a;
  20027. c5 *= a;
  20028. c6 *= a;
  20029. coefficients[0] = c1;
  20030. coefficients[1] = c2;
  20031. coefficients[2] = c3;
  20032. coefficients[3] = c4;
  20033. coefficients[4] = c5;
  20034. coefficients[5] = c6;
  20035. }
  20036. void ResamplingAudioSource::resetFilters()
  20037. {
  20038. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20039. }
  20040. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20041. {
  20042. while (--num >= 0)
  20043. {
  20044. const double in = *samples;
  20045. double out = coefficients[0] * in
  20046. + coefficients[1] * fs.x1
  20047. + coefficients[2] * fs.x2
  20048. - coefficients[4] * fs.y1
  20049. - coefficients[5] * fs.y2;
  20050. #if JUCE_INTEL
  20051. if (! (out < -1.0e-8 || out > 1.0e-8))
  20052. out = 0;
  20053. #endif
  20054. fs.x2 = fs.x1;
  20055. fs.x1 = in;
  20056. fs.y2 = fs.y1;
  20057. fs.y1 = out;
  20058. *samples++ = (float) out;
  20059. }
  20060. }
  20061. END_JUCE_NAMESPACE
  20062. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20063. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20064. BEGIN_JUCE_NAMESPACE
  20065. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20066. : frequency (1000.0),
  20067. sampleRate (44100.0),
  20068. currentPhase (0.0),
  20069. phasePerSample (0.0),
  20070. amplitude (0.5f)
  20071. {
  20072. }
  20073. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20074. {
  20075. }
  20076. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20077. {
  20078. amplitude = newAmplitude;
  20079. }
  20080. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20081. {
  20082. frequency = newFrequencyHz;
  20083. phasePerSample = 0.0;
  20084. }
  20085. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20086. double sampleRate_)
  20087. {
  20088. currentPhase = 0.0;
  20089. phasePerSample = 0.0;
  20090. sampleRate = sampleRate_;
  20091. }
  20092. void ToneGeneratorAudioSource::releaseResources()
  20093. {
  20094. }
  20095. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20096. {
  20097. if (phasePerSample == 0.0)
  20098. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20099. for (int i = 0; i < info.numSamples; ++i)
  20100. {
  20101. const float sample = amplitude * (float) std::sin (currentPhase);
  20102. currentPhase += phasePerSample;
  20103. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20104. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20105. }
  20106. }
  20107. END_JUCE_NAMESPACE
  20108. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20109. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20110. BEGIN_JUCE_NAMESPACE
  20111. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20112. : sampleRate (0),
  20113. bufferSize (0),
  20114. useDefaultInputChannels (true),
  20115. useDefaultOutputChannels (true)
  20116. {
  20117. }
  20118. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20119. {
  20120. return outputDeviceName == other.outputDeviceName
  20121. && inputDeviceName == other.inputDeviceName
  20122. && sampleRate == other.sampleRate
  20123. && bufferSize == other.bufferSize
  20124. && inputChannels == other.inputChannels
  20125. && useDefaultInputChannels == other.useDefaultInputChannels
  20126. && outputChannels == other.outputChannels
  20127. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20128. }
  20129. AudioDeviceManager::AudioDeviceManager()
  20130. : currentAudioDevice (0),
  20131. numInputChansNeeded (0),
  20132. numOutputChansNeeded (2),
  20133. listNeedsScanning (true),
  20134. useInputNames (false),
  20135. inputLevelMeasurementEnabledCount (0),
  20136. inputLevel (0),
  20137. tempBuffer (2, 2),
  20138. defaultMidiOutput (0),
  20139. cpuUsageMs (0),
  20140. timeToCpuScale (0)
  20141. {
  20142. callbackHandler.owner = this;
  20143. }
  20144. AudioDeviceManager::~AudioDeviceManager()
  20145. {
  20146. currentAudioDevice = 0;
  20147. defaultMidiOutput = 0;
  20148. }
  20149. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20150. {
  20151. if (availableDeviceTypes.size() == 0)
  20152. {
  20153. createAudioDeviceTypes (availableDeviceTypes);
  20154. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20155. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20156. if (availableDeviceTypes.size() > 0)
  20157. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20158. }
  20159. }
  20160. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20161. {
  20162. scanDevicesIfNeeded();
  20163. return availableDeviceTypes;
  20164. }
  20165. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20166. static void addIfNotNull (OwnedArray <AudioIODeviceType>& list, AudioIODeviceType* const device)
  20167. {
  20168. if (device != 0)
  20169. list.add (device);
  20170. }
  20171. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20172. {
  20173. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI());
  20174. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  20175. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  20176. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  20177. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  20178. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  20179. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  20180. }
  20181. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20182. const int numOutputChannelsNeeded,
  20183. const XmlElement* const e,
  20184. const bool selectDefaultDeviceOnFailure,
  20185. const String& preferredDefaultDeviceName,
  20186. const AudioDeviceSetup* preferredSetupOptions)
  20187. {
  20188. scanDevicesIfNeeded();
  20189. numInputChansNeeded = numInputChannelsNeeded;
  20190. numOutputChansNeeded = numOutputChannelsNeeded;
  20191. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20192. {
  20193. lastExplicitSettings = new XmlElement (*e);
  20194. String error;
  20195. AudioDeviceSetup setup;
  20196. if (preferredSetupOptions != 0)
  20197. setup = *preferredSetupOptions;
  20198. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20199. {
  20200. setup.inputDeviceName = setup.outputDeviceName
  20201. = e->getStringAttribute ("audioDeviceName");
  20202. }
  20203. else
  20204. {
  20205. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20206. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20207. }
  20208. currentDeviceType = e->getStringAttribute ("deviceType");
  20209. if (currentDeviceType.isEmpty())
  20210. {
  20211. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20212. if (type != 0)
  20213. currentDeviceType = type->getTypeName();
  20214. else if (availableDeviceTypes.size() > 0)
  20215. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20216. }
  20217. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20218. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20219. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20220. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20221. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20222. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20223. error = setAudioDeviceSetup (setup, true);
  20224. midiInsFromXml.clear();
  20225. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20226. midiInsFromXml.add (c->getStringAttribute ("name"));
  20227. const StringArray allMidiIns (MidiInput::getDevices());
  20228. for (int i = allMidiIns.size(); --i >= 0;)
  20229. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20230. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20231. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20232. false, preferredDefaultDeviceName);
  20233. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20234. return error;
  20235. }
  20236. else
  20237. {
  20238. AudioDeviceSetup setup;
  20239. if (preferredSetupOptions != 0)
  20240. {
  20241. setup = *preferredSetupOptions;
  20242. }
  20243. else if (preferredDefaultDeviceName.isNotEmpty())
  20244. {
  20245. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20246. {
  20247. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20248. StringArray outs (type->getDeviceNames (false));
  20249. int i;
  20250. for (i = 0; i < outs.size(); ++i)
  20251. {
  20252. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20253. {
  20254. setup.outputDeviceName = outs[i];
  20255. break;
  20256. }
  20257. }
  20258. StringArray ins (type->getDeviceNames (true));
  20259. for (i = 0; i < ins.size(); ++i)
  20260. {
  20261. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20262. {
  20263. setup.inputDeviceName = ins[i];
  20264. break;
  20265. }
  20266. }
  20267. }
  20268. }
  20269. insertDefaultDeviceNames (setup);
  20270. return setAudioDeviceSetup (setup, false);
  20271. }
  20272. }
  20273. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20274. {
  20275. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20276. if (type != 0)
  20277. {
  20278. if (setup.outputDeviceName.isEmpty())
  20279. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20280. if (setup.inputDeviceName.isEmpty())
  20281. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20282. }
  20283. }
  20284. XmlElement* AudioDeviceManager::createStateXml() const
  20285. {
  20286. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20287. }
  20288. void AudioDeviceManager::scanDevicesIfNeeded()
  20289. {
  20290. if (listNeedsScanning)
  20291. {
  20292. listNeedsScanning = false;
  20293. createDeviceTypesIfNeeded();
  20294. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20295. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20296. }
  20297. }
  20298. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20299. {
  20300. scanDevicesIfNeeded();
  20301. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20302. {
  20303. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20304. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20305. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20306. {
  20307. return type;
  20308. }
  20309. }
  20310. return 0;
  20311. }
  20312. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20313. {
  20314. setup = currentSetup;
  20315. }
  20316. void AudioDeviceManager::deleteCurrentDevice()
  20317. {
  20318. currentAudioDevice = 0;
  20319. currentSetup.inputDeviceName = String::empty;
  20320. currentSetup.outputDeviceName = String::empty;
  20321. }
  20322. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20323. const bool treatAsChosenDevice)
  20324. {
  20325. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20326. {
  20327. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20328. && currentDeviceType != type)
  20329. {
  20330. currentDeviceType = type;
  20331. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20332. insertDefaultDeviceNames (s);
  20333. setAudioDeviceSetup (s, treatAsChosenDevice);
  20334. sendChangeMessage();
  20335. break;
  20336. }
  20337. }
  20338. }
  20339. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20340. {
  20341. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20342. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20343. return availableDeviceTypes[i];
  20344. return availableDeviceTypes[0];
  20345. }
  20346. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20347. const bool treatAsChosenDevice)
  20348. {
  20349. jassert (&newSetup != &currentSetup); // this will have no effect
  20350. if (newSetup == currentSetup && currentAudioDevice != 0)
  20351. return String::empty;
  20352. if (! (newSetup == currentSetup))
  20353. sendChangeMessage();
  20354. stopDevice();
  20355. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20356. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20357. String error;
  20358. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20359. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20360. {
  20361. deleteCurrentDevice();
  20362. if (treatAsChosenDevice)
  20363. updateXml();
  20364. return String::empty;
  20365. }
  20366. if (currentSetup.inputDeviceName != newInputDeviceName
  20367. || currentSetup.outputDeviceName != newOutputDeviceName
  20368. || currentAudioDevice == 0)
  20369. {
  20370. deleteCurrentDevice();
  20371. scanDevicesIfNeeded();
  20372. if (newOutputDeviceName.isNotEmpty()
  20373. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20374. {
  20375. return "No such device: " + newOutputDeviceName;
  20376. }
  20377. if (newInputDeviceName.isNotEmpty()
  20378. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20379. {
  20380. return "No such device: " + newInputDeviceName;
  20381. }
  20382. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20383. if (currentAudioDevice == 0)
  20384. 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!";
  20385. else
  20386. error = currentAudioDevice->getLastError();
  20387. if (error.isNotEmpty())
  20388. {
  20389. deleteCurrentDevice();
  20390. return error;
  20391. }
  20392. if (newSetup.useDefaultInputChannels)
  20393. {
  20394. inputChannels.clear();
  20395. inputChannels.setRange (0, numInputChansNeeded, true);
  20396. }
  20397. if (newSetup.useDefaultOutputChannels)
  20398. {
  20399. outputChannels.clear();
  20400. outputChannels.setRange (0, numOutputChansNeeded, true);
  20401. }
  20402. if (newInputDeviceName.isEmpty())
  20403. inputChannels.clear();
  20404. if (newOutputDeviceName.isEmpty())
  20405. outputChannels.clear();
  20406. }
  20407. if (! newSetup.useDefaultInputChannels)
  20408. inputChannels = newSetup.inputChannels;
  20409. if (! newSetup.useDefaultOutputChannels)
  20410. outputChannels = newSetup.outputChannels;
  20411. currentSetup = newSetup;
  20412. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20413. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20414. error = currentAudioDevice->open (inputChannels,
  20415. outputChannels,
  20416. currentSetup.sampleRate,
  20417. currentSetup.bufferSize);
  20418. if (error.isEmpty())
  20419. {
  20420. currentDeviceType = currentAudioDevice->getTypeName();
  20421. currentAudioDevice->start (&callbackHandler);
  20422. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20423. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20424. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20425. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20426. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20427. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20428. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20429. if (treatAsChosenDevice)
  20430. updateXml();
  20431. }
  20432. else
  20433. {
  20434. deleteCurrentDevice();
  20435. }
  20436. return error;
  20437. }
  20438. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20439. {
  20440. jassert (currentAudioDevice != 0);
  20441. if (rate > 0)
  20442. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20443. if (currentAudioDevice->getSampleRate (i) == rate)
  20444. return rate;
  20445. double lowestAbove44 = 0.0;
  20446. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20447. {
  20448. const double sr = currentAudioDevice->getSampleRate (i);
  20449. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  20450. lowestAbove44 = sr;
  20451. }
  20452. if (lowestAbove44 > 0.0)
  20453. return lowestAbove44;
  20454. return currentAudioDevice->getSampleRate (0);
  20455. }
  20456. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20457. {
  20458. jassert (currentAudioDevice != 0);
  20459. if (bufferSize > 0)
  20460. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20461. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20462. return bufferSize;
  20463. return currentAudioDevice->getDefaultBufferSize();
  20464. }
  20465. void AudioDeviceManager::stopDevice()
  20466. {
  20467. if (currentAudioDevice != 0)
  20468. currentAudioDevice->stop();
  20469. testSound = 0;
  20470. }
  20471. void AudioDeviceManager::closeAudioDevice()
  20472. {
  20473. stopDevice();
  20474. currentAudioDevice = 0;
  20475. }
  20476. void AudioDeviceManager::restartLastAudioDevice()
  20477. {
  20478. if (currentAudioDevice == 0)
  20479. {
  20480. if (currentSetup.inputDeviceName.isEmpty()
  20481. && currentSetup.outputDeviceName.isEmpty())
  20482. {
  20483. // This method will only reload the last device that was running
  20484. // before closeAudioDevice() was called - you need to actually open
  20485. // one first, with setAudioDevice().
  20486. jassertfalse;
  20487. return;
  20488. }
  20489. AudioDeviceSetup s (currentSetup);
  20490. setAudioDeviceSetup (s, false);
  20491. }
  20492. }
  20493. void AudioDeviceManager::updateXml()
  20494. {
  20495. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20496. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20497. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20498. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20499. if (currentAudioDevice != 0)
  20500. {
  20501. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20502. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20503. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20504. if (! currentSetup.useDefaultInputChannels)
  20505. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20506. if (! currentSetup.useDefaultOutputChannels)
  20507. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20508. }
  20509. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20510. {
  20511. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20512. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20513. }
  20514. if (midiInsFromXml.size() > 0)
  20515. {
  20516. // Add any midi devices that have been enabled before, but which aren't currently
  20517. // open because the device has been disconnected.
  20518. const StringArray availableMidiDevices (MidiInput::getDevices());
  20519. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20520. {
  20521. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20522. {
  20523. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20524. m->setAttribute ("name", midiInsFromXml[i]);
  20525. }
  20526. }
  20527. }
  20528. if (defaultMidiOutputName.isNotEmpty())
  20529. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20530. }
  20531. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20532. {
  20533. {
  20534. const ScopedLock sl (audioCallbackLock);
  20535. if (callbacks.contains (newCallback))
  20536. return;
  20537. }
  20538. if (currentAudioDevice != 0 && newCallback != 0)
  20539. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20540. const ScopedLock sl (audioCallbackLock);
  20541. callbacks.add (newCallback);
  20542. }
  20543. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20544. {
  20545. if (callbackToRemove != 0)
  20546. {
  20547. bool needsDeinitialising = currentAudioDevice != 0;
  20548. {
  20549. const ScopedLock sl (audioCallbackLock);
  20550. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20551. callbacks.removeValue (callbackToRemove);
  20552. }
  20553. if (needsDeinitialising)
  20554. callbackToRemove->audioDeviceStopped();
  20555. }
  20556. }
  20557. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20558. int numInputChannels,
  20559. float** outputChannelData,
  20560. int numOutputChannels,
  20561. int numSamples)
  20562. {
  20563. const ScopedLock sl (audioCallbackLock);
  20564. if (inputLevelMeasurementEnabledCount > 0)
  20565. {
  20566. for (int j = 0; j < numSamples; ++j)
  20567. {
  20568. float s = 0;
  20569. for (int i = 0; i < numInputChannels; ++i)
  20570. s += std::abs (inputChannelData[i][j]);
  20571. s /= numInputChannels;
  20572. const double decayFactor = 0.99992;
  20573. if (s > inputLevel)
  20574. inputLevel = s;
  20575. else if (inputLevel > 0.001f)
  20576. inputLevel *= decayFactor;
  20577. else
  20578. inputLevel = 0;
  20579. }
  20580. }
  20581. if (callbacks.size() > 0)
  20582. {
  20583. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20584. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20585. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20586. outputChannelData, numOutputChannels, numSamples);
  20587. float** const tempChans = tempBuffer.getArrayOfChannels();
  20588. for (int i = callbacks.size(); --i > 0;)
  20589. {
  20590. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20591. tempChans, numOutputChannels, numSamples);
  20592. for (int chan = 0; chan < numOutputChannels; ++chan)
  20593. {
  20594. const float* const src = tempChans [chan];
  20595. float* const dst = outputChannelData [chan];
  20596. if (src != 0 && dst != 0)
  20597. for (int j = 0; j < numSamples; ++j)
  20598. dst[j] += src[j];
  20599. }
  20600. }
  20601. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20602. const double filterAmount = 0.2;
  20603. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20604. }
  20605. else
  20606. {
  20607. for (int i = 0; i < numOutputChannels; ++i)
  20608. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20609. }
  20610. if (testSound != 0)
  20611. {
  20612. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20613. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20614. for (int i = 0; i < numOutputChannels; ++i)
  20615. for (int j = 0; j < numSamps; ++j)
  20616. outputChannelData [i][j] += src[j];
  20617. testSoundPosition += numSamps;
  20618. if (testSoundPosition >= testSound->getNumSamples())
  20619. testSound = 0;
  20620. }
  20621. }
  20622. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20623. {
  20624. cpuUsageMs = 0;
  20625. const double sampleRate = device->getCurrentSampleRate();
  20626. const int blockSize = device->getCurrentBufferSizeSamples();
  20627. if (sampleRate > 0.0 && blockSize > 0)
  20628. {
  20629. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20630. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20631. }
  20632. {
  20633. const ScopedLock sl (audioCallbackLock);
  20634. for (int i = callbacks.size(); --i >= 0;)
  20635. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20636. }
  20637. sendChangeMessage();
  20638. }
  20639. void AudioDeviceManager::audioDeviceStoppedInt()
  20640. {
  20641. cpuUsageMs = 0;
  20642. timeToCpuScale = 0;
  20643. sendChangeMessage();
  20644. const ScopedLock sl (audioCallbackLock);
  20645. for (int i = callbacks.size(); --i >= 0;)
  20646. callbacks.getUnchecked(i)->audioDeviceStopped();
  20647. }
  20648. double AudioDeviceManager::getCpuUsage() const
  20649. {
  20650. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20651. }
  20652. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20653. const bool enabled)
  20654. {
  20655. if (enabled != isMidiInputEnabled (name))
  20656. {
  20657. if (enabled)
  20658. {
  20659. const int index = MidiInput::getDevices().indexOf (name);
  20660. if (index >= 0)
  20661. {
  20662. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20663. if (min != 0)
  20664. {
  20665. enabledMidiInputs.add (min);
  20666. min->start();
  20667. }
  20668. }
  20669. }
  20670. else
  20671. {
  20672. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20673. if (enabledMidiInputs[i]->getName() == name)
  20674. enabledMidiInputs.remove (i);
  20675. }
  20676. updateXml();
  20677. sendChangeMessage();
  20678. }
  20679. }
  20680. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20681. {
  20682. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20683. if (enabledMidiInputs[i]->getName() == name)
  20684. return true;
  20685. return false;
  20686. }
  20687. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20688. MidiInputCallback* callbackToAdd)
  20689. {
  20690. removeMidiInputCallback (name, callbackToAdd);
  20691. if (name.isEmpty() || isMidiInputEnabled (name))
  20692. {
  20693. const ScopedLock sl (midiCallbackLock);
  20694. midiCallbacks.add (callbackToAdd);
  20695. midiCallbackDevices.add (name);
  20696. }
  20697. }
  20698. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callback)
  20699. {
  20700. for (int i = midiCallbacks.size(); --i >= 0;)
  20701. {
  20702. if (midiCallbackDevices[i] == name && midiCallbacks.getUnchecked(i) == callback)
  20703. {
  20704. const ScopedLock sl (midiCallbackLock);
  20705. midiCallbacks.remove (i);
  20706. midiCallbackDevices.remove (i);
  20707. }
  20708. }
  20709. }
  20710. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20711. const MidiMessage& message)
  20712. {
  20713. if (! message.isActiveSense())
  20714. {
  20715. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20716. const ScopedLock sl (midiCallbackLock);
  20717. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20718. {
  20719. const String name (midiCallbackDevices[i]);
  20720. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20721. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20722. }
  20723. }
  20724. }
  20725. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20726. {
  20727. if (defaultMidiOutputName != deviceName)
  20728. {
  20729. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20730. {
  20731. const ScopedLock sl (audioCallbackLock);
  20732. oldCallbacks = callbacks;
  20733. callbacks.clear();
  20734. }
  20735. if (currentAudioDevice != 0)
  20736. for (int i = oldCallbacks.size(); --i >= 0;)
  20737. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20738. defaultMidiOutput = 0;
  20739. defaultMidiOutputName = deviceName;
  20740. if (deviceName.isNotEmpty())
  20741. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20742. if (currentAudioDevice != 0)
  20743. for (int i = oldCallbacks.size(); --i >= 0;)
  20744. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20745. {
  20746. const ScopedLock sl (audioCallbackLock);
  20747. callbacks = oldCallbacks;
  20748. }
  20749. updateXml();
  20750. sendChangeMessage();
  20751. }
  20752. }
  20753. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20754. int numInputChannels,
  20755. float** outputChannelData,
  20756. int numOutputChannels,
  20757. int numSamples)
  20758. {
  20759. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20760. }
  20761. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20762. {
  20763. owner->audioDeviceAboutToStartInt (device);
  20764. }
  20765. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20766. {
  20767. owner->audioDeviceStoppedInt();
  20768. }
  20769. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20770. {
  20771. owner->handleIncomingMidiMessageInt (source, message);
  20772. }
  20773. void AudioDeviceManager::playTestSound()
  20774. {
  20775. { // cunningly nested to swap, unlock and delete in that order.
  20776. ScopedPointer <AudioSampleBuffer> oldSound;
  20777. {
  20778. const ScopedLock sl (audioCallbackLock);
  20779. oldSound = testSound;
  20780. }
  20781. }
  20782. testSoundPosition = 0;
  20783. if (currentAudioDevice != 0)
  20784. {
  20785. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20786. const int soundLength = (int) sampleRate;
  20787. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20788. float* samples = newSound->getSampleData (0);
  20789. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20790. const float amplitude = 0.5f;
  20791. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20792. for (int i = 0; i < soundLength; ++i)
  20793. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20794. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20795. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20796. const ScopedLock sl (audioCallbackLock);
  20797. testSound = newSound;
  20798. }
  20799. }
  20800. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20801. {
  20802. const ScopedLock sl (audioCallbackLock);
  20803. if (enableMeasurement)
  20804. ++inputLevelMeasurementEnabledCount;
  20805. else
  20806. --inputLevelMeasurementEnabledCount;
  20807. inputLevel = 0;
  20808. }
  20809. double AudioDeviceManager::getCurrentInputLevel() const
  20810. {
  20811. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20812. return inputLevel;
  20813. }
  20814. END_JUCE_NAMESPACE
  20815. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20816. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20817. BEGIN_JUCE_NAMESPACE
  20818. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20819. : name (deviceName),
  20820. typeName (typeName_)
  20821. {
  20822. }
  20823. AudioIODevice::~AudioIODevice()
  20824. {
  20825. }
  20826. bool AudioIODevice::hasControlPanel() const
  20827. {
  20828. return false;
  20829. }
  20830. bool AudioIODevice::showControlPanel()
  20831. {
  20832. jassertfalse; // this should only be called for devices which return true from
  20833. // their hasControlPanel() method.
  20834. return false;
  20835. }
  20836. END_JUCE_NAMESPACE
  20837. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20838. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20839. BEGIN_JUCE_NAMESPACE
  20840. AudioIODeviceType::AudioIODeviceType (const String& name)
  20841. : typeName (name)
  20842. {
  20843. }
  20844. AudioIODeviceType::~AudioIODeviceType()
  20845. {
  20846. }
  20847. #if ! JUCE_MAC
  20848. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio() { return 0; }
  20849. #endif
  20850. #if ! JUCE_IOS
  20851. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio() { return 0; }
  20852. #endif
  20853. #if ! (JUCE_WINDOWS && JUCE_WASAPI)
  20854. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI() { return 0; }
  20855. #endif
  20856. #if ! (JUCE_WINDOWS && JUCE_DIRECTSOUND)
  20857. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound() { return 0; }
  20858. #endif
  20859. #if ! (JUCE_WINDOWS && JUCE_ASIO)
  20860. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO() { return 0; }
  20861. #endif
  20862. #if ! (JUCE_LINUX && JUCE_ALSA)
  20863. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA() { return 0; }
  20864. #endif
  20865. #if ! (JUCE_LINUX && JUCE_JACK)
  20866. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK() { return 0; }
  20867. #endif
  20868. END_JUCE_NAMESPACE
  20869. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20870. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20871. BEGIN_JUCE_NAMESPACE
  20872. MidiOutput::MidiOutput()
  20873. : Thread ("midi out"),
  20874. internal (0),
  20875. firstMessage (0)
  20876. {
  20877. }
  20878. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20879. const double sampleNumber)
  20880. : message (data, len, sampleNumber)
  20881. {
  20882. }
  20883. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20884. const double millisecondCounterToStartAt,
  20885. double samplesPerSecondForBuffer)
  20886. {
  20887. // You've got to call startBackgroundThread() for this to actually work..
  20888. jassert (isThreadRunning());
  20889. // this needs to be a value in the future - RTFM for this method!
  20890. jassert (millisecondCounterToStartAt > 0);
  20891. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20892. MidiBuffer::Iterator i (buffer);
  20893. const uint8* data;
  20894. int len, time;
  20895. while (i.getNextEvent (data, len, time))
  20896. {
  20897. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20898. PendingMessage* const m
  20899. = new PendingMessage (data, len, eventTime);
  20900. const ScopedLock sl (lock);
  20901. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20902. {
  20903. m->next = firstMessage;
  20904. firstMessage = m;
  20905. }
  20906. else
  20907. {
  20908. PendingMessage* mm = firstMessage;
  20909. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20910. mm = mm->next;
  20911. m->next = mm->next;
  20912. mm->next = m;
  20913. }
  20914. }
  20915. notify();
  20916. }
  20917. void MidiOutput::clearAllPendingMessages()
  20918. {
  20919. const ScopedLock sl (lock);
  20920. while (firstMessage != 0)
  20921. {
  20922. PendingMessage* const m = firstMessage;
  20923. firstMessage = firstMessage->next;
  20924. delete m;
  20925. }
  20926. }
  20927. void MidiOutput::startBackgroundThread()
  20928. {
  20929. startThread (9);
  20930. }
  20931. void MidiOutput::stopBackgroundThread()
  20932. {
  20933. stopThread (5000);
  20934. }
  20935. void MidiOutput::run()
  20936. {
  20937. while (! threadShouldExit())
  20938. {
  20939. uint32 now = Time::getMillisecondCounter();
  20940. uint32 eventTime = 0;
  20941. uint32 timeToWait = 500;
  20942. PendingMessage* message;
  20943. {
  20944. const ScopedLock sl (lock);
  20945. message = firstMessage;
  20946. if (message != 0)
  20947. {
  20948. eventTime = roundToInt (message->message.getTimeStamp());
  20949. if (eventTime > now + 20)
  20950. {
  20951. timeToWait = eventTime - (now + 20);
  20952. message = 0;
  20953. }
  20954. else
  20955. {
  20956. firstMessage = message->next;
  20957. }
  20958. }
  20959. }
  20960. if (message != 0)
  20961. {
  20962. if (eventTime > now)
  20963. {
  20964. Time::waitForMillisecondCounter (eventTime);
  20965. if (threadShouldExit())
  20966. break;
  20967. }
  20968. if (eventTime > now - 200)
  20969. sendMessageNow (message->message);
  20970. delete message;
  20971. }
  20972. else
  20973. {
  20974. jassert (timeToWait < 1000 * 30);
  20975. wait (timeToWait);
  20976. }
  20977. }
  20978. clearAllPendingMessages();
  20979. }
  20980. END_JUCE_NAMESPACE
  20981. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20982. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20983. BEGIN_JUCE_NAMESPACE
  20984. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20985. {
  20986. const double maxVal = (double) 0x7fff;
  20987. char* intData = static_cast <char*> (dest);
  20988. if (dest != (void*) source || destBytesPerSample <= 4)
  20989. {
  20990. for (int i = 0; i < numSamples; ++i)
  20991. {
  20992. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20993. intData += destBytesPerSample;
  20994. }
  20995. }
  20996. else
  20997. {
  20998. intData += destBytesPerSample * numSamples;
  20999. for (int i = numSamples; --i >= 0;)
  21000. {
  21001. intData -= destBytesPerSample;
  21002. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21003. }
  21004. }
  21005. }
  21006. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21007. {
  21008. const double maxVal = (double) 0x7fff;
  21009. char* intData = static_cast <char*> (dest);
  21010. if (dest != (void*) source || destBytesPerSample <= 4)
  21011. {
  21012. for (int i = 0; i < numSamples; ++i)
  21013. {
  21014. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21015. intData += destBytesPerSample;
  21016. }
  21017. }
  21018. else
  21019. {
  21020. intData += destBytesPerSample * numSamples;
  21021. for (int i = numSamples; --i >= 0;)
  21022. {
  21023. intData -= destBytesPerSample;
  21024. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21025. }
  21026. }
  21027. }
  21028. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21029. {
  21030. const double maxVal = (double) 0x7fffff;
  21031. char* intData = static_cast <char*> (dest);
  21032. if (dest != (void*) source || destBytesPerSample <= 4)
  21033. {
  21034. for (int i = 0; i < numSamples; ++i)
  21035. {
  21036. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21037. intData += destBytesPerSample;
  21038. }
  21039. }
  21040. else
  21041. {
  21042. intData += destBytesPerSample * numSamples;
  21043. for (int i = numSamples; --i >= 0;)
  21044. {
  21045. intData -= destBytesPerSample;
  21046. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21047. }
  21048. }
  21049. }
  21050. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21051. {
  21052. const double maxVal = (double) 0x7fffff;
  21053. char* intData = static_cast <char*> (dest);
  21054. if (dest != (void*) source || destBytesPerSample <= 4)
  21055. {
  21056. for (int i = 0; i < numSamples; ++i)
  21057. {
  21058. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21059. intData += destBytesPerSample;
  21060. }
  21061. }
  21062. else
  21063. {
  21064. intData += destBytesPerSample * numSamples;
  21065. for (int i = numSamples; --i >= 0;)
  21066. {
  21067. intData -= destBytesPerSample;
  21068. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21069. }
  21070. }
  21071. }
  21072. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21073. {
  21074. const double maxVal = (double) 0x7fffffff;
  21075. char* intData = static_cast <char*> (dest);
  21076. if (dest != (void*) source || destBytesPerSample <= 4)
  21077. {
  21078. for (int i = 0; i < numSamples; ++i)
  21079. {
  21080. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21081. intData += destBytesPerSample;
  21082. }
  21083. }
  21084. else
  21085. {
  21086. intData += destBytesPerSample * numSamples;
  21087. for (int i = numSamples; --i >= 0;)
  21088. {
  21089. intData -= destBytesPerSample;
  21090. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21091. }
  21092. }
  21093. }
  21094. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21095. {
  21096. const double maxVal = (double) 0x7fffffff;
  21097. char* intData = static_cast <char*> (dest);
  21098. if (dest != (void*) source || destBytesPerSample <= 4)
  21099. {
  21100. for (int i = 0; i < numSamples; ++i)
  21101. {
  21102. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21103. intData += destBytesPerSample;
  21104. }
  21105. }
  21106. else
  21107. {
  21108. intData += destBytesPerSample * numSamples;
  21109. for (int i = numSamples; --i >= 0;)
  21110. {
  21111. intData -= destBytesPerSample;
  21112. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21113. }
  21114. }
  21115. }
  21116. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21117. {
  21118. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21119. char* d = static_cast <char*> (dest);
  21120. for (int i = 0; i < numSamples; ++i)
  21121. {
  21122. *(float*) d = source[i];
  21123. #if JUCE_BIG_ENDIAN
  21124. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21125. #endif
  21126. d += destBytesPerSample;
  21127. }
  21128. }
  21129. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21130. {
  21131. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21132. char* d = static_cast <char*> (dest);
  21133. for (int i = 0; i < numSamples; ++i)
  21134. {
  21135. *(float*) d = source[i];
  21136. #if JUCE_LITTLE_ENDIAN
  21137. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21138. #endif
  21139. d += destBytesPerSample;
  21140. }
  21141. }
  21142. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21143. {
  21144. const float scale = 1.0f / 0x7fff;
  21145. const char* intData = static_cast <const char*> (source);
  21146. if (source != (void*) dest || srcBytesPerSample >= 4)
  21147. {
  21148. for (int i = 0; i < numSamples; ++i)
  21149. {
  21150. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21151. intData += srcBytesPerSample;
  21152. }
  21153. }
  21154. else
  21155. {
  21156. intData += srcBytesPerSample * numSamples;
  21157. for (int i = numSamples; --i >= 0;)
  21158. {
  21159. intData -= srcBytesPerSample;
  21160. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21161. }
  21162. }
  21163. }
  21164. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21165. {
  21166. const float scale = 1.0f / 0x7fff;
  21167. const char* intData = static_cast <const char*> (source);
  21168. if (source != (void*) dest || srcBytesPerSample >= 4)
  21169. {
  21170. for (int i = 0; i < numSamples; ++i)
  21171. {
  21172. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21173. intData += srcBytesPerSample;
  21174. }
  21175. }
  21176. else
  21177. {
  21178. intData += srcBytesPerSample * numSamples;
  21179. for (int i = numSamples; --i >= 0;)
  21180. {
  21181. intData -= srcBytesPerSample;
  21182. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21183. }
  21184. }
  21185. }
  21186. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21187. {
  21188. const float scale = 1.0f / 0x7fffff;
  21189. const char* intData = static_cast <const char*> (source);
  21190. if (source != (void*) dest || srcBytesPerSample >= 4)
  21191. {
  21192. for (int i = 0; i < numSamples; ++i)
  21193. {
  21194. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21195. intData += srcBytesPerSample;
  21196. }
  21197. }
  21198. else
  21199. {
  21200. intData += srcBytesPerSample * numSamples;
  21201. for (int i = numSamples; --i >= 0;)
  21202. {
  21203. intData -= srcBytesPerSample;
  21204. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21205. }
  21206. }
  21207. }
  21208. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21209. {
  21210. const float scale = 1.0f / 0x7fffff;
  21211. const char* intData = static_cast <const char*> (source);
  21212. if (source != (void*) dest || srcBytesPerSample >= 4)
  21213. {
  21214. for (int i = 0; i < numSamples; ++i)
  21215. {
  21216. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21217. intData += srcBytesPerSample;
  21218. }
  21219. }
  21220. else
  21221. {
  21222. intData += srcBytesPerSample * numSamples;
  21223. for (int i = numSamples; --i >= 0;)
  21224. {
  21225. intData -= srcBytesPerSample;
  21226. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21227. }
  21228. }
  21229. }
  21230. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21231. {
  21232. const float scale = 1.0f / 0x7fffffff;
  21233. const char* intData = static_cast <const char*> (source);
  21234. if (source != (void*) dest || srcBytesPerSample >= 4)
  21235. {
  21236. for (int i = 0; i < numSamples; ++i)
  21237. {
  21238. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21239. intData += srcBytesPerSample;
  21240. }
  21241. }
  21242. else
  21243. {
  21244. intData += srcBytesPerSample * numSamples;
  21245. for (int i = numSamples; --i >= 0;)
  21246. {
  21247. intData -= srcBytesPerSample;
  21248. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21249. }
  21250. }
  21251. }
  21252. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21253. {
  21254. const float scale = 1.0f / 0x7fffffff;
  21255. const char* intData = static_cast <const char*> (source);
  21256. if (source != (void*) dest || srcBytesPerSample >= 4)
  21257. {
  21258. for (int i = 0; i < numSamples; ++i)
  21259. {
  21260. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21261. intData += srcBytesPerSample;
  21262. }
  21263. }
  21264. else
  21265. {
  21266. intData += srcBytesPerSample * numSamples;
  21267. for (int i = numSamples; --i >= 0;)
  21268. {
  21269. intData -= srcBytesPerSample;
  21270. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21271. }
  21272. }
  21273. }
  21274. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21275. {
  21276. const char* s = static_cast <const char*> (source);
  21277. for (int i = 0; i < numSamples; ++i)
  21278. {
  21279. dest[i] = *(float*)s;
  21280. #if JUCE_BIG_ENDIAN
  21281. uint32* const d = (uint32*) (dest + i);
  21282. *d = ByteOrder::swap (*d);
  21283. #endif
  21284. s += srcBytesPerSample;
  21285. }
  21286. }
  21287. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21288. {
  21289. const char* s = static_cast <const char*> (source);
  21290. for (int i = 0; i < numSamples; ++i)
  21291. {
  21292. dest[i] = *(float*)s;
  21293. #if JUCE_LITTLE_ENDIAN
  21294. uint32* const d = (uint32*) (dest + i);
  21295. *d = ByteOrder::swap (*d);
  21296. #endif
  21297. s += srcBytesPerSample;
  21298. }
  21299. }
  21300. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21301. const float* const source,
  21302. void* const dest,
  21303. const int numSamples)
  21304. {
  21305. switch (destFormat)
  21306. {
  21307. case int16LE:
  21308. convertFloatToInt16LE (source, dest, numSamples);
  21309. break;
  21310. case int16BE:
  21311. convertFloatToInt16BE (source, dest, numSamples);
  21312. break;
  21313. case int24LE:
  21314. convertFloatToInt24LE (source, dest, numSamples);
  21315. break;
  21316. case int24BE:
  21317. convertFloatToInt24BE (source, dest, numSamples);
  21318. break;
  21319. case int32LE:
  21320. convertFloatToInt32LE (source, dest, numSamples);
  21321. break;
  21322. case int32BE:
  21323. convertFloatToInt32BE (source, dest, numSamples);
  21324. break;
  21325. case float32LE:
  21326. convertFloatToFloat32LE (source, dest, numSamples);
  21327. break;
  21328. case float32BE:
  21329. convertFloatToFloat32BE (source, dest, numSamples);
  21330. break;
  21331. default:
  21332. jassertfalse;
  21333. break;
  21334. }
  21335. }
  21336. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21337. const void* const source,
  21338. float* const dest,
  21339. const int numSamples)
  21340. {
  21341. switch (sourceFormat)
  21342. {
  21343. case int16LE:
  21344. convertInt16LEToFloat (source, dest, numSamples);
  21345. break;
  21346. case int16BE:
  21347. convertInt16BEToFloat (source, dest, numSamples);
  21348. break;
  21349. case int24LE:
  21350. convertInt24LEToFloat (source, dest, numSamples);
  21351. break;
  21352. case int24BE:
  21353. convertInt24BEToFloat (source, dest, numSamples);
  21354. break;
  21355. case int32LE:
  21356. convertInt32LEToFloat (source, dest, numSamples);
  21357. break;
  21358. case int32BE:
  21359. convertInt32BEToFloat (source, dest, numSamples);
  21360. break;
  21361. case float32LE:
  21362. convertFloat32LEToFloat (source, dest, numSamples);
  21363. break;
  21364. case float32BE:
  21365. convertFloat32BEToFloat (source, dest, numSamples);
  21366. break;
  21367. default:
  21368. jassertfalse;
  21369. break;
  21370. }
  21371. }
  21372. void AudioDataConverters::interleaveSamples (const float** const source,
  21373. float* const dest,
  21374. const int numSamples,
  21375. const int numChannels)
  21376. {
  21377. for (int chan = 0; chan < numChannels; ++chan)
  21378. {
  21379. int i = chan;
  21380. const float* src = source [chan];
  21381. for (int j = 0; j < numSamples; ++j)
  21382. {
  21383. dest [i] = src [j];
  21384. i += numChannels;
  21385. }
  21386. }
  21387. }
  21388. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21389. float** const dest,
  21390. const int numSamples,
  21391. const int numChannels)
  21392. {
  21393. for (int chan = 0; chan < numChannels; ++chan)
  21394. {
  21395. int i = chan;
  21396. float* dst = dest [chan];
  21397. for (int j = 0; j < numSamples; ++j)
  21398. {
  21399. dst [j] = source [i];
  21400. i += numChannels;
  21401. }
  21402. }
  21403. }
  21404. #if JUCE_UNIT_TESTS
  21405. class AudioConversionTests : public UnitTest
  21406. {
  21407. public:
  21408. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21409. template <class F1, class E1, class F2, class E2>
  21410. struct Test5
  21411. {
  21412. static void test (UnitTest& unitTest)
  21413. {
  21414. test (unitTest, false);
  21415. test (unitTest, true);
  21416. }
  21417. static void test (UnitTest& unitTest, bool inPlace)
  21418. {
  21419. const int numSamples = 2048;
  21420. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21421. {
  21422. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21423. bool clippingFailed = false;
  21424. for (int i = 0; i < numSamples / 2; ++i)
  21425. {
  21426. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21427. if (! d.isFloatingPoint())
  21428. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21429. ++d;
  21430. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21431. ++d;
  21432. }
  21433. unitTest.expect (! clippingFailed);
  21434. }
  21435. // convert data from the source to dest format..
  21436. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21437. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21438. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21439. // ..and back again..
  21440. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21441. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21442. if (! inPlace)
  21443. zerostruct (reversed);
  21444. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21445. {
  21446. int biggestDiff = 0;
  21447. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21448. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21449. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21450. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21451. for (int i = 0; i < numSamples; ++i)
  21452. {
  21453. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21454. ++d1;
  21455. ++d2;
  21456. }
  21457. unitTest.expect (biggestDiff <= errorMargin);
  21458. }
  21459. }
  21460. };
  21461. template <class F1, class E1, class FormatType>
  21462. struct Test3
  21463. {
  21464. static void test (UnitTest& unitTest)
  21465. {
  21466. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21467. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21468. }
  21469. };
  21470. template <class FormatType, class Endianness>
  21471. struct Test2
  21472. {
  21473. static void test (UnitTest& unitTest)
  21474. {
  21475. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21476. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21477. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21478. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21479. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21480. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21481. }
  21482. };
  21483. template <class FormatType>
  21484. struct Test1
  21485. {
  21486. static void test (UnitTest& unitTest)
  21487. {
  21488. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21489. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21490. }
  21491. };
  21492. void runTest()
  21493. {
  21494. beginTest ("Round-trip conversion: Int8");
  21495. Test1 <AudioData::Int8>::test (*this);
  21496. beginTest ("Round-trip conversion: Int16");
  21497. Test1 <AudioData::Int16>::test (*this);
  21498. beginTest ("Round-trip conversion: Int24");
  21499. Test1 <AudioData::Int24>::test (*this);
  21500. beginTest ("Round-trip conversion: Int32");
  21501. Test1 <AudioData::Int32>::test (*this);
  21502. beginTest ("Round-trip conversion: Float32");
  21503. Test1 <AudioData::Float32>::test (*this);
  21504. }
  21505. };
  21506. static AudioConversionTests audioConversionUnitTests;
  21507. #endif
  21508. END_JUCE_NAMESPACE
  21509. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21510. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21511. BEGIN_JUCE_NAMESPACE
  21512. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21513. const int numSamples) throw()
  21514. : numChannels (numChannels_),
  21515. size (numSamples)
  21516. {
  21517. jassert (numSamples >= 0);
  21518. jassert (numChannels_ > 0);
  21519. allocateData();
  21520. }
  21521. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21522. : numChannels (other.numChannels),
  21523. size (other.size)
  21524. {
  21525. allocateData();
  21526. const size_t numBytes = size * sizeof (float);
  21527. for (int i = 0; i < numChannels; ++i)
  21528. memcpy (channels[i], other.channels[i], numBytes);
  21529. }
  21530. void AudioSampleBuffer::allocateData()
  21531. {
  21532. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21533. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21534. allocatedData.malloc (allocatedBytes);
  21535. channels = reinterpret_cast <float**> (allocatedData.getData());
  21536. float* chan = (float*) (allocatedData + channelListSize);
  21537. for (int i = 0; i < numChannels; ++i)
  21538. {
  21539. channels[i] = chan;
  21540. chan += size;
  21541. }
  21542. channels [numChannels] = 0;
  21543. }
  21544. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21545. const int numChannels_,
  21546. const int numSamples) throw()
  21547. : numChannels (numChannels_),
  21548. size (numSamples),
  21549. allocatedBytes (0)
  21550. {
  21551. jassert (numChannels_ > 0);
  21552. allocateChannels (dataToReferTo, 0);
  21553. }
  21554. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21555. const int numChannels_,
  21556. const int startSample,
  21557. const int numSamples) throw()
  21558. : numChannels (numChannels_),
  21559. size (numSamples),
  21560. allocatedBytes (0)
  21561. {
  21562. jassert (numChannels_ > 0);
  21563. allocateChannels (dataToReferTo, startSample);
  21564. }
  21565. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21566. const int newNumChannels,
  21567. const int newNumSamples) throw()
  21568. {
  21569. jassert (newNumChannels > 0);
  21570. allocatedBytes = 0;
  21571. allocatedData.free();
  21572. numChannels = newNumChannels;
  21573. size = newNumSamples;
  21574. allocateChannels (dataToReferTo, 0);
  21575. }
  21576. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo, int offset)
  21577. {
  21578. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21579. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21580. {
  21581. channels = static_cast <float**> (preallocatedChannelSpace);
  21582. }
  21583. else
  21584. {
  21585. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21586. channels = reinterpret_cast <float**> (allocatedData.getData());
  21587. }
  21588. for (int i = 0; i < numChannels; ++i)
  21589. {
  21590. // you have to pass in the same number of valid pointers as numChannels
  21591. jassert (dataToReferTo[i] != 0);
  21592. channels[i] = dataToReferTo[i] + offset;
  21593. }
  21594. channels [numChannels] = 0;
  21595. }
  21596. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21597. {
  21598. if (this != &other)
  21599. {
  21600. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21601. const size_t numBytes = size * sizeof (float);
  21602. for (int i = 0; i < numChannels; ++i)
  21603. memcpy (channels[i], other.channels[i], numBytes);
  21604. }
  21605. return *this;
  21606. }
  21607. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21608. {
  21609. }
  21610. void AudioSampleBuffer::setSize (const int newNumChannels,
  21611. const int newNumSamples,
  21612. const bool keepExistingContent,
  21613. const bool clearExtraSpace,
  21614. const bool avoidReallocating) throw()
  21615. {
  21616. jassert (newNumChannels > 0);
  21617. if (newNumSamples != size || newNumChannels != numChannels)
  21618. {
  21619. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21620. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21621. if (keepExistingContent)
  21622. {
  21623. HeapBlock <char> newData;
  21624. newData.allocate (newTotalBytes, clearExtraSpace);
  21625. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21626. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21627. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21628. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21629. for (int i = 0; i < numChansToCopy; ++i)
  21630. {
  21631. memcpy (newChan, channels[i], numBytesToCopy);
  21632. newChannels[i] = newChan;
  21633. newChan += newNumSamples;
  21634. }
  21635. allocatedData.swapWith (newData);
  21636. allocatedBytes = (int) newTotalBytes;
  21637. channels = newChannels;
  21638. }
  21639. else
  21640. {
  21641. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21642. {
  21643. if (clearExtraSpace)
  21644. zeromem (allocatedData, newTotalBytes);
  21645. }
  21646. else
  21647. {
  21648. allocatedBytes = newTotalBytes;
  21649. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21650. channels = reinterpret_cast <float**> (allocatedData.getData());
  21651. }
  21652. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21653. for (int i = 0; i < newNumChannels; ++i)
  21654. {
  21655. channels[i] = chan;
  21656. chan += newNumSamples;
  21657. }
  21658. }
  21659. channels [newNumChannels] = 0;
  21660. size = newNumSamples;
  21661. numChannels = newNumChannels;
  21662. }
  21663. }
  21664. void AudioSampleBuffer::clear() throw()
  21665. {
  21666. for (int i = 0; i < numChannels; ++i)
  21667. zeromem (channels[i], size * sizeof (float));
  21668. }
  21669. void AudioSampleBuffer::clear (const int startSample,
  21670. const int numSamples) throw()
  21671. {
  21672. jassert (startSample >= 0 && startSample + numSamples <= size);
  21673. for (int i = 0; i < numChannels; ++i)
  21674. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21675. }
  21676. void AudioSampleBuffer::clear (const int channel,
  21677. const int startSample,
  21678. const int numSamples) throw()
  21679. {
  21680. jassert (isPositiveAndBelow (channel, numChannels));
  21681. jassert (startSample >= 0 && startSample + numSamples <= size);
  21682. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21683. }
  21684. void AudioSampleBuffer::applyGain (const int channel,
  21685. const int startSample,
  21686. int numSamples,
  21687. const float gain) throw()
  21688. {
  21689. jassert (isPositiveAndBelow (channel, numChannels));
  21690. jassert (startSample >= 0 && startSample + numSamples <= size);
  21691. if (gain != 1.0f)
  21692. {
  21693. float* d = channels [channel] + startSample;
  21694. if (gain == 0.0f)
  21695. {
  21696. zeromem (d, sizeof (float) * numSamples);
  21697. }
  21698. else
  21699. {
  21700. while (--numSamples >= 0)
  21701. *d++ *= gain;
  21702. }
  21703. }
  21704. }
  21705. void AudioSampleBuffer::applyGainRamp (const int channel,
  21706. const int startSample,
  21707. int numSamples,
  21708. float startGain,
  21709. float endGain) throw()
  21710. {
  21711. if (startGain == endGain)
  21712. {
  21713. applyGain (channel, startSample, numSamples, startGain);
  21714. }
  21715. else
  21716. {
  21717. jassert (isPositiveAndBelow (channel, numChannels));
  21718. jassert (startSample >= 0 && startSample + numSamples <= size);
  21719. const float increment = (endGain - startGain) / numSamples;
  21720. float* d = channels [channel] + startSample;
  21721. while (--numSamples >= 0)
  21722. {
  21723. *d++ *= startGain;
  21724. startGain += increment;
  21725. }
  21726. }
  21727. }
  21728. void AudioSampleBuffer::applyGain (const int startSample,
  21729. const int numSamples,
  21730. const float gain) throw()
  21731. {
  21732. for (int i = 0; i < numChannels; ++i)
  21733. applyGain (i, startSample, numSamples, gain);
  21734. }
  21735. void AudioSampleBuffer::addFrom (const int destChannel,
  21736. const int destStartSample,
  21737. const AudioSampleBuffer& source,
  21738. const int sourceChannel,
  21739. const int sourceStartSample,
  21740. int numSamples,
  21741. const float gain) throw()
  21742. {
  21743. jassert (&source != this || sourceChannel != destChannel);
  21744. jassert (isPositiveAndBelow (destChannel, numChannels));
  21745. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21746. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21747. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21748. if (gain != 0.0f && numSamples > 0)
  21749. {
  21750. float* d = channels [destChannel] + destStartSample;
  21751. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21752. if (gain != 1.0f)
  21753. {
  21754. while (--numSamples >= 0)
  21755. *d++ += gain * *s++;
  21756. }
  21757. else
  21758. {
  21759. while (--numSamples >= 0)
  21760. *d++ += *s++;
  21761. }
  21762. }
  21763. }
  21764. void AudioSampleBuffer::addFrom (const int destChannel,
  21765. const int destStartSample,
  21766. const float* source,
  21767. int numSamples,
  21768. const float gain) throw()
  21769. {
  21770. jassert (isPositiveAndBelow (destChannel, numChannels));
  21771. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21772. jassert (source != 0);
  21773. if (gain != 0.0f && numSamples > 0)
  21774. {
  21775. float* d = channels [destChannel] + destStartSample;
  21776. if (gain != 1.0f)
  21777. {
  21778. while (--numSamples >= 0)
  21779. *d++ += gain * *source++;
  21780. }
  21781. else
  21782. {
  21783. while (--numSamples >= 0)
  21784. *d++ += *source++;
  21785. }
  21786. }
  21787. }
  21788. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21789. const int destStartSample,
  21790. const float* source,
  21791. int numSamples,
  21792. float startGain,
  21793. const float endGain) throw()
  21794. {
  21795. jassert (isPositiveAndBelow (destChannel, numChannels));
  21796. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21797. jassert (source != 0);
  21798. if (startGain == endGain)
  21799. {
  21800. addFrom (destChannel,
  21801. destStartSample,
  21802. source,
  21803. numSamples,
  21804. startGain);
  21805. }
  21806. else
  21807. {
  21808. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21809. {
  21810. const float increment = (endGain - startGain) / numSamples;
  21811. float* d = channels [destChannel] + destStartSample;
  21812. while (--numSamples >= 0)
  21813. {
  21814. *d++ += startGain * *source++;
  21815. startGain += increment;
  21816. }
  21817. }
  21818. }
  21819. }
  21820. void AudioSampleBuffer::copyFrom (const int destChannel,
  21821. const int destStartSample,
  21822. const AudioSampleBuffer& source,
  21823. const int sourceChannel,
  21824. const int sourceStartSample,
  21825. int numSamples) throw()
  21826. {
  21827. jassert (&source != this || sourceChannel != destChannel);
  21828. jassert (isPositiveAndBelow (destChannel, numChannels));
  21829. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21830. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21831. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21832. if (numSamples > 0)
  21833. {
  21834. memcpy (channels [destChannel] + destStartSample,
  21835. source.channels [sourceChannel] + sourceStartSample,
  21836. sizeof (float) * numSamples);
  21837. }
  21838. }
  21839. void AudioSampleBuffer::copyFrom (const int destChannel,
  21840. const int destStartSample,
  21841. const float* source,
  21842. int numSamples) throw()
  21843. {
  21844. jassert (isPositiveAndBelow (destChannel, numChannels));
  21845. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21846. jassert (source != 0);
  21847. if (numSamples > 0)
  21848. {
  21849. memcpy (channels [destChannel] + destStartSample,
  21850. source,
  21851. sizeof (float) * numSamples);
  21852. }
  21853. }
  21854. void AudioSampleBuffer::copyFrom (const int destChannel,
  21855. const int destStartSample,
  21856. const float* source,
  21857. int numSamples,
  21858. const float gain) throw()
  21859. {
  21860. jassert (isPositiveAndBelow (destChannel, numChannels));
  21861. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21862. jassert (source != 0);
  21863. if (numSamples > 0)
  21864. {
  21865. float* d = channels [destChannel] + destStartSample;
  21866. if (gain != 1.0f)
  21867. {
  21868. if (gain == 0)
  21869. {
  21870. zeromem (d, sizeof (float) * numSamples);
  21871. }
  21872. else
  21873. {
  21874. while (--numSamples >= 0)
  21875. *d++ = gain * *source++;
  21876. }
  21877. }
  21878. else
  21879. {
  21880. memcpy (d, source, sizeof (float) * numSamples);
  21881. }
  21882. }
  21883. }
  21884. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21885. const int destStartSample,
  21886. const float* source,
  21887. int numSamples,
  21888. float startGain,
  21889. float endGain) throw()
  21890. {
  21891. jassert (isPositiveAndBelow (destChannel, numChannels));
  21892. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21893. jassert (source != 0);
  21894. if (startGain == endGain)
  21895. {
  21896. copyFrom (destChannel,
  21897. destStartSample,
  21898. source,
  21899. numSamples,
  21900. startGain);
  21901. }
  21902. else
  21903. {
  21904. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21905. {
  21906. const float increment = (endGain - startGain) / numSamples;
  21907. float* d = channels [destChannel] + destStartSample;
  21908. while (--numSamples >= 0)
  21909. {
  21910. *d++ = startGain * *source++;
  21911. startGain += increment;
  21912. }
  21913. }
  21914. }
  21915. }
  21916. void AudioSampleBuffer::findMinMax (const int channel,
  21917. const int startSample,
  21918. int numSamples,
  21919. float& minVal,
  21920. float& maxVal) const throw()
  21921. {
  21922. jassert (isPositiveAndBelow (channel, numChannels));
  21923. jassert (startSample >= 0 && startSample + numSamples <= size);
  21924. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21925. }
  21926. float AudioSampleBuffer::getMagnitude (const int channel,
  21927. const int startSample,
  21928. const int numSamples) const throw()
  21929. {
  21930. jassert (isPositiveAndBelow (channel, numChannels));
  21931. jassert (startSample >= 0 && startSample + numSamples <= size);
  21932. float mn, mx;
  21933. findMinMax (channel, startSample, numSamples, mn, mx);
  21934. return jmax (mn, -mn, mx, -mx);
  21935. }
  21936. float AudioSampleBuffer::getMagnitude (const int startSample,
  21937. const int numSamples) const throw()
  21938. {
  21939. float mag = 0.0f;
  21940. for (int i = 0; i < numChannels; ++i)
  21941. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21942. return mag;
  21943. }
  21944. float AudioSampleBuffer::getRMSLevel (const int channel,
  21945. const int startSample,
  21946. const int numSamples) const throw()
  21947. {
  21948. jassert (isPositiveAndBelow (channel, numChannels));
  21949. jassert (startSample >= 0 && startSample + numSamples <= size);
  21950. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21951. return 0.0f;
  21952. const float* const data = channels [channel] + startSample;
  21953. double sum = 0.0;
  21954. for (int i = 0; i < numSamples; ++i)
  21955. {
  21956. const float sample = data [i];
  21957. sum += sample * sample;
  21958. }
  21959. return (float) std::sqrt (sum / numSamples);
  21960. }
  21961. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21962. const int startSample,
  21963. const int numSamples,
  21964. const int64 readerStartSample,
  21965. const bool useLeftChan,
  21966. const bool useRightChan)
  21967. {
  21968. jassert (reader != 0);
  21969. jassert (startSample >= 0 && startSample + numSamples <= size);
  21970. if (numSamples > 0)
  21971. {
  21972. int* chans[3];
  21973. if (useLeftChan == useRightChan)
  21974. {
  21975. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21976. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21977. }
  21978. else if (useLeftChan || (reader->numChannels == 1))
  21979. {
  21980. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21981. chans[1] = 0;
  21982. }
  21983. else if (useRightChan)
  21984. {
  21985. chans[0] = 0;
  21986. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21987. }
  21988. chans[2] = 0;
  21989. reader->read (chans, 2, readerStartSample, numSamples, true);
  21990. if (! reader->usesFloatingPointData)
  21991. {
  21992. for (int j = 0; j < 2; ++j)
  21993. {
  21994. float* const d = reinterpret_cast <float*> (chans[j]);
  21995. if (d != 0)
  21996. {
  21997. const float multiplier = 1.0f / 0x7fffffff;
  21998. for (int i = 0; i < numSamples; ++i)
  21999. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22000. }
  22001. }
  22002. }
  22003. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22004. {
  22005. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22006. memcpy (getSampleData (1, startSample),
  22007. getSampleData (0, startSample),
  22008. sizeof (float) * numSamples);
  22009. }
  22010. }
  22011. }
  22012. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22013. const int startSample,
  22014. const int numSamples) const
  22015. {
  22016. jassert (writer != 0);
  22017. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22018. }
  22019. END_JUCE_NAMESPACE
  22020. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22021. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22022. BEGIN_JUCE_NAMESPACE
  22023. IIRFilter::IIRFilter()
  22024. : active (false)
  22025. {
  22026. reset();
  22027. }
  22028. IIRFilter::IIRFilter (const IIRFilter& other)
  22029. : active (other.active)
  22030. {
  22031. const ScopedLock sl (other.processLock);
  22032. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22033. reset();
  22034. }
  22035. IIRFilter::~IIRFilter()
  22036. {
  22037. }
  22038. void IIRFilter::reset() throw()
  22039. {
  22040. const ScopedLock sl (processLock);
  22041. x1 = 0;
  22042. x2 = 0;
  22043. y1 = 0;
  22044. y2 = 0;
  22045. }
  22046. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22047. {
  22048. float out = coefficients[0] * in
  22049. + coefficients[1] * x1
  22050. + coefficients[2] * x2
  22051. - coefficients[4] * y1
  22052. - coefficients[5] * y2;
  22053. #if JUCE_INTEL
  22054. if (! (out < -1.0e-8 || out > 1.0e-8))
  22055. out = 0;
  22056. #endif
  22057. x2 = x1;
  22058. x1 = in;
  22059. y2 = y1;
  22060. y1 = out;
  22061. return out;
  22062. }
  22063. void IIRFilter::processSamples (float* const samples,
  22064. const int numSamples) throw()
  22065. {
  22066. const ScopedLock sl (processLock);
  22067. if (active)
  22068. {
  22069. for (int i = 0; i < numSamples; ++i)
  22070. {
  22071. const float in = samples[i];
  22072. float out = coefficients[0] * in
  22073. + coefficients[1] * x1
  22074. + coefficients[2] * x2
  22075. - coefficients[4] * y1
  22076. - coefficients[5] * y2;
  22077. #if JUCE_INTEL
  22078. if (! (out < -1.0e-8 || out > 1.0e-8))
  22079. out = 0;
  22080. #endif
  22081. x2 = x1;
  22082. x1 = in;
  22083. y2 = y1;
  22084. y1 = out;
  22085. samples[i] = out;
  22086. }
  22087. }
  22088. }
  22089. void IIRFilter::makeLowPass (const double sampleRate,
  22090. const double frequency) throw()
  22091. {
  22092. jassert (sampleRate > 0);
  22093. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22094. const double nSquared = n * n;
  22095. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22096. setCoefficients (c1,
  22097. c1 * 2.0f,
  22098. c1,
  22099. 1.0,
  22100. c1 * 2.0 * (1.0 - nSquared),
  22101. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22102. }
  22103. void IIRFilter::makeHighPass (const double sampleRate,
  22104. const double frequency) throw()
  22105. {
  22106. const double n = tan (double_Pi * frequency / sampleRate);
  22107. const double nSquared = n * n;
  22108. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22109. setCoefficients (c1,
  22110. c1 * -2.0f,
  22111. c1,
  22112. 1.0,
  22113. c1 * 2.0 * (nSquared - 1.0),
  22114. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22115. }
  22116. void IIRFilter::makeLowShelf (const double sampleRate,
  22117. const double cutOffFrequency,
  22118. const double Q,
  22119. const float gainFactor) throw()
  22120. {
  22121. jassert (sampleRate > 0);
  22122. jassert (Q > 0);
  22123. const double A = jmax (0.0f, gainFactor);
  22124. const double aminus1 = A - 1.0;
  22125. const double aplus1 = A + 1.0;
  22126. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22127. const double coso = std::cos (omega);
  22128. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22129. const double aminus1TimesCoso = aminus1 * coso;
  22130. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22131. A * 2.0 * (aminus1 - aplus1 * coso),
  22132. A * (aplus1 - aminus1TimesCoso - beta),
  22133. aplus1 + aminus1TimesCoso + beta,
  22134. -2.0 * (aminus1 + aplus1 * coso),
  22135. aplus1 + aminus1TimesCoso - beta);
  22136. }
  22137. void IIRFilter::makeHighShelf (const double sampleRate,
  22138. const double cutOffFrequency,
  22139. const double Q,
  22140. const float gainFactor) throw()
  22141. {
  22142. jassert (sampleRate > 0);
  22143. jassert (Q > 0);
  22144. const double A = jmax (0.0f, gainFactor);
  22145. const double aminus1 = A - 1.0;
  22146. const double aplus1 = A + 1.0;
  22147. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22148. const double coso = std::cos (omega);
  22149. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22150. const double aminus1TimesCoso = aminus1 * coso;
  22151. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22152. A * -2.0 * (aminus1 + aplus1 * coso),
  22153. A * (aplus1 + aminus1TimesCoso - beta),
  22154. aplus1 - aminus1TimesCoso + beta,
  22155. 2.0 * (aminus1 - aplus1 * coso),
  22156. aplus1 - aminus1TimesCoso - beta);
  22157. }
  22158. void IIRFilter::makeBandPass (const double sampleRate,
  22159. const double centreFrequency,
  22160. const double Q,
  22161. const float gainFactor) throw()
  22162. {
  22163. jassert (sampleRate > 0);
  22164. jassert (Q > 0);
  22165. const double A = jmax (0.0f, gainFactor);
  22166. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22167. const double alpha = 0.5 * std::sin (omega) / Q;
  22168. const double c2 = -2.0 * std::cos (omega);
  22169. const double alphaTimesA = alpha * A;
  22170. const double alphaOverA = alpha / A;
  22171. setCoefficients (1.0 + alphaTimesA,
  22172. c2,
  22173. 1.0 - alphaTimesA,
  22174. 1.0 + alphaOverA,
  22175. c2,
  22176. 1.0 - alphaOverA);
  22177. }
  22178. void IIRFilter::makeInactive() throw()
  22179. {
  22180. const ScopedLock sl (processLock);
  22181. active = false;
  22182. }
  22183. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22184. {
  22185. const ScopedLock sl (processLock);
  22186. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22187. active = other.active;
  22188. }
  22189. void IIRFilter::setCoefficients (double c1,
  22190. double c2,
  22191. double c3,
  22192. double c4,
  22193. double c5,
  22194. double c6) throw()
  22195. {
  22196. const double a = 1.0 / c4;
  22197. c1 *= a;
  22198. c2 *= a;
  22199. c3 *= a;
  22200. c5 *= a;
  22201. c6 *= a;
  22202. const ScopedLock sl (processLock);
  22203. coefficients[0] = (float) c1;
  22204. coefficients[1] = (float) c2;
  22205. coefficients[2] = (float) c3;
  22206. coefficients[3] = (float) c4;
  22207. coefficients[4] = (float) c5;
  22208. coefficients[5] = (float) c6;
  22209. active = true;
  22210. }
  22211. END_JUCE_NAMESPACE
  22212. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22213. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22214. BEGIN_JUCE_NAMESPACE
  22215. MidiBuffer::MidiBuffer() throw()
  22216. : bytesUsed (0)
  22217. {
  22218. }
  22219. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22220. : bytesUsed (0)
  22221. {
  22222. addEvent (message, 0);
  22223. }
  22224. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22225. : data (other.data),
  22226. bytesUsed (other.bytesUsed)
  22227. {
  22228. }
  22229. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22230. {
  22231. bytesUsed = other.bytesUsed;
  22232. data = other.data;
  22233. return *this;
  22234. }
  22235. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22236. {
  22237. data.swapWith (other.data);
  22238. swapVariables <int> (bytesUsed, other.bytesUsed);
  22239. }
  22240. MidiBuffer::~MidiBuffer()
  22241. {
  22242. }
  22243. inline uint8* MidiBuffer::getData() const throw()
  22244. {
  22245. return static_cast <uint8*> (data.getData());
  22246. }
  22247. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22248. {
  22249. return *static_cast <const int*> (d);
  22250. }
  22251. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22252. {
  22253. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22254. }
  22255. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22256. {
  22257. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22258. }
  22259. void MidiBuffer::clear() throw()
  22260. {
  22261. bytesUsed = 0;
  22262. }
  22263. void MidiBuffer::clear (const int startSample, const int numSamples)
  22264. {
  22265. uint8* const start = findEventAfter (getData(), startSample - 1);
  22266. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22267. if (end > start)
  22268. {
  22269. const int bytesToMove = bytesUsed - (int) (end - getData());
  22270. if (bytesToMove > 0)
  22271. memmove (start, end, bytesToMove);
  22272. bytesUsed -= (int) (end - start);
  22273. }
  22274. }
  22275. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22276. {
  22277. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22278. }
  22279. namespace MidiBufferHelpers
  22280. {
  22281. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22282. {
  22283. unsigned int byte = (unsigned int) *data;
  22284. int size = 0;
  22285. if (byte == 0xf0 || byte == 0xf7)
  22286. {
  22287. const uint8* d = data + 1;
  22288. while (d < data + maxBytes)
  22289. if (*d++ == 0xf7)
  22290. break;
  22291. size = (int) (d - data);
  22292. }
  22293. else if (byte == 0xff)
  22294. {
  22295. int n;
  22296. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22297. size = jmin (maxBytes, n + 2 + bytesLeft);
  22298. }
  22299. else if (byte >= 0x80)
  22300. {
  22301. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22302. }
  22303. return size;
  22304. }
  22305. }
  22306. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22307. {
  22308. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22309. if (numBytes > 0)
  22310. {
  22311. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22312. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22313. uint8* d = findEventAfter (getData(), sampleNumber);
  22314. const int bytesToMove = bytesUsed - (int) (d - getData());
  22315. if (bytesToMove > 0)
  22316. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22317. *reinterpret_cast <int*> (d) = sampleNumber;
  22318. d += sizeof (int);
  22319. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22320. d += sizeof (uint16);
  22321. memcpy (d, newData, numBytes);
  22322. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22323. }
  22324. }
  22325. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22326. const int startSample,
  22327. const int numSamples,
  22328. const int sampleDeltaToAdd)
  22329. {
  22330. Iterator i (otherBuffer);
  22331. i.setNextSamplePosition (startSample);
  22332. const uint8* eventData;
  22333. int eventSize, position;
  22334. while (i.getNextEvent (eventData, eventSize, position)
  22335. && (position < startSample + numSamples || numSamples < 0))
  22336. {
  22337. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22338. }
  22339. }
  22340. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22341. {
  22342. data.ensureSize (minimumNumBytes);
  22343. }
  22344. bool MidiBuffer::isEmpty() const throw()
  22345. {
  22346. return bytesUsed == 0;
  22347. }
  22348. int MidiBuffer::getNumEvents() const throw()
  22349. {
  22350. int n = 0;
  22351. const uint8* d = getData();
  22352. const uint8* const end = d + bytesUsed;
  22353. while (d < end)
  22354. {
  22355. d += getEventTotalSize (d);
  22356. ++n;
  22357. }
  22358. return n;
  22359. }
  22360. int MidiBuffer::getFirstEventTime() const throw()
  22361. {
  22362. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22363. }
  22364. int MidiBuffer::getLastEventTime() const throw()
  22365. {
  22366. if (bytesUsed == 0)
  22367. return 0;
  22368. const uint8* d = getData();
  22369. const uint8* const endData = d + bytesUsed;
  22370. for (;;)
  22371. {
  22372. const uint8* const nextOne = d + getEventTotalSize (d);
  22373. if (nextOne >= endData)
  22374. return getEventTime (d);
  22375. d = nextOne;
  22376. }
  22377. }
  22378. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22379. {
  22380. const uint8* const endData = getData() + bytesUsed;
  22381. while (d < endData && getEventTime (d) <= samplePosition)
  22382. d += getEventTotalSize (d);
  22383. return d;
  22384. }
  22385. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22386. : buffer (buffer_),
  22387. data (buffer_.getData())
  22388. {
  22389. }
  22390. MidiBuffer::Iterator::~Iterator() throw()
  22391. {
  22392. }
  22393. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22394. {
  22395. data = buffer.getData();
  22396. const uint8* dataEnd = data + buffer.bytesUsed;
  22397. while (data < dataEnd && getEventTime (data) < samplePosition)
  22398. data += getEventTotalSize (data);
  22399. }
  22400. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22401. {
  22402. if (data >= buffer.getData() + buffer.bytesUsed)
  22403. return false;
  22404. samplePosition = getEventTime (data);
  22405. numBytes = getEventDataSize (data);
  22406. data += sizeof (int) + sizeof (uint16);
  22407. midiData = data;
  22408. data += numBytes;
  22409. return true;
  22410. }
  22411. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22412. {
  22413. if (data >= buffer.getData() + buffer.bytesUsed)
  22414. return false;
  22415. samplePosition = getEventTime (data);
  22416. const int numBytes = getEventDataSize (data);
  22417. data += sizeof (int) + sizeof (uint16);
  22418. result = MidiMessage (data, numBytes, samplePosition);
  22419. data += numBytes;
  22420. return true;
  22421. }
  22422. END_JUCE_NAMESPACE
  22423. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22424. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22425. BEGIN_JUCE_NAMESPACE
  22426. namespace MidiFileHelpers
  22427. {
  22428. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22429. {
  22430. unsigned int buffer = v & 0x7F;
  22431. while ((v >>= 7) != 0)
  22432. {
  22433. buffer <<= 8;
  22434. buffer |= ((v & 0x7F) | 0x80);
  22435. }
  22436. for (;;)
  22437. {
  22438. out.writeByte ((char) buffer);
  22439. if (buffer & 0x80)
  22440. buffer >>= 8;
  22441. else
  22442. break;
  22443. }
  22444. }
  22445. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22446. {
  22447. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22448. data += 4;
  22449. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22450. {
  22451. bool ok = false;
  22452. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22453. {
  22454. for (int i = 0; i < 8; ++i)
  22455. {
  22456. ch = ByteOrder::bigEndianInt (data);
  22457. data += 4;
  22458. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22459. {
  22460. ok = true;
  22461. break;
  22462. }
  22463. }
  22464. }
  22465. if (! ok)
  22466. return false;
  22467. }
  22468. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22469. data += 4;
  22470. fileType = (short) ByteOrder::bigEndianShort (data);
  22471. data += 2;
  22472. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22473. data += 2;
  22474. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22475. data += 2;
  22476. bytesRemaining -= 6;
  22477. data += bytesRemaining;
  22478. return true;
  22479. }
  22480. double convertTicksToSeconds (const double time,
  22481. const MidiMessageSequence& tempoEvents,
  22482. const int timeFormat)
  22483. {
  22484. if (timeFormat > 0)
  22485. {
  22486. int numer = 4, denom = 4;
  22487. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22488. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22489. double secsPerTick = 0.5 * tickLen;
  22490. const int numEvents = tempoEvents.getNumEvents();
  22491. for (int i = 0; i < numEvents; ++i)
  22492. {
  22493. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22494. if (time <= m.getTimeStamp())
  22495. break;
  22496. if (timeFormat > 0)
  22497. {
  22498. correctedTempoTime = correctedTempoTime
  22499. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22500. }
  22501. else
  22502. {
  22503. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22504. }
  22505. tempoTime = m.getTimeStamp();
  22506. if (m.isTempoMetaEvent())
  22507. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22508. else if (m.isTimeSignatureMetaEvent())
  22509. m.getTimeSignatureInfo (numer, denom);
  22510. while (i + 1 < numEvents)
  22511. {
  22512. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22513. if (m2.getTimeStamp() == tempoTime)
  22514. {
  22515. ++i;
  22516. if (m2.isTempoMetaEvent())
  22517. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22518. else if (m2.isTimeSignatureMetaEvent())
  22519. m2.getTimeSignatureInfo (numer, denom);
  22520. }
  22521. else
  22522. {
  22523. break;
  22524. }
  22525. }
  22526. }
  22527. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22528. }
  22529. else
  22530. {
  22531. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22532. }
  22533. }
  22534. // a comparator that puts all the note-offs before note-ons that have the same time
  22535. struct Sorter
  22536. {
  22537. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22538. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22539. {
  22540. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22541. if (diff > 0)
  22542. return 1;
  22543. else if (diff < 0)
  22544. return -1;
  22545. else if (first->message.isNoteOff() && second->message.isNoteOn())
  22546. return -1;
  22547. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22548. return 1;
  22549. return 0;
  22550. }
  22551. };
  22552. }
  22553. MidiFile::MidiFile()
  22554. : timeFormat ((short) (unsigned short) 0xe728)
  22555. {
  22556. }
  22557. MidiFile::~MidiFile()
  22558. {
  22559. clear();
  22560. }
  22561. void MidiFile::clear()
  22562. {
  22563. tracks.clear();
  22564. }
  22565. int MidiFile::getNumTracks() const throw()
  22566. {
  22567. return tracks.size();
  22568. }
  22569. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22570. {
  22571. return tracks [index];
  22572. }
  22573. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22574. {
  22575. tracks.add (new MidiMessageSequence (trackSequence));
  22576. }
  22577. short MidiFile::getTimeFormat() const throw()
  22578. {
  22579. return timeFormat;
  22580. }
  22581. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22582. {
  22583. timeFormat = (short) ticks;
  22584. }
  22585. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22586. const int subframeResolution) throw()
  22587. {
  22588. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22589. }
  22590. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22591. {
  22592. for (int i = tracks.size(); --i >= 0;)
  22593. {
  22594. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22595. for (int j = 0; j < numEvents; ++j)
  22596. {
  22597. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22598. if (m.isTempoMetaEvent())
  22599. tempoChangeEvents.addEvent (m);
  22600. }
  22601. }
  22602. }
  22603. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22604. {
  22605. for (int i = tracks.size(); --i >= 0;)
  22606. {
  22607. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22608. for (int j = 0; j < numEvents; ++j)
  22609. {
  22610. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22611. if (m.isTimeSignatureMetaEvent())
  22612. timeSigEvents.addEvent (m);
  22613. }
  22614. }
  22615. }
  22616. double MidiFile::getLastTimestamp() const
  22617. {
  22618. double t = 0.0;
  22619. for (int i = tracks.size(); --i >= 0;)
  22620. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22621. return t;
  22622. }
  22623. bool MidiFile::readFrom (InputStream& sourceStream)
  22624. {
  22625. clear();
  22626. MemoryBlock data;
  22627. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22628. // (put a sanity-check on the file size, as midi files are generally small)
  22629. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22630. {
  22631. size_t size = data.getSize();
  22632. const uint8* d = static_cast <const uint8*> (data.getData());
  22633. short fileType, expectedTracks;
  22634. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22635. {
  22636. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22637. int track = 0;
  22638. while (size > 0 && track < expectedTracks)
  22639. {
  22640. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22641. d += 4;
  22642. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22643. d += 4;
  22644. if (chunkSize <= 0)
  22645. break;
  22646. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22647. {
  22648. readNextTrack (d, chunkSize);
  22649. }
  22650. size -= chunkSize + 8;
  22651. d += chunkSize;
  22652. ++track;
  22653. }
  22654. return true;
  22655. }
  22656. }
  22657. return false;
  22658. }
  22659. void MidiFile::readNextTrack (const uint8* data, int size)
  22660. {
  22661. double time = 0;
  22662. char lastStatusByte = 0;
  22663. MidiMessageSequence result;
  22664. while (size > 0)
  22665. {
  22666. int bytesUsed;
  22667. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22668. data += bytesUsed;
  22669. size -= bytesUsed;
  22670. time += delay;
  22671. int messSize = 0;
  22672. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22673. if (messSize <= 0)
  22674. break;
  22675. size -= messSize;
  22676. data += messSize;
  22677. result.addEvent (mm);
  22678. const char firstByte = *(mm.getRawData());
  22679. if ((firstByte & 0xf0) != 0xf0)
  22680. lastStatusByte = firstByte;
  22681. }
  22682. // use a sort that puts all the note-offs before note-ons that have the same time
  22683. MidiFileHelpers::Sorter sorter;
  22684. result.list.sort (sorter, true);
  22685. result.updateMatchedPairs();
  22686. addTrack (result);
  22687. }
  22688. void MidiFile::convertTimestampTicksToSeconds()
  22689. {
  22690. MidiMessageSequence tempoEvents;
  22691. findAllTempoEvents (tempoEvents);
  22692. findAllTimeSigEvents (tempoEvents);
  22693. for (int i = 0; i < tracks.size(); ++i)
  22694. {
  22695. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22696. for (int j = ms.getNumEvents(); --j >= 0;)
  22697. {
  22698. MidiMessage& m = ms.getEventPointer(j)->message;
  22699. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22700. tempoEvents,
  22701. timeFormat));
  22702. }
  22703. }
  22704. }
  22705. bool MidiFile::writeTo (OutputStream& out)
  22706. {
  22707. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22708. out.writeIntBigEndian (6);
  22709. out.writeShortBigEndian (1); // type
  22710. out.writeShortBigEndian ((short) tracks.size());
  22711. out.writeShortBigEndian (timeFormat);
  22712. for (int i = 0; i < tracks.size(); ++i)
  22713. writeTrack (out, i);
  22714. out.flush();
  22715. return true;
  22716. }
  22717. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22718. {
  22719. MemoryOutputStream out;
  22720. const MidiMessageSequence& ms = *tracks[trackNum];
  22721. int lastTick = 0;
  22722. char lastStatusByte = 0;
  22723. for (int i = 0; i < ms.getNumEvents(); ++i)
  22724. {
  22725. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22726. const int tick = roundToInt (mm.getTimeStamp());
  22727. const int delta = jmax (0, tick - lastTick);
  22728. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22729. lastTick = tick;
  22730. const char statusByte = *(mm.getRawData());
  22731. if ((statusByte == lastStatusByte)
  22732. && ((statusByte & 0xf0) != 0xf0)
  22733. && i > 0
  22734. && mm.getRawDataSize() > 1)
  22735. {
  22736. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22737. }
  22738. else
  22739. {
  22740. out.write (mm.getRawData(), mm.getRawDataSize());
  22741. }
  22742. lastStatusByte = statusByte;
  22743. }
  22744. out.writeByte (0);
  22745. const MidiMessage m (MidiMessage::endOfTrack());
  22746. out.write (m.getRawData(),
  22747. m.getRawDataSize());
  22748. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22749. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22750. mainOut.write (out.getData(), (int) out.getDataSize());
  22751. }
  22752. END_JUCE_NAMESPACE
  22753. /*** End of inlined file: juce_MidiFile.cpp ***/
  22754. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22755. BEGIN_JUCE_NAMESPACE
  22756. MidiKeyboardState::MidiKeyboardState()
  22757. {
  22758. zerostruct (noteStates);
  22759. }
  22760. MidiKeyboardState::~MidiKeyboardState()
  22761. {
  22762. }
  22763. void MidiKeyboardState::reset()
  22764. {
  22765. const ScopedLock sl (lock);
  22766. zerostruct (noteStates);
  22767. eventsToAdd.clear();
  22768. }
  22769. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22770. {
  22771. jassert (midiChannel >= 0 && midiChannel <= 16);
  22772. return isPositiveAndBelow (n, (int) 128)
  22773. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22774. }
  22775. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22776. {
  22777. return isPositiveAndBelow (n, (int) 128)
  22778. && (noteStates[n] & midiChannelMask) != 0;
  22779. }
  22780. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22781. {
  22782. jassert (midiChannel >= 0 && midiChannel <= 16);
  22783. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22784. const ScopedLock sl (lock);
  22785. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22786. {
  22787. const int timeNow = (int) Time::getMillisecondCounter();
  22788. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22789. eventsToAdd.clear (0, timeNow - 500);
  22790. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22791. }
  22792. }
  22793. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22794. {
  22795. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22796. {
  22797. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22798. for (int i = listeners.size(); --i >= 0;)
  22799. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22800. }
  22801. }
  22802. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22803. {
  22804. const ScopedLock sl (lock);
  22805. if (isNoteOn (midiChannel, midiNoteNumber))
  22806. {
  22807. const int timeNow = (int) Time::getMillisecondCounter();
  22808. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22809. eventsToAdd.clear (0, timeNow - 500);
  22810. noteOffInternal (midiChannel, midiNoteNumber);
  22811. }
  22812. }
  22813. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22814. {
  22815. if (isNoteOn (midiChannel, midiNoteNumber))
  22816. {
  22817. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22818. for (int i = listeners.size(); --i >= 0;)
  22819. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22820. }
  22821. }
  22822. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22823. {
  22824. const ScopedLock sl (lock);
  22825. if (midiChannel <= 0)
  22826. {
  22827. for (int i = 1; i <= 16; ++i)
  22828. allNotesOff (i);
  22829. }
  22830. else
  22831. {
  22832. for (int i = 0; i < 128; ++i)
  22833. noteOff (midiChannel, i);
  22834. }
  22835. }
  22836. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22837. {
  22838. if (message.isNoteOn())
  22839. {
  22840. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22841. }
  22842. else if (message.isNoteOff())
  22843. {
  22844. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22845. }
  22846. else if (message.isAllNotesOff())
  22847. {
  22848. for (int i = 0; i < 128; ++i)
  22849. noteOffInternal (message.getChannel(), i);
  22850. }
  22851. }
  22852. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22853. const int startSample,
  22854. const int numSamples,
  22855. const bool injectIndirectEvents)
  22856. {
  22857. MidiBuffer::Iterator i (buffer);
  22858. MidiMessage message (0xf4, 0.0);
  22859. int time;
  22860. const ScopedLock sl (lock);
  22861. while (i.getNextEvent (message, time))
  22862. processNextMidiEvent (message);
  22863. if (injectIndirectEvents)
  22864. {
  22865. MidiBuffer::Iterator i2 (eventsToAdd);
  22866. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22867. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22868. while (i2.getNextEvent (message, time))
  22869. {
  22870. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22871. buffer.addEvent (message, startSample + pos);
  22872. }
  22873. }
  22874. eventsToAdd.clear();
  22875. }
  22876. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22877. {
  22878. const ScopedLock sl (lock);
  22879. listeners.addIfNotAlreadyThere (listener);
  22880. }
  22881. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22882. {
  22883. const ScopedLock sl (lock);
  22884. listeners.removeValue (listener);
  22885. }
  22886. END_JUCE_NAMESPACE
  22887. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22888. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22889. BEGIN_JUCE_NAMESPACE
  22890. namespace MidiHelpers
  22891. {
  22892. inline uint8 initialByte (const int type, const int channel) throw()
  22893. {
  22894. return (uint8) (type | jlimit (0, 15, channel - 1));
  22895. }
  22896. inline uint8 validVelocity (const int v) throw()
  22897. {
  22898. return (uint8) jlimit (0, 127, v);
  22899. }
  22900. }
  22901. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22902. {
  22903. numBytesUsed = 0;
  22904. int v = 0;
  22905. int i;
  22906. do
  22907. {
  22908. i = (int) *data++;
  22909. if (++numBytesUsed > 6)
  22910. break;
  22911. v = (v << 7) + (i & 0x7f);
  22912. } while (i & 0x80);
  22913. return v;
  22914. }
  22915. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22916. {
  22917. // this method only works for valid starting bytes of a short midi message
  22918. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22919. static const char messageLengths[] =
  22920. {
  22921. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22922. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22923. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22924. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22925. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22926. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22927. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22928. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22929. };
  22930. return messageLengths [firstByte & 0x7f];
  22931. }
  22932. MidiMessage::MidiMessage() throw()
  22933. : timeStamp (0),
  22934. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22935. size (2)
  22936. {
  22937. data[0] = 0xf0;
  22938. data[1] = 0xf7;
  22939. }
  22940. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22941. : timeStamp (t),
  22942. size (dataSize)
  22943. {
  22944. jassert (dataSize > 0);
  22945. if (dataSize <= 4)
  22946. data = static_cast<uint8*> (preallocatedData.asBytes);
  22947. else
  22948. data = new uint8 [dataSize];
  22949. memcpy (data, d, dataSize);
  22950. // check that the length matches the data..
  22951. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22952. }
  22953. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22954. : timeStamp (t),
  22955. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22956. size (1)
  22957. {
  22958. data[0] = (uint8) byte1;
  22959. // check that the length matches the data..
  22960. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22961. }
  22962. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22963. : timeStamp (t),
  22964. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22965. size (2)
  22966. {
  22967. data[0] = (uint8) byte1;
  22968. data[1] = (uint8) byte2;
  22969. // check that the length matches the data..
  22970. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22971. }
  22972. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22973. : timeStamp (t),
  22974. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22975. size (3)
  22976. {
  22977. data[0] = (uint8) byte1;
  22978. data[1] = (uint8) byte2;
  22979. data[2] = (uint8) byte3;
  22980. // check that the length matches the data..
  22981. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22982. }
  22983. MidiMessage::MidiMessage (const MidiMessage& other)
  22984. : timeStamp (other.timeStamp),
  22985. size (other.size)
  22986. {
  22987. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22988. {
  22989. data = new uint8 [size];
  22990. memcpy (data, other.data, size);
  22991. }
  22992. else
  22993. {
  22994. data = static_cast<uint8*> (preallocatedData.asBytes);
  22995. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22996. }
  22997. }
  22998. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22999. : timeStamp (newTimeStamp),
  23000. size (other.size)
  23001. {
  23002. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23003. {
  23004. data = new uint8 [size];
  23005. memcpy (data, other.data, size);
  23006. }
  23007. else
  23008. {
  23009. data = static_cast<uint8*> (preallocatedData.asBytes);
  23010. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23011. }
  23012. }
  23013. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23014. : timeStamp (t),
  23015. data (static_cast<uint8*> (preallocatedData.asBytes))
  23016. {
  23017. const uint8* src = static_cast <const uint8*> (src_);
  23018. unsigned int byte = (unsigned int) *src;
  23019. if (byte < 0x80)
  23020. {
  23021. byte = (unsigned int) (uint8) lastStatusByte;
  23022. numBytesUsed = -1;
  23023. }
  23024. else
  23025. {
  23026. numBytesUsed = 0;
  23027. --sz;
  23028. ++src;
  23029. }
  23030. if (byte >= 0x80)
  23031. {
  23032. if (byte == 0xf0)
  23033. {
  23034. const uint8* d = src;
  23035. bool haveReadAllLengthBytes = false;
  23036. while (d < src + sz)
  23037. {
  23038. if (*d >= 0x80)
  23039. {
  23040. if (*d == 0xf7)
  23041. {
  23042. ++d; // include the trailing 0xf7 when we hit it
  23043. break;
  23044. }
  23045. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23046. break; // bytes, assume it's the end of the sysex
  23047. ++d;
  23048. continue;
  23049. }
  23050. haveReadAllLengthBytes = true;
  23051. ++d;
  23052. }
  23053. size = 1 + (int) (d - src);
  23054. data = new uint8 [size];
  23055. *data = (uint8) byte;
  23056. memcpy (data + 1, src, size - 1);
  23057. }
  23058. else if (byte == 0xff)
  23059. {
  23060. int n;
  23061. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23062. size = jmin (sz + 1, n + 2 + bytesLeft);
  23063. data = new uint8 [size];
  23064. *data = (uint8) byte;
  23065. memcpy (data + 1, src, size - 1);
  23066. }
  23067. else
  23068. {
  23069. preallocatedData.asInt32 = 0;
  23070. size = getMessageLengthFromFirstByte ((uint8) byte);
  23071. data[0] = (uint8) byte;
  23072. if (size > 1)
  23073. {
  23074. data[1] = src[0];
  23075. if (size > 2)
  23076. data[2] = src[1];
  23077. }
  23078. }
  23079. numBytesUsed += size;
  23080. }
  23081. else
  23082. {
  23083. preallocatedData.asInt32 = 0;
  23084. size = 0;
  23085. }
  23086. }
  23087. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23088. {
  23089. if (this != &other)
  23090. {
  23091. timeStamp = other.timeStamp;
  23092. size = other.size;
  23093. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23094. delete[] data;
  23095. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23096. {
  23097. data = new uint8 [size];
  23098. memcpy (data, other.data, size);
  23099. }
  23100. else
  23101. {
  23102. data = static_cast<uint8*> (preallocatedData.asBytes);
  23103. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23104. }
  23105. }
  23106. return *this;
  23107. }
  23108. MidiMessage::~MidiMessage()
  23109. {
  23110. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23111. delete[] data;
  23112. }
  23113. int MidiMessage::getChannel() const throw()
  23114. {
  23115. if ((data[0] & 0xf0) != 0xf0)
  23116. return (data[0] & 0xf) + 1;
  23117. else
  23118. return 0;
  23119. }
  23120. bool MidiMessage::isForChannel (const int channel) const throw()
  23121. {
  23122. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23123. return ((data[0] & 0xf) == channel - 1)
  23124. && ((data[0] & 0xf0) != 0xf0);
  23125. }
  23126. void MidiMessage::setChannel (const int channel) throw()
  23127. {
  23128. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23129. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23130. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23131. | (uint8)(channel - 1));
  23132. }
  23133. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23134. {
  23135. return ((data[0] & 0xf0) == 0x90)
  23136. && (returnTrueForVelocity0 || data[2] != 0);
  23137. }
  23138. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23139. {
  23140. return ((data[0] & 0xf0) == 0x80)
  23141. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23142. }
  23143. bool MidiMessage::isNoteOnOrOff() const throw()
  23144. {
  23145. const int d = data[0] & 0xf0;
  23146. return (d == 0x90) || (d == 0x80);
  23147. }
  23148. int MidiMessage::getNoteNumber() const throw()
  23149. {
  23150. return data[1];
  23151. }
  23152. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23153. {
  23154. if (isNoteOnOrOff())
  23155. data[1] = newNoteNumber & 127;
  23156. }
  23157. uint8 MidiMessage::getVelocity() const throw()
  23158. {
  23159. if (isNoteOnOrOff())
  23160. return data[2];
  23161. else
  23162. return 0;
  23163. }
  23164. float MidiMessage::getFloatVelocity() const throw()
  23165. {
  23166. return getVelocity() * (1.0f / 127.0f);
  23167. }
  23168. void MidiMessage::setVelocity (const float newVelocity) throw()
  23169. {
  23170. if (isNoteOnOrOff())
  23171. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23172. }
  23173. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23174. {
  23175. if (isNoteOnOrOff())
  23176. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23177. }
  23178. bool MidiMessage::isAftertouch() const throw()
  23179. {
  23180. return (data[0] & 0xf0) == 0xa0;
  23181. }
  23182. int MidiMessage::getAfterTouchValue() const throw()
  23183. {
  23184. return data[2];
  23185. }
  23186. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23187. const int noteNum,
  23188. const int aftertouchValue) throw()
  23189. {
  23190. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23191. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23192. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23193. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23194. noteNum & 0x7f,
  23195. aftertouchValue & 0x7f);
  23196. }
  23197. bool MidiMessage::isChannelPressure() const throw()
  23198. {
  23199. return (data[0] & 0xf0) == 0xd0;
  23200. }
  23201. int MidiMessage::getChannelPressureValue() const throw()
  23202. {
  23203. jassert (isChannelPressure());
  23204. return data[1];
  23205. }
  23206. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23207. const int pressure) throw()
  23208. {
  23209. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23210. jassert (isPositiveAndBelow (pressure, (int) 128));
  23211. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23212. }
  23213. bool MidiMessage::isProgramChange() const throw()
  23214. {
  23215. return (data[0] & 0xf0) == 0xc0;
  23216. }
  23217. int MidiMessage::getProgramChangeNumber() const throw()
  23218. {
  23219. return data[1];
  23220. }
  23221. const MidiMessage MidiMessage::programChange (const int channel,
  23222. const int programNumber) throw()
  23223. {
  23224. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23225. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23226. }
  23227. bool MidiMessage::isPitchWheel() const throw()
  23228. {
  23229. return (data[0] & 0xf0) == 0xe0;
  23230. }
  23231. int MidiMessage::getPitchWheelValue() const throw()
  23232. {
  23233. return data[1] | (data[2] << 7);
  23234. }
  23235. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23236. const int position) throw()
  23237. {
  23238. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23239. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23240. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23241. }
  23242. bool MidiMessage::isController() const throw()
  23243. {
  23244. return (data[0] & 0xf0) == 0xb0;
  23245. }
  23246. int MidiMessage::getControllerNumber() const throw()
  23247. {
  23248. jassert (isController());
  23249. return data[1];
  23250. }
  23251. int MidiMessage::getControllerValue() const throw()
  23252. {
  23253. jassert (isController());
  23254. return data[2];
  23255. }
  23256. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23257. {
  23258. // the channel must be between 1 and 16 inclusive
  23259. jassert (channel > 0 && channel <= 16);
  23260. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23261. }
  23262. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23263. {
  23264. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23265. }
  23266. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23267. {
  23268. jassert (channel > 0 && channel <= 16);
  23269. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23270. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23271. }
  23272. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23273. {
  23274. jassert (channel > 0 && channel <= 16);
  23275. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23276. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23277. }
  23278. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23279. {
  23280. return controllerEvent (channel, 123, 0);
  23281. }
  23282. bool MidiMessage::isAllNotesOff() const throw()
  23283. {
  23284. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23285. }
  23286. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23287. {
  23288. return controllerEvent (channel, 120, 0);
  23289. }
  23290. bool MidiMessage::isAllSoundOff() const throw()
  23291. {
  23292. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23293. }
  23294. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23295. {
  23296. return controllerEvent (channel, 121, 0);
  23297. }
  23298. const MidiMessage MidiMessage::masterVolume (const float volume)
  23299. {
  23300. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23301. uint8 buf[8];
  23302. buf[0] = 0xf0;
  23303. buf[1] = 0x7f;
  23304. buf[2] = 0x7f;
  23305. buf[3] = 0x04;
  23306. buf[4] = 0x01;
  23307. buf[5] = (uint8) (vol & 0x7f);
  23308. buf[6] = (uint8) (vol >> 7);
  23309. buf[7] = 0xf7;
  23310. return MidiMessage (buf, 8);
  23311. }
  23312. bool MidiMessage::isSysEx() const throw()
  23313. {
  23314. return *data == 0xf0;
  23315. }
  23316. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23317. {
  23318. HeapBlock<uint8> m (dataSize + 2);
  23319. m[0] = 0xf0;
  23320. memcpy (m + 1, sysexData, dataSize);
  23321. m[dataSize + 1] = 0xf7;
  23322. return MidiMessage (m, dataSize + 2);
  23323. }
  23324. const uint8* MidiMessage::getSysExData() const throw()
  23325. {
  23326. return isSysEx() ? getRawData() + 1 : 0;
  23327. }
  23328. int MidiMessage::getSysExDataSize() const throw()
  23329. {
  23330. return isSysEx() ? size - 2 : 0;
  23331. }
  23332. bool MidiMessage::isMetaEvent() const throw()
  23333. {
  23334. return *data == 0xff;
  23335. }
  23336. bool MidiMessage::isActiveSense() const throw()
  23337. {
  23338. return *data == 0xfe;
  23339. }
  23340. int MidiMessage::getMetaEventType() const throw()
  23341. {
  23342. return *data != 0xff ? -1 : data[1];
  23343. }
  23344. int MidiMessage::getMetaEventLength() const throw()
  23345. {
  23346. if (*data == 0xff)
  23347. {
  23348. int n;
  23349. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23350. }
  23351. return 0;
  23352. }
  23353. const uint8* MidiMessage::getMetaEventData() const throw()
  23354. {
  23355. int n;
  23356. const uint8* d = data + 2;
  23357. readVariableLengthVal (d, n);
  23358. return d + n;
  23359. }
  23360. bool MidiMessage::isTrackMetaEvent() const throw()
  23361. {
  23362. return getMetaEventType() == 0;
  23363. }
  23364. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23365. {
  23366. return getMetaEventType() == 47;
  23367. }
  23368. bool MidiMessage::isTextMetaEvent() const throw()
  23369. {
  23370. const int t = getMetaEventType();
  23371. return t > 0 && t < 16;
  23372. }
  23373. const String MidiMessage::getTextFromTextMetaEvent() const
  23374. {
  23375. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23376. }
  23377. bool MidiMessage::isTrackNameEvent() const throw()
  23378. {
  23379. return (data[1] == 3) && (*data == 0xff);
  23380. }
  23381. bool MidiMessage::isTempoMetaEvent() const throw()
  23382. {
  23383. return (data[1] == 81) && (*data == 0xff);
  23384. }
  23385. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23386. {
  23387. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23388. }
  23389. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23390. {
  23391. return data[3] + 1;
  23392. }
  23393. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23394. {
  23395. if (! isTempoMetaEvent())
  23396. return 0.0;
  23397. const uint8* const d = getMetaEventData();
  23398. return (((unsigned int) d[0] << 16)
  23399. | ((unsigned int) d[1] << 8)
  23400. | d[2])
  23401. / 1000000.0;
  23402. }
  23403. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23404. {
  23405. if (timeFormat > 0)
  23406. {
  23407. if (! isTempoMetaEvent())
  23408. return 0.5 / timeFormat;
  23409. return getTempoSecondsPerQuarterNote() / timeFormat;
  23410. }
  23411. else
  23412. {
  23413. const int frameCode = (-timeFormat) >> 8;
  23414. double framesPerSecond;
  23415. switch (frameCode)
  23416. {
  23417. case 24: framesPerSecond = 24.0; break;
  23418. case 25: framesPerSecond = 25.0; break;
  23419. case 29: framesPerSecond = 29.97; break;
  23420. case 30: framesPerSecond = 30.0; break;
  23421. default: framesPerSecond = 30.0; break;
  23422. }
  23423. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23424. }
  23425. }
  23426. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23427. {
  23428. uint8 d[8];
  23429. d[0] = 0xff;
  23430. d[1] = 81;
  23431. d[2] = 3;
  23432. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23433. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23434. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23435. return MidiMessage (d, 6, 0.0);
  23436. }
  23437. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23438. {
  23439. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23440. }
  23441. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23442. {
  23443. if (isTimeSignatureMetaEvent())
  23444. {
  23445. const uint8* const d = getMetaEventData();
  23446. numerator = d[0];
  23447. denominator = 1 << d[1];
  23448. }
  23449. else
  23450. {
  23451. numerator = 4;
  23452. denominator = 4;
  23453. }
  23454. }
  23455. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23456. {
  23457. uint8 d[8];
  23458. d[0] = 0xff;
  23459. d[1] = 0x58;
  23460. d[2] = 0x04;
  23461. d[3] = (uint8) numerator;
  23462. int n = 1;
  23463. int powerOfTwo = 0;
  23464. while (n < denominator)
  23465. {
  23466. n <<= 1;
  23467. ++powerOfTwo;
  23468. }
  23469. d[4] = (uint8) powerOfTwo;
  23470. d[5] = 0x01;
  23471. d[6] = 96;
  23472. return MidiMessage (d, 7, 0.0);
  23473. }
  23474. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23475. {
  23476. uint8 d[8];
  23477. d[0] = 0xff;
  23478. d[1] = 0x20;
  23479. d[2] = 0x01;
  23480. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23481. return MidiMessage (d, 4, 0.0);
  23482. }
  23483. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23484. {
  23485. return getMetaEventType() == 89;
  23486. }
  23487. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23488. {
  23489. return (int) *getMetaEventData();
  23490. }
  23491. const MidiMessage MidiMessage::endOfTrack() throw()
  23492. {
  23493. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23494. }
  23495. bool MidiMessage::isSongPositionPointer() const throw()
  23496. {
  23497. return *data == 0xf2;
  23498. }
  23499. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23500. {
  23501. return data[1] | (data[2] << 7);
  23502. }
  23503. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23504. {
  23505. return MidiMessage (0xf2,
  23506. positionInMidiBeats & 127,
  23507. (positionInMidiBeats >> 7) & 127);
  23508. }
  23509. bool MidiMessage::isMidiStart() const throw()
  23510. {
  23511. return *data == 0xfa;
  23512. }
  23513. const MidiMessage MidiMessage::midiStart() throw()
  23514. {
  23515. return MidiMessage (0xfa);
  23516. }
  23517. bool MidiMessage::isMidiContinue() const throw()
  23518. {
  23519. return *data == 0xfb;
  23520. }
  23521. const MidiMessage MidiMessage::midiContinue() throw()
  23522. {
  23523. return MidiMessage (0xfb);
  23524. }
  23525. bool MidiMessage::isMidiStop() const throw()
  23526. {
  23527. return *data == 0xfc;
  23528. }
  23529. const MidiMessage MidiMessage::midiStop() throw()
  23530. {
  23531. return MidiMessage (0xfc);
  23532. }
  23533. bool MidiMessage::isMidiClock() const throw()
  23534. {
  23535. return *data == 0xf8;
  23536. }
  23537. const MidiMessage MidiMessage::midiClock() throw()
  23538. {
  23539. return MidiMessage (0xf8);
  23540. }
  23541. bool MidiMessage::isQuarterFrame() const throw()
  23542. {
  23543. return *data == 0xf1;
  23544. }
  23545. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23546. {
  23547. return ((int) data[1]) >> 4;
  23548. }
  23549. int MidiMessage::getQuarterFrameValue() const throw()
  23550. {
  23551. return ((int) data[1]) & 0x0f;
  23552. }
  23553. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23554. const int value) throw()
  23555. {
  23556. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23557. }
  23558. bool MidiMessage::isFullFrame() const throw()
  23559. {
  23560. return data[0] == 0xf0
  23561. && data[1] == 0x7f
  23562. && size >= 10
  23563. && data[3] == 0x01
  23564. && data[4] == 0x01;
  23565. }
  23566. void MidiMessage::getFullFrameParameters (int& hours,
  23567. int& minutes,
  23568. int& seconds,
  23569. int& frames,
  23570. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23571. {
  23572. jassert (isFullFrame());
  23573. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23574. hours = data[5] & 0x1f;
  23575. minutes = data[6];
  23576. seconds = data[7];
  23577. frames = data[8];
  23578. }
  23579. const MidiMessage MidiMessage::fullFrame (const int hours,
  23580. const int minutes,
  23581. const int seconds,
  23582. const int frames,
  23583. MidiMessage::SmpteTimecodeType timecodeType)
  23584. {
  23585. uint8 d[10];
  23586. d[0] = 0xf0;
  23587. d[1] = 0x7f;
  23588. d[2] = 0x7f;
  23589. d[3] = 0x01;
  23590. d[4] = 0x01;
  23591. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23592. d[6] = (uint8) minutes;
  23593. d[7] = (uint8) seconds;
  23594. d[8] = (uint8) frames;
  23595. d[9] = 0xf7;
  23596. return MidiMessage (d, 10, 0.0);
  23597. }
  23598. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23599. {
  23600. return data[0] == 0xf0
  23601. && data[1] == 0x7f
  23602. && data[3] == 0x06
  23603. && size > 5;
  23604. }
  23605. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23606. {
  23607. jassert (isMidiMachineControlMessage());
  23608. return (MidiMachineControlCommand) data[4];
  23609. }
  23610. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23611. {
  23612. uint8 d[6];
  23613. d[0] = 0xf0;
  23614. d[1] = 0x7f;
  23615. d[2] = 0x00;
  23616. d[3] = 0x06;
  23617. d[4] = (uint8) command;
  23618. d[5] = 0xf7;
  23619. return MidiMessage (d, 6, 0.0);
  23620. }
  23621. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23622. int& minutes,
  23623. int& seconds,
  23624. int& frames) const throw()
  23625. {
  23626. if (size >= 12
  23627. && data[0] == 0xf0
  23628. && data[1] == 0x7f
  23629. && data[3] == 0x06
  23630. && data[4] == 0x44
  23631. && data[5] == 0x06
  23632. && data[6] == 0x01)
  23633. {
  23634. hours = data[7] % 24; // (that some machines send out hours > 24)
  23635. minutes = data[8];
  23636. seconds = data[9];
  23637. frames = data[10];
  23638. return true;
  23639. }
  23640. return false;
  23641. }
  23642. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23643. int minutes,
  23644. int seconds,
  23645. int frames)
  23646. {
  23647. uint8 d[12];
  23648. d[0] = 0xf0;
  23649. d[1] = 0x7f;
  23650. d[2] = 0x00;
  23651. d[3] = 0x06;
  23652. d[4] = 0x44;
  23653. d[5] = 0x06;
  23654. d[6] = 0x01;
  23655. d[7] = (uint8) hours;
  23656. d[8] = (uint8) minutes;
  23657. d[9] = (uint8) seconds;
  23658. d[10] = (uint8) frames;
  23659. d[11] = 0xf7;
  23660. return MidiMessage (d, 12, 0.0);
  23661. }
  23662. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23663. {
  23664. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23665. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23666. if (isPositiveAndBelow (note, (int) 128))
  23667. {
  23668. String s (useSharps ? sharpNoteNames [note % 12]
  23669. : flatNoteNames [note % 12]);
  23670. if (includeOctaveNumber)
  23671. s << (note / 12 + (octaveNumForMiddleC - 5));
  23672. return s;
  23673. }
  23674. return String::empty;
  23675. }
  23676. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23677. {
  23678. noteNumber -= 12 * 6 + 9; // now 0 = A
  23679. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23680. }
  23681. const String MidiMessage::getGMInstrumentName (const int n)
  23682. {
  23683. const char* names[] =
  23684. {
  23685. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23686. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23687. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23688. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23689. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23690. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23691. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23692. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23693. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23694. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23695. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23696. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23697. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23698. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23699. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23700. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23701. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23702. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23703. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23704. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23705. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23706. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23707. "Applause", "Gunshot"
  23708. };
  23709. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23710. }
  23711. const String MidiMessage::getGMInstrumentBankName (const int n)
  23712. {
  23713. const char* names[] =
  23714. {
  23715. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23716. "Bass", "Strings", "Ensemble", "Brass",
  23717. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23718. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23719. };
  23720. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23721. }
  23722. const String MidiMessage::getRhythmInstrumentName (const int n)
  23723. {
  23724. const char* names[] =
  23725. {
  23726. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23727. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23728. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23729. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23730. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23731. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23732. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23733. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23734. "Mute Triangle", "Open Triangle"
  23735. };
  23736. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23737. }
  23738. const String MidiMessage::getControllerName (const int n)
  23739. {
  23740. const char* names[] =
  23741. {
  23742. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23743. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23744. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23745. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23746. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23747. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23748. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23749. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23750. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23751. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23752. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23753. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23754. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23755. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23756. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23757. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23758. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23759. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23760. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23762. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23763. "Poly Operation"
  23764. };
  23765. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23766. }
  23767. END_JUCE_NAMESPACE
  23768. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23769. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23770. BEGIN_JUCE_NAMESPACE
  23771. MidiMessageCollector::MidiMessageCollector()
  23772. : lastCallbackTime (0),
  23773. sampleRate (44100.0001)
  23774. {
  23775. }
  23776. MidiMessageCollector::~MidiMessageCollector()
  23777. {
  23778. }
  23779. void MidiMessageCollector::reset (const double sampleRate_)
  23780. {
  23781. jassert (sampleRate_ > 0);
  23782. const ScopedLock sl (midiCallbackLock);
  23783. sampleRate = sampleRate_;
  23784. incomingMessages.clear();
  23785. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23786. }
  23787. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23788. {
  23789. // you need to call reset() to set the correct sample rate before using this object
  23790. jassert (sampleRate != 44100.0001);
  23791. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23792. // for details of what the number should be.
  23793. jassert (message.getTimeStamp() != 0);
  23794. const ScopedLock sl (midiCallbackLock);
  23795. const int sampleNumber
  23796. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23797. incomingMessages.addEvent (message, sampleNumber);
  23798. // if the messages don't get used for over a second, we'd better
  23799. // get rid of any old ones to avoid the queue getting too big
  23800. if (sampleNumber > sampleRate)
  23801. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23802. }
  23803. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23804. const int numSamples)
  23805. {
  23806. // you need to call reset() to set the correct sample rate before using this object
  23807. jassert (sampleRate != 44100.0001);
  23808. const double timeNow = Time::getMillisecondCounterHiRes();
  23809. const double msElapsed = timeNow - lastCallbackTime;
  23810. const ScopedLock sl (midiCallbackLock);
  23811. lastCallbackTime = timeNow;
  23812. if (! incomingMessages.isEmpty())
  23813. {
  23814. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23815. int startSample = 0;
  23816. int scale = 1 << 16;
  23817. const uint8* midiData;
  23818. int numBytes, samplePosition;
  23819. MidiBuffer::Iterator iter (incomingMessages);
  23820. if (numSourceSamples > numSamples)
  23821. {
  23822. // if our list of events is longer than the buffer we're being
  23823. // asked for, scale them down to squeeze them all in..
  23824. const int maxBlockLengthToUse = numSamples << 5;
  23825. if (numSourceSamples > maxBlockLengthToUse)
  23826. {
  23827. startSample = numSourceSamples - maxBlockLengthToUse;
  23828. numSourceSamples = maxBlockLengthToUse;
  23829. iter.setNextSamplePosition (startSample);
  23830. }
  23831. scale = (numSamples << 10) / numSourceSamples;
  23832. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23833. {
  23834. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23835. destBuffer.addEvent (midiData, numBytes,
  23836. jlimit (0, numSamples - 1, samplePosition));
  23837. }
  23838. }
  23839. else
  23840. {
  23841. // if our event list is shorter than the number we need, put them
  23842. // towards the end of the buffer
  23843. startSample = numSamples - numSourceSamples;
  23844. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23845. {
  23846. destBuffer.addEvent (midiData, numBytes,
  23847. jlimit (0, numSamples - 1, samplePosition + startSample));
  23848. }
  23849. }
  23850. incomingMessages.clear();
  23851. }
  23852. }
  23853. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23854. {
  23855. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23856. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23857. addMessageToQueue (m);
  23858. }
  23859. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23860. {
  23861. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23862. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23863. addMessageToQueue (m);
  23864. }
  23865. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23866. {
  23867. addMessageToQueue (message);
  23868. }
  23869. END_JUCE_NAMESPACE
  23870. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23871. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23872. BEGIN_JUCE_NAMESPACE
  23873. MidiMessageSequence::MidiMessageSequence()
  23874. {
  23875. }
  23876. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23877. {
  23878. list.ensureStorageAllocated (other.list.size());
  23879. for (int i = 0; i < other.list.size(); ++i)
  23880. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23881. }
  23882. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23883. {
  23884. MidiMessageSequence otherCopy (other);
  23885. swapWith (otherCopy);
  23886. return *this;
  23887. }
  23888. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23889. {
  23890. list.swapWithArray (other.list);
  23891. }
  23892. MidiMessageSequence::~MidiMessageSequence()
  23893. {
  23894. }
  23895. void MidiMessageSequence::clear()
  23896. {
  23897. list.clear();
  23898. }
  23899. int MidiMessageSequence::getNumEvents() const
  23900. {
  23901. return list.size();
  23902. }
  23903. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23904. {
  23905. return list [index];
  23906. }
  23907. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23908. {
  23909. const MidiEventHolder* const meh = list [index];
  23910. if (meh != 0 && meh->noteOffObject != 0)
  23911. return meh->noteOffObject->message.getTimeStamp();
  23912. else
  23913. return 0.0;
  23914. }
  23915. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23916. {
  23917. const MidiEventHolder* const meh = list [index];
  23918. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23919. }
  23920. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23921. {
  23922. return list.indexOf (event);
  23923. }
  23924. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23925. {
  23926. const int numEvents = list.size();
  23927. int i;
  23928. for (i = 0; i < numEvents; ++i)
  23929. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23930. break;
  23931. return i;
  23932. }
  23933. double MidiMessageSequence::getStartTime() const
  23934. {
  23935. if (list.size() > 0)
  23936. return list.getUnchecked(0)->message.getTimeStamp();
  23937. else
  23938. return 0;
  23939. }
  23940. double MidiMessageSequence::getEndTime() const
  23941. {
  23942. if (list.size() > 0)
  23943. return list.getLast()->message.getTimeStamp();
  23944. else
  23945. return 0;
  23946. }
  23947. double MidiMessageSequence::getEventTime (const int index) const
  23948. {
  23949. if (isPositiveAndBelow (index, list.size()))
  23950. return list.getUnchecked (index)->message.getTimeStamp();
  23951. return 0.0;
  23952. }
  23953. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23954. double timeAdjustment)
  23955. {
  23956. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23957. timeAdjustment += newMessage.getTimeStamp();
  23958. newOne->message.setTimeStamp (timeAdjustment);
  23959. int i;
  23960. for (i = list.size(); --i >= 0;)
  23961. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23962. break;
  23963. list.insert (i + 1, newOne);
  23964. }
  23965. void MidiMessageSequence::deleteEvent (const int index,
  23966. const bool deleteMatchingNoteUp)
  23967. {
  23968. if (isPositiveAndBelow (index, list.size()))
  23969. {
  23970. if (deleteMatchingNoteUp)
  23971. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23972. list.remove (index);
  23973. }
  23974. }
  23975. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23976. double timeAdjustment,
  23977. double firstAllowableTime,
  23978. double endOfAllowableDestTimes)
  23979. {
  23980. firstAllowableTime -= timeAdjustment;
  23981. endOfAllowableDestTimes -= timeAdjustment;
  23982. for (int i = 0; i < other.list.size(); ++i)
  23983. {
  23984. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23985. const double t = m.getTimeStamp();
  23986. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23987. {
  23988. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23989. newOne->message.setTimeStamp (timeAdjustment + t);
  23990. list.add (newOne);
  23991. }
  23992. }
  23993. sort();
  23994. }
  23995. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23996. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23997. {
  23998. const double diff = first->message.getTimeStamp()
  23999. - second->message.getTimeStamp();
  24000. return (diff > 0) - (diff < 0);
  24001. }
  24002. void MidiMessageSequence::sort()
  24003. {
  24004. list.sort (*this, true);
  24005. }
  24006. void MidiMessageSequence::updateMatchedPairs()
  24007. {
  24008. for (int i = 0; i < list.size(); ++i)
  24009. {
  24010. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24011. if (m1.isNoteOn())
  24012. {
  24013. list.getUnchecked(i)->noteOffObject = 0;
  24014. const int note = m1.getNoteNumber();
  24015. const int chan = m1.getChannel();
  24016. const int len = list.size();
  24017. for (int j = i + 1; j < len; ++j)
  24018. {
  24019. const MidiMessage& m = list.getUnchecked(j)->message;
  24020. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24021. {
  24022. if (m.isNoteOff())
  24023. {
  24024. list.getUnchecked(i)->noteOffObject = list[j];
  24025. break;
  24026. }
  24027. else if (m.isNoteOn())
  24028. {
  24029. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24030. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24031. list.getUnchecked(i)->noteOffObject = list[j];
  24032. break;
  24033. }
  24034. }
  24035. }
  24036. }
  24037. }
  24038. }
  24039. void MidiMessageSequence::addTimeToMessages (const double delta)
  24040. {
  24041. for (int i = list.size(); --i >= 0;)
  24042. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24043. + delta);
  24044. }
  24045. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24046. MidiMessageSequence& destSequence,
  24047. const bool alsoIncludeMetaEvents) const
  24048. {
  24049. for (int i = 0; i < list.size(); ++i)
  24050. {
  24051. const MidiMessage& mm = list.getUnchecked(i)->message;
  24052. if (mm.isForChannel (channelNumberToExtract)
  24053. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24054. {
  24055. destSequence.addEvent (mm);
  24056. }
  24057. }
  24058. }
  24059. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24060. {
  24061. for (int i = 0; i < list.size(); ++i)
  24062. {
  24063. const MidiMessage& mm = list.getUnchecked(i)->message;
  24064. if (mm.isSysEx())
  24065. destSequence.addEvent (mm);
  24066. }
  24067. }
  24068. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24069. {
  24070. for (int i = list.size(); --i >= 0;)
  24071. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24072. list.remove(i);
  24073. }
  24074. void MidiMessageSequence::deleteSysExMessages()
  24075. {
  24076. for (int i = list.size(); --i >= 0;)
  24077. if (list.getUnchecked(i)->message.isSysEx())
  24078. list.remove(i);
  24079. }
  24080. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24081. const double time,
  24082. OwnedArray<MidiMessage>& dest)
  24083. {
  24084. bool doneProg = false;
  24085. bool donePitchWheel = false;
  24086. Array <int> doneControllers;
  24087. doneControllers.ensureStorageAllocated (32);
  24088. for (int i = list.size(); --i >= 0;)
  24089. {
  24090. const MidiMessage& mm = list.getUnchecked(i)->message;
  24091. if (mm.isForChannel (channelNumber)
  24092. && mm.getTimeStamp() <= time)
  24093. {
  24094. if (mm.isProgramChange())
  24095. {
  24096. if (! doneProg)
  24097. {
  24098. dest.add (new MidiMessage (mm, 0.0));
  24099. doneProg = true;
  24100. }
  24101. }
  24102. else if (mm.isController())
  24103. {
  24104. if (! doneControllers.contains (mm.getControllerNumber()))
  24105. {
  24106. dest.add (new MidiMessage (mm, 0.0));
  24107. doneControllers.add (mm.getControllerNumber());
  24108. }
  24109. }
  24110. else if (mm.isPitchWheel())
  24111. {
  24112. if (! donePitchWheel)
  24113. {
  24114. dest.add (new MidiMessage (mm, 0.0));
  24115. donePitchWheel = true;
  24116. }
  24117. }
  24118. }
  24119. }
  24120. }
  24121. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24122. : message (message_),
  24123. noteOffObject (0)
  24124. {
  24125. }
  24126. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24127. {
  24128. }
  24129. END_JUCE_NAMESPACE
  24130. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24131. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24132. BEGIN_JUCE_NAMESPACE
  24133. AudioPluginFormat::AudioPluginFormat() throw()
  24134. {
  24135. }
  24136. AudioPluginFormat::~AudioPluginFormat()
  24137. {
  24138. }
  24139. END_JUCE_NAMESPACE
  24140. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24141. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24142. BEGIN_JUCE_NAMESPACE
  24143. AudioPluginFormatManager::AudioPluginFormatManager()
  24144. {
  24145. }
  24146. AudioPluginFormatManager::~AudioPluginFormatManager()
  24147. {
  24148. clearSingletonInstance();
  24149. }
  24150. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24151. void AudioPluginFormatManager::addDefaultFormats()
  24152. {
  24153. #if JUCE_DEBUG
  24154. // you should only call this method once!
  24155. for (int i = formats.size(); --i >= 0;)
  24156. {
  24157. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24158. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24159. #endif
  24160. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24161. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24162. #endif
  24163. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24164. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24165. #endif
  24166. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24167. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24168. #endif
  24169. }
  24170. #endif
  24171. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24172. formats.add (new AudioUnitPluginFormat());
  24173. #endif
  24174. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24175. formats.add (new VSTPluginFormat());
  24176. #endif
  24177. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24178. formats.add (new DirectXPluginFormat());
  24179. #endif
  24180. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24181. formats.add (new LADSPAPluginFormat());
  24182. #endif
  24183. }
  24184. int AudioPluginFormatManager::getNumFormats()
  24185. {
  24186. return formats.size();
  24187. }
  24188. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24189. {
  24190. return formats [index];
  24191. }
  24192. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24193. {
  24194. formats.add (format);
  24195. }
  24196. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24197. String& errorMessage) const
  24198. {
  24199. AudioPluginInstance* result = 0;
  24200. for (int i = 0; i < formats.size(); ++i)
  24201. {
  24202. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24203. if (result != 0)
  24204. break;
  24205. }
  24206. if (result == 0)
  24207. {
  24208. if (! doesPluginStillExist (description))
  24209. errorMessage = TRANS ("This plug-in file no longer exists");
  24210. else
  24211. errorMessage = TRANS ("This plug-in failed to load correctly");
  24212. }
  24213. return result;
  24214. }
  24215. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24216. {
  24217. for (int i = 0; i < formats.size(); ++i)
  24218. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24219. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24220. return false;
  24221. }
  24222. END_JUCE_NAMESPACE
  24223. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24224. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24225. #define JUCE_PLUGIN_HOST 1
  24226. BEGIN_JUCE_NAMESPACE
  24227. AudioPluginInstance::AudioPluginInstance()
  24228. {
  24229. }
  24230. AudioPluginInstance::~AudioPluginInstance()
  24231. {
  24232. }
  24233. void* AudioPluginInstance::getPlatformSpecificData()
  24234. {
  24235. return 0;
  24236. }
  24237. END_JUCE_NAMESPACE
  24238. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24239. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24240. BEGIN_JUCE_NAMESPACE
  24241. KnownPluginList::KnownPluginList()
  24242. {
  24243. }
  24244. KnownPluginList::~KnownPluginList()
  24245. {
  24246. }
  24247. void KnownPluginList::clear()
  24248. {
  24249. if (types.size() > 0)
  24250. {
  24251. types.clear();
  24252. sendChangeMessage();
  24253. }
  24254. }
  24255. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24256. {
  24257. for (int i = 0; i < types.size(); ++i)
  24258. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24259. return types.getUnchecked(i);
  24260. return 0;
  24261. }
  24262. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24263. {
  24264. for (int i = 0; i < types.size(); ++i)
  24265. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24266. return types.getUnchecked(i);
  24267. return 0;
  24268. }
  24269. bool KnownPluginList::addType (const PluginDescription& type)
  24270. {
  24271. for (int i = types.size(); --i >= 0;)
  24272. {
  24273. if (types.getUnchecked(i)->isDuplicateOf (type))
  24274. {
  24275. // strange - found a duplicate plugin with different info..
  24276. jassert (types.getUnchecked(i)->name == type.name);
  24277. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24278. *types.getUnchecked(i) = type;
  24279. return false;
  24280. }
  24281. }
  24282. types.add (new PluginDescription (type));
  24283. sendChangeMessage();
  24284. return true;
  24285. }
  24286. void KnownPluginList::removeType (const int index)
  24287. {
  24288. types.remove (index);
  24289. sendChangeMessage();
  24290. }
  24291. namespace
  24292. {
  24293. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24294. {
  24295. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24296. return File (fileOrIdentifier).getLastModificationTime();
  24297. return Time();
  24298. }
  24299. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24300. {
  24301. return t1 != t2 || t1 == Time();
  24302. }
  24303. }
  24304. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24305. {
  24306. if (getTypeForFile (fileOrIdentifier) == 0)
  24307. return false;
  24308. for (int i = types.size(); --i >= 0;)
  24309. {
  24310. const PluginDescription* const d = types.getUnchecked(i);
  24311. if (d->fileOrIdentifier == fileOrIdentifier
  24312. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24313. {
  24314. return false;
  24315. }
  24316. }
  24317. return true;
  24318. }
  24319. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24320. const bool dontRescanIfAlreadyInList,
  24321. OwnedArray <PluginDescription>& typesFound,
  24322. AudioPluginFormat& format)
  24323. {
  24324. bool addedOne = false;
  24325. if (dontRescanIfAlreadyInList
  24326. && getTypeForFile (fileOrIdentifier) != 0)
  24327. {
  24328. bool needsRescanning = false;
  24329. for (int i = types.size(); --i >= 0;)
  24330. {
  24331. const PluginDescription* const d = types.getUnchecked(i);
  24332. if (d->fileOrIdentifier == fileOrIdentifier)
  24333. {
  24334. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24335. needsRescanning = true;
  24336. else
  24337. typesFound.add (new PluginDescription (*d));
  24338. }
  24339. }
  24340. if (! needsRescanning)
  24341. return false;
  24342. }
  24343. OwnedArray <PluginDescription> found;
  24344. format.findAllTypesForFile (found, fileOrIdentifier);
  24345. for (int i = 0; i < found.size(); ++i)
  24346. {
  24347. PluginDescription* const desc = found.getUnchecked(i);
  24348. jassert (desc != 0);
  24349. if (addType (*desc))
  24350. addedOne = true;
  24351. typesFound.add (new PluginDescription (*desc));
  24352. }
  24353. return addedOne;
  24354. }
  24355. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24356. OwnedArray <PluginDescription>& typesFound)
  24357. {
  24358. for (int i = 0; i < files.size(); ++i)
  24359. {
  24360. bool loaded = false;
  24361. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24362. {
  24363. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24364. if (scanAndAddFile (files[i], true, typesFound, *format))
  24365. loaded = true;
  24366. }
  24367. if (! loaded)
  24368. {
  24369. const File f (files[i]);
  24370. if (f.isDirectory())
  24371. {
  24372. StringArray s;
  24373. {
  24374. Array<File> subFiles;
  24375. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24376. for (int j = 0; j < subFiles.size(); ++j)
  24377. s.add (subFiles.getReference(j).getFullPathName());
  24378. }
  24379. scanAndAddDragAndDroppedFiles (s, typesFound);
  24380. }
  24381. }
  24382. }
  24383. }
  24384. class PluginSorter
  24385. {
  24386. public:
  24387. KnownPluginList::SortMethod method;
  24388. PluginSorter() throw() {}
  24389. int compareElements (const PluginDescription* const first,
  24390. const PluginDescription* const second) const
  24391. {
  24392. int diff = 0;
  24393. if (method == KnownPluginList::sortByCategory)
  24394. diff = first->category.compareLexicographically (second->category);
  24395. else if (method == KnownPluginList::sortByManufacturer)
  24396. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24397. else if (method == KnownPluginList::sortByFileSystemLocation)
  24398. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24399. .upToLastOccurrenceOf ("/", false, false)
  24400. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24401. .upToLastOccurrenceOf ("/", false, false));
  24402. if (diff == 0)
  24403. diff = first->name.compareLexicographically (second->name);
  24404. return diff;
  24405. }
  24406. };
  24407. void KnownPluginList::sort (const SortMethod method)
  24408. {
  24409. if (method != defaultOrder)
  24410. {
  24411. PluginSorter sorter;
  24412. sorter.method = method;
  24413. types.sort (sorter, true);
  24414. sendChangeMessage();
  24415. }
  24416. }
  24417. XmlElement* KnownPluginList::createXml() const
  24418. {
  24419. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24420. for (int i = 0; i < types.size(); ++i)
  24421. e->addChildElement (types.getUnchecked(i)->createXml());
  24422. return e;
  24423. }
  24424. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24425. {
  24426. clear();
  24427. if (xml.hasTagName ("KNOWNPLUGINS"))
  24428. {
  24429. forEachXmlChildElement (xml, e)
  24430. {
  24431. PluginDescription info;
  24432. if (info.loadFromXml (*e))
  24433. addType (info);
  24434. }
  24435. }
  24436. }
  24437. const int menuIdBase = 0x324503f4;
  24438. // This is used to turn a bunch of paths into a nested menu structure.
  24439. struct PluginFilesystemTree
  24440. {
  24441. private:
  24442. String folder;
  24443. OwnedArray <PluginFilesystemTree> subFolders;
  24444. Array <PluginDescription*> plugins;
  24445. void addPlugin (PluginDescription* const pd, const String& path)
  24446. {
  24447. if (path.isEmpty())
  24448. {
  24449. plugins.add (pd);
  24450. }
  24451. else
  24452. {
  24453. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24454. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24455. for (int i = subFolders.size(); --i >= 0;)
  24456. {
  24457. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24458. {
  24459. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24460. return;
  24461. }
  24462. }
  24463. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24464. newFolder->folder = firstSubFolder;
  24465. subFolders.add (newFolder);
  24466. newFolder->addPlugin (pd, remainingPath);
  24467. }
  24468. }
  24469. // removes any deeply nested folders that don't contain any actual plugins
  24470. void optimise()
  24471. {
  24472. for (int i = subFolders.size(); --i >= 0;)
  24473. {
  24474. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24475. sub->optimise();
  24476. if (sub->plugins.size() == 0)
  24477. {
  24478. for (int j = 0; j < sub->subFolders.size(); ++j)
  24479. subFolders.add (sub->subFolders.getUnchecked(j));
  24480. sub->subFolders.clear (false);
  24481. subFolders.remove (i);
  24482. }
  24483. }
  24484. }
  24485. public:
  24486. void buildTree (const Array <PluginDescription*>& allPlugins)
  24487. {
  24488. for (int i = 0; i < allPlugins.size(); ++i)
  24489. {
  24490. String path (allPlugins.getUnchecked(i)
  24491. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24492. .upToLastOccurrenceOf ("/", false, false));
  24493. if (path.substring (1, 2) == ":")
  24494. path = path.substring (2);
  24495. addPlugin (allPlugins.getUnchecked(i), path);
  24496. }
  24497. optimise();
  24498. }
  24499. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24500. {
  24501. int i;
  24502. for (i = 0; i < subFolders.size(); ++i)
  24503. {
  24504. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24505. PopupMenu subMenu;
  24506. sub->addToMenu (subMenu, allPlugins);
  24507. #if JUCE_MAC
  24508. // avoid the special AU formatting nonsense on Mac..
  24509. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24510. #else
  24511. m.addSubMenu (sub->folder, subMenu);
  24512. #endif
  24513. }
  24514. for (i = 0; i < plugins.size(); ++i)
  24515. {
  24516. PluginDescription* const plugin = plugins.getUnchecked(i);
  24517. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24518. plugin->name, true, false);
  24519. }
  24520. }
  24521. };
  24522. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24523. {
  24524. Array <PluginDescription*> sorted;
  24525. {
  24526. PluginSorter sorter;
  24527. sorter.method = sortMethod;
  24528. for (int i = 0; i < types.size(); ++i)
  24529. sorted.addSorted (sorter, types.getUnchecked(i));
  24530. }
  24531. if (sortMethod == sortByCategory
  24532. || sortMethod == sortByManufacturer)
  24533. {
  24534. String lastSubMenuName;
  24535. PopupMenu sub;
  24536. for (int i = 0; i < sorted.size(); ++i)
  24537. {
  24538. const PluginDescription* const pd = sorted.getUnchecked(i);
  24539. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24540. : pd->manufacturerName);
  24541. if (! thisSubMenuName.containsNonWhitespaceChars())
  24542. thisSubMenuName = "Other";
  24543. if (thisSubMenuName != lastSubMenuName)
  24544. {
  24545. if (sub.getNumItems() > 0)
  24546. {
  24547. menu.addSubMenu (lastSubMenuName, sub);
  24548. sub.clear();
  24549. }
  24550. lastSubMenuName = thisSubMenuName;
  24551. }
  24552. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24553. }
  24554. if (sub.getNumItems() > 0)
  24555. menu.addSubMenu (lastSubMenuName, sub);
  24556. }
  24557. else if (sortMethod == sortByFileSystemLocation)
  24558. {
  24559. PluginFilesystemTree root;
  24560. root.buildTree (sorted);
  24561. root.addToMenu (menu, types);
  24562. }
  24563. else
  24564. {
  24565. for (int i = 0; i < sorted.size(); ++i)
  24566. {
  24567. const PluginDescription* const pd = sorted.getUnchecked(i);
  24568. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24569. }
  24570. }
  24571. }
  24572. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24573. {
  24574. const int i = menuResultCode - menuIdBase;
  24575. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24576. }
  24577. END_JUCE_NAMESPACE
  24578. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24579. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24580. BEGIN_JUCE_NAMESPACE
  24581. PluginDescription::PluginDescription()
  24582. : uid (0),
  24583. isInstrument (false),
  24584. numInputChannels (0),
  24585. numOutputChannels (0)
  24586. {
  24587. }
  24588. PluginDescription::~PluginDescription()
  24589. {
  24590. }
  24591. PluginDescription::PluginDescription (const PluginDescription& other)
  24592. : name (other.name),
  24593. descriptiveName (other.descriptiveName),
  24594. pluginFormatName (other.pluginFormatName),
  24595. category (other.category),
  24596. manufacturerName (other.manufacturerName),
  24597. version (other.version),
  24598. fileOrIdentifier (other.fileOrIdentifier),
  24599. lastFileModTime (other.lastFileModTime),
  24600. uid (other.uid),
  24601. isInstrument (other.isInstrument),
  24602. numInputChannels (other.numInputChannels),
  24603. numOutputChannels (other.numOutputChannels)
  24604. {
  24605. }
  24606. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24607. {
  24608. name = other.name;
  24609. descriptiveName = other.descriptiveName;
  24610. pluginFormatName = other.pluginFormatName;
  24611. category = other.category;
  24612. manufacturerName = other.manufacturerName;
  24613. version = other.version;
  24614. fileOrIdentifier = other.fileOrIdentifier;
  24615. uid = other.uid;
  24616. isInstrument = other.isInstrument;
  24617. lastFileModTime = other.lastFileModTime;
  24618. numInputChannels = other.numInputChannels;
  24619. numOutputChannels = other.numOutputChannels;
  24620. return *this;
  24621. }
  24622. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24623. {
  24624. return fileOrIdentifier == other.fileOrIdentifier
  24625. && uid == other.uid;
  24626. }
  24627. const String PluginDescription::createIdentifierString() const
  24628. {
  24629. return pluginFormatName
  24630. + "-" + name
  24631. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24632. + "-" + String::toHexString (uid);
  24633. }
  24634. XmlElement* PluginDescription::createXml() const
  24635. {
  24636. XmlElement* const e = new XmlElement ("PLUGIN");
  24637. e->setAttribute ("name", name);
  24638. if (descriptiveName != name)
  24639. e->setAttribute ("descriptiveName", descriptiveName);
  24640. e->setAttribute ("format", pluginFormatName);
  24641. e->setAttribute ("category", category);
  24642. e->setAttribute ("manufacturer", manufacturerName);
  24643. e->setAttribute ("version", version);
  24644. e->setAttribute ("file", fileOrIdentifier);
  24645. e->setAttribute ("uid", String::toHexString (uid));
  24646. e->setAttribute ("isInstrument", isInstrument);
  24647. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24648. e->setAttribute ("numInputs", numInputChannels);
  24649. e->setAttribute ("numOutputs", numOutputChannels);
  24650. return e;
  24651. }
  24652. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24653. {
  24654. if (xml.hasTagName ("PLUGIN"))
  24655. {
  24656. name = xml.getStringAttribute ("name");
  24657. descriptiveName = xml.getStringAttribute ("name", name);
  24658. pluginFormatName = xml.getStringAttribute ("format");
  24659. category = xml.getStringAttribute ("category");
  24660. manufacturerName = xml.getStringAttribute ("manufacturer");
  24661. version = xml.getStringAttribute ("version");
  24662. fileOrIdentifier = xml.getStringAttribute ("file");
  24663. uid = xml.getStringAttribute ("uid").getHexValue32();
  24664. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24665. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24666. numInputChannels = xml.getIntAttribute ("numInputs");
  24667. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24668. return true;
  24669. }
  24670. return false;
  24671. }
  24672. END_JUCE_NAMESPACE
  24673. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24674. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24675. BEGIN_JUCE_NAMESPACE
  24676. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24677. AudioPluginFormat& formatToLookFor,
  24678. FileSearchPath directoriesToSearch,
  24679. const bool recursive,
  24680. const File& deadMansPedalFile_)
  24681. : list (listToAddTo),
  24682. format (formatToLookFor),
  24683. deadMansPedalFile (deadMansPedalFile_),
  24684. nextIndex (0),
  24685. progress (0)
  24686. {
  24687. directoriesToSearch.removeRedundantPaths();
  24688. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24689. // If any plugins have crashed recently when being loaded, move them to the
  24690. // end of the list to give the others a chance to load correctly..
  24691. const StringArray crashedPlugins (getDeadMansPedalFile());
  24692. for (int i = 0; i < crashedPlugins.size(); ++i)
  24693. {
  24694. const String f = crashedPlugins[i];
  24695. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24696. if (f == filesOrIdentifiersToScan[j])
  24697. filesOrIdentifiersToScan.move (j, -1);
  24698. }
  24699. }
  24700. PluginDirectoryScanner::~PluginDirectoryScanner()
  24701. {
  24702. }
  24703. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24704. {
  24705. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24706. }
  24707. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24708. {
  24709. String file (filesOrIdentifiersToScan [nextIndex]);
  24710. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24711. {
  24712. OwnedArray <PluginDescription> typesFound;
  24713. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24714. StringArray crashedPlugins (getDeadMansPedalFile());
  24715. crashedPlugins.removeString (file);
  24716. crashedPlugins.add (file);
  24717. setDeadMansPedalFile (crashedPlugins);
  24718. list.scanAndAddFile (file,
  24719. dontRescanIfAlreadyInList,
  24720. typesFound,
  24721. format);
  24722. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24723. crashedPlugins.removeString (file);
  24724. setDeadMansPedalFile (crashedPlugins);
  24725. if (typesFound.size() == 0)
  24726. failedFiles.add (file);
  24727. }
  24728. return skipNextFile();
  24729. }
  24730. bool PluginDirectoryScanner::skipNextFile()
  24731. {
  24732. if (nextIndex >= filesOrIdentifiersToScan.size())
  24733. return false;
  24734. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24735. return nextIndex < filesOrIdentifiersToScan.size();
  24736. }
  24737. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24738. {
  24739. StringArray lines;
  24740. if (deadMansPedalFile != File::nonexistent)
  24741. {
  24742. lines.addLines (deadMansPedalFile.loadFileAsString());
  24743. lines.removeEmptyStrings();
  24744. }
  24745. return lines;
  24746. }
  24747. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24748. {
  24749. if (deadMansPedalFile != File::nonexistent)
  24750. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24751. }
  24752. END_JUCE_NAMESPACE
  24753. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24754. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24755. BEGIN_JUCE_NAMESPACE
  24756. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24757. const File& deadMansPedalFile_,
  24758. PropertiesFile* const propertiesToUse_)
  24759. : list (listToEdit),
  24760. deadMansPedalFile (deadMansPedalFile_),
  24761. optionsButton ("Options..."),
  24762. propertiesToUse (propertiesToUse_)
  24763. {
  24764. listBox.setModel (this);
  24765. addAndMakeVisible (&listBox);
  24766. addAndMakeVisible (&optionsButton);
  24767. optionsButton.addListener (this);
  24768. optionsButton.setTriggeredOnMouseDown (true);
  24769. setSize (400, 600);
  24770. list.addChangeListener (this);
  24771. changeListenerCallback (0);
  24772. }
  24773. PluginListComponent::~PluginListComponent()
  24774. {
  24775. list.removeChangeListener (this);
  24776. }
  24777. void PluginListComponent::resized()
  24778. {
  24779. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24780. optionsButton.changeWidthToFitText (24);
  24781. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24782. }
  24783. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24784. {
  24785. listBox.updateContent();
  24786. listBox.repaint();
  24787. }
  24788. int PluginListComponent::getNumRows()
  24789. {
  24790. return list.getNumTypes();
  24791. }
  24792. void PluginListComponent::paintListBoxItem (int row,
  24793. Graphics& g,
  24794. int width, int height,
  24795. bool rowIsSelected)
  24796. {
  24797. if (rowIsSelected)
  24798. g.fillAll (findColour (TextEditor::highlightColourId));
  24799. const PluginDescription* const pd = list.getType (row);
  24800. if (pd != 0)
  24801. {
  24802. GlyphArrangement ga;
  24803. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24804. g.setColour (Colours::black);
  24805. ga.draw (g);
  24806. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24807. String desc;
  24808. desc << pd->pluginFormatName
  24809. << (pd->isInstrument ? " instrument" : " effect")
  24810. << " - "
  24811. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24812. << " / "
  24813. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24814. if (pd->manufacturerName.isNotEmpty())
  24815. desc << " - " << pd->manufacturerName;
  24816. if (pd->version.isNotEmpty())
  24817. desc << " - " << pd->version;
  24818. if (pd->category.isNotEmpty())
  24819. desc << " - category: '" << pd->category << '\'';
  24820. g.setColour (Colours::grey);
  24821. ga.clear();
  24822. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24823. ga.draw (g);
  24824. }
  24825. }
  24826. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24827. {
  24828. list.removeType (lastRowSelected);
  24829. }
  24830. void PluginListComponent::optionsMenuCallback (int result)
  24831. {
  24832. switch (result)
  24833. {
  24834. case 1:
  24835. list.clear();
  24836. break;
  24837. case 2:
  24838. list.sort (KnownPluginList::sortAlphabetically);
  24839. break;
  24840. case 3:
  24841. list.sort (KnownPluginList::sortByCategory);
  24842. break;
  24843. case 4:
  24844. list.sort (KnownPluginList::sortByManufacturer);
  24845. break;
  24846. case 5:
  24847. {
  24848. const SparseSet <int> selected (listBox.getSelectedRows());
  24849. for (int i = list.getNumTypes(); --i >= 0;)
  24850. if (selected.contains (i))
  24851. list.removeType (i);
  24852. break;
  24853. }
  24854. case 6:
  24855. {
  24856. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24857. if (desc != 0)
  24858. {
  24859. if (File (desc->fileOrIdentifier).existsAsFile())
  24860. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24861. }
  24862. break;
  24863. }
  24864. case 7:
  24865. for (int i = list.getNumTypes(); --i >= 0;)
  24866. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24867. list.removeType (i);
  24868. break;
  24869. default:
  24870. if (result != 0)
  24871. {
  24872. typeToScan = result - 10;
  24873. startTimer (1);
  24874. }
  24875. break;
  24876. }
  24877. }
  24878. void PluginListComponent::optionsMenuStaticCallback (int result, PluginListComponent* pluginList)
  24879. {
  24880. if (pluginList != 0)
  24881. pluginList->optionsMenuCallback (result);
  24882. }
  24883. void PluginListComponent::buttonClicked (Button* button)
  24884. {
  24885. if (button == &optionsButton)
  24886. {
  24887. PopupMenu menu;
  24888. menu.addItem (1, TRANS("Clear list"));
  24889. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24890. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24891. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24892. menu.addSeparator();
  24893. menu.addItem (2, TRANS("Sort alphabetically"));
  24894. menu.addItem (3, TRANS("Sort by category"));
  24895. menu.addItem (4, TRANS("Sort by manufacturer"));
  24896. menu.addSeparator();
  24897. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24898. {
  24899. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24900. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24901. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24902. }
  24903. menu.showMenuAsync (PopupMenu::Options().withTargetComponent (&optionsButton),
  24904. ModalCallbackFunction::forComponent (optionsMenuStaticCallback, this));
  24905. }
  24906. }
  24907. void PluginListComponent::timerCallback()
  24908. {
  24909. stopTimer();
  24910. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24911. }
  24912. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24913. {
  24914. return true;
  24915. }
  24916. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24917. {
  24918. OwnedArray <PluginDescription> typesFound;
  24919. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24920. }
  24921. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24922. {
  24923. #if JUCE_MODAL_LOOPS_PERMITTED
  24924. if (format == 0)
  24925. return;
  24926. FileSearchPath path (format->getDefaultLocationsToSearch());
  24927. if (propertiesToUse != 0)
  24928. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24929. {
  24930. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24931. FileSearchPathListComponent pathList;
  24932. pathList.setSize (500, 300);
  24933. pathList.setPath (path);
  24934. aw.addCustomComponent (&pathList);
  24935. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24936. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24937. if (aw.runModalLoop() == 0)
  24938. return;
  24939. path = pathList.getPath();
  24940. }
  24941. if (propertiesToUse != 0)
  24942. {
  24943. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24944. propertiesToUse->saveIfNeeded();
  24945. }
  24946. double progress = 0.0;
  24947. AlertWindow aw (TRANS("Scanning for plugins..."),
  24948. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24949. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24950. aw.addProgressBarComponent (progress);
  24951. aw.enterModalState();
  24952. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24953. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24954. for (;;)
  24955. {
  24956. aw.setMessage (TRANS("Testing:\n\n")
  24957. + scanner.getNextPluginFileThatWillBeScanned());
  24958. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24959. if (! scanner.scanNextFile (true))
  24960. break;
  24961. if (! aw.isCurrentlyModal())
  24962. break;
  24963. progress = scanner.getProgress();
  24964. }
  24965. if (scanner.getFailedFiles().size() > 0)
  24966. {
  24967. StringArray shortNames;
  24968. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24969. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24970. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24971. TRANS("Scan complete"),
  24972. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24973. + shortNames.joinIntoString (", "));
  24974. }
  24975. #else
  24976. jassertfalse; // this method needs refactoring to work without modal loops..
  24977. #endif
  24978. }
  24979. END_JUCE_NAMESPACE
  24980. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24981. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24982. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24983. #include <AudioUnit/AudioUnit.h>
  24984. #include <AudioUnit/AUCocoaUIView.h>
  24985. #include <CoreAudioKit/AUGenericView.h>
  24986. #if JUCE_SUPPORT_CARBON
  24987. #include <AudioToolbox/AudioUnitUtilities.h>
  24988. #include <AudioUnit/AudioUnitCarbonView.h>
  24989. #endif
  24990. BEGIN_JUCE_NAMESPACE
  24991. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24992. #endif
  24993. #if JUCE_MAC
  24994. // Change this to disable logging of various activities
  24995. #ifndef AU_LOGGING
  24996. #define AU_LOGGING 1
  24997. #endif
  24998. #if AU_LOGGING
  24999. #define log(a) Logger::writeToLog(a);
  25000. #else
  25001. #define log(a)
  25002. #endif
  25003. namespace AudioUnitFormatHelpers
  25004. {
  25005. static int insideCallback = 0;
  25006. const String osTypeToString (OSType type)
  25007. {
  25008. char s[4];
  25009. s[0] = (char) (((uint32) type) >> 24);
  25010. s[1] = (char) (((uint32) type) >> 16);
  25011. s[2] = (char) (((uint32) type) >> 8);
  25012. s[3] = (char) ((uint32) type);
  25013. return String (s, 4);
  25014. }
  25015. OSType stringToOSType (const String& s1)
  25016. {
  25017. const String s (s1 + " ");
  25018. return (((OSType) (unsigned char) s[0]) << 24)
  25019. | (((OSType) (unsigned char) s[1]) << 16)
  25020. | (((OSType) (unsigned char) s[2]) << 8)
  25021. | ((OSType) (unsigned char) s[3]);
  25022. }
  25023. static const char* auIdentifierPrefix = "AudioUnit:";
  25024. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25025. {
  25026. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25027. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25028. String s (auIdentifierPrefix);
  25029. if (desc.componentType == kAudioUnitType_MusicDevice)
  25030. s << "Synths/";
  25031. else if (desc.componentType == kAudioUnitType_MusicEffect
  25032. || desc.componentType == kAudioUnitType_Effect)
  25033. s << "Effects/";
  25034. else if (desc.componentType == kAudioUnitType_Generator)
  25035. s << "Generators/";
  25036. else if (desc.componentType == kAudioUnitType_Panner)
  25037. s << "Panners/";
  25038. s << osTypeToString (desc.componentType) << ","
  25039. << osTypeToString (desc.componentSubType) << ","
  25040. << osTypeToString (desc.componentManufacturer);
  25041. return s;
  25042. }
  25043. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25044. {
  25045. Handle componentNameHandle = NewHandle (sizeof (void*));
  25046. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25047. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25048. {
  25049. ComponentDescription desc;
  25050. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25051. {
  25052. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25053. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25054. if (nameString != 0 && nameString[0] != 0)
  25055. {
  25056. const String all ((const char*) nameString + 1, nameString[0]);
  25057. DBG ("name: "+ all);
  25058. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25059. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25060. }
  25061. if (infoString != 0 && infoString[0] != 0)
  25062. {
  25063. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25064. }
  25065. if (name.isEmpty())
  25066. name = "<Unknown>";
  25067. }
  25068. DisposeHandle (componentNameHandle);
  25069. DisposeHandle (componentInfoHandle);
  25070. }
  25071. }
  25072. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25073. String& name, String& version, String& manufacturer)
  25074. {
  25075. zerostruct (desc);
  25076. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25077. {
  25078. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25079. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25080. StringArray tokens;
  25081. tokens.addTokens (s, ",", String::empty);
  25082. tokens.trim();
  25083. tokens.removeEmptyStrings();
  25084. if (tokens.size() == 3)
  25085. {
  25086. desc.componentType = stringToOSType (tokens[0]);
  25087. desc.componentSubType = stringToOSType (tokens[1]);
  25088. desc.componentManufacturer = stringToOSType (tokens[2]);
  25089. ComponentRecord* comp = FindNextComponent (0, &desc);
  25090. if (comp != 0)
  25091. {
  25092. getAUDetails (comp, name, manufacturer);
  25093. return true;
  25094. }
  25095. }
  25096. }
  25097. return false;
  25098. }
  25099. }
  25100. class AudioUnitPluginWindowCarbon;
  25101. class AudioUnitPluginWindowCocoa;
  25102. class AudioUnitPluginInstance : public AudioPluginInstance
  25103. {
  25104. public:
  25105. ~AudioUnitPluginInstance();
  25106. void initialise();
  25107. // AudioPluginInstance methods:
  25108. void fillInPluginDescription (PluginDescription& desc) const
  25109. {
  25110. desc.name = pluginName;
  25111. desc.descriptiveName = pluginName;
  25112. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25113. desc.uid = ((int) componentDesc.componentType)
  25114. ^ ((int) componentDesc.componentSubType)
  25115. ^ ((int) componentDesc.componentManufacturer);
  25116. desc.lastFileModTime = Time();
  25117. desc.pluginFormatName = "AudioUnit";
  25118. desc.category = getCategory();
  25119. desc.manufacturerName = manufacturer;
  25120. desc.version = version;
  25121. desc.numInputChannels = getNumInputChannels();
  25122. desc.numOutputChannels = getNumOutputChannels();
  25123. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25124. }
  25125. void* getPlatformSpecificData() { return audioUnit; }
  25126. const String getName() const { return pluginName; }
  25127. bool acceptsMidi() const { return wantsMidiMessages; }
  25128. bool producesMidi() const { return false; }
  25129. // AudioProcessor methods:
  25130. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25131. void releaseResources();
  25132. void processBlock (AudioSampleBuffer& buffer,
  25133. MidiBuffer& midiMessages);
  25134. bool hasEditor() const;
  25135. AudioProcessorEditor* createEditor();
  25136. const String getInputChannelName (int index) const;
  25137. bool isInputChannelStereoPair (int index) const;
  25138. const String getOutputChannelName (int index) const;
  25139. bool isOutputChannelStereoPair (int index) const;
  25140. int getNumParameters();
  25141. float getParameter (int index);
  25142. void setParameter (int index, float newValue);
  25143. const String getParameterName (int index);
  25144. const String getParameterText (int index);
  25145. bool isParameterAutomatable (int index) const;
  25146. int getNumPrograms();
  25147. int getCurrentProgram();
  25148. void setCurrentProgram (int index);
  25149. const String getProgramName (int index);
  25150. void changeProgramName (int index, const String& newName);
  25151. void getStateInformation (MemoryBlock& destData);
  25152. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25153. void setStateInformation (const void* data, int sizeInBytes);
  25154. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25155. void refreshParameterListFromPlugin();
  25156. private:
  25157. friend class AudioUnitPluginWindowCarbon;
  25158. friend class AudioUnitPluginWindowCocoa;
  25159. friend class AudioUnitPluginFormat;
  25160. ComponentDescription componentDesc;
  25161. String pluginName, manufacturer, version;
  25162. String fileOrIdentifier;
  25163. CriticalSection lock;
  25164. bool wantsMidiMessages, wasPlaying, prepared;
  25165. HeapBlock <AudioBufferList> outputBufferList;
  25166. AudioTimeStamp timeStamp;
  25167. AudioSampleBuffer* currentBuffer;
  25168. AudioUnit audioUnit;
  25169. Array <int> parameterIds;
  25170. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25171. void setPluginCallbacks();
  25172. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25173. const AudioTimeStamp* inTimeStamp,
  25174. UInt32 inBusNumber,
  25175. UInt32 inNumberFrames,
  25176. AudioBufferList* ioData) const;
  25177. static OSStatus renderGetInputCallback (void* inRefCon,
  25178. AudioUnitRenderActionFlags* ioActionFlags,
  25179. const AudioTimeStamp* inTimeStamp,
  25180. UInt32 inBusNumber,
  25181. UInt32 inNumberFrames,
  25182. AudioBufferList* ioData)
  25183. {
  25184. return ((AudioUnitPluginInstance*) inRefCon)
  25185. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25186. }
  25187. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25188. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25189. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25190. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25191. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25192. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25193. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25194. {
  25195. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25196. }
  25197. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25198. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25199. Float64* outCurrentMeasureDownBeat)
  25200. {
  25201. return ((AudioUnitPluginInstance*) inHostUserData)
  25202. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25203. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25204. }
  25205. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25206. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25207. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25208. {
  25209. return ((AudioUnitPluginInstance*) inHostUserData)
  25210. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25211. outCurrentSampleInTimeLine, outIsCycling,
  25212. outCycleStartBeat, outCycleEndBeat);
  25213. }
  25214. void getNumChannels (int& numIns, int& numOuts)
  25215. {
  25216. numIns = 0;
  25217. numOuts = 0;
  25218. AUChannelInfo supportedChannels [128];
  25219. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25220. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25221. 0, supportedChannels, &supportedChannelsSize) == noErr
  25222. && supportedChannelsSize > 0)
  25223. {
  25224. int explicitNumIns = 0;
  25225. int explicitNumOuts = 0;
  25226. int maximumNumIns = 0;
  25227. int maximumNumOuts = 0;
  25228. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25229. {
  25230. const int inChannels = (int) supportedChannels[i].inChannels;
  25231. const int outChannels = (int) supportedChannels[i].outChannels;
  25232. if (inChannels < 0)
  25233. maximumNumIns = jmin (maximumNumIns, inChannels);
  25234. else
  25235. explicitNumIns = jmax (explicitNumIns, inChannels);
  25236. if (outChannels < 0)
  25237. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25238. else
  25239. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25240. }
  25241. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25242. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25243. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25244. {
  25245. numIns = numOuts = 2;
  25246. }
  25247. else
  25248. {
  25249. numIns = explicitNumIns;
  25250. numOuts = explicitNumOuts;
  25251. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25252. numIns = 2;
  25253. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25254. numOuts = 2;
  25255. }
  25256. }
  25257. else
  25258. {
  25259. // (this really means the plugin will take any number of ins/outs as long
  25260. // as they are the same)
  25261. numIns = numOuts = 2;
  25262. }
  25263. }
  25264. const String getCategory() const;
  25265. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25266. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25267. };
  25268. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25269. : fileOrIdentifier (fileOrIdentifier),
  25270. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25271. currentBuffer (0),
  25272. audioUnit (0)
  25273. {
  25274. using namespace AudioUnitFormatHelpers;
  25275. try
  25276. {
  25277. ++insideCallback;
  25278. log ("Opening AU: " + fileOrIdentifier);
  25279. if (getComponentDescFromFile (fileOrIdentifier))
  25280. {
  25281. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25282. if (comp != 0)
  25283. {
  25284. audioUnit = (AudioUnit) OpenComponent (comp);
  25285. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25286. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25287. }
  25288. }
  25289. --insideCallback;
  25290. }
  25291. catch (...)
  25292. {
  25293. --insideCallback;
  25294. }
  25295. }
  25296. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25297. {
  25298. const ScopedLock sl (lock);
  25299. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25300. if (audioUnit != 0)
  25301. {
  25302. AudioUnitUninitialize (audioUnit);
  25303. CloseComponent (audioUnit);
  25304. audioUnit = 0;
  25305. }
  25306. }
  25307. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25308. {
  25309. zerostruct (componentDesc);
  25310. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25311. return true;
  25312. const File file (fileOrIdentifier);
  25313. if (! file.hasFileExtension (".component"))
  25314. return false;
  25315. const char* const utf8 = fileOrIdentifier.toUTF8();
  25316. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25317. strlen (utf8), file.isDirectory());
  25318. if (url != 0)
  25319. {
  25320. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25321. CFRelease (url);
  25322. if (bundleRef != 0)
  25323. {
  25324. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25325. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25326. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25327. if (pluginName.isEmpty())
  25328. pluginName = file.getFileNameWithoutExtension();
  25329. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25330. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25331. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25332. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25333. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25334. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25335. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25336. UseResFile (resFileId);
  25337. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25338. {
  25339. Handle h = Get1IndResource ('thng', i);
  25340. if (h != 0)
  25341. {
  25342. HLock (h);
  25343. const uint32* const types = (const uint32*) *h;
  25344. if (types[0] == kAudioUnitType_MusicDevice
  25345. || types[0] == kAudioUnitType_MusicEffect
  25346. || types[0] == kAudioUnitType_Effect
  25347. || types[0] == kAudioUnitType_Generator
  25348. || types[0] == kAudioUnitType_Panner)
  25349. {
  25350. componentDesc.componentType = types[0];
  25351. componentDesc.componentSubType = types[1];
  25352. componentDesc.componentManufacturer = types[2];
  25353. break;
  25354. }
  25355. HUnlock (h);
  25356. ReleaseResource (h);
  25357. }
  25358. }
  25359. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25360. CFRelease (bundleRef);
  25361. }
  25362. }
  25363. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25364. }
  25365. void AudioUnitPluginInstance::initialise()
  25366. {
  25367. refreshParameterListFromPlugin();
  25368. setPluginCallbacks();
  25369. int numIns, numOuts;
  25370. getNumChannels (numIns, numOuts);
  25371. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25372. setLatencySamples (0);
  25373. }
  25374. void AudioUnitPluginInstance::refreshParameterListFromPlugin()
  25375. {
  25376. parameterIds.clear();
  25377. if (audioUnit != 0)
  25378. {
  25379. UInt32 paramListSize = 0;
  25380. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25381. 0, 0, &paramListSize);
  25382. if (paramListSize > 0)
  25383. {
  25384. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25385. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25386. 0, parameterIds.getRawDataPointer(), &paramListSize);
  25387. }
  25388. }
  25389. }
  25390. void AudioUnitPluginInstance::setPluginCallbacks()
  25391. {
  25392. if (audioUnit != 0)
  25393. {
  25394. {
  25395. AURenderCallbackStruct info;
  25396. zerostruct (info);
  25397. info.inputProcRefCon = this;
  25398. info.inputProc = renderGetInputCallback;
  25399. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25400. 0, &info, sizeof (info));
  25401. }
  25402. {
  25403. HostCallbackInfo info;
  25404. zerostruct (info);
  25405. info.hostUserData = this;
  25406. info.beatAndTempoProc = getBeatAndTempoCallback;
  25407. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25408. info.transportStateProc = getTransportStateCallback;
  25409. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25410. 0, &info, sizeof (info));
  25411. }
  25412. }
  25413. }
  25414. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25415. int samplesPerBlockExpected)
  25416. {
  25417. if (audioUnit != 0)
  25418. {
  25419. releaseResources();
  25420. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25421. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25422. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25423. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25424. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25425. {
  25426. Float64 sr = sampleRate_;
  25427. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25428. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25429. }
  25430. int numIns, numOuts;
  25431. getNumChannels (numIns, numOuts);
  25432. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25433. Float64 latencySecs = 0.0;
  25434. UInt32 latencySize = sizeof (latencySecs);
  25435. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25436. 0, &latencySecs, &latencySize);
  25437. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25438. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25439. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25440. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25441. {
  25442. AudioStreamBasicDescription stream;
  25443. zerostruct (stream);
  25444. stream.mSampleRate = sampleRate_;
  25445. stream.mFormatID = kAudioFormatLinearPCM;
  25446. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25447. stream.mFramesPerPacket = 1;
  25448. stream.mBytesPerPacket = 4;
  25449. stream.mBytesPerFrame = 4;
  25450. stream.mBitsPerChannel = 32;
  25451. stream.mChannelsPerFrame = numIns;
  25452. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25453. 0, &stream, sizeof (stream));
  25454. stream.mChannelsPerFrame = numOuts;
  25455. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25456. 0, &stream, sizeof (stream));
  25457. }
  25458. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25459. outputBufferList->mNumberBuffers = numOuts;
  25460. for (int i = numOuts; --i >= 0;)
  25461. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25462. zerostruct (timeStamp);
  25463. timeStamp.mSampleTime = 0;
  25464. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25465. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25466. currentBuffer = 0;
  25467. wasPlaying = false;
  25468. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25469. }
  25470. }
  25471. void AudioUnitPluginInstance::releaseResources()
  25472. {
  25473. if (prepared)
  25474. {
  25475. AudioUnitUninitialize (audioUnit);
  25476. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25477. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25478. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25479. outputBufferList.free();
  25480. currentBuffer = 0;
  25481. prepared = false;
  25482. }
  25483. }
  25484. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25485. const AudioTimeStamp* inTimeStamp,
  25486. UInt32 inBusNumber,
  25487. UInt32 inNumberFrames,
  25488. AudioBufferList* ioData) const
  25489. {
  25490. if (inBusNumber == 0
  25491. && currentBuffer != 0)
  25492. {
  25493. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25494. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25495. {
  25496. if (i < currentBuffer->getNumChannels())
  25497. {
  25498. memcpy (ioData->mBuffers[i].mData,
  25499. currentBuffer->getSampleData (i, 0),
  25500. sizeof (float) * inNumberFrames);
  25501. }
  25502. else
  25503. {
  25504. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25505. }
  25506. }
  25507. }
  25508. return noErr;
  25509. }
  25510. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25511. MidiBuffer& midiMessages)
  25512. {
  25513. const int numSamples = buffer.getNumSamples();
  25514. if (prepared)
  25515. {
  25516. AudioUnitRenderActionFlags flags = 0;
  25517. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25518. for (int i = getNumOutputChannels(); --i >= 0;)
  25519. {
  25520. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25521. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25522. }
  25523. currentBuffer = &buffer;
  25524. if (wantsMidiMessages)
  25525. {
  25526. const uint8* midiEventData;
  25527. int midiEventSize, midiEventPosition;
  25528. MidiBuffer::Iterator i (midiMessages);
  25529. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25530. {
  25531. if (midiEventSize <= 3)
  25532. MusicDeviceMIDIEvent (audioUnit,
  25533. midiEventData[0], midiEventData[1], midiEventData[2],
  25534. midiEventPosition);
  25535. else
  25536. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25537. }
  25538. midiMessages.clear();
  25539. }
  25540. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25541. 0, numSamples, outputBufferList);
  25542. timeStamp.mSampleTime += numSamples;
  25543. }
  25544. else
  25545. {
  25546. // Plugin not working correctly, so just bypass..
  25547. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25548. buffer.clear (i, 0, buffer.getNumSamples());
  25549. }
  25550. }
  25551. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25552. {
  25553. AudioPlayHead* const ph = getPlayHead();
  25554. AudioPlayHead::CurrentPositionInfo result;
  25555. if (ph != 0 && ph->getCurrentPosition (result))
  25556. {
  25557. if (outCurrentBeat != 0)
  25558. *outCurrentBeat = result.ppqPosition;
  25559. if (outCurrentTempo != 0)
  25560. *outCurrentTempo = result.bpm;
  25561. }
  25562. else
  25563. {
  25564. if (outCurrentBeat != 0)
  25565. *outCurrentBeat = 0;
  25566. if (outCurrentTempo != 0)
  25567. *outCurrentTempo = 120.0;
  25568. }
  25569. return noErr;
  25570. }
  25571. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25572. Float32* outTimeSig_Numerator,
  25573. UInt32* outTimeSig_Denominator,
  25574. Float64* outCurrentMeasureDownBeat) const
  25575. {
  25576. AudioPlayHead* const ph = getPlayHead();
  25577. AudioPlayHead::CurrentPositionInfo result;
  25578. if (ph != 0 && ph->getCurrentPosition (result))
  25579. {
  25580. if (outTimeSig_Numerator != 0)
  25581. *outTimeSig_Numerator = result.timeSigNumerator;
  25582. if (outTimeSig_Denominator != 0)
  25583. *outTimeSig_Denominator = result.timeSigDenominator;
  25584. if (outDeltaSampleOffsetToNextBeat != 0)
  25585. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25586. if (outCurrentMeasureDownBeat != 0)
  25587. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25588. }
  25589. else
  25590. {
  25591. if (outDeltaSampleOffsetToNextBeat != 0)
  25592. *outDeltaSampleOffsetToNextBeat = 0;
  25593. if (outTimeSig_Numerator != 0)
  25594. *outTimeSig_Numerator = 4;
  25595. if (outTimeSig_Denominator != 0)
  25596. *outTimeSig_Denominator = 4;
  25597. if (outCurrentMeasureDownBeat != 0)
  25598. *outCurrentMeasureDownBeat = 0;
  25599. }
  25600. return noErr;
  25601. }
  25602. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25603. Boolean* outTransportStateChanged,
  25604. Float64* outCurrentSampleInTimeLine,
  25605. Boolean* outIsCycling,
  25606. Float64* outCycleStartBeat,
  25607. Float64* outCycleEndBeat)
  25608. {
  25609. AudioPlayHead* const ph = getPlayHead();
  25610. AudioPlayHead::CurrentPositionInfo result;
  25611. if (ph != 0 && ph->getCurrentPosition (result))
  25612. {
  25613. if (outIsPlaying != 0)
  25614. *outIsPlaying = result.isPlaying;
  25615. if (outTransportStateChanged != 0)
  25616. {
  25617. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25618. wasPlaying = result.isPlaying;
  25619. }
  25620. if (outCurrentSampleInTimeLine != 0)
  25621. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25622. if (outIsCycling != 0)
  25623. *outIsCycling = false;
  25624. if (outCycleStartBeat != 0)
  25625. *outCycleStartBeat = 0;
  25626. if (outCycleEndBeat != 0)
  25627. *outCycleEndBeat = 0;
  25628. }
  25629. else
  25630. {
  25631. if (outIsPlaying != 0)
  25632. *outIsPlaying = false;
  25633. if (outTransportStateChanged != 0)
  25634. *outTransportStateChanged = false;
  25635. if (outCurrentSampleInTimeLine != 0)
  25636. *outCurrentSampleInTimeLine = 0;
  25637. if (outIsCycling != 0)
  25638. *outIsCycling = false;
  25639. if (outCycleStartBeat != 0)
  25640. *outCycleStartBeat = 0;
  25641. if (outCycleEndBeat != 0)
  25642. *outCycleEndBeat = 0;
  25643. }
  25644. return noErr;
  25645. }
  25646. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25647. public Timer
  25648. {
  25649. public:
  25650. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25651. : AudioProcessorEditor (&plugin_),
  25652. plugin (plugin_)
  25653. {
  25654. addAndMakeVisible (&wrapper);
  25655. setOpaque (true);
  25656. setVisible (true);
  25657. setSize (100, 100);
  25658. createView (createGenericViewIfNeeded);
  25659. }
  25660. ~AudioUnitPluginWindowCocoa()
  25661. {
  25662. const bool wasValid = isValid();
  25663. wrapper.setView (0);
  25664. if (wasValid)
  25665. plugin.editorBeingDeleted (this);
  25666. }
  25667. bool isValid() const { return wrapper.getView() != 0; }
  25668. void paint (Graphics& g)
  25669. {
  25670. g.fillAll (Colours::white);
  25671. }
  25672. void resized()
  25673. {
  25674. wrapper.setSize (getWidth(), getHeight());
  25675. }
  25676. void timerCallback()
  25677. {
  25678. wrapper.resizeToFitView();
  25679. startTimer (jmin (713, getTimerInterval() + 51));
  25680. }
  25681. void childBoundsChanged (Component* child)
  25682. {
  25683. setSize (wrapper.getWidth(), wrapper.getHeight());
  25684. startTimer (70);
  25685. }
  25686. private:
  25687. AudioUnitPluginInstance& plugin;
  25688. NSViewComponent wrapper;
  25689. bool createView (const bool createGenericViewIfNeeded)
  25690. {
  25691. NSView* pluginView = 0;
  25692. UInt32 dataSize = 0;
  25693. Boolean isWritable = false;
  25694. AudioUnitInitialize (plugin.audioUnit);
  25695. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25696. 0, &dataSize, &isWritable) == noErr
  25697. && dataSize != 0
  25698. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25699. 0, &dataSize, &isWritable) == noErr)
  25700. {
  25701. HeapBlock <AudioUnitCocoaViewInfo> info;
  25702. info.calloc (dataSize, 1);
  25703. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25704. 0, info, &dataSize) == noErr)
  25705. {
  25706. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25707. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25708. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25709. Class viewClass = [viewBundle classNamed: viewClassName];
  25710. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25711. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25712. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25713. {
  25714. id factory = [[[viewClass alloc] init] autorelease];
  25715. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25716. withSize: NSMakeSize (getWidth(), getHeight())];
  25717. }
  25718. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25719. CFRelease (info->mCocoaAUViewClass[i]);
  25720. CFRelease (info->mCocoaAUViewBundleLocation);
  25721. }
  25722. }
  25723. if (createGenericViewIfNeeded && (pluginView == 0))
  25724. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25725. wrapper.setView (pluginView);
  25726. if (pluginView != 0)
  25727. {
  25728. timerCallback();
  25729. startTimer (70);
  25730. }
  25731. return pluginView != 0;
  25732. }
  25733. };
  25734. #if JUCE_SUPPORT_CARBON
  25735. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25736. {
  25737. public:
  25738. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25739. : AudioProcessorEditor (&plugin_),
  25740. plugin (plugin_),
  25741. viewComponent (0)
  25742. {
  25743. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25744. setOpaque (true);
  25745. setVisible (true);
  25746. setSize (400, 300);
  25747. ComponentDescription viewList [16];
  25748. UInt32 viewListSize = sizeof (viewList);
  25749. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25750. 0, &viewList, &viewListSize);
  25751. componentRecord = FindNextComponent (0, &viewList[0]);
  25752. }
  25753. ~AudioUnitPluginWindowCarbon()
  25754. {
  25755. innerWrapper = 0;
  25756. if (isValid())
  25757. plugin.editorBeingDeleted (this);
  25758. }
  25759. bool isValid() const throw() { return componentRecord != 0; }
  25760. void paint (Graphics& g)
  25761. {
  25762. g.fillAll (Colours::black);
  25763. }
  25764. void resized()
  25765. {
  25766. innerWrapper->setSize (getWidth(), getHeight());
  25767. }
  25768. bool keyStateChanged (bool)
  25769. {
  25770. return false;
  25771. }
  25772. bool keyPressed (const KeyPress&)
  25773. {
  25774. return false;
  25775. }
  25776. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25777. AudioUnitCarbonView getViewComponent()
  25778. {
  25779. if (viewComponent == 0 && componentRecord != 0)
  25780. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25781. return viewComponent;
  25782. }
  25783. void closeViewComponent()
  25784. {
  25785. if (viewComponent != 0)
  25786. {
  25787. log ("Closing AU GUI: " + plugin.getName());
  25788. CloseComponent (viewComponent);
  25789. viewComponent = 0;
  25790. }
  25791. }
  25792. private:
  25793. AudioUnitPluginInstance& plugin;
  25794. ComponentRecord* componentRecord;
  25795. AudioUnitCarbonView viewComponent;
  25796. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25797. {
  25798. public:
  25799. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25800. : owner (owner_)
  25801. {
  25802. }
  25803. ~InnerWrapperComponent()
  25804. {
  25805. deleteWindow();
  25806. }
  25807. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25808. {
  25809. log ("Opening AU GUI: " + owner->plugin.getName());
  25810. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25811. if (viewComponent == 0)
  25812. return 0;
  25813. Float32Point pos = { 0, 0 };
  25814. Float32Point size = { 250, 200 };
  25815. HIViewRef pluginView = 0;
  25816. AudioUnitCarbonViewCreate (viewComponent,
  25817. owner->getAudioUnit(),
  25818. windowRef,
  25819. rootView,
  25820. &pos,
  25821. &size,
  25822. (ControlRef*) &pluginView);
  25823. return pluginView;
  25824. }
  25825. void removeView (HIViewRef)
  25826. {
  25827. owner->closeViewComponent();
  25828. }
  25829. private:
  25830. AudioUnitPluginWindowCarbon* const owner;
  25831. };
  25832. friend class InnerWrapperComponent;
  25833. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25834. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25835. };
  25836. #endif
  25837. bool AudioUnitPluginInstance::hasEditor() const
  25838. {
  25839. return true;
  25840. }
  25841. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25842. {
  25843. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25844. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25845. w = 0;
  25846. #if JUCE_SUPPORT_CARBON
  25847. if (w == 0)
  25848. {
  25849. w = new AudioUnitPluginWindowCarbon (*this);
  25850. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25851. w = 0;
  25852. }
  25853. #endif
  25854. if (w == 0)
  25855. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25856. return w.release();
  25857. }
  25858. const String AudioUnitPluginInstance::getCategory() const
  25859. {
  25860. const char* result = 0;
  25861. switch (componentDesc.componentType)
  25862. {
  25863. case kAudioUnitType_Effect:
  25864. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25865. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25866. case kAudioUnitType_Generator: result = "Generator"; break;
  25867. case kAudioUnitType_Panner: result = "Panner"; break;
  25868. default: break;
  25869. }
  25870. return result;
  25871. }
  25872. int AudioUnitPluginInstance::getNumParameters()
  25873. {
  25874. return parameterIds.size();
  25875. }
  25876. float AudioUnitPluginInstance::getParameter (int index)
  25877. {
  25878. const ScopedLock sl (lock);
  25879. Float32 value = 0.0f;
  25880. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25881. {
  25882. AudioUnitGetParameter (audioUnit,
  25883. (UInt32) parameterIds.getUnchecked (index),
  25884. kAudioUnitScope_Global, 0,
  25885. &value);
  25886. }
  25887. return value;
  25888. }
  25889. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25890. {
  25891. const ScopedLock sl (lock);
  25892. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25893. {
  25894. AudioUnitSetParameter (audioUnit,
  25895. (UInt32) parameterIds.getUnchecked (index),
  25896. kAudioUnitScope_Global, 0,
  25897. newValue, 0);
  25898. }
  25899. }
  25900. const String AudioUnitPluginInstance::getParameterName (int index)
  25901. {
  25902. AudioUnitParameterInfo info;
  25903. zerostruct (info);
  25904. UInt32 sz = sizeof (info);
  25905. String name;
  25906. if (AudioUnitGetProperty (audioUnit,
  25907. kAudioUnitProperty_ParameterInfo,
  25908. kAudioUnitScope_Global,
  25909. parameterIds [index], &info, &sz) == noErr)
  25910. {
  25911. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25912. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25913. else
  25914. name = String (info.name, sizeof (info.name));
  25915. }
  25916. return name;
  25917. }
  25918. const String AudioUnitPluginInstance::getParameterText (int index)
  25919. {
  25920. return String (getParameter (index));
  25921. }
  25922. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25923. {
  25924. AudioUnitParameterInfo info;
  25925. UInt32 sz = sizeof (info);
  25926. if (AudioUnitGetProperty (audioUnit,
  25927. kAudioUnitProperty_ParameterInfo,
  25928. kAudioUnitScope_Global,
  25929. parameterIds [index], &info, &sz) == noErr)
  25930. {
  25931. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25932. }
  25933. return true;
  25934. }
  25935. int AudioUnitPluginInstance::getNumPrograms()
  25936. {
  25937. CFArrayRef presets;
  25938. UInt32 sz = sizeof (CFArrayRef);
  25939. int num = 0;
  25940. if (AudioUnitGetProperty (audioUnit,
  25941. kAudioUnitProperty_FactoryPresets,
  25942. kAudioUnitScope_Global,
  25943. 0, &presets, &sz) == noErr)
  25944. {
  25945. num = (int) CFArrayGetCount (presets);
  25946. CFRelease (presets);
  25947. }
  25948. return num;
  25949. }
  25950. int AudioUnitPluginInstance::getCurrentProgram()
  25951. {
  25952. AUPreset current;
  25953. current.presetNumber = 0;
  25954. UInt32 sz = sizeof (AUPreset);
  25955. AudioUnitGetProperty (audioUnit,
  25956. kAudioUnitProperty_FactoryPresets,
  25957. kAudioUnitScope_Global,
  25958. 0, &current, &sz);
  25959. return current.presetNumber;
  25960. }
  25961. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25962. {
  25963. AUPreset current;
  25964. current.presetNumber = newIndex;
  25965. current.presetName = 0;
  25966. AudioUnitSetProperty (audioUnit,
  25967. kAudioUnitProperty_FactoryPresets,
  25968. kAudioUnitScope_Global,
  25969. 0, &current, sizeof (AUPreset));
  25970. }
  25971. const String AudioUnitPluginInstance::getProgramName (int index)
  25972. {
  25973. String s;
  25974. CFArrayRef presets;
  25975. UInt32 sz = sizeof (CFArrayRef);
  25976. if (AudioUnitGetProperty (audioUnit,
  25977. kAudioUnitProperty_FactoryPresets,
  25978. kAudioUnitScope_Global,
  25979. 0, &presets, &sz) == noErr)
  25980. {
  25981. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25982. {
  25983. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25984. if (p != 0 && p->presetNumber == index)
  25985. {
  25986. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25987. break;
  25988. }
  25989. }
  25990. CFRelease (presets);
  25991. }
  25992. return s;
  25993. }
  25994. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25995. {
  25996. jassertfalse; // xxx not implemented!
  25997. }
  25998. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25999. {
  26000. if (isPositiveAndBelow (index, getNumInputChannels()))
  26001. return "Input " + String (index + 1);
  26002. return String::empty;
  26003. }
  26004. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26005. {
  26006. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26007. return false;
  26008. return true;
  26009. }
  26010. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26011. {
  26012. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26013. return "Output " + String (index + 1);
  26014. return String::empty;
  26015. }
  26016. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26017. {
  26018. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26019. return false;
  26020. return true;
  26021. }
  26022. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26023. {
  26024. getCurrentProgramStateInformation (destData);
  26025. }
  26026. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26027. {
  26028. CFPropertyListRef propertyList = 0;
  26029. UInt32 sz = sizeof (CFPropertyListRef);
  26030. if (AudioUnitGetProperty (audioUnit,
  26031. kAudioUnitProperty_ClassInfo,
  26032. kAudioUnitScope_Global,
  26033. 0, &propertyList, &sz) == noErr)
  26034. {
  26035. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26036. CFWriteStreamOpen (stream);
  26037. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26038. CFWriteStreamClose (stream);
  26039. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26040. destData.setSize (bytesWritten);
  26041. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26042. CFRelease (data);
  26043. CFRelease (stream);
  26044. CFRelease (propertyList);
  26045. }
  26046. }
  26047. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26048. {
  26049. setCurrentProgramStateInformation (data, sizeInBytes);
  26050. }
  26051. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26052. {
  26053. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26054. (const UInt8*) data,
  26055. sizeInBytes,
  26056. kCFAllocatorNull);
  26057. CFReadStreamOpen (stream);
  26058. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26059. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26060. stream,
  26061. 0,
  26062. kCFPropertyListImmutable,
  26063. &format,
  26064. 0);
  26065. CFRelease (stream);
  26066. if (propertyList != 0)
  26067. AudioUnitSetProperty (audioUnit,
  26068. kAudioUnitProperty_ClassInfo,
  26069. kAudioUnitScope_Global,
  26070. 0, &propertyList, sizeof (propertyList));
  26071. }
  26072. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26073. {
  26074. }
  26075. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26076. {
  26077. }
  26078. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26079. const String& fileOrIdentifier)
  26080. {
  26081. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26082. return;
  26083. PluginDescription desc;
  26084. desc.fileOrIdentifier = fileOrIdentifier;
  26085. desc.uid = 0;
  26086. try
  26087. {
  26088. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26089. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26090. if (auInstance != 0)
  26091. {
  26092. auInstance->fillInPluginDescription (desc);
  26093. results.add (new PluginDescription (desc));
  26094. }
  26095. }
  26096. catch (...)
  26097. {
  26098. // crashed while loading...
  26099. }
  26100. }
  26101. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26102. {
  26103. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26104. {
  26105. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26106. if (result->audioUnit != 0)
  26107. {
  26108. result->initialise();
  26109. return result.release();
  26110. }
  26111. }
  26112. return 0;
  26113. }
  26114. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26115. const bool /*recursive*/)
  26116. {
  26117. StringArray result;
  26118. ComponentRecord* comp = 0;
  26119. ComponentDescription desc;
  26120. zerostruct (desc);
  26121. for (;;)
  26122. {
  26123. zerostruct (desc);
  26124. comp = FindNextComponent (comp, &desc);
  26125. if (comp == 0)
  26126. break;
  26127. GetComponentInfo (comp, &desc, 0, 0, 0);
  26128. if (desc.componentType == kAudioUnitType_MusicDevice
  26129. || desc.componentType == kAudioUnitType_MusicEffect
  26130. || desc.componentType == kAudioUnitType_Effect
  26131. || desc.componentType == kAudioUnitType_Generator
  26132. || desc.componentType == kAudioUnitType_Panner)
  26133. {
  26134. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26135. DBG (s);
  26136. result.add (s);
  26137. }
  26138. }
  26139. return result;
  26140. }
  26141. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26142. {
  26143. ComponentDescription desc;
  26144. String name, version, manufacturer;
  26145. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26146. return FindNextComponent (0, &desc) != 0;
  26147. const File f (fileOrIdentifier);
  26148. return f.hasFileExtension (".component")
  26149. && f.isDirectory();
  26150. }
  26151. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26152. {
  26153. ComponentDescription desc;
  26154. String name, version, manufacturer;
  26155. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26156. if (name.isEmpty())
  26157. name = fileOrIdentifier;
  26158. return name;
  26159. }
  26160. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26161. {
  26162. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26163. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26164. else
  26165. return File (desc.fileOrIdentifier).exists();
  26166. }
  26167. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26168. {
  26169. return FileSearchPath ("/(Default AudioUnit locations)");
  26170. }
  26171. #endif
  26172. END_JUCE_NAMESPACE
  26173. #undef log
  26174. #endif
  26175. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26176. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26177. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26178. #define JUCE_MAC_VST_INCLUDED 1
  26179. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26180. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26181. #if JUCE_WINDOWS
  26182. #undef _WIN32_WINNT
  26183. #define _WIN32_WINNT 0x500
  26184. #undef STRICT
  26185. #define STRICT
  26186. #include <windows.h>
  26187. #include <float.h>
  26188. #pragma warning (disable : 4312 4355)
  26189. #ifdef __INTEL_COMPILER
  26190. #pragma warning (disable : 1899)
  26191. #endif
  26192. #elif JUCE_LINUX
  26193. #include <float.h>
  26194. #include <sys/time.h>
  26195. #include <X11/Xlib.h>
  26196. #include <X11/Xutil.h>
  26197. #include <X11/Xatom.h>
  26198. #undef Font
  26199. #undef KeyPress
  26200. #undef Drawable
  26201. #undef Time
  26202. #else
  26203. #include <Cocoa/Cocoa.h>
  26204. #include <Carbon/Carbon.h>
  26205. #endif
  26206. #if ! (JUCE_MAC && JUCE_64BIT)
  26207. BEGIN_JUCE_NAMESPACE
  26208. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26209. #endif
  26210. #undef PRAGMA_ALIGN_SUPPORTED
  26211. #define VST_FORCE_DEPRECATED 0
  26212. #if JUCE_MSVC
  26213. #pragma warning (push)
  26214. #pragma warning (disable: 4996)
  26215. #endif
  26216. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26217. your include path if you want to add VST support.
  26218. If you're not interested in VSTs, you can disable them by changing the
  26219. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26220. */
  26221. #include <pluginterfaces/vst2.x/aeffectx.h>
  26222. #if JUCE_MSVC
  26223. #pragma warning (pop)
  26224. #endif
  26225. #if JUCE_LINUX
  26226. #define Font JUCE_NAMESPACE::Font
  26227. #define KeyPress JUCE_NAMESPACE::KeyPress
  26228. #define Drawable JUCE_NAMESPACE::Drawable
  26229. #define Time JUCE_NAMESPACE::Time
  26230. #endif
  26231. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26232. #ifdef __aeffect__
  26233. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26234. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26235. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26236. events to the list.
  26237. This is used by both the VST hosting code and the plugin wrapper.
  26238. */
  26239. class VSTMidiEventList
  26240. {
  26241. public:
  26242. VSTMidiEventList()
  26243. : numEventsUsed (0), numEventsAllocated (0)
  26244. {
  26245. }
  26246. ~VSTMidiEventList()
  26247. {
  26248. freeEvents();
  26249. }
  26250. void clear()
  26251. {
  26252. numEventsUsed = 0;
  26253. if (events != 0)
  26254. events->numEvents = 0;
  26255. }
  26256. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26257. {
  26258. ensureSize (numEventsUsed + 1);
  26259. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26260. events->numEvents = ++numEventsUsed;
  26261. if (numBytes <= 4)
  26262. {
  26263. if (e->type == kVstSysExType)
  26264. {
  26265. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26266. e->type = kVstMidiType;
  26267. e->byteSize = sizeof (VstMidiEvent);
  26268. e->noteLength = 0;
  26269. e->noteOffset = 0;
  26270. e->detune = 0;
  26271. e->noteOffVelocity = 0;
  26272. }
  26273. e->deltaFrames = frameOffset;
  26274. memcpy (e->midiData, midiData, numBytes);
  26275. }
  26276. else
  26277. {
  26278. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26279. if (se->type == kVstSysExType)
  26280. delete[] se->sysexDump;
  26281. se->sysexDump = new char [numBytes];
  26282. memcpy (se->sysexDump, midiData, numBytes);
  26283. se->type = kVstSysExType;
  26284. se->byteSize = sizeof (VstMidiSysexEvent);
  26285. se->deltaFrames = frameOffset;
  26286. se->flags = 0;
  26287. se->dumpBytes = numBytes;
  26288. se->resvd1 = 0;
  26289. se->resvd2 = 0;
  26290. }
  26291. }
  26292. // Handy method to pull the events out of an event buffer supplied by the host
  26293. // or plugin.
  26294. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26295. {
  26296. for (int i = 0; i < events->numEvents; ++i)
  26297. {
  26298. const VstEvent* const e = events->events[i];
  26299. if (e != 0)
  26300. {
  26301. if (e->type == kVstMidiType)
  26302. {
  26303. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26304. 4, e->deltaFrames);
  26305. }
  26306. else if (e->type == kVstSysExType)
  26307. {
  26308. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26309. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26310. e->deltaFrames);
  26311. }
  26312. }
  26313. }
  26314. }
  26315. void ensureSize (int numEventsNeeded)
  26316. {
  26317. if (numEventsNeeded > numEventsAllocated)
  26318. {
  26319. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26320. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26321. if (events == 0)
  26322. events.calloc (size, 1);
  26323. else
  26324. events.realloc (size, 1);
  26325. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26326. {
  26327. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26328. (int) sizeof (VstMidiSysexEvent)));
  26329. e->type = kVstMidiType;
  26330. e->byteSize = sizeof (VstMidiEvent);
  26331. events->events[i] = (VstEvent*) e;
  26332. }
  26333. numEventsAllocated = numEventsNeeded;
  26334. }
  26335. }
  26336. void freeEvents()
  26337. {
  26338. if (events != 0)
  26339. {
  26340. for (int i = numEventsAllocated; --i >= 0;)
  26341. {
  26342. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26343. if (e->type == kVstSysExType)
  26344. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26345. juce_free (e);
  26346. }
  26347. events.free();
  26348. numEventsUsed = 0;
  26349. numEventsAllocated = 0;
  26350. }
  26351. }
  26352. HeapBlock <VstEvents> events;
  26353. private:
  26354. int numEventsUsed, numEventsAllocated;
  26355. };
  26356. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26357. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26358. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26359. #if ! JUCE_WINDOWS
  26360. static void _fpreset() {}
  26361. static void _clearfp() {}
  26362. #endif
  26363. extern void juce_callAnyTimersSynchronously();
  26364. const int fxbVersionNum = 1;
  26365. struct fxProgram
  26366. {
  26367. long chunkMagic; // 'CcnK'
  26368. long byteSize; // of this chunk, excl. magic + byteSize
  26369. long fxMagic; // 'FxCk'
  26370. long version;
  26371. long fxID; // fx unique id
  26372. long fxVersion;
  26373. long numParams;
  26374. char prgName[28];
  26375. float params[1]; // variable no. of parameters
  26376. };
  26377. struct fxSet
  26378. {
  26379. long chunkMagic; // 'CcnK'
  26380. long byteSize; // of this chunk, excl. magic + byteSize
  26381. long fxMagic; // 'FxBk'
  26382. long version;
  26383. long fxID; // fx unique id
  26384. long fxVersion;
  26385. long numPrograms;
  26386. char future[128];
  26387. fxProgram programs[1]; // variable no. of programs
  26388. };
  26389. struct fxChunkSet
  26390. {
  26391. long chunkMagic; // 'CcnK'
  26392. long byteSize; // of this chunk, excl. magic + byteSize
  26393. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26394. long version;
  26395. long fxID; // fx unique id
  26396. long fxVersion;
  26397. long numPrograms;
  26398. char future[128];
  26399. long chunkSize;
  26400. char chunk[8]; // variable
  26401. };
  26402. struct fxProgramSet
  26403. {
  26404. long chunkMagic; // 'CcnK'
  26405. long byteSize; // of this chunk, excl. magic + byteSize
  26406. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26407. long version;
  26408. long fxID; // fx unique id
  26409. long fxVersion;
  26410. long numPrograms;
  26411. char name[28];
  26412. long chunkSize;
  26413. char chunk[8]; // variable
  26414. };
  26415. namespace
  26416. {
  26417. long vst_swap (const long x) throw()
  26418. {
  26419. #ifdef JUCE_LITTLE_ENDIAN
  26420. return (long) ByteOrder::swap ((uint32) x);
  26421. #else
  26422. return x;
  26423. #endif
  26424. }
  26425. float vst_swapFloat (const float x) throw()
  26426. {
  26427. #ifdef JUCE_LITTLE_ENDIAN
  26428. union { uint32 asInt; float asFloat; } n;
  26429. n.asFloat = x;
  26430. n.asInt = ByteOrder::swap (n.asInt);
  26431. return n.asFloat;
  26432. #else
  26433. return x;
  26434. #endif
  26435. }
  26436. double getVSTHostTimeNanoseconds()
  26437. {
  26438. #if JUCE_WINDOWS
  26439. return timeGetTime() * 1000000.0;
  26440. #elif JUCE_LINUX
  26441. timeval micro;
  26442. gettimeofday (&micro, 0);
  26443. return micro.tv_usec * 1000.0;
  26444. #elif JUCE_MAC
  26445. UnsignedWide micro;
  26446. Microseconds (&micro);
  26447. return micro.lo * 1000.0;
  26448. #endif
  26449. }
  26450. }
  26451. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26452. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26453. static int shellUIDToCreate = 0;
  26454. static int insideVSTCallback = 0;
  26455. class VSTPluginWindow;
  26456. // Change this to disable logging of various VST activities
  26457. #ifndef VST_LOGGING
  26458. #define VST_LOGGING 1
  26459. #endif
  26460. #if VST_LOGGING
  26461. #define log(a) Logger::writeToLog(a);
  26462. #else
  26463. #define log(a)
  26464. #endif
  26465. #if JUCE_MAC && JUCE_PPC
  26466. static void* NewCFMFromMachO (void* const machofp) throw()
  26467. {
  26468. void* result = (void*) new char[8];
  26469. ((void**) result)[0] = machofp;
  26470. ((void**) result)[1] = result;
  26471. return result;
  26472. }
  26473. #endif
  26474. #if JUCE_LINUX
  26475. extern Display* display;
  26476. extern XContext windowHandleXContext;
  26477. typedef void (*EventProcPtr) (XEvent* ev);
  26478. static bool xErrorTriggered;
  26479. namespace
  26480. {
  26481. int temporaryErrorHandler (Display*, XErrorEvent*)
  26482. {
  26483. xErrorTriggered = true;
  26484. return 0;
  26485. }
  26486. int getPropertyFromXWindow (Window handle, Atom atom)
  26487. {
  26488. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26489. xErrorTriggered = false;
  26490. int userSize;
  26491. unsigned long bytes, userCount;
  26492. unsigned char* data;
  26493. Atom userType;
  26494. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26495. &userType, &userSize, &userCount, &bytes, &data);
  26496. XSetErrorHandler (oldErrorHandler);
  26497. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26498. : 0;
  26499. }
  26500. Window getChildWindow (Window windowToCheck)
  26501. {
  26502. Window rootWindow, parentWindow;
  26503. Window* childWindows;
  26504. unsigned int numChildren;
  26505. XQueryTree (display,
  26506. windowToCheck,
  26507. &rootWindow,
  26508. &parentWindow,
  26509. &childWindows,
  26510. &numChildren);
  26511. if (numChildren > 0)
  26512. return childWindows [0];
  26513. return 0;
  26514. }
  26515. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26516. {
  26517. if (e.mods.isLeftButtonDown())
  26518. {
  26519. ev.xbutton.button = Button1;
  26520. ev.xbutton.state |= Button1Mask;
  26521. }
  26522. else if (e.mods.isRightButtonDown())
  26523. {
  26524. ev.xbutton.button = Button3;
  26525. ev.xbutton.state |= Button3Mask;
  26526. }
  26527. else if (e.mods.isMiddleButtonDown())
  26528. {
  26529. ev.xbutton.button = Button2;
  26530. ev.xbutton.state |= Button2Mask;
  26531. }
  26532. }
  26533. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26534. {
  26535. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26536. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26537. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26538. }
  26539. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26540. {
  26541. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26542. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26543. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26544. }
  26545. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26546. {
  26547. if (increment < 0)
  26548. {
  26549. ev.xbutton.button = Button5;
  26550. ev.xbutton.state |= Button5Mask;
  26551. }
  26552. else if (increment > 0)
  26553. {
  26554. ev.xbutton.button = Button4;
  26555. ev.xbutton.state |= Button4Mask;
  26556. }
  26557. }
  26558. }
  26559. #endif
  26560. class ModuleHandle : public ReferenceCountedObject
  26561. {
  26562. public:
  26563. File file;
  26564. MainCall moduleMain;
  26565. String pluginName;
  26566. static Array <ModuleHandle*>& getActiveModules()
  26567. {
  26568. static Array <ModuleHandle*> activeModules;
  26569. return activeModules;
  26570. }
  26571. static ModuleHandle* findOrCreateModule (const File& file)
  26572. {
  26573. for (int i = getActiveModules().size(); --i >= 0;)
  26574. {
  26575. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26576. if (module->file == file)
  26577. return module;
  26578. }
  26579. _fpreset(); // (doesn't do any harm)
  26580. ++insideVSTCallback;
  26581. shellUIDToCreate = 0;
  26582. log ("Attempting to load VST: " + file.getFullPathName());
  26583. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26584. if (! m->open())
  26585. m = 0;
  26586. --insideVSTCallback;
  26587. _fpreset(); // (doesn't do any harm)
  26588. return m.release();
  26589. }
  26590. ModuleHandle (const File& file_)
  26591. : file (file_),
  26592. moduleMain (0),
  26593. #if JUCE_WINDOWS || JUCE_LINUX
  26594. hModule (0)
  26595. #elif JUCE_MAC
  26596. fragId (0),
  26597. resHandle (0),
  26598. bundleRef (0),
  26599. resFileId (0)
  26600. #endif
  26601. {
  26602. getActiveModules().add (this);
  26603. #if JUCE_WINDOWS || JUCE_LINUX
  26604. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26605. #elif JUCE_MAC
  26606. FSRef ref;
  26607. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26608. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26609. #endif
  26610. }
  26611. ~ModuleHandle()
  26612. {
  26613. getActiveModules().removeValue (this);
  26614. close();
  26615. }
  26616. #if JUCE_WINDOWS || JUCE_LINUX
  26617. void* hModule;
  26618. String fullParentDirectoryPathName;
  26619. bool open()
  26620. {
  26621. #if JUCE_WINDOWS
  26622. static bool timePeriodSet = false;
  26623. if (! timePeriodSet)
  26624. {
  26625. timePeriodSet = true;
  26626. timeBeginPeriod (2);
  26627. }
  26628. #endif
  26629. pluginName = file.getFileNameWithoutExtension();
  26630. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26631. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26632. if (moduleMain == 0)
  26633. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26634. return moduleMain != 0;
  26635. }
  26636. void close()
  26637. {
  26638. _fpreset(); // (doesn't do any harm)
  26639. PlatformUtilities::freeDynamicLibrary (hModule);
  26640. }
  26641. void closeEffect (AEffect* eff)
  26642. {
  26643. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26644. }
  26645. #else
  26646. CFragConnectionID fragId;
  26647. Handle resHandle;
  26648. CFBundleRef bundleRef;
  26649. FSSpec parentDirFSSpec;
  26650. short resFileId;
  26651. bool open()
  26652. {
  26653. bool ok = false;
  26654. const String filename (file.getFullPathName());
  26655. if (file.hasFileExtension (".vst"))
  26656. {
  26657. const char* const utf8 = filename.toUTF8();
  26658. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26659. strlen (utf8), file.isDirectory());
  26660. if (url != 0)
  26661. {
  26662. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26663. CFRelease (url);
  26664. if (bundleRef != 0)
  26665. {
  26666. if (CFBundleLoadExecutable (bundleRef))
  26667. {
  26668. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26669. if (moduleMain == 0)
  26670. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26671. if (moduleMain != 0)
  26672. {
  26673. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26674. if (name != 0)
  26675. {
  26676. if (CFGetTypeID (name) == CFStringGetTypeID())
  26677. {
  26678. char buffer[1024];
  26679. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26680. pluginName = buffer;
  26681. }
  26682. }
  26683. if (pluginName.isEmpty())
  26684. pluginName = file.getFileNameWithoutExtension();
  26685. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26686. ok = true;
  26687. }
  26688. }
  26689. if (! ok)
  26690. {
  26691. CFBundleUnloadExecutable (bundleRef);
  26692. CFRelease (bundleRef);
  26693. bundleRef = 0;
  26694. }
  26695. }
  26696. }
  26697. }
  26698. #if JUCE_PPC
  26699. else
  26700. {
  26701. FSRef fn;
  26702. if (FSPathMakeRef ((UInt8*) filename.toUTF8().getAddress(), &fn, 0) == noErr)
  26703. {
  26704. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26705. if (resFileId != -1)
  26706. {
  26707. const int numEffs = Count1Resources ('aEff');
  26708. for (int i = 0; i < numEffs; ++i)
  26709. {
  26710. resHandle = Get1IndResource ('aEff', i + 1);
  26711. if (resHandle != 0)
  26712. {
  26713. OSType type;
  26714. Str255 name;
  26715. SInt16 id;
  26716. GetResInfo (resHandle, &id, &type, name);
  26717. pluginName = String ((const char*) name + 1, name[0]);
  26718. DetachResource (resHandle);
  26719. HLock (resHandle);
  26720. Ptr ptr;
  26721. Str255 errorText;
  26722. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26723. name, kPrivateCFragCopy,
  26724. &fragId, &ptr, errorText);
  26725. if (err == noErr)
  26726. {
  26727. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26728. ok = true;
  26729. }
  26730. else
  26731. {
  26732. HUnlock (resHandle);
  26733. }
  26734. break;
  26735. }
  26736. }
  26737. if (! ok)
  26738. CloseResFile (resFileId);
  26739. }
  26740. }
  26741. }
  26742. #endif
  26743. return ok;
  26744. }
  26745. void close()
  26746. {
  26747. #if JUCE_PPC
  26748. if (fragId != 0)
  26749. {
  26750. if (moduleMain != 0)
  26751. disposeMachOFromCFM ((void*) moduleMain);
  26752. CloseConnection (&fragId);
  26753. HUnlock (resHandle);
  26754. if (resFileId != 0)
  26755. CloseResFile (resFileId);
  26756. }
  26757. else
  26758. #endif
  26759. if (bundleRef != 0)
  26760. {
  26761. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26762. if (CFGetRetainCount (bundleRef) == 1)
  26763. CFBundleUnloadExecutable (bundleRef);
  26764. if (CFGetRetainCount (bundleRef) > 0)
  26765. CFRelease (bundleRef);
  26766. }
  26767. }
  26768. void closeEffect (AEffect* eff)
  26769. {
  26770. #if JUCE_PPC
  26771. if (fragId != 0)
  26772. {
  26773. Array<void*> thingsToDelete;
  26774. thingsToDelete.add ((void*) eff->dispatcher);
  26775. thingsToDelete.add ((void*) eff->process);
  26776. thingsToDelete.add ((void*) eff->setParameter);
  26777. thingsToDelete.add ((void*) eff->getParameter);
  26778. thingsToDelete.add ((void*) eff->processReplacing);
  26779. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26780. for (int i = thingsToDelete.size(); --i >= 0;)
  26781. disposeMachOFromCFM (thingsToDelete[i]);
  26782. }
  26783. else
  26784. #endif
  26785. {
  26786. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26787. }
  26788. }
  26789. #if JUCE_PPC
  26790. static void* newMachOFromCFM (void* cfmfp)
  26791. {
  26792. if (cfmfp == 0)
  26793. return 0;
  26794. UInt32* const mfp = new UInt32[6];
  26795. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26796. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26797. mfp[2] = 0x800c0000;
  26798. mfp[3] = 0x804c0004;
  26799. mfp[4] = 0x7c0903a6;
  26800. mfp[5] = 0x4e800420;
  26801. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26802. return mfp;
  26803. }
  26804. static void disposeMachOFromCFM (void* ptr)
  26805. {
  26806. delete[] static_cast <UInt32*> (ptr);
  26807. }
  26808. void coerceAEffectFunctionCalls (AEffect* eff)
  26809. {
  26810. if (fragId != 0)
  26811. {
  26812. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26813. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26814. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26815. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26816. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26817. }
  26818. }
  26819. #endif
  26820. #endif
  26821. private:
  26822. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26823. };
  26824. /**
  26825. An instance of a plugin, created by a VSTPluginFormat.
  26826. */
  26827. class VSTPluginInstance : public AudioPluginInstance,
  26828. private Timer,
  26829. private AsyncUpdater
  26830. {
  26831. public:
  26832. ~VSTPluginInstance();
  26833. // AudioPluginInstance methods:
  26834. void fillInPluginDescription (PluginDescription& desc) const
  26835. {
  26836. desc.name = name;
  26837. {
  26838. char buffer [512];
  26839. zerostruct (buffer);
  26840. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26841. desc.descriptiveName = String (buffer).trim();
  26842. if (desc.descriptiveName.isEmpty())
  26843. desc.descriptiveName = name;
  26844. }
  26845. desc.fileOrIdentifier = module->file.getFullPathName();
  26846. desc.uid = getUID();
  26847. desc.lastFileModTime = module->file.getLastModificationTime();
  26848. desc.pluginFormatName = "VST";
  26849. desc.category = getCategory();
  26850. {
  26851. char buffer [kVstMaxVendorStrLen + 8];
  26852. zerostruct (buffer);
  26853. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26854. desc.manufacturerName = buffer;
  26855. }
  26856. desc.version = getVersion();
  26857. desc.numInputChannels = getNumInputChannels();
  26858. desc.numOutputChannels = getNumOutputChannels();
  26859. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26860. }
  26861. void* getPlatformSpecificData() { return effect; }
  26862. const String getName() const { return name; }
  26863. int getUID() const;
  26864. bool acceptsMidi() const { return wantsMidiMessages; }
  26865. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26866. // AudioProcessor methods:
  26867. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26868. void releaseResources();
  26869. void processBlock (AudioSampleBuffer& buffer,
  26870. MidiBuffer& midiMessages);
  26871. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26872. AudioProcessorEditor* createEditor();
  26873. const String getInputChannelName (int index) const;
  26874. bool isInputChannelStereoPair (int index) const;
  26875. const String getOutputChannelName (int index) const;
  26876. bool isOutputChannelStereoPair (int index) const;
  26877. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26878. float getParameter (int index);
  26879. void setParameter (int index, float newValue);
  26880. const String getParameterName (int index);
  26881. const String getParameterText (int index);
  26882. bool isParameterAutomatable (int index) const;
  26883. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26884. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26885. void setCurrentProgram (int index);
  26886. const String getProgramName (int index);
  26887. void changeProgramName (int index, const String& newName);
  26888. void getStateInformation (MemoryBlock& destData);
  26889. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26890. void setStateInformation (const void* data, int sizeInBytes);
  26891. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26892. void timerCallback();
  26893. void handleAsyncUpdate();
  26894. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26895. private:
  26896. friend class VSTPluginWindow;
  26897. friend class VSTPluginFormat;
  26898. AEffect* effect;
  26899. String name;
  26900. CriticalSection lock;
  26901. bool wantsMidiMessages, initialised, isPowerOn;
  26902. mutable StringArray programNames;
  26903. AudioSampleBuffer tempBuffer;
  26904. CriticalSection midiInLock;
  26905. MidiBuffer incomingMidi;
  26906. VSTMidiEventList midiEventsToSend;
  26907. VstTimeInfo vstHostTime;
  26908. ReferenceCountedObjectPtr <ModuleHandle> module;
  26909. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26910. bool restoreProgramSettings (const fxProgram* const prog);
  26911. const String getCurrentProgramName();
  26912. void setParamsInProgramBlock (fxProgram* const prog);
  26913. void updateStoredProgramNames();
  26914. void initialise();
  26915. void handleMidiFromPlugin (const VstEvents* const events);
  26916. void createTempParameterStore (MemoryBlock& dest);
  26917. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26918. const String getParameterLabel (int index) const;
  26919. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26920. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26921. void setChunkData (const char* data, int size, bool isPreset);
  26922. bool loadFromFXBFile (const void* data, int numBytes);
  26923. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26924. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26925. const String getVersion() const;
  26926. const String getCategory() const;
  26927. void setPower (const bool on);
  26928. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26929. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26930. };
  26931. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26932. : effect (0),
  26933. wantsMidiMessages (false),
  26934. initialised (false),
  26935. isPowerOn (false),
  26936. tempBuffer (1, 1),
  26937. module (module_)
  26938. {
  26939. try
  26940. {
  26941. _fpreset();
  26942. ++insideVSTCallback;
  26943. name = module->pluginName;
  26944. log ("Creating VST instance: " + name);
  26945. #if JUCE_MAC
  26946. if (module->resFileId != 0)
  26947. UseResFile (module->resFileId);
  26948. #if JUCE_PPC
  26949. if (module->fragId != 0)
  26950. {
  26951. static void* audioMasterCoerced = 0;
  26952. if (audioMasterCoerced == 0)
  26953. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26954. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26955. }
  26956. else
  26957. #endif
  26958. #endif
  26959. {
  26960. effect = module->moduleMain (&audioMaster);
  26961. }
  26962. --insideVSTCallback;
  26963. if (effect != 0 && effect->magic == kEffectMagic)
  26964. {
  26965. #if JUCE_PPC
  26966. module->coerceAEffectFunctionCalls (effect);
  26967. #endif
  26968. jassert (effect->resvd2 == 0);
  26969. jassert (effect->object != 0);
  26970. _fpreset(); // some dodgy plugs fuck around with this
  26971. }
  26972. else
  26973. {
  26974. effect = 0;
  26975. }
  26976. }
  26977. catch (...)
  26978. {
  26979. --insideVSTCallback;
  26980. }
  26981. }
  26982. VSTPluginInstance::~VSTPluginInstance()
  26983. {
  26984. const ScopedLock sl (lock);
  26985. jassert (insideVSTCallback == 0);
  26986. if (effect != 0 && effect->magic == kEffectMagic)
  26987. {
  26988. try
  26989. {
  26990. #if JUCE_MAC
  26991. if (module->resFileId != 0)
  26992. UseResFile (module->resFileId);
  26993. #endif
  26994. // Must delete any editors before deleting the plugin instance!
  26995. jassert (getActiveEditor() == 0);
  26996. _fpreset(); // some dodgy plugs fuck around with this
  26997. module->closeEffect (effect);
  26998. }
  26999. catch (...)
  27000. {}
  27001. }
  27002. module = 0;
  27003. effect = 0;
  27004. }
  27005. void VSTPluginInstance::initialise()
  27006. {
  27007. if (initialised || effect == 0)
  27008. return;
  27009. log ("Initialising VST: " + module->pluginName);
  27010. initialised = true;
  27011. dispatch (effIdentify, 0, 0, 0, 0);
  27012. if (getSampleRate() > 0)
  27013. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27014. if (getBlockSize() > 0)
  27015. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27016. dispatch (effOpen, 0, 0, 0, 0);
  27017. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27018. getSampleRate(), getBlockSize());
  27019. if (getNumPrograms() > 1)
  27020. setCurrentProgram (0);
  27021. else
  27022. dispatch (effSetProgram, 0, 0, 0, 0);
  27023. int i;
  27024. for (i = effect->numInputs; --i >= 0;)
  27025. dispatch (effConnectInput, i, 1, 0, 0);
  27026. for (i = effect->numOutputs; --i >= 0;)
  27027. dispatch (effConnectOutput, i, 1, 0, 0);
  27028. updateStoredProgramNames();
  27029. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27030. setLatencySamples (effect->initialDelay);
  27031. }
  27032. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27033. int samplesPerBlockExpected)
  27034. {
  27035. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27036. sampleRate_, samplesPerBlockExpected);
  27037. setLatencySamples (effect->initialDelay);
  27038. vstHostTime.tempo = 120.0;
  27039. vstHostTime.timeSigNumerator = 4;
  27040. vstHostTime.timeSigDenominator = 4;
  27041. vstHostTime.sampleRate = sampleRate_;
  27042. vstHostTime.samplePos = 0;
  27043. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27044. initialise();
  27045. if (initialised)
  27046. {
  27047. wantsMidiMessages = wantsMidiMessages
  27048. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27049. if (wantsMidiMessages)
  27050. midiEventsToSend.ensureSize (256);
  27051. else
  27052. midiEventsToSend.freeEvents();
  27053. incomingMidi.clear();
  27054. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27055. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27056. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27057. if (! isPowerOn)
  27058. setPower (true);
  27059. // dodgy hack to force some plugins to initialise the sample rate..
  27060. if ((! hasEditor()) && getNumParameters() > 0)
  27061. {
  27062. const float old = getParameter (0);
  27063. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27064. setParameter (0, old);
  27065. }
  27066. dispatch (effStartProcess, 0, 0, 0, 0);
  27067. }
  27068. }
  27069. void VSTPluginInstance::releaseResources()
  27070. {
  27071. if (initialised)
  27072. {
  27073. dispatch (effStopProcess, 0, 0, 0, 0);
  27074. setPower (false);
  27075. }
  27076. tempBuffer.setSize (1, 1);
  27077. incomingMidi.clear();
  27078. midiEventsToSend.freeEvents();
  27079. }
  27080. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27081. MidiBuffer& midiMessages)
  27082. {
  27083. const int numSamples = buffer.getNumSamples();
  27084. if (initialised)
  27085. {
  27086. AudioPlayHead* playHead = getPlayHead();
  27087. if (playHead != 0)
  27088. {
  27089. AudioPlayHead::CurrentPositionInfo position;
  27090. playHead->getCurrentPosition (position);
  27091. vstHostTime.tempo = position.bpm;
  27092. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27093. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27094. vstHostTime.ppqPos = position.ppqPosition;
  27095. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27096. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27097. if (position.isPlaying)
  27098. vstHostTime.flags |= kVstTransportPlaying;
  27099. else
  27100. vstHostTime.flags &= ~kVstTransportPlaying;
  27101. }
  27102. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27103. if (wantsMidiMessages)
  27104. {
  27105. midiEventsToSend.clear();
  27106. midiEventsToSend.ensureSize (1);
  27107. MidiBuffer::Iterator iter (midiMessages);
  27108. const uint8* midiData;
  27109. int numBytesOfMidiData, samplePosition;
  27110. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27111. {
  27112. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27113. jlimit (0, numSamples - 1, samplePosition));
  27114. }
  27115. try
  27116. {
  27117. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27118. }
  27119. catch (...)
  27120. {}
  27121. }
  27122. _clearfp();
  27123. if ((effect->flags & effFlagsCanReplacing) != 0)
  27124. {
  27125. try
  27126. {
  27127. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27128. }
  27129. catch (...)
  27130. {}
  27131. }
  27132. else
  27133. {
  27134. tempBuffer.setSize (effect->numOutputs, numSamples);
  27135. tempBuffer.clear();
  27136. try
  27137. {
  27138. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27139. }
  27140. catch (...)
  27141. {}
  27142. for (int i = effect->numOutputs; --i >= 0;)
  27143. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27144. }
  27145. }
  27146. else
  27147. {
  27148. // Not initialised, so just bypass..
  27149. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27150. buffer.clear (i, 0, buffer.getNumSamples());
  27151. }
  27152. {
  27153. // copy any incoming midi..
  27154. const ScopedLock sl (midiInLock);
  27155. midiMessages.swapWith (incomingMidi);
  27156. incomingMidi.clear();
  27157. }
  27158. }
  27159. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27160. {
  27161. if (events != 0)
  27162. {
  27163. const ScopedLock sl (midiInLock);
  27164. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27165. }
  27166. }
  27167. static Array <VSTPluginWindow*> activeVSTWindows;
  27168. class VSTPluginWindow : public AudioProcessorEditor,
  27169. #if ! JUCE_MAC
  27170. public ComponentMovementWatcher,
  27171. #endif
  27172. public Timer
  27173. {
  27174. public:
  27175. VSTPluginWindow (VSTPluginInstance& plugin_)
  27176. : AudioProcessorEditor (&plugin_),
  27177. #if ! JUCE_MAC
  27178. ComponentMovementWatcher (this),
  27179. #endif
  27180. plugin (plugin_),
  27181. isOpen (false),
  27182. recursiveResize (false),
  27183. pluginWantsKeys (false),
  27184. pluginRefusesToResize (false),
  27185. alreadyInside (false)
  27186. {
  27187. #if JUCE_WINDOWS
  27188. sizeCheckCount = 0;
  27189. pluginHWND = 0;
  27190. #elif JUCE_LINUX
  27191. pluginWindow = None;
  27192. pluginProc = None;
  27193. #else
  27194. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27195. #endif
  27196. activeVSTWindows.add (this);
  27197. setSize (1, 1);
  27198. setOpaque (true);
  27199. setVisible (true);
  27200. }
  27201. ~VSTPluginWindow()
  27202. {
  27203. #if JUCE_MAC
  27204. innerWrapper = 0;
  27205. #else
  27206. closePluginWindow();
  27207. #endif
  27208. activeVSTWindows.removeValue (this);
  27209. plugin.editorBeingDeleted (this);
  27210. }
  27211. #if ! JUCE_MAC
  27212. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27213. {
  27214. if (recursiveResize)
  27215. return;
  27216. Component* const topComp = getTopLevelComponent();
  27217. if (topComp->getPeer() != 0)
  27218. {
  27219. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27220. recursiveResize = true;
  27221. #if JUCE_WINDOWS
  27222. if (pluginHWND != 0)
  27223. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27224. #elif JUCE_LINUX
  27225. if (pluginWindow != 0)
  27226. {
  27227. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27228. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27229. XMapRaised (display, pluginWindow);
  27230. }
  27231. #endif
  27232. recursiveResize = false;
  27233. }
  27234. }
  27235. void componentVisibilityChanged()
  27236. {
  27237. if (isShowing())
  27238. openPluginWindow();
  27239. else
  27240. closePluginWindow();
  27241. componentMovedOrResized (true, true);
  27242. }
  27243. void componentPeerChanged()
  27244. {
  27245. closePluginWindow();
  27246. openPluginWindow();
  27247. }
  27248. #endif
  27249. bool keyStateChanged (bool)
  27250. {
  27251. return pluginWantsKeys;
  27252. }
  27253. bool keyPressed (const KeyPress&)
  27254. {
  27255. return pluginWantsKeys;
  27256. }
  27257. #if JUCE_MAC
  27258. void paint (Graphics& g)
  27259. {
  27260. g.fillAll (Colours::black);
  27261. }
  27262. #else
  27263. void paint (Graphics& g)
  27264. {
  27265. if (isOpen)
  27266. {
  27267. ComponentPeer* const peer = getPeer();
  27268. if (peer != 0)
  27269. {
  27270. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27271. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27272. #if JUCE_LINUX
  27273. if (pluginWindow != 0)
  27274. {
  27275. const Rectangle<int> clip (g.getClipBounds());
  27276. XEvent ev;
  27277. zerostruct (ev);
  27278. ev.xexpose.type = Expose;
  27279. ev.xexpose.display = display;
  27280. ev.xexpose.window = pluginWindow;
  27281. ev.xexpose.x = clip.getX();
  27282. ev.xexpose.y = clip.getY();
  27283. ev.xexpose.width = clip.getWidth();
  27284. ev.xexpose.height = clip.getHeight();
  27285. sendEventToChild (&ev);
  27286. }
  27287. #endif
  27288. }
  27289. }
  27290. else
  27291. {
  27292. g.fillAll (Colours::black);
  27293. }
  27294. }
  27295. #endif
  27296. void timerCallback()
  27297. {
  27298. #if JUCE_WINDOWS
  27299. if (--sizeCheckCount <= 0)
  27300. {
  27301. sizeCheckCount = 10;
  27302. checkPluginWindowSize();
  27303. }
  27304. #endif
  27305. try
  27306. {
  27307. static bool reentrant = false;
  27308. if (! reentrant)
  27309. {
  27310. reentrant = true;
  27311. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27312. reentrant = false;
  27313. }
  27314. }
  27315. catch (...)
  27316. {}
  27317. }
  27318. void mouseDown (const MouseEvent& e)
  27319. {
  27320. #if JUCE_LINUX
  27321. if (pluginWindow == 0)
  27322. return;
  27323. toFront (true);
  27324. XEvent ev;
  27325. zerostruct (ev);
  27326. ev.xbutton.display = display;
  27327. ev.xbutton.type = ButtonPress;
  27328. ev.xbutton.window = pluginWindow;
  27329. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27330. ev.xbutton.time = CurrentTime;
  27331. ev.xbutton.x = e.x;
  27332. ev.xbutton.y = e.y;
  27333. ev.xbutton.x_root = e.getScreenX();
  27334. ev.xbutton.y_root = e.getScreenY();
  27335. translateJuceToXButtonModifiers (e, ev);
  27336. sendEventToChild (&ev);
  27337. #elif JUCE_WINDOWS
  27338. (void) e;
  27339. toFront (true);
  27340. #endif
  27341. }
  27342. void broughtToFront()
  27343. {
  27344. activeVSTWindows.removeValue (this);
  27345. activeVSTWindows.add (this);
  27346. #if JUCE_MAC
  27347. dispatch (effEditTop, 0, 0, 0, 0);
  27348. #endif
  27349. }
  27350. private:
  27351. VSTPluginInstance& plugin;
  27352. bool isOpen, recursiveResize;
  27353. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27354. #if JUCE_WINDOWS
  27355. HWND pluginHWND;
  27356. void* originalWndProc;
  27357. int sizeCheckCount;
  27358. #elif JUCE_LINUX
  27359. Window pluginWindow;
  27360. EventProcPtr pluginProc;
  27361. #endif
  27362. #if JUCE_MAC
  27363. void openPluginWindow (WindowRef parentWindow)
  27364. {
  27365. if (isOpen || parentWindow == 0)
  27366. return;
  27367. isOpen = true;
  27368. ERect* rect = 0;
  27369. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27370. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27371. // do this before and after like in the steinberg example
  27372. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27373. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27374. // Install keyboard hooks
  27375. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27376. // double-check it's not too tiny
  27377. int w = 250, h = 150;
  27378. if (rect != 0)
  27379. {
  27380. w = rect->right - rect->left;
  27381. h = rect->bottom - rect->top;
  27382. if (w == 0 || h == 0)
  27383. {
  27384. w = 250;
  27385. h = 150;
  27386. }
  27387. }
  27388. w = jmax (w, 32);
  27389. h = jmax (h, 32);
  27390. setSize (w, h);
  27391. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27392. repaint();
  27393. }
  27394. #else
  27395. void openPluginWindow()
  27396. {
  27397. if (isOpen || getWindowHandle() == 0)
  27398. return;
  27399. log ("Opening VST UI: " + plugin.name);
  27400. isOpen = true;
  27401. ERect* rect = 0;
  27402. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27403. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27404. // do this before and after like in the steinberg example
  27405. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27406. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27407. // Install keyboard hooks
  27408. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27409. #if JUCE_WINDOWS
  27410. originalWndProc = 0;
  27411. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27412. if (pluginHWND == 0)
  27413. {
  27414. isOpen = false;
  27415. setSize (300, 150);
  27416. return;
  27417. }
  27418. #pragma warning (push)
  27419. #pragma warning (disable: 4244)
  27420. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27421. if (! pluginWantsKeys)
  27422. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27423. #pragma warning (pop)
  27424. int w, h;
  27425. RECT r;
  27426. GetWindowRect (pluginHWND, &r);
  27427. w = r.right - r.left;
  27428. h = r.bottom - r.top;
  27429. if (rect != 0)
  27430. {
  27431. const int rw = rect->right - rect->left;
  27432. const int rh = rect->bottom - rect->top;
  27433. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27434. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27435. {
  27436. // very dodgy logic to decide which size is right.
  27437. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27438. {
  27439. SetWindowPos (pluginHWND, 0,
  27440. 0, 0, rw, rh,
  27441. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27442. GetWindowRect (pluginHWND, &r);
  27443. w = r.right - r.left;
  27444. h = r.bottom - r.top;
  27445. pluginRefusesToResize = (w != rw) || (h != rh);
  27446. w = rw;
  27447. h = rh;
  27448. }
  27449. }
  27450. }
  27451. #elif JUCE_LINUX
  27452. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27453. if (pluginWindow != 0)
  27454. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27455. XInternAtom (display, "_XEventProc", False));
  27456. int w = 250, h = 150;
  27457. if (rect != 0)
  27458. {
  27459. w = rect->right - rect->left;
  27460. h = rect->bottom - rect->top;
  27461. if (w == 0 || h == 0)
  27462. {
  27463. w = 250;
  27464. h = 150;
  27465. }
  27466. }
  27467. if (pluginWindow != 0)
  27468. XMapRaised (display, pluginWindow);
  27469. #endif
  27470. // double-check it's not too tiny
  27471. w = jmax (w, 32);
  27472. h = jmax (h, 32);
  27473. setSize (w, h);
  27474. #if JUCE_WINDOWS
  27475. checkPluginWindowSize();
  27476. #endif
  27477. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27478. repaint();
  27479. }
  27480. #endif
  27481. #if ! JUCE_MAC
  27482. void closePluginWindow()
  27483. {
  27484. if (isOpen)
  27485. {
  27486. log ("Closing VST UI: " + plugin.getName());
  27487. isOpen = false;
  27488. dispatch (effEditClose, 0, 0, 0, 0);
  27489. #if JUCE_WINDOWS
  27490. #pragma warning (push)
  27491. #pragma warning (disable: 4244)
  27492. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27493. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27494. #pragma warning (pop)
  27495. stopTimer();
  27496. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27497. DestroyWindow (pluginHWND);
  27498. pluginHWND = 0;
  27499. #elif JUCE_LINUX
  27500. stopTimer();
  27501. pluginWindow = 0;
  27502. pluginProc = 0;
  27503. #endif
  27504. }
  27505. }
  27506. #endif
  27507. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27508. {
  27509. return plugin.dispatch (opcode, index, value, ptr, opt);
  27510. }
  27511. #if JUCE_WINDOWS
  27512. void checkPluginWindowSize()
  27513. {
  27514. RECT r;
  27515. GetWindowRect (pluginHWND, &r);
  27516. const int w = r.right - r.left;
  27517. const int h = r.bottom - r.top;
  27518. if (isShowing() && w > 0 && h > 0
  27519. && (w != getWidth() || h != getHeight())
  27520. && ! pluginRefusesToResize)
  27521. {
  27522. setSize (w, h);
  27523. sizeCheckCount = 0;
  27524. }
  27525. }
  27526. // hooks to get keyboard events from VST windows..
  27527. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27528. {
  27529. for (int i = activeVSTWindows.size(); --i >= 0;)
  27530. {
  27531. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27532. if (w->pluginHWND == hW)
  27533. {
  27534. if (message == WM_CHAR
  27535. || message == WM_KEYDOWN
  27536. || message == WM_SYSKEYDOWN
  27537. || message == WM_KEYUP
  27538. || message == WM_SYSKEYUP
  27539. || message == WM_APPCOMMAND)
  27540. {
  27541. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27542. message, wParam, lParam);
  27543. }
  27544. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27545. (HWND) w->pluginHWND,
  27546. message,
  27547. wParam,
  27548. lParam);
  27549. }
  27550. }
  27551. return DefWindowProc (hW, message, wParam, lParam);
  27552. }
  27553. #endif
  27554. #if JUCE_LINUX
  27555. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27556. void sendEventToChild (XEvent* event)
  27557. {
  27558. if (pluginProc != 0)
  27559. {
  27560. // if the plugin publishes an event procedure, pass the event directly..
  27561. pluginProc (event);
  27562. }
  27563. else if (pluginWindow != 0)
  27564. {
  27565. // if the plugin has a window, then send the event to the window so that
  27566. // its message thread will pick it up..
  27567. XSendEvent (display, pluginWindow, False, 0L, event);
  27568. XFlush (display);
  27569. }
  27570. }
  27571. void mouseEnter (const MouseEvent& e)
  27572. {
  27573. if (pluginWindow != 0)
  27574. {
  27575. XEvent ev;
  27576. zerostruct (ev);
  27577. ev.xcrossing.display = display;
  27578. ev.xcrossing.type = EnterNotify;
  27579. ev.xcrossing.window = pluginWindow;
  27580. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27581. ev.xcrossing.time = CurrentTime;
  27582. ev.xcrossing.x = e.x;
  27583. ev.xcrossing.y = e.y;
  27584. ev.xcrossing.x_root = e.getScreenX();
  27585. ev.xcrossing.y_root = e.getScreenY();
  27586. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27587. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27588. translateJuceToXCrossingModifiers (e, ev);
  27589. sendEventToChild (&ev);
  27590. }
  27591. }
  27592. void mouseExit (const MouseEvent& e)
  27593. {
  27594. if (pluginWindow != 0)
  27595. {
  27596. XEvent ev;
  27597. zerostruct (ev);
  27598. ev.xcrossing.display = display;
  27599. ev.xcrossing.type = LeaveNotify;
  27600. ev.xcrossing.window = pluginWindow;
  27601. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27602. ev.xcrossing.time = CurrentTime;
  27603. ev.xcrossing.x = e.x;
  27604. ev.xcrossing.y = e.y;
  27605. ev.xcrossing.x_root = e.getScreenX();
  27606. ev.xcrossing.y_root = e.getScreenY();
  27607. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27608. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27609. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27610. translateJuceToXCrossingModifiers (e, ev);
  27611. sendEventToChild (&ev);
  27612. }
  27613. }
  27614. void mouseMove (const MouseEvent& e)
  27615. {
  27616. if (pluginWindow != 0)
  27617. {
  27618. XEvent ev;
  27619. zerostruct (ev);
  27620. ev.xmotion.display = display;
  27621. ev.xmotion.type = MotionNotify;
  27622. ev.xmotion.window = pluginWindow;
  27623. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27624. ev.xmotion.time = CurrentTime;
  27625. ev.xmotion.is_hint = NotifyNormal;
  27626. ev.xmotion.x = e.x;
  27627. ev.xmotion.y = e.y;
  27628. ev.xmotion.x_root = e.getScreenX();
  27629. ev.xmotion.y_root = e.getScreenY();
  27630. sendEventToChild (&ev);
  27631. }
  27632. }
  27633. void mouseDrag (const MouseEvent& e)
  27634. {
  27635. if (pluginWindow != 0)
  27636. {
  27637. XEvent ev;
  27638. zerostruct (ev);
  27639. ev.xmotion.display = display;
  27640. ev.xmotion.type = MotionNotify;
  27641. ev.xmotion.window = pluginWindow;
  27642. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27643. ev.xmotion.time = CurrentTime;
  27644. ev.xmotion.x = e.x ;
  27645. ev.xmotion.y = e.y;
  27646. ev.xmotion.x_root = e.getScreenX();
  27647. ev.xmotion.y_root = e.getScreenY();
  27648. ev.xmotion.is_hint = NotifyNormal;
  27649. translateJuceToXMotionModifiers (e, ev);
  27650. sendEventToChild (&ev);
  27651. }
  27652. }
  27653. void mouseUp (const MouseEvent& e)
  27654. {
  27655. if (pluginWindow != 0)
  27656. {
  27657. XEvent ev;
  27658. zerostruct (ev);
  27659. ev.xbutton.display = display;
  27660. ev.xbutton.type = ButtonRelease;
  27661. ev.xbutton.window = pluginWindow;
  27662. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27663. ev.xbutton.time = CurrentTime;
  27664. ev.xbutton.x = e.x;
  27665. ev.xbutton.y = e.y;
  27666. ev.xbutton.x_root = e.getScreenX();
  27667. ev.xbutton.y_root = e.getScreenY();
  27668. translateJuceToXButtonModifiers (e, ev);
  27669. sendEventToChild (&ev);
  27670. }
  27671. }
  27672. void mouseWheelMove (const MouseEvent& e,
  27673. float incrementX,
  27674. float incrementY)
  27675. {
  27676. if (pluginWindow != 0)
  27677. {
  27678. XEvent ev;
  27679. zerostruct (ev);
  27680. ev.xbutton.display = display;
  27681. ev.xbutton.type = ButtonPress;
  27682. ev.xbutton.window = pluginWindow;
  27683. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27684. ev.xbutton.time = CurrentTime;
  27685. ev.xbutton.x = e.x;
  27686. ev.xbutton.y = e.y;
  27687. ev.xbutton.x_root = e.getScreenX();
  27688. ev.xbutton.y_root = e.getScreenY();
  27689. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27690. sendEventToChild (&ev);
  27691. // TODO - put a usleep here ?
  27692. ev.xbutton.type = ButtonRelease;
  27693. sendEventToChild (&ev);
  27694. }
  27695. }
  27696. #endif
  27697. #if JUCE_MAC
  27698. #if ! JUCE_SUPPORT_CARBON
  27699. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27700. #endif
  27701. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27702. {
  27703. public:
  27704. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27705. : owner (owner_),
  27706. alreadyInside (false)
  27707. {
  27708. }
  27709. ~InnerWrapperComponent()
  27710. {
  27711. deleteWindow();
  27712. }
  27713. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27714. {
  27715. owner->openPluginWindow (windowRef);
  27716. return 0;
  27717. }
  27718. void removeView (HIViewRef)
  27719. {
  27720. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27721. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27722. }
  27723. bool getEmbeddedViewSize (int& w, int& h)
  27724. {
  27725. ERect* rect = 0;
  27726. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27727. w = rect->right - rect->left;
  27728. h = rect->bottom - rect->top;
  27729. return true;
  27730. }
  27731. void mouseDown (int x, int y)
  27732. {
  27733. if (! alreadyInside)
  27734. {
  27735. alreadyInside = true;
  27736. getTopLevelComponent()->toFront (true);
  27737. owner->dispatch (effEditMouse, x, y, 0, 0);
  27738. alreadyInside = false;
  27739. }
  27740. else
  27741. {
  27742. PostEvent (::mouseDown, 0);
  27743. }
  27744. }
  27745. void paint()
  27746. {
  27747. ComponentPeer* const peer = getPeer();
  27748. if (peer != 0)
  27749. {
  27750. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27751. ERect r;
  27752. r.left = pos.getX();
  27753. r.right = r.left + getWidth();
  27754. r.top = pos.getY();
  27755. r.bottom = r.top + getHeight();
  27756. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27757. }
  27758. }
  27759. private:
  27760. VSTPluginWindow* const owner;
  27761. bool alreadyInside;
  27762. };
  27763. friend class InnerWrapperComponent;
  27764. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27765. void resized()
  27766. {
  27767. innerWrapper->setSize (getWidth(), getHeight());
  27768. }
  27769. #endif
  27770. private:
  27771. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27772. };
  27773. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27774. {
  27775. if (hasEditor())
  27776. return new VSTPluginWindow (*this);
  27777. return 0;
  27778. }
  27779. void VSTPluginInstance::handleAsyncUpdate()
  27780. {
  27781. // indicates that something about the plugin has changed..
  27782. updateHostDisplay();
  27783. }
  27784. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27785. {
  27786. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27787. {
  27788. changeProgramName (getCurrentProgram(), prog->prgName);
  27789. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27790. setParameter (i, vst_swapFloat (prog->params[i]));
  27791. return true;
  27792. }
  27793. return false;
  27794. }
  27795. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27796. const int dataSize)
  27797. {
  27798. if (dataSize < 28)
  27799. return false;
  27800. const fxSet* const set = (const fxSet*) data;
  27801. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27802. || vst_swap (set->version) > fxbVersionNum)
  27803. return false;
  27804. if (vst_swap (set->fxMagic) == 'FxBk')
  27805. {
  27806. // bank of programs
  27807. if (vst_swap (set->numPrograms) >= 0)
  27808. {
  27809. const int oldProg = getCurrentProgram();
  27810. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27811. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27812. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27813. {
  27814. if (i != oldProg)
  27815. {
  27816. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27817. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27818. return false;
  27819. if (vst_swap (set->numPrograms) > 0)
  27820. setCurrentProgram (i);
  27821. if (! restoreProgramSettings (prog))
  27822. return false;
  27823. }
  27824. }
  27825. if (vst_swap (set->numPrograms) > 0)
  27826. setCurrentProgram (oldProg);
  27827. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27828. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27829. return false;
  27830. if (! restoreProgramSettings (prog))
  27831. return false;
  27832. }
  27833. }
  27834. else if (vst_swap (set->fxMagic) == 'FxCk')
  27835. {
  27836. // single program
  27837. const fxProgram* const prog = (const fxProgram*) data;
  27838. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27839. return false;
  27840. changeProgramName (getCurrentProgram(), prog->prgName);
  27841. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27842. setParameter (i, vst_swapFloat (prog->params[i]));
  27843. }
  27844. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27845. {
  27846. // non-preset chunk
  27847. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27848. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27849. return false;
  27850. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27851. }
  27852. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27853. {
  27854. // preset chunk
  27855. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27856. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27857. return false;
  27858. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27859. changeProgramName (getCurrentProgram(), cset->name);
  27860. }
  27861. else
  27862. {
  27863. return false;
  27864. }
  27865. return true;
  27866. }
  27867. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27868. {
  27869. const int numParams = getNumParameters();
  27870. prog->chunkMagic = vst_swap ('CcnK');
  27871. prog->byteSize = 0;
  27872. prog->fxMagic = vst_swap ('FxCk');
  27873. prog->version = vst_swap (fxbVersionNum);
  27874. prog->fxID = vst_swap (getUID());
  27875. prog->fxVersion = vst_swap (getVersionNumber());
  27876. prog->numParams = vst_swap (numParams);
  27877. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27878. for (int i = 0; i < numParams; ++i)
  27879. prog->params[i] = vst_swapFloat (getParameter (i));
  27880. }
  27881. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27882. {
  27883. const int numPrograms = getNumPrograms();
  27884. const int numParams = getNumParameters();
  27885. if (usesChunks())
  27886. {
  27887. if (isFXB)
  27888. {
  27889. MemoryBlock chunk;
  27890. getChunkData (chunk, false, maxSizeMB);
  27891. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27892. dest.setSize (totalLen, true);
  27893. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27894. set->chunkMagic = vst_swap ('CcnK');
  27895. set->byteSize = 0;
  27896. set->fxMagic = vst_swap ('FBCh');
  27897. set->version = vst_swap (fxbVersionNum);
  27898. set->fxID = vst_swap (getUID());
  27899. set->fxVersion = vst_swap (getVersionNumber());
  27900. set->numPrograms = vst_swap (numPrograms);
  27901. set->chunkSize = vst_swap ((long) chunk.getSize());
  27902. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27903. }
  27904. else
  27905. {
  27906. MemoryBlock chunk;
  27907. getChunkData (chunk, true, maxSizeMB);
  27908. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27909. dest.setSize (totalLen, true);
  27910. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27911. set->chunkMagic = vst_swap ('CcnK');
  27912. set->byteSize = 0;
  27913. set->fxMagic = vst_swap ('FPCh');
  27914. set->version = vst_swap (fxbVersionNum);
  27915. set->fxID = vst_swap (getUID());
  27916. set->fxVersion = vst_swap (getVersionNumber());
  27917. set->numPrograms = vst_swap (numPrograms);
  27918. set->chunkSize = vst_swap ((long) chunk.getSize());
  27919. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27920. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27921. }
  27922. }
  27923. else
  27924. {
  27925. if (isFXB)
  27926. {
  27927. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27928. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27929. dest.setSize (len, true);
  27930. fxSet* const set = (fxSet*) dest.getData();
  27931. set->chunkMagic = vst_swap ('CcnK');
  27932. set->byteSize = 0;
  27933. set->fxMagic = vst_swap ('FxBk');
  27934. set->version = vst_swap (fxbVersionNum);
  27935. set->fxID = vst_swap (getUID());
  27936. set->fxVersion = vst_swap (getVersionNumber());
  27937. set->numPrograms = vst_swap (numPrograms);
  27938. const int oldProgram = getCurrentProgram();
  27939. MemoryBlock oldSettings;
  27940. createTempParameterStore (oldSettings);
  27941. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27942. for (int i = 0; i < numPrograms; ++i)
  27943. {
  27944. if (i != oldProgram)
  27945. {
  27946. setCurrentProgram (i);
  27947. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27948. }
  27949. }
  27950. setCurrentProgram (oldProgram);
  27951. restoreFromTempParameterStore (oldSettings);
  27952. }
  27953. else
  27954. {
  27955. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27956. dest.setSize (totalLen, true);
  27957. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27958. }
  27959. }
  27960. return true;
  27961. }
  27962. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27963. {
  27964. if (usesChunks())
  27965. {
  27966. void* data = 0;
  27967. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27968. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27969. {
  27970. mb.setSize (bytes);
  27971. mb.copyFrom (data, 0, bytes);
  27972. }
  27973. }
  27974. }
  27975. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27976. {
  27977. if (size > 0 && usesChunks())
  27978. {
  27979. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27980. if (! isPreset)
  27981. updateStoredProgramNames();
  27982. }
  27983. }
  27984. void VSTPluginInstance::timerCallback()
  27985. {
  27986. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27987. stopTimer();
  27988. }
  27989. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27990. {
  27991. const ScopedLock sl (lock);
  27992. ++insideVSTCallback;
  27993. int result = 0;
  27994. try
  27995. {
  27996. if (effect != 0)
  27997. {
  27998. #if JUCE_MAC
  27999. if (module->resFileId != 0)
  28000. UseResFile (module->resFileId);
  28001. #endif
  28002. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28003. #if JUCE_MAC
  28004. module->resFileId = CurResFile();
  28005. #endif
  28006. --insideVSTCallback;
  28007. return result;
  28008. }
  28009. }
  28010. catch (...)
  28011. {
  28012. }
  28013. --insideVSTCallback;
  28014. return result;
  28015. }
  28016. namespace
  28017. {
  28018. static const int defaultVSTSampleRateValue = 16384;
  28019. static const int defaultVSTBlockSizeValue = 512;
  28020. // handles non plugin-specific callbacks..
  28021. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28022. {
  28023. (void) index;
  28024. (void) value;
  28025. (void) opt;
  28026. switch (opcode)
  28027. {
  28028. case audioMasterCanDo:
  28029. {
  28030. static const char* canDos[] = { "supplyIdle",
  28031. "sendVstEvents",
  28032. "sendVstMidiEvent",
  28033. "sendVstTimeInfo",
  28034. "receiveVstEvents",
  28035. "receiveVstMidiEvent",
  28036. "supportShell",
  28037. "shellCategory" };
  28038. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28039. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28040. return 1;
  28041. return 0;
  28042. }
  28043. case audioMasterVersion: return 0x2400;
  28044. case audioMasterCurrentId: return shellUIDToCreate;
  28045. case audioMasterGetNumAutomatableParameters: return 0;
  28046. case audioMasterGetAutomationState: return 1;
  28047. case audioMasterGetVendorVersion: return 0x0101;
  28048. case audioMasterGetVendorString:
  28049. case audioMasterGetProductString:
  28050. {
  28051. String hostName ("Juce VST Host");
  28052. if (JUCEApplication::getInstance() != 0)
  28053. hostName = JUCEApplication::getInstance()->getApplicationName();
  28054. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28055. break;
  28056. }
  28057. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28058. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28059. case audioMasterSetOutputSampleRate: return 0;
  28060. default:
  28061. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28062. break;
  28063. }
  28064. return 0;
  28065. }
  28066. }
  28067. // handles callbacks for a specific plugin
  28068. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28069. {
  28070. switch (opcode)
  28071. {
  28072. case audioMasterAutomate:
  28073. sendParamChangeMessageToListeners (index, opt);
  28074. break;
  28075. case audioMasterProcessEvents:
  28076. handleMidiFromPlugin ((const VstEvents*) ptr);
  28077. break;
  28078. case audioMasterGetTime:
  28079. #if JUCE_MSVC
  28080. #pragma warning (push)
  28081. #pragma warning (disable: 4311)
  28082. #endif
  28083. return (VstIntPtr) &vstHostTime;
  28084. #if JUCE_MSVC
  28085. #pragma warning (pop)
  28086. #endif
  28087. break;
  28088. case audioMasterIdle:
  28089. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28090. {
  28091. ++insideVSTCallback;
  28092. #if JUCE_MAC
  28093. if (getActiveEditor() != 0)
  28094. dispatch (effEditIdle, 0, 0, 0, 0);
  28095. #endif
  28096. juce_callAnyTimersSynchronously();
  28097. handleUpdateNowIfNeeded();
  28098. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28099. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28100. --insideVSTCallback;
  28101. }
  28102. break;
  28103. case audioMasterUpdateDisplay:
  28104. triggerAsyncUpdate();
  28105. break;
  28106. case audioMasterTempoAt:
  28107. // returns (10000 * bpm)
  28108. break;
  28109. case audioMasterNeedIdle:
  28110. startTimer (50);
  28111. break;
  28112. case audioMasterSizeWindow:
  28113. if (getActiveEditor() != 0)
  28114. getActiveEditor()->setSize (index, value);
  28115. return 1;
  28116. case audioMasterGetSampleRate:
  28117. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28118. case audioMasterGetBlockSize:
  28119. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28120. case audioMasterWantMidi:
  28121. wantsMidiMessages = true;
  28122. break;
  28123. case audioMasterGetDirectory:
  28124. #if JUCE_MAC
  28125. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28126. #else
  28127. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  28128. #endif
  28129. case audioMasterGetAutomationState:
  28130. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28131. break;
  28132. // none of these are handled (yet)..
  28133. case audioMasterBeginEdit:
  28134. case audioMasterEndEdit:
  28135. case audioMasterSetTime:
  28136. case audioMasterPinConnected:
  28137. case audioMasterGetParameterQuantization:
  28138. case audioMasterIOChanged:
  28139. case audioMasterGetInputLatency:
  28140. case audioMasterGetOutputLatency:
  28141. case audioMasterGetPreviousPlug:
  28142. case audioMasterGetNextPlug:
  28143. case audioMasterWillReplaceOrAccumulate:
  28144. case audioMasterGetCurrentProcessLevel:
  28145. case audioMasterOfflineStart:
  28146. case audioMasterOfflineRead:
  28147. case audioMasterOfflineWrite:
  28148. case audioMasterOfflineGetCurrentPass:
  28149. case audioMasterOfflineGetCurrentMetaPass:
  28150. case audioMasterVendorSpecific:
  28151. case audioMasterSetIcon:
  28152. case audioMasterGetLanguage:
  28153. case audioMasterOpenWindow:
  28154. case audioMasterCloseWindow:
  28155. break;
  28156. default:
  28157. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28158. }
  28159. return 0;
  28160. }
  28161. // entry point for all callbacks from the plugin
  28162. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28163. {
  28164. try
  28165. {
  28166. if (effect != 0 && effect->resvd2 != 0)
  28167. {
  28168. return ((VSTPluginInstance*)(effect->resvd2))
  28169. ->handleCallback (opcode, index, value, ptr, opt);
  28170. }
  28171. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28172. }
  28173. catch (...)
  28174. {
  28175. return 0;
  28176. }
  28177. }
  28178. const String VSTPluginInstance::getVersion() const
  28179. {
  28180. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28181. String s;
  28182. if (v == 0 || v == -1)
  28183. v = getVersionNumber();
  28184. if (v != 0)
  28185. {
  28186. int versionBits[4];
  28187. int n = 0;
  28188. while (v != 0)
  28189. {
  28190. versionBits [n++] = (v & 0xff);
  28191. v >>= 8;
  28192. }
  28193. s << 'V';
  28194. while (n > 0)
  28195. {
  28196. s << versionBits [--n];
  28197. if (n > 0)
  28198. s << '.';
  28199. }
  28200. }
  28201. return s;
  28202. }
  28203. int VSTPluginInstance::getUID() const
  28204. {
  28205. int uid = effect != 0 ? effect->uniqueID : 0;
  28206. if (uid == 0)
  28207. uid = module->file.hashCode();
  28208. return uid;
  28209. }
  28210. const String VSTPluginInstance::getCategory() const
  28211. {
  28212. const char* result = 0;
  28213. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28214. {
  28215. case kPlugCategEffect: result = "Effect"; break;
  28216. case kPlugCategSynth: result = "Synth"; break;
  28217. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28218. case kPlugCategMastering: result = "Mastering"; break;
  28219. case kPlugCategSpacializer: result = "Spacial"; break;
  28220. case kPlugCategRoomFx: result = "Reverb"; break;
  28221. case kPlugSurroundFx: result = "Surround"; break;
  28222. case kPlugCategRestoration: result = "Restoration"; break;
  28223. case kPlugCategGenerator: result = "Tone generation"; break;
  28224. default: break;
  28225. }
  28226. return result;
  28227. }
  28228. float VSTPluginInstance::getParameter (int index)
  28229. {
  28230. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28231. {
  28232. try
  28233. {
  28234. const ScopedLock sl (lock);
  28235. return effect->getParameter (effect, index);
  28236. }
  28237. catch (...)
  28238. {
  28239. }
  28240. }
  28241. return 0.0f;
  28242. }
  28243. void VSTPluginInstance::setParameter (int index, float newValue)
  28244. {
  28245. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28246. {
  28247. try
  28248. {
  28249. const ScopedLock sl (lock);
  28250. if (effect->getParameter (effect, index) != newValue)
  28251. effect->setParameter (effect, index, newValue);
  28252. }
  28253. catch (...)
  28254. {
  28255. }
  28256. }
  28257. }
  28258. const String VSTPluginInstance::getParameterName (int index)
  28259. {
  28260. if (effect != 0)
  28261. {
  28262. jassert (index >= 0 && index < effect->numParams);
  28263. char nm [256];
  28264. zerostruct (nm);
  28265. dispatch (effGetParamName, index, 0, nm, 0);
  28266. return String (nm).trim();
  28267. }
  28268. return String::empty;
  28269. }
  28270. const String VSTPluginInstance::getParameterLabel (int index) const
  28271. {
  28272. if (effect != 0)
  28273. {
  28274. jassert (index >= 0 && index < effect->numParams);
  28275. char nm [256];
  28276. zerostruct (nm);
  28277. dispatch (effGetParamLabel, index, 0, nm, 0);
  28278. return String (nm).trim();
  28279. }
  28280. return String::empty;
  28281. }
  28282. const String VSTPluginInstance::getParameterText (int index)
  28283. {
  28284. if (effect != 0)
  28285. {
  28286. jassert (index >= 0 && index < effect->numParams);
  28287. char nm [256];
  28288. zerostruct (nm);
  28289. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28290. return String (nm).trim();
  28291. }
  28292. return String::empty;
  28293. }
  28294. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28295. {
  28296. if (effect != 0)
  28297. {
  28298. jassert (index >= 0 && index < effect->numParams);
  28299. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28300. }
  28301. return false;
  28302. }
  28303. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28304. {
  28305. dest.setSize (64 + 4 * getNumParameters());
  28306. dest.fillWith (0);
  28307. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28308. float* const p = (float*) (((char*) dest.getData()) + 64);
  28309. for (int i = 0; i < getNumParameters(); ++i)
  28310. p[i] = getParameter(i);
  28311. }
  28312. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28313. {
  28314. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28315. float* p = (float*) (((char*) m.getData()) + 64);
  28316. for (int i = 0; i < getNumParameters(); ++i)
  28317. setParameter (i, p[i]);
  28318. }
  28319. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28320. {
  28321. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28322. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28323. }
  28324. const String VSTPluginInstance::getProgramName (int index)
  28325. {
  28326. if (index == getCurrentProgram())
  28327. {
  28328. return getCurrentProgramName();
  28329. }
  28330. else if (effect != 0)
  28331. {
  28332. char nm [256];
  28333. zerostruct (nm);
  28334. if (dispatch (effGetProgramNameIndexed,
  28335. jlimit (0, getNumPrograms(), index),
  28336. -1, nm, 0) != 0)
  28337. {
  28338. return String (nm).trim();
  28339. }
  28340. }
  28341. return programNames [index];
  28342. }
  28343. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28344. {
  28345. if (index == getCurrentProgram())
  28346. {
  28347. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28348. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28349. }
  28350. else
  28351. {
  28352. jassertfalse; // xxx not implemented!
  28353. }
  28354. }
  28355. void VSTPluginInstance::updateStoredProgramNames()
  28356. {
  28357. if (effect != 0 && getNumPrograms() > 0)
  28358. {
  28359. char nm [256];
  28360. zerostruct (nm);
  28361. // only do this if the plugin can't use indexed names..
  28362. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28363. {
  28364. const int oldProgram = getCurrentProgram();
  28365. MemoryBlock oldSettings;
  28366. createTempParameterStore (oldSettings);
  28367. for (int i = 0; i < getNumPrograms(); ++i)
  28368. {
  28369. setCurrentProgram (i);
  28370. getCurrentProgramName(); // (this updates the list)
  28371. }
  28372. setCurrentProgram (oldProgram);
  28373. restoreFromTempParameterStore (oldSettings);
  28374. }
  28375. }
  28376. }
  28377. const String VSTPluginInstance::getCurrentProgramName()
  28378. {
  28379. if (effect != 0)
  28380. {
  28381. char nm [256];
  28382. zerostruct (nm);
  28383. dispatch (effGetProgramName, 0, 0, nm, 0);
  28384. const int index = getCurrentProgram();
  28385. if (programNames[index].isEmpty())
  28386. {
  28387. while (programNames.size() < index)
  28388. programNames.add (String::empty);
  28389. programNames.set (index, String (nm).trim());
  28390. }
  28391. return String (nm).trim();
  28392. }
  28393. return String::empty;
  28394. }
  28395. const String VSTPluginInstance::getInputChannelName (int index) const
  28396. {
  28397. if (index >= 0 && index < getNumInputChannels())
  28398. {
  28399. VstPinProperties pinProps;
  28400. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28401. return String (pinProps.label, sizeof (pinProps.label));
  28402. }
  28403. return String::empty;
  28404. }
  28405. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28406. {
  28407. if (index < 0 || index >= getNumInputChannels())
  28408. return false;
  28409. VstPinProperties pinProps;
  28410. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28411. return (pinProps.flags & kVstPinIsStereo) != 0;
  28412. return true;
  28413. }
  28414. const String VSTPluginInstance::getOutputChannelName (int index) const
  28415. {
  28416. if (index >= 0 && index < getNumOutputChannels())
  28417. {
  28418. VstPinProperties pinProps;
  28419. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28420. return String (pinProps.label, sizeof (pinProps.label));
  28421. }
  28422. return String::empty;
  28423. }
  28424. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28425. {
  28426. if (index < 0 || index >= getNumOutputChannels())
  28427. return false;
  28428. VstPinProperties pinProps;
  28429. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28430. return (pinProps.flags & kVstPinIsStereo) != 0;
  28431. return true;
  28432. }
  28433. void VSTPluginInstance::setPower (const bool on)
  28434. {
  28435. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28436. isPowerOn = on;
  28437. }
  28438. const int defaultMaxSizeMB = 64;
  28439. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28440. {
  28441. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28442. }
  28443. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28444. {
  28445. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28446. }
  28447. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28448. {
  28449. loadFromFXBFile (data, sizeInBytes);
  28450. }
  28451. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28452. {
  28453. loadFromFXBFile (data, sizeInBytes);
  28454. }
  28455. VSTPluginFormat::VSTPluginFormat()
  28456. {
  28457. }
  28458. VSTPluginFormat::~VSTPluginFormat()
  28459. {
  28460. }
  28461. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28462. const String& fileOrIdentifier)
  28463. {
  28464. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28465. return;
  28466. PluginDescription desc;
  28467. desc.fileOrIdentifier = fileOrIdentifier;
  28468. desc.uid = 0;
  28469. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28470. if (instance == 0)
  28471. return;
  28472. try
  28473. {
  28474. #if JUCE_MAC
  28475. if (instance->module->resFileId != 0)
  28476. UseResFile (instance->module->resFileId);
  28477. #endif
  28478. instance->fillInPluginDescription (desc);
  28479. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28480. if (category != kPlugCategShell)
  28481. {
  28482. // Normal plugin...
  28483. results.add (new PluginDescription (desc));
  28484. ++insideVSTCallback;
  28485. instance->dispatch (effOpen, 0, 0, 0, 0);
  28486. --insideVSTCallback;
  28487. }
  28488. else
  28489. {
  28490. // It's a shell plugin, so iterate all the subtypes...
  28491. char shellEffectName [64];
  28492. for (;;)
  28493. {
  28494. zerostruct (shellEffectName);
  28495. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28496. if (uid == 0)
  28497. {
  28498. break;
  28499. }
  28500. else
  28501. {
  28502. desc.uid = uid;
  28503. desc.name = shellEffectName;
  28504. desc.descriptiveName = shellEffectName;
  28505. bool alreadyThere = false;
  28506. for (int i = results.size(); --i >= 0;)
  28507. {
  28508. PluginDescription* const d = results.getUnchecked(i);
  28509. if (d->isDuplicateOf (desc))
  28510. {
  28511. alreadyThere = true;
  28512. break;
  28513. }
  28514. }
  28515. if (! alreadyThere)
  28516. results.add (new PluginDescription (desc));
  28517. }
  28518. }
  28519. }
  28520. }
  28521. catch (...)
  28522. {
  28523. // crashed while loading...
  28524. }
  28525. }
  28526. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28527. {
  28528. ScopedPointer <VSTPluginInstance> result;
  28529. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28530. {
  28531. File file (desc.fileOrIdentifier);
  28532. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28533. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28534. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28535. if (module != 0)
  28536. {
  28537. shellUIDToCreate = desc.uid;
  28538. result = new VSTPluginInstance (module);
  28539. if (result->effect != 0)
  28540. {
  28541. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28542. result->initialise();
  28543. }
  28544. else
  28545. {
  28546. result = 0;
  28547. }
  28548. }
  28549. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28550. }
  28551. return result.release();
  28552. }
  28553. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28554. {
  28555. const File f (fileOrIdentifier);
  28556. #if JUCE_MAC
  28557. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28558. return true;
  28559. #if JUCE_PPC
  28560. FSRef fileRef;
  28561. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28562. {
  28563. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28564. if (resFileId != -1)
  28565. {
  28566. const int numEffects = Count1Resources ('aEff');
  28567. CloseResFile (resFileId);
  28568. if (numEffects > 0)
  28569. return true;
  28570. }
  28571. }
  28572. #endif
  28573. return false;
  28574. #elif JUCE_WINDOWS
  28575. return f.existsAsFile() && f.hasFileExtension (".dll");
  28576. #elif JUCE_LINUX
  28577. return f.existsAsFile() && f.hasFileExtension (".so");
  28578. #endif
  28579. }
  28580. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28581. {
  28582. return fileOrIdentifier;
  28583. }
  28584. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28585. {
  28586. return File (desc.fileOrIdentifier).exists();
  28587. }
  28588. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28589. {
  28590. StringArray results;
  28591. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28592. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28593. return results;
  28594. }
  28595. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28596. {
  28597. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28598. // .component or .vst directories.
  28599. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28600. while (iter.next())
  28601. {
  28602. const File f (iter.getFile());
  28603. bool isPlugin = false;
  28604. if (fileMightContainThisPluginType (f.getFullPathName()))
  28605. {
  28606. isPlugin = true;
  28607. results.add (f.getFullPathName());
  28608. }
  28609. if (recursive && (! isPlugin) && f.isDirectory())
  28610. recursiveFileSearch (results, f, true);
  28611. }
  28612. }
  28613. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28614. {
  28615. #if JUCE_MAC
  28616. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28617. #elif JUCE_WINDOWS
  28618. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28619. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28620. #elif JUCE_LINUX
  28621. return FileSearchPath ("/usr/lib/vst");
  28622. #endif
  28623. }
  28624. END_JUCE_NAMESPACE
  28625. #endif
  28626. #undef log
  28627. #endif
  28628. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28629. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28630. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28631. BEGIN_JUCE_NAMESPACE
  28632. AudioProcessor::AudioProcessor()
  28633. : playHead (0),
  28634. sampleRate (0),
  28635. blockSize (0),
  28636. numInputChannels (0),
  28637. numOutputChannels (0),
  28638. latencySamples (0),
  28639. suspended (false),
  28640. nonRealtime (false)
  28641. {
  28642. }
  28643. AudioProcessor::~AudioProcessor()
  28644. {
  28645. // ooh, nasty - the editor should have been deleted before the filter
  28646. // that it refers to is deleted..
  28647. jassert (activeEditor == 0);
  28648. #if JUCE_DEBUG
  28649. // This will fail if you've called beginParameterChangeGesture() for one
  28650. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28651. jassert (changingParams.countNumberOfSetBits() == 0);
  28652. #endif
  28653. }
  28654. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28655. {
  28656. playHead = newPlayHead;
  28657. }
  28658. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28659. {
  28660. const ScopedLock sl (listenerLock);
  28661. listeners.addIfNotAlreadyThere (newListener);
  28662. }
  28663. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28664. {
  28665. const ScopedLock sl (listenerLock);
  28666. listeners.removeValue (listenerToRemove);
  28667. }
  28668. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28669. const int numOuts,
  28670. const double sampleRate_,
  28671. const int blockSize_) throw()
  28672. {
  28673. numInputChannels = numIns;
  28674. numOutputChannels = numOuts;
  28675. sampleRate = sampleRate_;
  28676. blockSize = blockSize_;
  28677. }
  28678. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28679. {
  28680. nonRealtime = nonRealtime_;
  28681. }
  28682. void AudioProcessor::setLatencySamples (const int newLatency)
  28683. {
  28684. if (latencySamples != newLatency)
  28685. {
  28686. latencySamples = newLatency;
  28687. updateHostDisplay();
  28688. }
  28689. }
  28690. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28691. const float newValue)
  28692. {
  28693. setParameter (parameterIndex, newValue);
  28694. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28695. }
  28696. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28697. {
  28698. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28699. for (int i = listeners.size(); --i >= 0;)
  28700. {
  28701. AudioProcessorListener* l;
  28702. {
  28703. const ScopedLock sl (listenerLock);
  28704. l = listeners [i];
  28705. }
  28706. if (l != 0)
  28707. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28708. }
  28709. }
  28710. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28711. {
  28712. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28713. #if JUCE_DEBUG
  28714. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28715. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28716. jassert (! changingParams [parameterIndex]);
  28717. changingParams.setBit (parameterIndex);
  28718. #endif
  28719. for (int i = listeners.size(); --i >= 0;)
  28720. {
  28721. AudioProcessorListener* l;
  28722. {
  28723. const ScopedLock sl (listenerLock);
  28724. l = listeners [i];
  28725. }
  28726. if (l != 0)
  28727. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28728. }
  28729. }
  28730. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28731. {
  28732. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28733. #if JUCE_DEBUG
  28734. // This means you've called endParameterChangeGesture without having previously called
  28735. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28736. // calls matched correctly.
  28737. jassert (changingParams [parameterIndex]);
  28738. changingParams.clearBit (parameterIndex);
  28739. #endif
  28740. for (int i = listeners.size(); --i >= 0;)
  28741. {
  28742. AudioProcessorListener* l;
  28743. {
  28744. const ScopedLock sl (listenerLock);
  28745. l = listeners [i];
  28746. }
  28747. if (l != 0)
  28748. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28749. }
  28750. }
  28751. void AudioProcessor::updateHostDisplay()
  28752. {
  28753. for (int i = listeners.size(); --i >= 0;)
  28754. {
  28755. AudioProcessorListener* l;
  28756. {
  28757. const ScopedLock sl (listenerLock);
  28758. l = listeners [i];
  28759. }
  28760. if (l != 0)
  28761. l->audioProcessorChanged (this);
  28762. }
  28763. }
  28764. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28765. {
  28766. return true;
  28767. }
  28768. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28769. {
  28770. return false;
  28771. }
  28772. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28773. {
  28774. const ScopedLock sl (callbackLock);
  28775. suspended = shouldBeSuspended;
  28776. }
  28777. void AudioProcessor::reset()
  28778. {
  28779. }
  28780. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28781. {
  28782. const ScopedLock sl (callbackLock);
  28783. if (activeEditor == editor)
  28784. activeEditor = 0;
  28785. }
  28786. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28787. {
  28788. if (activeEditor != 0)
  28789. return activeEditor;
  28790. AudioProcessorEditor* const ed = createEditor();
  28791. // You must make your hasEditor() method return a consistent result!
  28792. jassert (hasEditor() == (ed != 0));
  28793. if (ed != 0)
  28794. {
  28795. // you must give your editor comp a size before returning it..
  28796. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28797. const ScopedLock sl (callbackLock);
  28798. activeEditor = ed;
  28799. }
  28800. return ed;
  28801. }
  28802. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28803. {
  28804. getStateInformation (destData);
  28805. }
  28806. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28807. {
  28808. setStateInformation (data, sizeInBytes);
  28809. }
  28810. // magic number to identify memory blocks that we've stored as XML
  28811. const uint32 magicXmlNumber = 0x21324356;
  28812. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28813. JUCE_NAMESPACE::MemoryBlock& destData)
  28814. {
  28815. const String xmlString (xml.createDocument (String::empty, true, false));
  28816. const int stringLength = xmlString.getNumBytesAsUTF8();
  28817. destData.setSize (stringLength + 10);
  28818. char* const d = static_cast<char*> (destData.getData());
  28819. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28820. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28821. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28822. }
  28823. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28824. const int sizeInBytes)
  28825. {
  28826. if (sizeInBytes > 8
  28827. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28828. {
  28829. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28830. if (stringLength > 0)
  28831. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28832. jmin ((sizeInBytes - 8), stringLength)));
  28833. }
  28834. return 0;
  28835. }
  28836. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28837. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28838. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28839. {
  28840. return timeInSeconds == other.timeInSeconds
  28841. && ppqPosition == other.ppqPosition
  28842. && editOriginTime == other.editOriginTime
  28843. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28844. && frameRate == other.frameRate
  28845. && isPlaying == other.isPlaying
  28846. && isRecording == other.isRecording
  28847. && bpm == other.bpm
  28848. && timeSigNumerator == other.timeSigNumerator
  28849. && timeSigDenominator == other.timeSigDenominator;
  28850. }
  28851. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28852. {
  28853. return ! operator== (other);
  28854. }
  28855. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28856. {
  28857. zerostruct (*this);
  28858. timeSigNumerator = 4;
  28859. timeSigDenominator = 4;
  28860. bpm = 120;
  28861. }
  28862. END_JUCE_NAMESPACE
  28863. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28864. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28865. BEGIN_JUCE_NAMESPACE
  28866. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28867. : owner (owner_)
  28868. {
  28869. // the filter must be valid..
  28870. jassert (owner != 0);
  28871. }
  28872. AudioProcessorEditor::~AudioProcessorEditor()
  28873. {
  28874. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28875. // filter for some reason..
  28876. jassert (owner->getActiveEditor() != this);
  28877. }
  28878. END_JUCE_NAMESPACE
  28879. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28880. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28881. BEGIN_JUCE_NAMESPACE
  28882. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28883. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28884. : id (id_),
  28885. processor (processor_),
  28886. isPrepared (false)
  28887. {
  28888. jassert (processor_ != 0);
  28889. }
  28890. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28891. AudioProcessorGraph* const graph)
  28892. {
  28893. if (! isPrepared)
  28894. {
  28895. isPrepared = true;
  28896. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28897. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28898. if (ioProc != 0)
  28899. ioProc->setParentGraph (graph);
  28900. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28901. processor->getNumOutputChannels(),
  28902. sampleRate, blockSize);
  28903. processor->prepareToPlay (sampleRate, blockSize);
  28904. }
  28905. }
  28906. void AudioProcessorGraph::Node::unprepare()
  28907. {
  28908. if (isPrepared)
  28909. {
  28910. isPrepared = false;
  28911. processor->releaseResources();
  28912. }
  28913. }
  28914. AudioProcessorGraph::AudioProcessorGraph()
  28915. : lastNodeId (0),
  28916. renderingBuffers (1, 1),
  28917. currentAudioOutputBuffer (1, 1)
  28918. {
  28919. }
  28920. AudioProcessorGraph::~AudioProcessorGraph()
  28921. {
  28922. clearRenderingSequence();
  28923. clear();
  28924. }
  28925. const String AudioProcessorGraph::getName() const
  28926. {
  28927. return "Audio Graph";
  28928. }
  28929. void AudioProcessorGraph::clear()
  28930. {
  28931. nodes.clear();
  28932. connections.clear();
  28933. triggerAsyncUpdate();
  28934. }
  28935. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28936. {
  28937. for (int i = nodes.size(); --i >= 0;)
  28938. if (nodes.getUnchecked(i)->id == nodeId)
  28939. return nodes.getUnchecked(i);
  28940. return 0;
  28941. }
  28942. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28943. uint32 nodeId)
  28944. {
  28945. if (newProcessor == 0)
  28946. {
  28947. jassertfalse;
  28948. return 0;
  28949. }
  28950. if (nodeId == 0)
  28951. {
  28952. nodeId = ++lastNodeId;
  28953. }
  28954. else
  28955. {
  28956. // you can't add a node with an id that already exists in the graph..
  28957. jassert (getNodeForId (nodeId) == 0);
  28958. removeNode (nodeId);
  28959. }
  28960. lastNodeId = nodeId;
  28961. Node* const n = new Node (nodeId, newProcessor);
  28962. nodes.add (n);
  28963. triggerAsyncUpdate();
  28964. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28965. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28966. if (ioProc != 0)
  28967. ioProc->setParentGraph (this);
  28968. return n;
  28969. }
  28970. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28971. {
  28972. disconnectNode (nodeId);
  28973. for (int i = nodes.size(); --i >= 0;)
  28974. {
  28975. if (nodes.getUnchecked(i)->id == nodeId)
  28976. {
  28977. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28978. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28979. if (ioProc != 0)
  28980. ioProc->setParentGraph (0);
  28981. nodes.remove (i);
  28982. triggerAsyncUpdate();
  28983. return true;
  28984. }
  28985. }
  28986. return false;
  28987. }
  28988. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28989. const int sourceChannelIndex,
  28990. const uint32 destNodeId,
  28991. const int destChannelIndex) const
  28992. {
  28993. for (int i = connections.size(); --i >= 0;)
  28994. {
  28995. const Connection* const c = connections.getUnchecked(i);
  28996. if (c->sourceNodeId == sourceNodeId
  28997. && c->destNodeId == destNodeId
  28998. && c->sourceChannelIndex == sourceChannelIndex
  28999. && c->destChannelIndex == destChannelIndex)
  29000. {
  29001. return c;
  29002. }
  29003. }
  29004. return 0;
  29005. }
  29006. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29007. const uint32 possibleDestNodeId) const
  29008. {
  29009. for (int i = connections.size(); --i >= 0;)
  29010. {
  29011. const Connection* const c = connections.getUnchecked(i);
  29012. if (c->sourceNodeId == possibleSourceNodeId
  29013. && c->destNodeId == possibleDestNodeId)
  29014. {
  29015. return true;
  29016. }
  29017. }
  29018. return false;
  29019. }
  29020. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29021. const int sourceChannelIndex,
  29022. const uint32 destNodeId,
  29023. const int destChannelIndex) const
  29024. {
  29025. if (sourceChannelIndex < 0
  29026. || destChannelIndex < 0
  29027. || sourceNodeId == destNodeId
  29028. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29029. return false;
  29030. const Node* const source = getNodeForId (sourceNodeId);
  29031. if (source == 0
  29032. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29033. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29034. return false;
  29035. const Node* const dest = getNodeForId (destNodeId);
  29036. if (dest == 0
  29037. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29038. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29039. return false;
  29040. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29041. destNodeId, destChannelIndex) == 0;
  29042. }
  29043. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29044. const int sourceChannelIndex,
  29045. const uint32 destNodeId,
  29046. const int destChannelIndex)
  29047. {
  29048. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29049. return false;
  29050. Connection* const c = new Connection();
  29051. c->sourceNodeId = sourceNodeId;
  29052. c->sourceChannelIndex = sourceChannelIndex;
  29053. c->destNodeId = destNodeId;
  29054. c->destChannelIndex = destChannelIndex;
  29055. connections.add (c);
  29056. triggerAsyncUpdate();
  29057. return true;
  29058. }
  29059. void AudioProcessorGraph::removeConnection (const int index)
  29060. {
  29061. connections.remove (index);
  29062. triggerAsyncUpdate();
  29063. }
  29064. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29065. const uint32 destNodeId, const int destChannelIndex)
  29066. {
  29067. bool doneAnything = false;
  29068. for (int i = connections.size(); --i >= 0;)
  29069. {
  29070. const Connection* const c = connections.getUnchecked(i);
  29071. if (c->sourceNodeId == sourceNodeId
  29072. && c->destNodeId == destNodeId
  29073. && c->sourceChannelIndex == sourceChannelIndex
  29074. && c->destChannelIndex == destChannelIndex)
  29075. {
  29076. removeConnection (i);
  29077. doneAnything = true;
  29078. triggerAsyncUpdate();
  29079. }
  29080. }
  29081. return doneAnything;
  29082. }
  29083. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29084. {
  29085. bool doneAnything = false;
  29086. for (int i = connections.size(); --i >= 0;)
  29087. {
  29088. const Connection* const c = connections.getUnchecked(i);
  29089. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29090. {
  29091. removeConnection (i);
  29092. doneAnything = true;
  29093. triggerAsyncUpdate();
  29094. }
  29095. }
  29096. return doneAnything;
  29097. }
  29098. bool AudioProcessorGraph::removeIllegalConnections()
  29099. {
  29100. bool doneAnything = false;
  29101. for (int i = connections.size(); --i >= 0;)
  29102. {
  29103. const Connection* const c = connections.getUnchecked(i);
  29104. const Node* const source = getNodeForId (c->sourceNodeId);
  29105. const Node* const dest = getNodeForId (c->destNodeId);
  29106. if (source == 0 || dest == 0
  29107. || (c->sourceChannelIndex != midiChannelIndex
  29108. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29109. || (c->sourceChannelIndex == midiChannelIndex
  29110. && ! source->processor->producesMidi())
  29111. || (c->destChannelIndex != midiChannelIndex
  29112. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29113. || (c->destChannelIndex == midiChannelIndex
  29114. && ! dest->processor->acceptsMidi()))
  29115. {
  29116. removeConnection (i);
  29117. doneAnything = true;
  29118. triggerAsyncUpdate();
  29119. }
  29120. }
  29121. return doneAnything;
  29122. }
  29123. namespace GraphRenderingOps
  29124. {
  29125. class AudioGraphRenderingOp
  29126. {
  29127. public:
  29128. AudioGraphRenderingOp() {}
  29129. virtual ~AudioGraphRenderingOp() {}
  29130. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29131. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29132. const int numSamples) = 0;
  29133. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29134. };
  29135. class ClearChannelOp : public AudioGraphRenderingOp
  29136. {
  29137. public:
  29138. ClearChannelOp (const int channelNum_)
  29139. : channelNum (channelNum_)
  29140. {}
  29141. ~ClearChannelOp() {}
  29142. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29143. {
  29144. sharedBufferChans.clear (channelNum, 0, numSamples);
  29145. }
  29146. private:
  29147. const int channelNum;
  29148. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29149. };
  29150. class CopyChannelOp : public AudioGraphRenderingOp
  29151. {
  29152. public:
  29153. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29154. : srcChannelNum (srcChannelNum_),
  29155. dstChannelNum (dstChannelNum_)
  29156. {}
  29157. ~CopyChannelOp() {}
  29158. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29159. {
  29160. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29161. }
  29162. private:
  29163. const int srcChannelNum, dstChannelNum;
  29164. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29165. };
  29166. class AddChannelOp : public AudioGraphRenderingOp
  29167. {
  29168. public:
  29169. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29170. : srcChannelNum (srcChannelNum_),
  29171. dstChannelNum (dstChannelNum_)
  29172. {}
  29173. ~AddChannelOp() {}
  29174. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29175. {
  29176. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29177. }
  29178. private:
  29179. const int srcChannelNum, dstChannelNum;
  29180. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29181. };
  29182. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29183. {
  29184. public:
  29185. ClearMidiBufferOp (const int bufferNum_)
  29186. : bufferNum (bufferNum_)
  29187. {}
  29188. ~ClearMidiBufferOp() {}
  29189. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29190. {
  29191. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29192. }
  29193. private:
  29194. const int bufferNum;
  29195. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29196. };
  29197. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29198. {
  29199. public:
  29200. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29201. : srcBufferNum (srcBufferNum_),
  29202. dstBufferNum (dstBufferNum_)
  29203. {}
  29204. ~CopyMidiBufferOp() {}
  29205. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29206. {
  29207. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29208. }
  29209. private:
  29210. const int srcBufferNum, dstBufferNum;
  29211. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29212. };
  29213. class AddMidiBufferOp : public AudioGraphRenderingOp
  29214. {
  29215. public:
  29216. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29217. : srcBufferNum (srcBufferNum_),
  29218. dstBufferNum (dstBufferNum_)
  29219. {}
  29220. ~AddMidiBufferOp() {}
  29221. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29222. {
  29223. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29224. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29225. }
  29226. private:
  29227. const int srcBufferNum, dstBufferNum;
  29228. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29229. };
  29230. class ProcessBufferOp : public AudioGraphRenderingOp
  29231. {
  29232. public:
  29233. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29234. const Array <int>& audioChannelsToUse_,
  29235. const int totalChans_,
  29236. const int midiBufferToUse_)
  29237. : node (node_),
  29238. processor (node_->getProcessor()),
  29239. audioChannelsToUse (audioChannelsToUse_),
  29240. totalChans (jmax (1, totalChans_)),
  29241. midiBufferToUse (midiBufferToUse_)
  29242. {
  29243. channels.calloc (totalChans);
  29244. while (audioChannelsToUse.size() < totalChans)
  29245. audioChannelsToUse.add (0);
  29246. }
  29247. ~ProcessBufferOp()
  29248. {
  29249. }
  29250. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29251. {
  29252. for (int i = totalChans; --i >= 0;)
  29253. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29254. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29255. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29256. }
  29257. const AudioProcessorGraph::Node::Ptr node;
  29258. AudioProcessor* const processor;
  29259. private:
  29260. Array <int> audioChannelsToUse;
  29261. HeapBlock <float*> channels;
  29262. int totalChans;
  29263. int midiBufferToUse;
  29264. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29265. };
  29266. /** Used to calculate the correct sequence of rendering ops needed, based on
  29267. the best re-use of shared buffers at each stage.
  29268. */
  29269. class RenderingOpSequenceCalculator
  29270. {
  29271. public:
  29272. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29273. const Array<void*>& orderedNodes_,
  29274. Array<void*>& renderingOps)
  29275. : graph (graph_),
  29276. orderedNodes (orderedNodes_)
  29277. {
  29278. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29279. channels.add (0);
  29280. midiNodeIds.add ((uint32) zeroNodeID);
  29281. for (int i = 0; i < orderedNodes.size(); ++i)
  29282. {
  29283. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29284. renderingOps, i);
  29285. markAnyUnusedBuffersAsFree (i);
  29286. }
  29287. }
  29288. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29289. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29290. private:
  29291. AudioProcessorGraph& graph;
  29292. const Array<void*>& orderedNodes;
  29293. Array <int> channels;
  29294. Array <uint32> nodeIds, midiNodeIds;
  29295. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29296. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29297. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29298. Array<void*>& renderingOps,
  29299. const int ourRenderingIndex)
  29300. {
  29301. const int numIns = node->getProcessor()->getNumInputChannels();
  29302. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29303. const int totalChans = jmax (numIns, numOuts);
  29304. Array <int> audioChannelsToUse;
  29305. int midiBufferToUse = -1;
  29306. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29307. {
  29308. // get a list of all the inputs to this node
  29309. Array <int> sourceNodes, sourceOutputChans;
  29310. for (int i = graph.getNumConnections(); --i >= 0;)
  29311. {
  29312. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29313. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29314. {
  29315. sourceNodes.add (c->sourceNodeId);
  29316. sourceOutputChans.add (c->sourceChannelIndex);
  29317. }
  29318. }
  29319. int bufIndex = -1;
  29320. if (sourceNodes.size() == 0)
  29321. {
  29322. // unconnected input channel
  29323. if (inputChan >= numOuts)
  29324. {
  29325. bufIndex = getReadOnlyEmptyBuffer();
  29326. jassert (bufIndex >= 0);
  29327. }
  29328. else
  29329. {
  29330. bufIndex = getFreeBuffer (false);
  29331. renderingOps.add (new ClearChannelOp (bufIndex));
  29332. }
  29333. }
  29334. else if (sourceNodes.size() == 1)
  29335. {
  29336. // channel with a straightforward single input..
  29337. const int srcNode = sourceNodes.getUnchecked(0);
  29338. const int srcChan = sourceOutputChans.getUnchecked(0);
  29339. bufIndex = getBufferContaining (srcNode, srcChan);
  29340. if (bufIndex < 0)
  29341. {
  29342. // if not found, this is probably a feedback loop
  29343. bufIndex = getReadOnlyEmptyBuffer();
  29344. jassert (bufIndex >= 0);
  29345. }
  29346. if (inputChan < numOuts
  29347. && isBufferNeededLater (ourRenderingIndex,
  29348. inputChan,
  29349. srcNode, srcChan))
  29350. {
  29351. // can't mess up this channel because it's needed later by another node, so we
  29352. // need to use a copy of it..
  29353. const int newFreeBuffer = getFreeBuffer (false);
  29354. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29355. bufIndex = newFreeBuffer;
  29356. }
  29357. }
  29358. else
  29359. {
  29360. // channel with a mix of several inputs..
  29361. // try to find a re-usable channel from our inputs..
  29362. int reusableInputIndex = -1;
  29363. for (int i = 0; i < sourceNodes.size(); ++i)
  29364. {
  29365. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29366. sourceOutputChans.getUnchecked(i));
  29367. if (sourceBufIndex >= 0
  29368. && ! isBufferNeededLater (ourRenderingIndex,
  29369. inputChan,
  29370. sourceNodes.getUnchecked(i),
  29371. sourceOutputChans.getUnchecked(i)))
  29372. {
  29373. // we've found one of our input chans that can be re-used..
  29374. reusableInputIndex = i;
  29375. bufIndex = sourceBufIndex;
  29376. break;
  29377. }
  29378. }
  29379. if (reusableInputIndex < 0)
  29380. {
  29381. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29382. bufIndex = getFreeBuffer (false);
  29383. jassert (bufIndex != 0);
  29384. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29385. sourceOutputChans.getUnchecked (0));
  29386. if (srcIndex < 0)
  29387. {
  29388. // if not found, this is probably a feedback loop
  29389. renderingOps.add (new ClearChannelOp (bufIndex));
  29390. }
  29391. else
  29392. {
  29393. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29394. }
  29395. reusableInputIndex = 0;
  29396. }
  29397. for (int j = 0; j < sourceNodes.size(); ++j)
  29398. {
  29399. if (j != reusableInputIndex)
  29400. {
  29401. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29402. sourceOutputChans.getUnchecked(j));
  29403. if (srcIndex >= 0)
  29404. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29405. }
  29406. }
  29407. }
  29408. jassert (bufIndex >= 0);
  29409. audioChannelsToUse.add (bufIndex);
  29410. if (inputChan < numOuts)
  29411. markBufferAsContaining (bufIndex, node->id, inputChan);
  29412. }
  29413. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29414. {
  29415. const int bufIndex = getFreeBuffer (false);
  29416. jassert (bufIndex != 0);
  29417. audioChannelsToUse.add (bufIndex);
  29418. markBufferAsContaining (bufIndex, node->id, outputChan);
  29419. }
  29420. // Now the same thing for midi..
  29421. Array <int> midiSourceNodes;
  29422. for (int i = graph.getNumConnections(); --i >= 0;)
  29423. {
  29424. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29425. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29426. midiSourceNodes.add (c->sourceNodeId);
  29427. }
  29428. if (midiSourceNodes.size() == 0)
  29429. {
  29430. // No midi inputs..
  29431. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29432. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29433. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29434. }
  29435. else if (midiSourceNodes.size() == 1)
  29436. {
  29437. // One midi input..
  29438. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29439. AudioProcessorGraph::midiChannelIndex);
  29440. if (midiBufferToUse >= 0)
  29441. {
  29442. if (isBufferNeededLater (ourRenderingIndex,
  29443. AudioProcessorGraph::midiChannelIndex,
  29444. midiSourceNodes.getUnchecked(0),
  29445. AudioProcessorGraph::midiChannelIndex))
  29446. {
  29447. // can't mess up this channel because it's needed later by another node, so we
  29448. // need to use a copy of it..
  29449. const int newFreeBuffer = getFreeBuffer (true);
  29450. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29451. midiBufferToUse = newFreeBuffer;
  29452. }
  29453. }
  29454. else
  29455. {
  29456. // probably a feedback loop, so just use an empty one..
  29457. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29458. }
  29459. }
  29460. else
  29461. {
  29462. // More than one midi input being mixed..
  29463. int reusableInputIndex = -1;
  29464. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29465. {
  29466. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29467. AudioProcessorGraph::midiChannelIndex);
  29468. if (sourceBufIndex >= 0
  29469. && ! isBufferNeededLater (ourRenderingIndex,
  29470. AudioProcessorGraph::midiChannelIndex,
  29471. midiSourceNodes.getUnchecked(i),
  29472. AudioProcessorGraph::midiChannelIndex))
  29473. {
  29474. // we've found one of our input buffers that can be re-used..
  29475. reusableInputIndex = i;
  29476. midiBufferToUse = sourceBufIndex;
  29477. break;
  29478. }
  29479. }
  29480. if (reusableInputIndex < 0)
  29481. {
  29482. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29483. midiBufferToUse = getFreeBuffer (true);
  29484. jassert (midiBufferToUse >= 0);
  29485. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29486. AudioProcessorGraph::midiChannelIndex);
  29487. if (srcIndex >= 0)
  29488. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29489. else
  29490. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29491. reusableInputIndex = 0;
  29492. }
  29493. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29494. {
  29495. if (j != reusableInputIndex)
  29496. {
  29497. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29498. AudioProcessorGraph::midiChannelIndex);
  29499. if (srcIndex >= 0)
  29500. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29501. }
  29502. }
  29503. }
  29504. if (node->getProcessor()->producesMidi())
  29505. markBufferAsContaining (midiBufferToUse, node->id,
  29506. AudioProcessorGraph::midiChannelIndex);
  29507. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29508. totalChans, midiBufferToUse));
  29509. }
  29510. int getFreeBuffer (const bool forMidi)
  29511. {
  29512. if (forMidi)
  29513. {
  29514. for (int i = 1; i < midiNodeIds.size(); ++i)
  29515. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29516. return i;
  29517. midiNodeIds.add ((uint32) freeNodeID);
  29518. return midiNodeIds.size() - 1;
  29519. }
  29520. else
  29521. {
  29522. for (int i = 1; i < nodeIds.size(); ++i)
  29523. if (nodeIds.getUnchecked(i) == freeNodeID)
  29524. return i;
  29525. nodeIds.add ((uint32) freeNodeID);
  29526. channels.add (0);
  29527. return nodeIds.size() - 1;
  29528. }
  29529. }
  29530. int getReadOnlyEmptyBuffer() const
  29531. {
  29532. return 0;
  29533. }
  29534. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29535. {
  29536. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29537. {
  29538. for (int i = midiNodeIds.size(); --i >= 0;)
  29539. if (midiNodeIds.getUnchecked(i) == nodeId)
  29540. return i;
  29541. }
  29542. else
  29543. {
  29544. for (int i = nodeIds.size(); --i >= 0;)
  29545. if (nodeIds.getUnchecked(i) == nodeId
  29546. && channels.getUnchecked(i) == outputChannel)
  29547. return i;
  29548. }
  29549. return -1;
  29550. }
  29551. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29552. {
  29553. int i;
  29554. for (i = 0; i < nodeIds.size(); ++i)
  29555. {
  29556. if (isNodeBusy (nodeIds.getUnchecked(i))
  29557. && ! isBufferNeededLater (stepIndex, -1,
  29558. nodeIds.getUnchecked(i),
  29559. channels.getUnchecked(i)))
  29560. {
  29561. nodeIds.set (i, (uint32) freeNodeID);
  29562. }
  29563. }
  29564. for (i = 0; i < midiNodeIds.size(); ++i)
  29565. {
  29566. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29567. && ! isBufferNeededLater (stepIndex, -1,
  29568. midiNodeIds.getUnchecked(i),
  29569. AudioProcessorGraph::midiChannelIndex))
  29570. {
  29571. midiNodeIds.set (i, (uint32) freeNodeID);
  29572. }
  29573. }
  29574. }
  29575. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29576. int inputChannelOfIndexToIgnore,
  29577. const uint32 nodeId,
  29578. const int outputChanIndex) const
  29579. {
  29580. while (stepIndexToSearchFrom < orderedNodes.size())
  29581. {
  29582. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29583. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29584. {
  29585. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29586. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29587. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29588. return true;
  29589. }
  29590. else
  29591. {
  29592. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29593. if (i != inputChannelOfIndexToIgnore
  29594. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29595. node->id, i) != 0)
  29596. return true;
  29597. }
  29598. inputChannelOfIndexToIgnore = -1;
  29599. ++stepIndexToSearchFrom;
  29600. }
  29601. return false;
  29602. }
  29603. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29604. {
  29605. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29606. {
  29607. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29608. midiNodeIds.set (bufferNum, nodeId);
  29609. }
  29610. else
  29611. {
  29612. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29613. nodeIds.set (bufferNum, nodeId);
  29614. channels.set (bufferNum, outputIndex);
  29615. }
  29616. }
  29617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29618. };
  29619. }
  29620. void AudioProcessorGraph::clearRenderingSequence()
  29621. {
  29622. const ScopedLock sl (renderLock);
  29623. for (int i = renderingOps.size(); --i >= 0;)
  29624. {
  29625. GraphRenderingOps::AudioGraphRenderingOp* const r
  29626. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29627. renderingOps.remove (i);
  29628. delete r;
  29629. }
  29630. }
  29631. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29632. const uint32 possibleDestinationId,
  29633. const int recursionCheck) const
  29634. {
  29635. if (recursionCheck > 0)
  29636. {
  29637. for (int i = connections.size(); --i >= 0;)
  29638. {
  29639. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29640. if (c->destNodeId == possibleDestinationId
  29641. && (c->sourceNodeId == possibleInputId
  29642. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29643. return true;
  29644. }
  29645. }
  29646. return false;
  29647. }
  29648. void AudioProcessorGraph::buildRenderingSequence()
  29649. {
  29650. Array<void*> newRenderingOps;
  29651. int numRenderingBuffersNeeded = 2;
  29652. int numMidiBuffersNeeded = 1;
  29653. {
  29654. MessageManagerLock mml;
  29655. Array<void*> orderedNodes;
  29656. int i;
  29657. for (i = 0; i < nodes.size(); ++i)
  29658. {
  29659. Node* const node = nodes.getUnchecked(i);
  29660. node->prepare (getSampleRate(), getBlockSize(), this);
  29661. int j = 0;
  29662. for (; j < orderedNodes.size(); ++j)
  29663. if (isAnInputTo (node->id,
  29664. ((Node*) orderedNodes.getUnchecked (j))->id,
  29665. nodes.size() + 1))
  29666. break;
  29667. orderedNodes.insert (j, node);
  29668. }
  29669. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29670. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29671. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29672. }
  29673. Array<void*> oldRenderingOps (renderingOps);
  29674. {
  29675. // swap over to the new rendering sequence..
  29676. const ScopedLock sl (renderLock);
  29677. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29678. renderingBuffers.clear();
  29679. for (int i = midiBuffers.size(); --i >= 0;)
  29680. midiBuffers.getUnchecked(i)->clear();
  29681. while (midiBuffers.size() < numMidiBuffersNeeded)
  29682. midiBuffers.add (new MidiBuffer());
  29683. renderingOps = newRenderingOps;
  29684. }
  29685. for (int i = oldRenderingOps.size(); --i >= 0;)
  29686. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29687. }
  29688. void AudioProcessorGraph::handleAsyncUpdate()
  29689. {
  29690. buildRenderingSequence();
  29691. }
  29692. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29693. {
  29694. currentAudioInputBuffer = 0;
  29695. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29696. currentMidiInputBuffer = 0;
  29697. currentMidiOutputBuffer.clear();
  29698. clearRenderingSequence();
  29699. buildRenderingSequence();
  29700. }
  29701. void AudioProcessorGraph::releaseResources()
  29702. {
  29703. for (int i = 0; i < nodes.size(); ++i)
  29704. nodes.getUnchecked(i)->unprepare();
  29705. renderingBuffers.setSize (1, 1);
  29706. midiBuffers.clear();
  29707. currentAudioInputBuffer = 0;
  29708. currentAudioOutputBuffer.setSize (1, 1);
  29709. currentMidiInputBuffer = 0;
  29710. currentMidiOutputBuffer.clear();
  29711. }
  29712. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29713. {
  29714. const int numSamples = buffer.getNumSamples();
  29715. const ScopedLock sl (renderLock);
  29716. currentAudioInputBuffer = &buffer;
  29717. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29718. currentAudioOutputBuffer.clear();
  29719. currentMidiInputBuffer = &midiMessages;
  29720. currentMidiOutputBuffer.clear();
  29721. int i;
  29722. for (i = 0; i < renderingOps.size(); ++i)
  29723. {
  29724. GraphRenderingOps::AudioGraphRenderingOp* const op
  29725. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29726. op->perform (renderingBuffers, midiBuffers, numSamples);
  29727. }
  29728. for (i = 0; i < buffer.getNumChannels(); ++i)
  29729. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29730. midiMessages.clear();
  29731. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29732. }
  29733. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29734. {
  29735. return "Input " + String (channelIndex + 1);
  29736. }
  29737. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29738. {
  29739. return "Output " + String (channelIndex + 1);
  29740. }
  29741. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29742. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29743. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29744. bool AudioProcessorGraph::producesMidi() const { return true; }
  29745. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29746. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29747. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29748. : type (type_),
  29749. graph (0)
  29750. {
  29751. }
  29752. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29753. {
  29754. }
  29755. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29756. {
  29757. switch (type)
  29758. {
  29759. case audioOutputNode: return "Audio Output";
  29760. case audioInputNode: return "Audio Input";
  29761. case midiOutputNode: return "Midi Output";
  29762. case midiInputNode: return "Midi Input";
  29763. default: break;
  29764. }
  29765. return String::empty;
  29766. }
  29767. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29768. {
  29769. d.name = getName();
  29770. d.uid = d.name.hashCode();
  29771. d.category = "I/O devices";
  29772. d.pluginFormatName = "Internal";
  29773. d.manufacturerName = "Raw Material Software";
  29774. d.version = "1.0";
  29775. d.isInstrument = false;
  29776. d.numInputChannels = getNumInputChannels();
  29777. if (type == audioOutputNode && graph != 0)
  29778. d.numInputChannels = graph->getNumInputChannels();
  29779. d.numOutputChannels = getNumOutputChannels();
  29780. if (type == audioInputNode && graph != 0)
  29781. d.numOutputChannels = graph->getNumOutputChannels();
  29782. }
  29783. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29784. {
  29785. jassert (graph != 0);
  29786. }
  29787. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29788. {
  29789. }
  29790. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29791. MidiBuffer& midiMessages)
  29792. {
  29793. jassert (graph != 0);
  29794. switch (type)
  29795. {
  29796. case audioOutputNode:
  29797. {
  29798. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29799. buffer.getNumChannels()); --i >= 0;)
  29800. {
  29801. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29802. }
  29803. break;
  29804. }
  29805. case audioInputNode:
  29806. {
  29807. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29808. buffer.getNumChannels()); --i >= 0;)
  29809. {
  29810. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29811. }
  29812. break;
  29813. }
  29814. case midiOutputNode:
  29815. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29816. break;
  29817. case midiInputNode:
  29818. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29819. break;
  29820. default:
  29821. break;
  29822. }
  29823. }
  29824. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29825. {
  29826. return type == midiOutputNode;
  29827. }
  29828. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29829. {
  29830. return type == midiInputNode;
  29831. }
  29832. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29833. {
  29834. switch (type)
  29835. {
  29836. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29837. case midiOutputNode: return "Midi Output";
  29838. default: break;
  29839. }
  29840. return String::empty;
  29841. }
  29842. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29843. {
  29844. switch (type)
  29845. {
  29846. case audioInputNode: return "Input " + String (channelIndex + 1);
  29847. case midiInputNode: return "Midi Input";
  29848. default: break;
  29849. }
  29850. return String::empty;
  29851. }
  29852. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29853. {
  29854. return type == audioInputNode || type == audioOutputNode;
  29855. }
  29856. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29857. {
  29858. return isInputChannelStereoPair (index);
  29859. }
  29860. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29861. {
  29862. return type == audioInputNode || type == midiInputNode;
  29863. }
  29864. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29865. {
  29866. return type == audioOutputNode || type == midiOutputNode;
  29867. }
  29868. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29869. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29870. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29871. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29872. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29873. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29874. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29875. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29876. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29877. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29878. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29879. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29880. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29881. {
  29882. }
  29883. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29884. {
  29885. }
  29886. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29887. {
  29888. graph = newGraph;
  29889. if (graph != 0)
  29890. {
  29891. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29892. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29893. getSampleRate(),
  29894. getBlockSize());
  29895. updateHostDisplay();
  29896. }
  29897. }
  29898. END_JUCE_NAMESPACE
  29899. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29900. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29901. BEGIN_JUCE_NAMESPACE
  29902. AudioProcessorPlayer::AudioProcessorPlayer()
  29903. : processor (0),
  29904. sampleRate (0),
  29905. blockSize (0),
  29906. isPrepared (false),
  29907. numInputChans (0),
  29908. numOutputChans (0),
  29909. tempBuffer (1, 1)
  29910. {
  29911. }
  29912. AudioProcessorPlayer::~AudioProcessorPlayer()
  29913. {
  29914. setProcessor (0);
  29915. }
  29916. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29917. {
  29918. if (processor != processorToPlay)
  29919. {
  29920. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29921. {
  29922. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29923. sampleRate, blockSize);
  29924. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29925. }
  29926. AudioProcessor* oldOne;
  29927. {
  29928. const ScopedLock sl (lock);
  29929. oldOne = isPrepared ? processor : 0;
  29930. processor = processorToPlay;
  29931. isPrepared = true;
  29932. }
  29933. if (oldOne != 0)
  29934. oldOne->releaseResources();
  29935. }
  29936. }
  29937. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29938. const int numInputChannels,
  29939. float** const outputChannelData,
  29940. const int numOutputChannels,
  29941. const int numSamples)
  29942. {
  29943. // these should have been prepared by audioDeviceAboutToStart()...
  29944. jassert (sampleRate > 0 && blockSize > 0);
  29945. incomingMidi.clear();
  29946. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29947. int i, totalNumChans = 0;
  29948. if (numInputChannels > numOutputChannels)
  29949. {
  29950. // if there aren't enough output channels for the number of
  29951. // inputs, we need to create some temporary extra ones (can't
  29952. // use the input data in case it gets written to)
  29953. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29954. false, false, true);
  29955. for (i = 0; i < numOutputChannels; ++i)
  29956. {
  29957. channels[totalNumChans] = outputChannelData[i];
  29958. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29959. ++totalNumChans;
  29960. }
  29961. for (i = numOutputChannels; i < numInputChannels; ++i)
  29962. {
  29963. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29964. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29965. ++totalNumChans;
  29966. }
  29967. }
  29968. else
  29969. {
  29970. for (i = 0; i < numInputChannels; ++i)
  29971. {
  29972. channels[totalNumChans] = outputChannelData[i];
  29973. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29974. ++totalNumChans;
  29975. }
  29976. for (i = numInputChannels; i < numOutputChannels; ++i)
  29977. {
  29978. channels[totalNumChans] = outputChannelData[i];
  29979. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29980. ++totalNumChans;
  29981. }
  29982. }
  29983. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29984. const ScopedLock sl (lock);
  29985. if (processor != 0)
  29986. {
  29987. const ScopedLock sl2 (processor->getCallbackLock());
  29988. if (processor->isSuspended())
  29989. {
  29990. for (i = 0; i < numOutputChannels; ++i)
  29991. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29992. }
  29993. else
  29994. {
  29995. processor->processBlock (buffer, incomingMidi);
  29996. }
  29997. }
  29998. }
  29999. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30000. {
  30001. const ScopedLock sl (lock);
  30002. sampleRate = device->getCurrentSampleRate();
  30003. blockSize = device->getCurrentBufferSizeSamples();
  30004. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30005. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30006. messageCollector.reset (sampleRate);
  30007. zeromem (channels, sizeof (channels));
  30008. if (processor != 0)
  30009. {
  30010. if (isPrepared)
  30011. processor->releaseResources();
  30012. AudioProcessor* const oldProcessor = processor;
  30013. setProcessor (0);
  30014. setProcessor (oldProcessor);
  30015. }
  30016. }
  30017. void AudioProcessorPlayer::audioDeviceStopped()
  30018. {
  30019. const ScopedLock sl (lock);
  30020. if (processor != 0 && isPrepared)
  30021. processor->releaseResources();
  30022. sampleRate = 0.0;
  30023. blockSize = 0;
  30024. isPrepared = false;
  30025. tempBuffer.setSize (1, 1);
  30026. }
  30027. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30028. {
  30029. messageCollector.addMessageToQueue (message);
  30030. }
  30031. END_JUCE_NAMESPACE
  30032. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30033. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30034. BEGIN_JUCE_NAMESPACE
  30035. class ProcessorParameterPropertyComp : public PropertyComponent,
  30036. public AudioProcessorListener,
  30037. public Timer
  30038. {
  30039. public:
  30040. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30041. : PropertyComponent (name),
  30042. owner (owner_),
  30043. index (index_),
  30044. paramHasChanged (false),
  30045. slider (owner_, index_)
  30046. {
  30047. startTimer (100);
  30048. addAndMakeVisible (&slider);
  30049. owner_.addListener (this);
  30050. }
  30051. ~ProcessorParameterPropertyComp()
  30052. {
  30053. owner.removeListener (this);
  30054. }
  30055. void refresh()
  30056. {
  30057. paramHasChanged = false;
  30058. slider.setValue (owner.getParameter (index), false);
  30059. }
  30060. void audioProcessorChanged (AudioProcessor*) {}
  30061. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30062. {
  30063. if (parameterIndex == index)
  30064. paramHasChanged = true;
  30065. }
  30066. void timerCallback()
  30067. {
  30068. if (paramHasChanged)
  30069. {
  30070. refresh();
  30071. startTimer (1000 / 50);
  30072. }
  30073. else
  30074. {
  30075. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30076. }
  30077. }
  30078. private:
  30079. class ParamSlider : public Slider
  30080. {
  30081. public:
  30082. ParamSlider (AudioProcessor& owner_, const int index_)
  30083. : owner (owner_),
  30084. index (index_)
  30085. {
  30086. setRange (0.0, 1.0, 0.0);
  30087. setSliderStyle (Slider::LinearBar);
  30088. setTextBoxIsEditable (false);
  30089. setScrollWheelEnabled (false);
  30090. }
  30091. void valueChanged()
  30092. {
  30093. const float newVal = (float) getValue();
  30094. if (owner.getParameter (index) != newVal)
  30095. owner.setParameter (index, newVal);
  30096. }
  30097. const String getTextFromValue (double /*value*/)
  30098. {
  30099. return owner.getParameterText (index);
  30100. }
  30101. private:
  30102. AudioProcessor& owner;
  30103. const int index;
  30104. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30105. };
  30106. AudioProcessor& owner;
  30107. const int index;
  30108. bool volatile paramHasChanged;
  30109. ParamSlider slider;
  30110. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30111. };
  30112. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30113. : AudioProcessorEditor (owner_)
  30114. {
  30115. jassert (owner_ != 0);
  30116. setOpaque (true);
  30117. addAndMakeVisible (&panel);
  30118. Array <PropertyComponent*> params;
  30119. const int numParams = owner_->getNumParameters();
  30120. int totalHeight = 0;
  30121. for (int i = 0; i < numParams; ++i)
  30122. {
  30123. String name (owner_->getParameterName (i));
  30124. if (name.trim().isEmpty())
  30125. name = "Unnamed";
  30126. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30127. params.add (pc);
  30128. totalHeight += pc->getPreferredHeight();
  30129. }
  30130. panel.addProperties (params);
  30131. setSize (400, jlimit (25, 400, totalHeight));
  30132. }
  30133. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30134. {
  30135. }
  30136. void GenericAudioProcessorEditor::paint (Graphics& g)
  30137. {
  30138. g.fillAll (Colours::white);
  30139. }
  30140. void GenericAudioProcessorEditor::resized()
  30141. {
  30142. panel.setBounds (getLocalBounds());
  30143. }
  30144. END_JUCE_NAMESPACE
  30145. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30146. /*** Start of inlined file: juce_Sampler.cpp ***/
  30147. BEGIN_JUCE_NAMESPACE
  30148. SamplerSound::SamplerSound (const String& name_,
  30149. AudioFormatReader& source,
  30150. const BigInteger& midiNotes_,
  30151. const int midiNoteForNormalPitch,
  30152. const double attackTimeSecs,
  30153. const double releaseTimeSecs,
  30154. const double maxSampleLengthSeconds)
  30155. : name (name_),
  30156. midiNotes (midiNotes_),
  30157. midiRootNote (midiNoteForNormalPitch)
  30158. {
  30159. sourceSampleRate = source.sampleRate;
  30160. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30161. {
  30162. length = 0;
  30163. attackSamples = 0;
  30164. releaseSamples = 0;
  30165. }
  30166. else
  30167. {
  30168. length = jmin ((int) source.lengthInSamples,
  30169. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30170. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30171. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30172. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30173. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30174. }
  30175. }
  30176. SamplerSound::~SamplerSound()
  30177. {
  30178. }
  30179. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30180. {
  30181. return midiNotes [midiNoteNumber];
  30182. }
  30183. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30184. {
  30185. return true;
  30186. }
  30187. SamplerVoice::SamplerVoice()
  30188. : pitchRatio (0.0),
  30189. sourceSamplePosition (0.0),
  30190. lgain (0.0f),
  30191. rgain (0.0f),
  30192. isInAttack (false),
  30193. isInRelease (false)
  30194. {
  30195. }
  30196. SamplerVoice::~SamplerVoice()
  30197. {
  30198. }
  30199. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30200. {
  30201. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30202. }
  30203. void SamplerVoice::startNote (const int midiNoteNumber,
  30204. const float velocity,
  30205. SynthesiserSound* s,
  30206. const int /*currentPitchWheelPosition*/)
  30207. {
  30208. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30209. jassert (sound != 0); // this object can only play SamplerSounds!
  30210. if (sound != 0)
  30211. {
  30212. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30213. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30214. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30215. sourceSamplePosition = 0.0;
  30216. lgain = velocity;
  30217. rgain = velocity;
  30218. isInAttack = (sound->attackSamples > 0);
  30219. isInRelease = false;
  30220. if (isInAttack)
  30221. {
  30222. attackReleaseLevel = 0.0f;
  30223. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30224. }
  30225. else
  30226. {
  30227. attackReleaseLevel = 1.0f;
  30228. attackDelta = 0.0f;
  30229. }
  30230. if (sound->releaseSamples > 0)
  30231. {
  30232. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30233. }
  30234. else
  30235. {
  30236. releaseDelta = 0.0f;
  30237. }
  30238. }
  30239. }
  30240. void SamplerVoice::stopNote (const bool allowTailOff)
  30241. {
  30242. if (allowTailOff)
  30243. {
  30244. isInAttack = false;
  30245. isInRelease = true;
  30246. }
  30247. else
  30248. {
  30249. clearCurrentNote();
  30250. }
  30251. }
  30252. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30253. {
  30254. }
  30255. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30256. const int /*newValue*/)
  30257. {
  30258. }
  30259. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30260. {
  30261. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30262. if (playingSound != 0)
  30263. {
  30264. const float* const inL = playingSound->data->getSampleData (0, 0);
  30265. const float* const inR = playingSound->data->getNumChannels() > 1
  30266. ? playingSound->data->getSampleData (1, 0) : 0;
  30267. float* outL = outputBuffer.getSampleData (0, startSample);
  30268. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30269. while (--numSamples >= 0)
  30270. {
  30271. const int pos = (int) sourceSamplePosition;
  30272. const float alpha = (float) (sourceSamplePosition - pos);
  30273. const float invAlpha = 1.0f - alpha;
  30274. // just using a very simple linear interpolation here..
  30275. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30276. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30277. : l;
  30278. l *= lgain;
  30279. r *= rgain;
  30280. if (isInAttack)
  30281. {
  30282. l *= attackReleaseLevel;
  30283. r *= attackReleaseLevel;
  30284. attackReleaseLevel += attackDelta;
  30285. if (attackReleaseLevel >= 1.0f)
  30286. {
  30287. attackReleaseLevel = 1.0f;
  30288. isInAttack = false;
  30289. }
  30290. }
  30291. else if (isInRelease)
  30292. {
  30293. l *= attackReleaseLevel;
  30294. r *= attackReleaseLevel;
  30295. attackReleaseLevel += releaseDelta;
  30296. if (attackReleaseLevel <= 0.0f)
  30297. {
  30298. stopNote (false);
  30299. break;
  30300. }
  30301. }
  30302. if (outR != 0)
  30303. {
  30304. *outL++ += l;
  30305. *outR++ += r;
  30306. }
  30307. else
  30308. {
  30309. *outL++ += (l + r) * 0.5f;
  30310. }
  30311. sourceSamplePosition += pitchRatio;
  30312. if (sourceSamplePosition > playingSound->length)
  30313. {
  30314. stopNote (false);
  30315. break;
  30316. }
  30317. }
  30318. }
  30319. }
  30320. END_JUCE_NAMESPACE
  30321. /*** End of inlined file: juce_Sampler.cpp ***/
  30322. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30323. BEGIN_JUCE_NAMESPACE
  30324. SynthesiserSound::SynthesiserSound()
  30325. {
  30326. }
  30327. SynthesiserSound::~SynthesiserSound()
  30328. {
  30329. }
  30330. SynthesiserVoice::SynthesiserVoice()
  30331. : currentSampleRate (44100.0),
  30332. currentlyPlayingNote (-1),
  30333. noteOnTime (0),
  30334. currentlyPlayingSound (0)
  30335. {
  30336. }
  30337. SynthesiserVoice::~SynthesiserVoice()
  30338. {
  30339. }
  30340. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30341. {
  30342. return currentlyPlayingSound != 0
  30343. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30344. }
  30345. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30346. {
  30347. currentSampleRate = newRate;
  30348. }
  30349. void SynthesiserVoice::clearCurrentNote()
  30350. {
  30351. currentlyPlayingNote = -1;
  30352. currentlyPlayingSound = 0;
  30353. }
  30354. Synthesiser::Synthesiser()
  30355. : sampleRate (0),
  30356. lastNoteOnCounter (0),
  30357. shouldStealNotes (true)
  30358. {
  30359. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30360. lastPitchWheelValues[i] = 0x2000;
  30361. }
  30362. Synthesiser::~Synthesiser()
  30363. {
  30364. }
  30365. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30366. {
  30367. const ScopedLock sl (lock);
  30368. return voices [index];
  30369. }
  30370. void Synthesiser::clearVoices()
  30371. {
  30372. const ScopedLock sl (lock);
  30373. voices.clear();
  30374. }
  30375. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30376. {
  30377. const ScopedLock sl (lock);
  30378. voices.add (newVoice);
  30379. }
  30380. void Synthesiser::removeVoice (const int index)
  30381. {
  30382. const ScopedLock sl (lock);
  30383. voices.remove (index);
  30384. }
  30385. void Synthesiser::clearSounds()
  30386. {
  30387. const ScopedLock sl (lock);
  30388. sounds.clear();
  30389. }
  30390. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30391. {
  30392. const ScopedLock sl (lock);
  30393. sounds.add (newSound);
  30394. }
  30395. void Synthesiser::removeSound (const int index)
  30396. {
  30397. const ScopedLock sl (lock);
  30398. sounds.remove (index);
  30399. }
  30400. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30401. {
  30402. shouldStealNotes = shouldStealNotes_;
  30403. }
  30404. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30405. {
  30406. if (sampleRate != newRate)
  30407. {
  30408. const ScopedLock sl (lock);
  30409. allNotesOff (0, false);
  30410. sampleRate = newRate;
  30411. for (int i = voices.size(); --i >= 0;)
  30412. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30413. }
  30414. }
  30415. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30416. const MidiBuffer& midiData,
  30417. int startSample,
  30418. int numSamples)
  30419. {
  30420. // must set the sample rate before using this!
  30421. jassert (sampleRate != 0);
  30422. const ScopedLock sl (lock);
  30423. MidiBuffer::Iterator midiIterator (midiData);
  30424. midiIterator.setNextSamplePosition (startSample);
  30425. MidiMessage m (0xf4, 0.0);
  30426. while (numSamples > 0)
  30427. {
  30428. int midiEventPos;
  30429. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30430. && midiEventPos < startSample + numSamples;
  30431. const int numThisTime = useEvent ? midiEventPos - startSample
  30432. : numSamples;
  30433. if (numThisTime > 0)
  30434. {
  30435. for (int i = voices.size(); --i >= 0;)
  30436. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30437. }
  30438. if (useEvent)
  30439. {
  30440. if (m.isNoteOn())
  30441. {
  30442. const int channel = m.getChannel();
  30443. noteOn (channel,
  30444. m.getNoteNumber(),
  30445. m.getFloatVelocity());
  30446. }
  30447. else if (m.isNoteOff())
  30448. {
  30449. noteOff (m.getChannel(),
  30450. m.getNoteNumber(),
  30451. true);
  30452. }
  30453. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30454. {
  30455. allNotesOff (m.getChannel(), true);
  30456. }
  30457. else if (m.isPitchWheel())
  30458. {
  30459. const int channel = m.getChannel();
  30460. const int wheelPos = m.getPitchWheelValue();
  30461. lastPitchWheelValues [channel - 1] = wheelPos;
  30462. handlePitchWheel (channel, wheelPos);
  30463. }
  30464. else if (m.isController())
  30465. {
  30466. handleController (m.getChannel(),
  30467. m.getControllerNumber(),
  30468. m.getControllerValue());
  30469. }
  30470. }
  30471. startSample += numThisTime;
  30472. numSamples -= numThisTime;
  30473. }
  30474. }
  30475. void Synthesiser::noteOn (const int midiChannel,
  30476. const int midiNoteNumber,
  30477. const float velocity)
  30478. {
  30479. const ScopedLock sl (lock);
  30480. for (int i = sounds.size(); --i >= 0;)
  30481. {
  30482. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30483. if (sound->appliesToNote (midiNoteNumber)
  30484. && sound->appliesToChannel (midiChannel))
  30485. {
  30486. startVoice (findFreeVoice (sound, shouldStealNotes),
  30487. sound, midiChannel, midiNoteNumber, velocity);
  30488. }
  30489. }
  30490. }
  30491. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30492. SynthesiserSound* const sound,
  30493. const int midiChannel,
  30494. const int midiNoteNumber,
  30495. const float velocity)
  30496. {
  30497. if (voice != 0 && sound != 0)
  30498. {
  30499. if (voice->currentlyPlayingSound != 0)
  30500. voice->stopNote (false);
  30501. voice->startNote (midiNoteNumber,
  30502. velocity,
  30503. sound,
  30504. lastPitchWheelValues [midiChannel - 1]);
  30505. voice->currentlyPlayingNote = midiNoteNumber;
  30506. voice->noteOnTime = ++lastNoteOnCounter;
  30507. voice->currentlyPlayingSound = sound;
  30508. }
  30509. }
  30510. void Synthesiser::noteOff (const int midiChannel,
  30511. const int midiNoteNumber,
  30512. const bool allowTailOff)
  30513. {
  30514. const ScopedLock sl (lock);
  30515. for (int i = voices.size(); --i >= 0;)
  30516. {
  30517. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30518. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30519. {
  30520. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30521. if (sound != 0
  30522. && sound->appliesToNote (midiNoteNumber)
  30523. && sound->appliesToChannel (midiChannel))
  30524. {
  30525. voice->stopNote (allowTailOff);
  30526. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30527. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30528. }
  30529. }
  30530. }
  30531. }
  30532. void Synthesiser::allNotesOff (const int midiChannel,
  30533. const bool allowTailOff)
  30534. {
  30535. const ScopedLock sl (lock);
  30536. for (int i = voices.size(); --i >= 0;)
  30537. {
  30538. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30539. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30540. voice->stopNote (allowTailOff);
  30541. }
  30542. }
  30543. void Synthesiser::handlePitchWheel (const int midiChannel,
  30544. const int wheelValue)
  30545. {
  30546. const ScopedLock sl (lock);
  30547. for (int i = voices.size(); --i >= 0;)
  30548. {
  30549. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30550. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30551. {
  30552. voice->pitchWheelMoved (wheelValue);
  30553. }
  30554. }
  30555. }
  30556. void Synthesiser::handleController (const int midiChannel,
  30557. const int controllerNumber,
  30558. const int controllerValue)
  30559. {
  30560. const ScopedLock sl (lock);
  30561. for (int i = voices.size(); --i >= 0;)
  30562. {
  30563. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30564. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30565. voice->controllerMoved (controllerNumber, controllerValue);
  30566. }
  30567. }
  30568. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30569. const bool stealIfNoneAvailable) const
  30570. {
  30571. const ScopedLock sl (lock);
  30572. for (int i = voices.size(); --i >= 0;)
  30573. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30574. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30575. return voices.getUnchecked (i);
  30576. if (stealIfNoneAvailable)
  30577. {
  30578. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30579. SynthesiserVoice* oldest = 0;
  30580. for (int i = voices.size(); --i >= 0;)
  30581. {
  30582. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30583. if (voice->canPlaySound (soundToPlay)
  30584. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30585. oldest = voice;
  30586. }
  30587. jassert (oldest != 0);
  30588. return oldest;
  30589. }
  30590. return 0;
  30591. }
  30592. END_JUCE_NAMESPACE
  30593. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30594. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30595. BEGIN_JUCE_NAMESPACE
  30596. // special message of our own with a string in it
  30597. class ActionMessage : public Message
  30598. {
  30599. public:
  30600. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30601. : message (messageText)
  30602. {
  30603. pointerParameter = listener_;
  30604. }
  30605. const String message;
  30606. private:
  30607. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30608. };
  30609. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30610. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30611. {
  30612. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30613. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30614. if (owner->actionListeners.contains (target))
  30615. target->actionListenerCallback (am.message);
  30616. }
  30617. ActionBroadcaster::ActionBroadcaster()
  30618. {
  30619. // are you trying to create this object before or after juce has been intialised??
  30620. jassert (MessageManager::instance != 0);
  30621. callback.owner = this;
  30622. }
  30623. ActionBroadcaster::~ActionBroadcaster()
  30624. {
  30625. // all event-based objects must be deleted BEFORE juce is shut down!
  30626. jassert (MessageManager::instance != 0);
  30627. }
  30628. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30629. {
  30630. const ScopedLock sl (actionListenerLock);
  30631. if (listener != 0)
  30632. actionListeners.add (listener);
  30633. }
  30634. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30635. {
  30636. const ScopedLock sl (actionListenerLock);
  30637. actionListeners.removeValue (listener);
  30638. }
  30639. void ActionBroadcaster::removeAllActionListeners()
  30640. {
  30641. const ScopedLock sl (actionListenerLock);
  30642. actionListeners.clear();
  30643. }
  30644. void ActionBroadcaster::sendActionMessage (const String& message) const
  30645. {
  30646. const ScopedLock sl (actionListenerLock);
  30647. for (int i = actionListeners.size(); --i >= 0;)
  30648. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30649. }
  30650. END_JUCE_NAMESPACE
  30651. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30652. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30653. BEGIN_JUCE_NAMESPACE
  30654. class AsyncUpdaterMessage : public CallbackMessage
  30655. {
  30656. public:
  30657. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30658. : owner (owner_)
  30659. {
  30660. }
  30661. void messageCallback()
  30662. {
  30663. if (shouldDeliver.compareAndSetBool (0, 1))
  30664. owner.handleAsyncUpdate();
  30665. }
  30666. Atomic<int> shouldDeliver;
  30667. private:
  30668. AsyncUpdater& owner;
  30669. };
  30670. AsyncUpdater::AsyncUpdater()
  30671. {
  30672. message = new AsyncUpdaterMessage (*this);
  30673. }
  30674. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30675. {
  30676. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30677. }
  30678. AsyncUpdater::~AsyncUpdater()
  30679. {
  30680. // You're deleting this object with a background thread while there's an update
  30681. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30682. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30683. // deleting this object, or find some other way to avoid such a race condition.
  30684. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30685. getDeliveryFlag().set (0);
  30686. }
  30687. void AsyncUpdater::triggerAsyncUpdate()
  30688. {
  30689. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30690. message->post();
  30691. }
  30692. void AsyncUpdater::cancelPendingUpdate() throw()
  30693. {
  30694. getDeliveryFlag().set (0);
  30695. }
  30696. void AsyncUpdater::handleUpdateNowIfNeeded()
  30697. {
  30698. // This can only be called by the event thread.
  30699. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30700. if (getDeliveryFlag().exchange (0) != 0)
  30701. handleAsyncUpdate();
  30702. }
  30703. bool AsyncUpdater::isUpdatePending() const throw()
  30704. {
  30705. return getDeliveryFlag().value != 0;
  30706. }
  30707. END_JUCE_NAMESPACE
  30708. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30709. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30710. BEGIN_JUCE_NAMESPACE
  30711. ChangeBroadcaster::ChangeBroadcaster() throw()
  30712. {
  30713. // are you trying to create this object before or after juce has been intialised??
  30714. jassert (MessageManager::instance != 0);
  30715. callback.owner = this;
  30716. }
  30717. ChangeBroadcaster::~ChangeBroadcaster()
  30718. {
  30719. // all event-based objects must be deleted BEFORE juce is shut down!
  30720. jassert (MessageManager::instance != 0);
  30721. }
  30722. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30723. {
  30724. // Listeners can only be safely added when the event thread is locked
  30725. // You can use a MessageManagerLock if you need to call this from another thread.
  30726. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30727. changeListeners.add (listener);
  30728. }
  30729. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30730. {
  30731. // Listeners can only be safely added when the event thread is locked
  30732. // You can use a MessageManagerLock if you need to call this from another thread.
  30733. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30734. changeListeners.remove (listener);
  30735. }
  30736. void ChangeBroadcaster::removeAllChangeListeners()
  30737. {
  30738. // Listeners can only be safely added when the event thread is locked
  30739. // You can use a MessageManagerLock if you need to call this from another thread.
  30740. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30741. changeListeners.clear();
  30742. }
  30743. void ChangeBroadcaster::sendChangeMessage()
  30744. {
  30745. if (changeListeners.size() > 0)
  30746. callback.triggerAsyncUpdate();
  30747. }
  30748. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30749. {
  30750. // This can only be called by the event thread.
  30751. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30752. callback.cancelPendingUpdate();
  30753. callListeners();
  30754. }
  30755. void ChangeBroadcaster::dispatchPendingMessages()
  30756. {
  30757. callback.handleUpdateNowIfNeeded();
  30758. }
  30759. void ChangeBroadcaster::callListeners()
  30760. {
  30761. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30762. }
  30763. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30764. : owner (0)
  30765. {
  30766. }
  30767. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30768. {
  30769. jassert (owner != 0);
  30770. owner->callListeners();
  30771. }
  30772. END_JUCE_NAMESPACE
  30773. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30774. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30775. BEGIN_JUCE_NAMESPACE
  30776. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30777. const uint32 magicMessageHeaderNumber)
  30778. : Thread ("Juce IPC connection"),
  30779. callbackConnectionState (false),
  30780. useMessageThread (callbacksOnMessageThread),
  30781. magicMessageHeader (magicMessageHeaderNumber),
  30782. pipeReceiveMessageTimeout (-1)
  30783. {
  30784. }
  30785. InterprocessConnection::~InterprocessConnection()
  30786. {
  30787. callbackConnectionState = false;
  30788. disconnect();
  30789. }
  30790. bool InterprocessConnection::connectToSocket (const String& hostName,
  30791. const int portNumber,
  30792. const int timeOutMillisecs)
  30793. {
  30794. disconnect();
  30795. const ScopedLock sl (pipeAndSocketLock);
  30796. socket = new StreamingSocket();
  30797. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30798. {
  30799. connectionMadeInt();
  30800. startThread();
  30801. return true;
  30802. }
  30803. else
  30804. {
  30805. socket = 0;
  30806. return false;
  30807. }
  30808. }
  30809. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30810. const int pipeReceiveMessageTimeoutMs)
  30811. {
  30812. disconnect();
  30813. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30814. if (newPipe->openExisting (pipeName))
  30815. {
  30816. const ScopedLock sl (pipeAndSocketLock);
  30817. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30818. initialiseWithPipe (newPipe.release());
  30819. return true;
  30820. }
  30821. return false;
  30822. }
  30823. bool InterprocessConnection::createPipe (const String& pipeName,
  30824. const int pipeReceiveMessageTimeoutMs)
  30825. {
  30826. disconnect();
  30827. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30828. if (newPipe->createNewPipe (pipeName))
  30829. {
  30830. const ScopedLock sl (pipeAndSocketLock);
  30831. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30832. initialiseWithPipe (newPipe.release());
  30833. return true;
  30834. }
  30835. return false;
  30836. }
  30837. void InterprocessConnection::disconnect()
  30838. {
  30839. if (socket != 0)
  30840. socket->close();
  30841. if (pipe != 0)
  30842. {
  30843. pipe->cancelPendingReads();
  30844. pipe->close();
  30845. }
  30846. stopThread (4000);
  30847. {
  30848. const ScopedLock sl (pipeAndSocketLock);
  30849. socket = 0;
  30850. pipe = 0;
  30851. }
  30852. connectionLostInt();
  30853. }
  30854. bool InterprocessConnection::isConnected() const
  30855. {
  30856. const ScopedLock sl (pipeAndSocketLock);
  30857. return ((socket != 0 && socket->isConnected())
  30858. || (pipe != 0 && pipe->isOpen()))
  30859. && isThreadRunning();
  30860. }
  30861. const String InterprocessConnection::getConnectedHostName() const
  30862. {
  30863. if (pipe != 0)
  30864. {
  30865. return "localhost";
  30866. }
  30867. else if (socket != 0)
  30868. {
  30869. if (! socket->isLocal())
  30870. return socket->getHostName();
  30871. return "localhost";
  30872. }
  30873. return String::empty;
  30874. }
  30875. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30876. {
  30877. uint32 messageHeader[2];
  30878. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30879. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30880. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30881. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30882. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30883. int bytesWritten = 0;
  30884. const ScopedLock sl (pipeAndSocketLock);
  30885. if (socket != 0)
  30886. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30887. else if (pipe != 0)
  30888. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30889. return bytesWritten == (int) messageData.getSize();
  30890. }
  30891. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30892. {
  30893. jassert (socket == 0);
  30894. socket = socket_;
  30895. connectionMadeInt();
  30896. startThread();
  30897. }
  30898. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30899. {
  30900. jassert (pipe == 0);
  30901. pipe = pipe_;
  30902. connectionMadeInt();
  30903. startThread();
  30904. }
  30905. const int messageMagicNumber = 0xb734128b;
  30906. void InterprocessConnection::handleMessage (const Message& message)
  30907. {
  30908. if (message.intParameter1 == messageMagicNumber)
  30909. {
  30910. switch (message.intParameter2)
  30911. {
  30912. case 0:
  30913. {
  30914. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30915. messageReceived (*data);
  30916. break;
  30917. }
  30918. case 1:
  30919. connectionMade();
  30920. break;
  30921. case 2:
  30922. connectionLost();
  30923. break;
  30924. }
  30925. }
  30926. }
  30927. void InterprocessConnection::connectionMadeInt()
  30928. {
  30929. if (! callbackConnectionState)
  30930. {
  30931. callbackConnectionState = true;
  30932. if (useMessageThread)
  30933. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30934. else
  30935. connectionMade();
  30936. }
  30937. }
  30938. void InterprocessConnection::connectionLostInt()
  30939. {
  30940. if (callbackConnectionState)
  30941. {
  30942. callbackConnectionState = false;
  30943. if (useMessageThread)
  30944. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30945. else
  30946. connectionLost();
  30947. }
  30948. }
  30949. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30950. {
  30951. jassert (callbackConnectionState);
  30952. if (useMessageThread)
  30953. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30954. else
  30955. messageReceived (data);
  30956. }
  30957. bool InterprocessConnection::readNextMessageInt()
  30958. {
  30959. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30960. uint32 messageHeader[2];
  30961. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30962. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30963. if (bytes == sizeof (messageHeader)
  30964. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30965. {
  30966. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30967. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30968. {
  30969. MemoryBlock messageData (bytesInMessage, true);
  30970. int bytesRead = 0;
  30971. while (bytesInMessage > 0)
  30972. {
  30973. if (threadShouldExit())
  30974. return false;
  30975. const int numThisTime = jmin (bytesInMessage, 65536);
  30976. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30977. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30978. if (bytesIn <= 0)
  30979. break;
  30980. bytesRead += bytesIn;
  30981. bytesInMessage -= bytesIn;
  30982. }
  30983. if (bytesRead >= 0)
  30984. deliverDataInt (messageData);
  30985. }
  30986. }
  30987. else if (bytes < 0)
  30988. {
  30989. {
  30990. const ScopedLock sl (pipeAndSocketLock);
  30991. socket = 0;
  30992. }
  30993. connectionLostInt();
  30994. return false;
  30995. }
  30996. return true;
  30997. }
  30998. void InterprocessConnection::run()
  30999. {
  31000. while (! threadShouldExit())
  31001. {
  31002. if (socket != 0)
  31003. {
  31004. const int ready = socket->waitUntilReady (true, 0);
  31005. if (ready < 0)
  31006. {
  31007. {
  31008. const ScopedLock sl (pipeAndSocketLock);
  31009. socket = 0;
  31010. }
  31011. connectionLostInt();
  31012. break;
  31013. }
  31014. else if (ready > 0)
  31015. {
  31016. if (! readNextMessageInt())
  31017. break;
  31018. }
  31019. else
  31020. {
  31021. Thread::sleep (2);
  31022. }
  31023. }
  31024. else if (pipe != 0)
  31025. {
  31026. if (! pipe->isOpen())
  31027. {
  31028. {
  31029. const ScopedLock sl (pipeAndSocketLock);
  31030. pipe = 0;
  31031. }
  31032. connectionLostInt();
  31033. break;
  31034. }
  31035. else
  31036. {
  31037. if (! readNextMessageInt())
  31038. break;
  31039. }
  31040. }
  31041. else
  31042. {
  31043. break;
  31044. }
  31045. }
  31046. }
  31047. END_JUCE_NAMESPACE
  31048. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31049. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31050. BEGIN_JUCE_NAMESPACE
  31051. InterprocessConnectionServer::InterprocessConnectionServer()
  31052. : Thread ("Juce IPC server")
  31053. {
  31054. }
  31055. InterprocessConnectionServer::~InterprocessConnectionServer()
  31056. {
  31057. stop();
  31058. }
  31059. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31060. {
  31061. stop();
  31062. socket = new StreamingSocket();
  31063. if (socket->createListener (portNumber))
  31064. {
  31065. startThread();
  31066. return true;
  31067. }
  31068. socket = 0;
  31069. return false;
  31070. }
  31071. void InterprocessConnectionServer::stop()
  31072. {
  31073. signalThreadShouldExit();
  31074. if (socket != 0)
  31075. socket->close();
  31076. stopThread (4000);
  31077. socket = 0;
  31078. }
  31079. void InterprocessConnectionServer::run()
  31080. {
  31081. while ((! threadShouldExit()) && socket != 0)
  31082. {
  31083. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31084. if (clientSocket != 0)
  31085. {
  31086. InterprocessConnection* newConnection = createConnectionObject();
  31087. if (newConnection != 0)
  31088. newConnection->initialiseWithSocket (clientSocket.release());
  31089. }
  31090. }
  31091. }
  31092. END_JUCE_NAMESPACE
  31093. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31094. /*** Start of inlined file: juce_Message.cpp ***/
  31095. BEGIN_JUCE_NAMESPACE
  31096. Message::Message() throw()
  31097. : intParameter1 (0),
  31098. intParameter2 (0),
  31099. intParameter3 (0),
  31100. pointerParameter (0),
  31101. messageRecipient (0)
  31102. {
  31103. }
  31104. Message::Message (const int intParameter1_,
  31105. const int intParameter2_,
  31106. const int intParameter3_,
  31107. void* const pointerParameter_) throw()
  31108. : intParameter1 (intParameter1_),
  31109. intParameter2 (intParameter2_),
  31110. intParameter3 (intParameter3_),
  31111. pointerParameter (pointerParameter_),
  31112. messageRecipient (0)
  31113. {
  31114. }
  31115. Message::~Message()
  31116. {
  31117. }
  31118. END_JUCE_NAMESPACE
  31119. /*** End of inlined file: juce_Message.cpp ***/
  31120. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31121. BEGIN_JUCE_NAMESPACE
  31122. MessageListener::MessageListener() throw()
  31123. {
  31124. // are you trying to create a messagelistener before or after juce has been intialised??
  31125. jassert (MessageManager::instance != 0);
  31126. if (MessageManager::instance != 0)
  31127. MessageManager::instance->messageListeners.add (this);
  31128. }
  31129. MessageListener::~MessageListener()
  31130. {
  31131. if (MessageManager::instance != 0)
  31132. MessageManager::instance->messageListeners.removeValue (this);
  31133. }
  31134. void MessageListener::postMessage (Message* const message) const throw()
  31135. {
  31136. message->messageRecipient = const_cast <MessageListener*> (this);
  31137. if (MessageManager::instance == 0)
  31138. MessageManager::getInstance();
  31139. MessageManager::instance->postMessageToQueue (message);
  31140. }
  31141. bool MessageListener::isValidMessageListener() const throw()
  31142. {
  31143. return (MessageManager::instance != 0)
  31144. && MessageManager::instance->messageListeners.contains (this);
  31145. }
  31146. END_JUCE_NAMESPACE
  31147. /*** End of inlined file: juce_MessageListener.cpp ***/
  31148. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31149. BEGIN_JUCE_NAMESPACE
  31150. // platform-specific functions..
  31151. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31152. bool juce_postMessageToSystemQueue (Message* message);
  31153. MessageManager* MessageManager::instance = 0;
  31154. static const int quitMessageId = 0xfffff321;
  31155. MessageManager::MessageManager() throw()
  31156. : quitMessagePosted (false),
  31157. quitMessageReceived (false),
  31158. threadWithLock (0)
  31159. {
  31160. messageThreadId = Thread::getCurrentThreadId();
  31161. if (JUCEApplication::isStandaloneApp())
  31162. Thread::setCurrentThreadName ("Juce Message Thread");
  31163. }
  31164. MessageManager::~MessageManager() throw()
  31165. {
  31166. broadcaster = 0;
  31167. doPlatformSpecificShutdown();
  31168. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31169. jassert (messageListeners.size() == 0);
  31170. jassert (instance == this);
  31171. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31172. }
  31173. MessageManager* MessageManager::getInstance() throw()
  31174. {
  31175. if (instance == 0)
  31176. {
  31177. instance = new MessageManager();
  31178. doPlatformSpecificInitialisation();
  31179. }
  31180. return instance;
  31181. }
  31182. void MessageManager::postMessageToQueue (Message* const message)
  31183. {
  31184. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31185. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31186. }
  31187. CallbackMessage::CallbackMessage() throw() {}
  31188. CallbackMessage::~CallbackMessage() {}
  31189. void CallbackMessage::post()
  31190. {
  31191. if (MessageManager::instance != 0)
  31192. MessageManager::instance->postMessageToQueue (this);
  31193. }
  31194. // not for public use..
  31195. void MessageManager::deliverMessage (Message* const message)
  31196. {
  31197. JUCE_TRY
  31198. {
  31199. MessageListener* const recipient = message->messageRecipient;
  31200. if (recipient == 0)
  31201. {
  31202. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31203. if (callbackMessage != 0)
  31204. {
  31205. callbackMessage->messageCallback();
  31206. }
  31207. else if (message->intParameter1 == quitMessageId)
  31208. {
  31209. quitMessageReceived = true;
  31210. }
  31211. }
  31212. else if (messageListeners.contains (recipient))
  31213. {
  31214. recipient->handleMessage (*message);
  31215. }
  31216. }
  31217. JUCE_CATCH_EXCEPTION
  31218. }
  31219. #if JUCE_MODAL_LOOPS_PERMITTED && ! (JUCE_MAC || JUCE_IOS)
  31220. void MessageManager::runDispatchLoop()
  31221. {
  31222. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31223. runDispatchLoopUntil (-1);
  31224. }
  31225. void MessageManager::stopDispatchLoop()
  31226. {
  31227. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31228. quitMessagePosted = true;
  31229. }
  31230. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31231. {
  31232. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31233. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31234. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31235. && ! quitMessageReceived)
  31236. {
  31237. JUCE_TRY
  31238. {
  31239. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31240. {
  31241. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31242. if (msToWait > 0)
  31243. Thread::sleep (jmin (5, msToWait));
  31244. }
  31245. }
  31246. JUCE_CATCH_EXCEPTION
  31247. }
  31248. return ! quitMessageReceived;
  31249. }
  31250. #endif
  31251. void MessageManager::deliverBroadcastMessage (const String& value)
  31252. {
  31253. if (broadcaster != 0)
  31254. broadcaster->sendActionMessage (value);
  31255. }
  31256. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31257. {
  31258. if (broadcaster == 0)
  31259. broadcaster = new ActionBroadcaster();
  31260. broadcaster->addActionListener (listener);
  31261. }
  31262. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31263. {
  31264. if (broadcaster != 0)
  31265. broadcaster->removeActionListener (listener);
  31266. }
  31267. bool MessageManager::isThisTheMessageThread() const throw()
  31268. {
  31269. return Thread::getCurrentThreadId() == messageThreadId;
  31270. }
  31271. void MessageManager::setCurrentThreadAsMessageThread()
  31272. {
  31273. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31274. if (messageThreadId != thisThread)
  31275. {
  31276. messageThreadId = thisThread;
  31277. // This is needed on windows to make sure the message window is created by this thread
  31278. doPlatformSpecificShutdown();
  31279. doPlatformSpecificInitialisation();
  31280. }
  31281. }
  31282. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31283. {
  31284. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31285. return thisThread == messageThreadId || thisThread == threadWithLock;
  31286. }
  31287. /* The only safe way to lock the message thread while another thread does
  31288. some work is by posting a special message, whose purpose is to tie up the event
  31289. loop until the other thread has finished its business.
  31290. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31291. get locked before making an event callback, because if the same OS lock gets indirectly
  31292. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31293. in Cocoa).
  31294. */
  31295. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31296. {
  31297. public:
  31298. BlockingMessage() {}
  31299. void messageCallback()
  31300. {
  31301. lockedEvent.signal();
  31302. releaseEvent.wait();
  31303. }
  31304. WaitableEvent lockedEvent, releaseEvent;
  31305. private:
  31306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31307. };
  31308. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31309. : locked (false)
  31310. {
  31311. init (threadToCheck, 0);
  31312. }
  31313. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31314. : locked (false)
  31315. {
  31316. init (0, jobToCheckForExitSignal);
  31317. }
  31318. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31319. {
  31320. if (MessageManager::instance != 0)
  31321. {
  31322. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31323. {
  31324. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31325. }
  31326. else
  31327. {
  31328. if (threadToCheck == 0 && job == 0)
  31329. {
  31330. MessageManager::instance->lockingLock.enter();
  31331. }
  31332. else
  31333. {
  31334. while (! MessageManager::instance->lockingLock.tryEnter())
  31335. {
  31336. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31337. || (job != 0 && job->shouldExit()))
  31338. return;
  31339. Thread::sleep (1);
  31340. }
  31341. }
  31342. blockingMessage = new BlockingMessage();
  31343. blockingMessage->post();
  31344. while (! blockingMessage->lockedEvent.wait (20))
  31345. {
  31346. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31347. || (job != 0 && job->shouldExit()))
  31348. {
  31349. blockingMessage->releaseEvent.signal();
  31350. blockingMessage = 0;
  31351. MessageManager::instance->lockingLock.exit();
  31352. return;
  31353. }
  31354. }
  31355. jassert (MessageManager::instance->threadWithLock == 0);
  31356. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31357. locked = true;
  31358. }
  31359. }
  31360. }
  31361. MessageManagerLock::~MessageManagerLock() throw()
  31362. {
  31363. if (blockingMessage != 0)
  31364. {
  31365. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31366. blockingMessage->releaseEvent.signal();
  31367. blockingMessage = 0;
  31368. if (MessageManager::instance != 0)
  31369. {
  31370. MessageManager::instance->threadWithLock = 0;
  31371. MessageManager::instance->lockingLock.exit();
  31372. }
  31373. }
  31374. }
  31375. END_JUCE_NAMESPACE
  31376. /*** End of inlined file: juce_MessageManager.cpp ***/
  31377. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31378. BEGIN_JUCE_NAMESPACE
  31379. class MultiTimer::MultiTimerCallback : public Timer
  31380. {
  31381. public:
  31382. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31383. : timerId (timerId_),
  31384. owner (owner_)
  31385. {
  31386. }
  31387. ~MultiTimerCallback()
  31388. {
  31389. }
  31390. void timerCallback()
  31391. {
  31392. owner.timerCallback (timerId);
  31393. }
  31394. const int timerId;
  31395. private:
  31396. MultiTimer& owner;
  31397. };
  31398. MultiTimer::MultiTimer() throw()
  31399. {
  31400. }
  31401. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31402. {
  31403. }
  31404. MultiTimer::~MultiTimer()
  31405. {
  31406. const ScopedLock sl (timerListLock);
  31407. timers.clear();
  31408. }
  31409. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31410. {
  31411. const ScopedLock sl (timerListLock);
  31412. for (int i = timers.size(); --i >= 0;)
  31413. {
  31414. MultiTimerCallback* const t = timers.getUnchecked(i);
  31415. if (t->timerId == timerId)
  31416. {
  31417. t->startTimer (intervalInMilliseconds);
  31418. return;
  31419. }
  31420. }
  31421. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31422. timers.add (newTimer);
  31423. newTimer->startTimer (intervalInMilliseconds);
  31424. }
  31425. void MultiTimer::stopTimer (const int timerId) throw()
  31426. {
  31427. const ScopedLock sl (timerListLock);
  31428. for (int i = timers.size(); --i >= 0;)
  31429. {
  31430. MultiTimerCallback* const t = timers.getUnchecked(i);
  31431. if (t->timerId == timerId)
  31432. t->stopTimer();
  31433. }
  31434. }
  31435. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31436. {
  31437. const ScopedLock sl (timerListLock);
  31438. for (int i = timers.size(); --i >= 0;)
  31439. {
  31440. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31441. if (t->timerId == timerId)
  31442. return t->isTimerRunning();
  31443. }
  31444. return false;
  31445. }
  31446. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31447. {
  31448. const ScopedLock sl (timerListLock);
  31449. for (int i = timers.size(); --i >= 0;)
  31450. {
  31451. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31452. if (t->timerId == timerId)
  31453. return t->getTimerInterval();
  31454. }
  31455. return 0;
  31456. }
  31457. END_JUCE_NAMESPACE
  31458. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31459. /*** Start of inlined file: juce_Timer.cpp ***/
  31460. BEGIN_JUCE_NAMESPACE
  31461. class InternalTimerThread : private Thread,
  31462. private MessageListener,
  31463. private DeletedAtShutdown,
  31464. private AsyncUpdater
  31465. {
  31466. public:
  31467. InternalTimerThread()
  31468. : Thread ("Juce Timer"),
  31469. firstTimer (0),
  31470. callbackNeeded (0)
  31471. {
  31472. triggerAsyncUpdate();
  31473. }
  31474. ~InternalTimerThread() throw()
  31475. {
  31476. stopThread (4000);
  31477. jassert (instance == this || instance == 0);
  31478. if (instance == this)
  31479. instance = 0;
  31480. }
  31481. void run()
  31482. {
  31483. uint32 lastTime = Time::getMillisecondCounter();
  31484. Message::Ptr message (new Message());
  31485. while (! threadShouldExit())
  31486. {
  31487. const uint32 now = Time::getMillisecondCounter();
  31488. if (now <= lastTime)
  31489. {
  31490. wait (2);
  31491. continue;
  31492. }
  31493. const int elapsed = now - lastTime;
  31494. lastTime = now;
  31495. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31496. if (timeUntilFirstTimer <= 0)
  31497. {
  31498. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31499. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31500. but if it fails it means the message-thread changed the value from under us so at least
  31501. some processing is happenening and we can just loop around and try again
  31502. */
  31503. if (callbackNeeded.compareAndSetBool (1, 0))
  31504. {
  31505. postMessage (message);
  31506. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31507. when the app has a modal loop), so this is how long to wait before assuming the
  31508. message has been lost and trying again.
  31509. */
  31510. const uint32 messageDeliveryTimeout = now + 2000;
  31511. while (callbackNeeded.get() != 0)
  31512. {
  31513. wait (4);
  31514. if (threadShouldExit())
  31515. return;
  31516. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31517. break;
  31518. }
  31519. }
  31520. }
  31521. else
  31522. {
  31523. // don't wait for too long because running this loop also helps keep the
  31524. // Time::getApproximateMillisecondTimer value stay up-to-date
  31525. wait (jlimit (1, 50, timeUntilFirstTimer));
  31526. }
  31527. }
  31528. }
  31529. void callTimers()
  31530. {
  31531. const ScopedLock sl (lock);
  31532. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31533. {
  31534. Timer* const t = firstTimer;
  31535. t->countdownMs = t->periodMs;
  31536. removeTimer (t);
  31537. addTimer (t);
  31538. const ScopedUnlock ul (lock);
  31539. JUCE_TRY
  31540. {
  31541. t->timerCallback();
  31542. }
  31543. JUCE_CATCH_EXCEPTION
  31544. }
  31545. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31546. before the boolean is set. This set should never fail since if it was false in the first place,
  31547. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31548. get a message then the value is true and the other thread can only set it to true again and
  31549. we will get another callback to set it to false.
  31550. */
  31551. callbackNeeded.set (0);
  31552. }
  31553. void handleMessage (const Message&)
  31554. {
  31555. callTimers();
  31556. }
  31557. void callTimersSynchronously()
  31558. {
  31559. if (! isThreadRunning())
  31560. {
  31561. // (This is relied on by some plugins in cases where the MM has
  31562. // had to restart and the async callback never started)
  31563. cancelPendingUpdate();
  31564. triggerAsyncUpdate();
  31565. }
  31566. callTimers();
  31567. }
  31568. static void callAnyTimersSynchronously()
  31569. {
  31570. if (InternalTimerThread::instance != 0)
  31571. InternalTimerThread::instance->callTimersSynchronously();
  31572. }
  31573. static inline void add (Timer* const tim) throw()
  31574. {
  31575. if (instance == 0)
  31576. instance = new InternalTimerThread();
  31577. const ScopedLock sl (instance->lock);
  31578. instance->addTimer (tim);
  31579. }
  31580. static inline void remove (Timer* const tim) throw()
  31581. {
  31582. if (instance != 0)
  31583. {
  31584. const ScopedLock sl (instance->lock);
  31585. instance->removeTimer (tim);
  31586. }
  31587. }
  31588. static inline void resetCounter (Timer* const tim,
  31589. const int newCounter) throw()
  31590. {
  31591. if (instance != 0)
  31592. {
  31593. tim->countdownMs = newCounter;
  31594. tim->periodMs = newCounter;
  31595. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31596. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31597. {
  31598. const ScopedLock sl (instance->lock);
  31599. instance->removeTimer (tim);
  31600. instance->addTimer (tim);
  31601. }
  31602. }
  31603. }
  31604. private:
  31605. friend class Timer;
  31606. static InternalTimerThread* instance;
  31607. static CriticalSection lock;
  31608. Timer* volatile firstTimer;
  31609. Atomic <int> callbackNeeded;
  31610. void addTimer (Timer* const t) throw()
  31611. {
  31612. #if JUCE_DEBUG
  31613. Timer* tt = firstTimer;
  31614. while (tt != 0)
  31615. {
  31616. // trying to add a timer that's already here - shouldn't get to this point,
  31617. // so if you get this assertion, let me know!
  31618. jassert (tt != t);
  31619. tt = tt->next;
  31620. }
  31621. jassert (t->previous == 0 && t->next == 0);
  31622. #endif
  31623. Timer* i = firstTimer;
  31624. if (i == 0 || i->countdownMs > t->countdownMs)
  31625. {
  31626. t->next = firstTimer;
  31627. firstTimer = t;
  31628. }
  31629. else
  31630. {
  31631. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31632. i = i->next;
  31633. jassert (i != 0);
  31634. t->next = i->next;
  31635. t->previous = i;
  31636. i->next = t;
  31637. }
  31638. if (t->next != 0)
  31639. t->next->previous = t;
  31640. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31641. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31642. notify();
  31643. }
  31644. void removeTimer (Timer* const t) throw()
  31645. {
  31646. #if JUCE_DEBUG
  31647. Timer* tt = firstTimer;
  31648. bool found = false;
  31649. while (tt != 0)
  31650. {
  31651. if (tt == t)
  31652. {
  31653. found = true;
  31654. break;
  31655. }
  31656. tt = tt->next;
  31657. }
  31658. // trying to remove a timer that's not here - shouldn't get to this point,
  31659. // so if you get this assertion, let me know!
  31660. jassert (found);
  31661. #endif
  31662. if (t->previous != 0)
  31663. {
  31664. jassert (firstTimer != t);
  31665. t->previous->next = t->next;
  31666. }
  31667. else
  31668. {
  31669. jassert (firstTimer == t);
  31670. firstTimer = t->next;
  31671. }
  31672. if (t->next != 0)
  31673. t->next->previous = t->previous;
  31674. t->next = 0;
  31675. t->previous = 0;
  31676. }
  31677. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31678. {
  31679. const ScopedLock sl (lock);
  31680. for (Timer* t = firstTimer; t != 0; t = t->next)
  31681. t->countdownMs -= numMillisecsElapsed;
  31682. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31683. }
  31684. void handleAsyncUpdate()
  31685. {
  31686. startThread (7);
  31687. }
  31688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31689. };
  31690. InternalTimerThread* InternalTimerThread::instance = 0;
  31691. CriticalSection InternalTimerThread::lock;
  31692. void juce_callAnyTimersSynchronously()
  31693. {
  31694. InternalTimerThread::callAnyTimersSynchronously();
  31695. }
  31696. #if JUCE_DEBUG
  31697. static SortedSet <Timer*> activeTimers;
  31698. #endif
  31699. Timer::Timer() throw()
  31700. : countdownMs (0),
  31701. periodMs (0),
  31702. previous (0),
  31703. next (0)
  31704. {
  31705. #if JUCE_DEBUG
  31706. activeTimers.add (this);
  31707. #endif
  31708. }
  31709. Timer::Timer (const Timer&) throw()
  31710. : countdownMs (0),
  31711. periodMs (0),
  31712. previous (0),
  31713. next (0)
  31714. {
  31715. #if JUCE_DEBUG
  31716. activeTimers.add (this);
  31717. #endif
  31718. }
  31719. Timer::~Timer()
  31720. {
  31721. stopTimer();
  31722. #if JUCE_DEBUG
  31723. activeTimers.removeValue (this);
  31724. #endif
  31725. }
  31726. void Timer::startTimer (const int interval) throw()
  31727. {
  31728. const ScopedLock sl (InternalTimerThread::lock);
  31729. #if JUCE_DEBUG
  31730. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31731. jassert (activeTimers.contains (this));
  31732. #endif
  31733. if (periodMs == 0)
  31734. {
  31735. countdownMs = interval;
  31736. periodMs = jmax (1, interval);
  31737. InternalTimerThread::add (this);
  31738. }
  31739. else
  31740. {
  31741. InternalTimerThread::resetCounter (this, interval);
  31742. }
  31743. }
  31744. void Timer::stopTimer() throw()
  31745. {
  31746. const ScopedLock sl (InternalTimerThread::lock);
  31747. #if JUCE_DEBUG
  31748. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31749. jassert (activeTimers.contains (this));
  31750. #endif
  31751. if (periodMs > 0)
  31752. {
  31753. InternalTimerThread::remove (this);
  31754. periodMs = 0;
  31755. }
  31756. }
  31757. END_JUCE_NAMESPACE
  31758. /*** End of inlined file: juce_Timer.cpp ***/
  31759. #endif
  31760. #if JUCE_BUILD_GUI
  31761. /*** Start of inlined file: juce_Component.cpp ***/
  31762. BEGIN_JUCE_NAMESPACE
  31763. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31764. Component* Component::currentlyFocusedComponent = 0;
  31765. class Component::MouseListenerList
  31766. {
  31767. public:
  31768. MouseListenerList()
  31769. : numDeepMouseListeners (0)
  31770. {
  31771. }
  31772. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31773. {
  31774. if (! listeners.contains (newListener))
  31775. {
  31776. if (wantsEventsForAllNestedChildComponents)
  31777. {
  31778. listeners.insert (0, newListener);
  31779. ++numDeepMouseListeners;
  31780. }
  31781. else
  31782. {
  31783. listeners.add (newListener);
  31784. }
  31785. }
  31786. }
  31787. void removeListener (MouseListener* const listenerToRemove)
  31788. {
  31789. const int index = listeners.indexOf (listenerToRemove);
  31790. if (index >= 0)
  31791. {
  31792. if (index < numDeepMouseListeners)
  31793. --numDeepMouseListeners;
  31794. listeners.remove (index);
  31795. }
  31796. }
  31797. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31798. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31799. {
  31800. if (checker.shouldBailOut())
  31801. return;
  31802. {
  31803. MouseListenerList* const list = comp.mouseListeners;
  31804. if (list != 0)
  31805. {
  31806. for (int i = list->listeners.size(); --i >= 0;)
  31807. {
  31808. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31809. if (checker.shouldBailOut())
  31810. return;
  31811. i = jmin (i, list->listeners.size());
  31812. }
  31813. }
  31814. }
  31815. Component* p = comp.parentComponent;
  31816. while (p != 0)
  31817. {
  31818. MouseListenerList* const list = p->mouseListeners;
  31819. if (list != 0 && list->numDeepMouseListeners > 0)
  31820. {
  31821. BailOutChecker2 checker2 (checker, p);
  31822. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31823. {
  31824. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31825. if (checker2.shouldBailOut())
  31826. return;
  31827. i = jmin (i, list->numDeepMouseListeners);
  31828. }
  31829. }
  31830. p = p->parentComponent;
  31831. }
  31832. }
  31833. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31834. const float wheelIncrementX, const float wheelIncrementY)
  31835. {
  31836. {
  31837. MouseListenerList* const list = comp.mouseListeners;
  31838. if (list != 0)
  31839. {
  31840. for (int i = list->listeners.size(); --i >= 0;)
  31841. {
  31842. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31843. if (checker.shouldBailOut())
  31844. return;
  31845. i = jmin (i, list->listeners.size());
  31846. }
  31847. }
  31848. }
  31849. Component* p = comp.parentComponent;
  31850. while (p != 0)
  31851. {
  31852. MouseListenerList* const list = p->mouseListeners;
  31853. if (list != 0 && list->numDeepMouseListeners > 0)
  31854. {
  31855. BailOutChecker2 checker2 (checker, p);
  31856. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31857. {
  31858. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31859. if (checker2.shouldBailOut())
  31860. return;
  31861. i = jmin (i, list->numDeepMouseListeners);
  31862. }
  31863. }
  31864. p = p->parentComponent;
  31865. }
  31866. }
  31867. private:
  31868. Array <MouseListener*> listeners;
  31869. int numDeepMouseListeners;
  31870. class BailOutChecker2
  31871. {
  31872. public:
  31873. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31874. : checker (checker_), safePointer (component)
  31875. {
  31876. }
  31877. bool shouldBailOut() const throw()
  31878. {
  31879. return checker.shouldBailOut() || safePointer == 0;
  31880. }
  31881. private:
  31882. BailOutChecker& checker;
  31883. const WeakReference<Component> safePointer;
  31884. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31885. };
  31886. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31887. };
  31888. class Component::ComponentHelpers
  31889. {
  31890. public:
  31891. #if JUCE_MODAL_LOOPS_PERMITTED
  31892. static void* runModalLoopCallback (void* userData)
  31893. {
  31894. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31895. }
  31896. #endif
  31897. static const Identifier getColourPropertyId (const int colourId)
  31898. {
  31899. String s;
  31900. s.preallocateStorage (18);
  31901. s << "jcclr_" << String::toHexString (colourId);
  31902. return s;
  31903. }
  31904. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31905. {
  31906. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31907. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31908. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31909. }
  31910. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31911. {
  31912. if (comp.affineTransform == 0)
  31913. return pointInParentSpace - comp.getPosition();
  31914. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31915. }
  31916. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31917. {
  31918. if (comp.affineTransform == 0)
  31919. return areaInParentSpace - comp.getPosition();
  31920. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31921. }
  31922. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31923. {
  31924. if (comp.affineTransform == 0)
  31925. return pointInLocalSpace + comp.getPosition();
  31926. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31927. }
  31928. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31929. {
  31930. if (comp.affineTransform == 0)
  31931. return areaInLocalSpace + comp.getPosition();
  31932. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31933. }
  31934. template <typename Type>
  31935. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31936. {
  31937. const Component* const directParent = target.getParentComponent();
  31938. jassert (directParent != 0);
  31939. if (directParent == parent)
  31940. return convertFromParentSpace (target, coordInParent);
  31941. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31942. }
  31943. template <typename Type>
  31944. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31945. {
  31946. while (source != 0)
  31947. {
  31948. if (source == target)
  31949. return p;
  31950. if (source->isParentOf (target))
  31951. return convertFromDistantParentSpace (source, *target, p);
  31952. if (source->isOnDesktop())
  31953. {
  31954. p = source->getPeer()->localToGlobal (p);
  31955. source = 0;
  31956. }
  31957. else
  31958. {
  31959. p = convertToParentSpace (*source, p);
  31960. source = source->getParentComponent();
  31961. }
  31962. }
  31963. jassert (source == 0);
  31964. if (target == 0)
  31965. return p;
  31966. const Component* const topLevelComp = target->getTopLevelComponent();
  31967. if (topLevelComp->isOnDesktop())
  31968. p = topLevelComp->getPeer()->globalToLocal (p);
  31969. else
  31970. p = convertFromParentSpace (*topLevelComp, p);
  31971. if (topLevelComp == target)
  31972. return p;
  31973. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31974. }
  31975. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31976. {
  31977. Rectangle<int> r (comp.getLocalBounds());
  31978. Component* const p = comp.getParentComponent();
  31979. if (p != 0)
  31980. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31981. return r;
  31982. }
  31983. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  31984. {
  31985. for (int i = comp.childComponentList.size(); --i >= 0;)
  31986. {
  31987. const Component& child = *comp.childComponentList.getUnchecked(i);
  31988. if (child.isVisible() && ! child.isTransformed())
  31989. {
  31990. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  31991. if (! newClip.isEmpty())
  31992. {
  31993. if (child.isOpaque())
  31994. {
  31995. g.excludeClipRegion (newClip + delta);
  31996. }
  31997. else
  31998. {
  31999. const Point<int> childPos (child.getPosition());
  32000. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32001. }
  32002. }
  32003. }
  32004. }
  32005. }
  32006. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32007. const Point<int>& delta,
  32008. const Rectangle<int>& clipRect,
  32009. const Component* const compToAvoid)
  32010. {
  32011. for (int i = comp.childComponentList.size(); --i >= 0;)
  32012. {
  32013. const Component* const c = comp.childComponentList.getUnchecked(i);
  32014. if (c != compToAvoid && c->isVisible())
  32015. {
  32016. if (c->isOpaque())
  32017. {
  32018. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  32019. childBounds.translate (delta.getX(), delta.getY());
  32020. result.subtract (childBounds);
  32021. }
  32022. else
  32023. {
  32024. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  32025. newClip.translate (-c->getX(), -c->getY());
  32026. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32027. newClip, compToAvoid);
  32028. }
  32029. }
  32030. }
  32031. }
  32032. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32033. {
  32034. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32035. : Desktop::getInstance().getMainMonitorArea();
  32036. }
  32037. };
  32038. Component::Component()
  32039. : parentComponent (0),
  32040. lookAndFeel (0),
  32041. effect (0),
  32042. componentFlags (0),
  32043. componentTransparency (0)
  32044. {
  32045. }
  32046. Component::Component (const String& name)
  32047. : componentName (name),
  32048. parentComponent (0),
  32049. lookAndFeel (0),
  32050. effect (0),
  32051. componentFlags (0),
  32052. componentTransparency (0)
  32053. {
  32054. }
  32055. Component::~Component()
  32056. {
  32057. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32058. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  32059. #endif
  32060. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32061. weakReferenceMaster.clear();
  32062. while (childComponentList.size() > 0)
  32063. removeChildComponent (childComponentList.size() - 1, false, true);
  32064. if (parentComponent != 0)
  32065. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  32066. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32067. giveAwayFocus (currentlyFocusedComponent != this);
  32068. if (flags.hasHeavyweightPeerFlag)
  32069. removeFromDesktop();
  32070. // Something has added some children to this component during its destructor! Not a smart idea!
  32071. jassert (childComponentList.size() == 0);
  32072. }
  32073. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32074. {
  32075. return weakReferenceMaster (this);
  32076. }
  32077. void Component::setName (const String& name)
  32078. {
  32079. // if component methods are being called from threads other than the message
  32080. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32081. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32082. if (componentName != name)
  32083. {
  32084. componentName = name;
  32085. if (flags.hasHeavyweightPeerFlag)
  32086. {
  32087. ComponentPeer* const peer = getPeer();
  32088. jassert (peer != 0);
  32089. if (peer != 0)
  32090. peer->setTitle (name);
  32091. }
  32092. BailOutChecker checker (this);
  32093. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32094. }
  32095. }
  32096. void Component::setComponentID (const String& newID)
  32097. {
  32098. componentID = newID;
  32099. }
  32100. void Component::setVisible (bool shouldBeVisible)
  32101. {
  32102. if (flags.visibleFlag != shouldBeVisible)
  32103. {
  32104. // if component methods are being called from threads other than the message
  32105. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32106. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32107. WeakReference<Component> safePointer (this);
  32108. flags.visibleFlag = shouldBeVisible;
  32109. internalRepaint (0, 0, getWidth(), getHeight());
  32110. sendFakeMouseMove();
  32111. if (! shouldBeVisible)
  32112. {
  32113. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32114. {
  32115. if (parentComponent != 0)
  32116. parentComponent->grabKeyboardFocus();
  32117. else
  32118. giveAwayFocus (true);
  32119. }
  32120. }
  32121. if (safePointer != 0)
  32122. {
  32123. sendVisibilityChangeMessage();
  32124. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32125. {
  32126. ComponentPeer* const peer = getPeer();
  32127. jassert (peer != 0);
  32128. if (peer != 0)
  32129. {
  32130. peer->setVisible (shouldBeVisible);
  32131. internalHierarchyChanged();
  32132. }
  32133. }
  32134. }
  32135. }
  32136. }
  32137. void Component::visibilityChanged()
  32138. {
  32139. }
  32140. void Component::sendVisibilityChangeMessage()
  32141. {
  32142. BailOutChecker checker (this);
  32143. visibilityChanged();
  32144. if (! checker.shouldBailOut())
  32145. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32146. }
  32147. bool Component::isShowing() const
  32148. {
  32149. if (flags.visibleFlag)
  32150. {
  32151. if (parentComponent != 0)
  32152. {
  32153. return parentComponent->isShowing();
  32154. }
  32155. else
  32156. {
  32157. const ComponentPeer* const peer = getPeer();
  32158. return peer != 0 && ! peer->isMinimised();
  32159. }
  32160. }
  32161. return false;
  32162. }
  32163. void* Component::getWindowHandle() const
  32164. {
  32165. const ComponentPeer* const peer = getPeer();
  32166. if (peer != 0)
  32167. return peer->getNativeHandle();
  32168. return 0;
  32169. }
  32170. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32171. {
  32172. // if component methods are being called from threads other than the message
  32173. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32174. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32175. if (isOpaque())
  32176. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32177. else
  32178. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32179. int currentStyleFlags = 0;
  32180. // don't use getPeer(), so that we only get the peer that's specifically
  32181. // for this comp, and not for one of its parents.
  32182. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32183. if (peer != 0)
  32184. currentStyleFlags = peer->getStyleFlags();
  32185. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32186. {
  32187. WeakReference<Component> safePointer (this);
  32188. #if JUCE_LINUX
  32189. // it's wise to give the component a non-zero size before
  32190. // putting it on the desktop, as X windows get confused by this, and
  32191. // a (1, 1) minimum size is enforced here.
  32192. setSize (jmax (1, getWidth()),
  32193. jmax (1, getHeight()));
  32194. #endif
  32195. const Point<int> topLeft (getScreenPosition());
  32196. bool wasFullscreen = false;
  32197. bool wasMinimised = false;
  32198. ComponentBoundsConstrainer* currentConstainer = 0;
  32199. Rectangle<int> oldNonFullScreenBounds;
  32200. if (peer != 0)
  32201. {
  32202. wasFullscreen = peer->isFullScreen();
  32203. wasMinimised = peer->isMinimised();
  32204. currentConstainer = peer->getConstrainer();
  32205. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32206. removeFromDesktop();
  32207. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32208. }
  32209. if (parentComponent != 0)
  32210. parentComponent->removeChildComponent (this);
  32211. if (safePointer != 0)
  32212. {
  32213. flags.hasHeavyweightPeerFlag = true;
  32214. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32215. Desktop::getInstance().addDesktopComponent (this);
  32216. bounds.setPosition (topLeft);
  32217. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32218. peer->setVisible (isVisible());
  32219. if (wasFullscreen)
  32220. {
  32221. peer->setFullScreen (true);
  32222. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32223. }
  32224. if (wasMinimised)
  32225. peer->setMinimised (true);
  32226. if (isAlwaysOnTop())
  32227. peer->setAlwaysOnTop (true);
  32228. peer->setConstrainer (currentConstainer);
  32229. repaint();
  32230. }
  32231. internalHierarchyChanged();
  32232. }
  32233. }
  32234. void Component::removeFromDesktop()
  32235. {
  32236. // if component methods are being called from threads other than the message
  32237. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32238. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32239. if (flags.hasHeavyweightPeerFlag)
  32240. {
  32241. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32242. flags.hasHeavyweightPeerFlag = false;
  32243. jassert (peer != 0);
  32244. delete peer;
  32245. Desktop::getInstance().removeDesktopComponent (this);
  32246. }
  32247. }
  32248. bool Component::isOnDesktop() const throw()
  32249. {
  32250. return flags.hasHeavyweightPeerFlag;
  32251. }
  32252. void Component::userTriedToCloseWindow()
  32253. {
  32254. /* This means that the user's trying to get rid of your window with the 'close window' system
  32255. menu option (on windows) or possibly the task manager - you should really handle this
  32256. and delete or hide your component in an appropriate way.
  32257. If you want to ignore the event and don't want to trigger this assertion, just override
  32258. this method and do nothing.
  32259. */
  32260. jassertfalse;
  32261. }
  32262. void Component::minimisationStateChanged (bool)
  32263. {
  32264. }
  32265. void Component::setOpaque (const bool shouldBeOpaque)
  32266. {
  32267. if (shouldBeOpaque != flags.opaqueFlag)
  32268. {
  32269. flags.opaqueFlag = shouldBeOpaque;
  32270. if (flags.hasHeavyweightPeerFlag)
  32271. {
  32272. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32273. if (peer != 0)
  32274. {
  32275. // to make it recreate the heavyweight window
  32276. addToDesktop (peer->getStyleFlags());
  32277. }
  32278. }
  32279. repaint();
  32280. }
  32281. }
  32282. bool Component::isOpaque() const throw()
  32283. {
  32284. return flags.opaqueFlag;
  32285. }
  32286. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32287. {
  32288. if (shouldBeBuffered != flags.bufferToImageFlag)
  32289. {
  32290. bufferedImage = Image::null;
  32291. flags.bufferToImageFlag = shouldBeBuffered;
  32292. }
  32293. }
  32294. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32295. {
  32296. if (sourceIndex != destIndex)
  32297. {
  32298. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32299. jassert (c != 0);
  32300. c->repaintParent();
  32301. childComponentList.move (sourceIndex, destIndex);
  32302. sendFakeMouseMove();
  32303. internalChildrenChanged();
  32304. }
  32305. }
  32306. void Component::toFront (const bool setAsForeground)
  32307. {
  32308. // if component methods are being called from threads other than the message
  32309. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32310. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32311. if (flags.hasHeavyweightPeerFlag)
  32312. {
  32313. ComponentPeer* const peer = getPeer();
  32314. if (peer != 0)
  32315. {
  32316. peer->toFront (setAsForeground);
  32317. if (setAsForeground && ! hasKeyboardFocus (true))
  32318. grabKeyboardFocus();
  32319. }
  32320. }
  32321. else if (parentComponent != 0)
  32322. {
  32323. const Array<Component*>& childList = parentComponent->childComponentList;
  32324. if (childList.getLast() != this)
  32325. {
  32326. const int index = childList.indexOf (this);
  32327. if (index >= 0)
  32328. {
  32329. int insertIndex = -1;
  32330. if (! flags.alwaysOnTopFlag)
  32331. {
  32332. insertIndex = childList.size() - 1;
  32333. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32334. --insertIndex;
  32335. }
  32336. parentComponent->moveChildInternal (index, insertIndex);
  32337. }
  32338. }
  32339. if (setAsForeground)
  32340. {
  32341. internalBroughtToFront();
  32342. grabKeyboardFocus();
  32343. }
  32344. }
  32345. }
  32346. void Component::toBehind (Component* const other)
  32347. {
  32348. if (other != 0 && other != this)
  32349. {
  32350. // the two components must belong to the same parent..
  32351. jassert (parentComponent == other->parentComponent);
  32352. if (parentComponent != 0)
  32353. {
  32354. const Array<Component*>& childList = parentComponent->childComponentList;
  32355. const int index = childList.indexOf (this);
  32356. if (index >= 0 && childList [index + 1] != other)
  32357. {
  32358. int otherIndex = childList.indexOf (other);
  32359. if (otherIndex >= 0)
  32360. {
  32361. if (index < otherIndex)
  32362. --otherIndex;
  32363. parentComponent->moveChildInternal (index, otherIndex);
  32364. }
  32365. }
  32366. }
  32367. else if (isOnDesktop())
  32368. {
  32369. jassert (other->isOnDesktop());
  32370. if (other->isOnDesktop())
  32371. {
  32372. ComponentPeer* const us = getPeer();
  32373. ComponentPeer* const them = other->getPeer();
  32374. jassert (us != 0 && them != 0);
  32375. if (us != 0 && them != 0)
  32376. us->toBehind (them);
  32377. }
  32378. }
  32379. }
  32380. }
  32381. void Component::toBack()
  32382. {
  32383. if (isOnDesktop())
  32384. {
  32385. jassertfalse; //xxx need to add this to native window
  32386. }
  32387. else if (parentComponent != 0)
  32388. {
  32389. const Array<Component*>& childList = parentComponent->childComponentList;
  32390. if (childList.getFirst() != this)
  32391. {
  32392. const int index = childList.indexOf (this);
  32393. if (index > 0)
  32394. {
  32395. int insertIndex = 0;
  32396. if (flags.alwaysOnTopFlag)
  32397. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32398. ++insertIndex;
  32399. parentComponent->moveChildInternal (index, insertIndex);
  32400. }
  32401. }
  32402. }
  32403. }
  32404. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32405. {
  32406. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32407. {
  32408. flags.alwaysOnTopFlag = shouldStayOnTop;
  32409. if (isOnDesktop())
  32410. {
  32411. ComponentPeer* const peer = getPeer();
  32412. jassert (peer != 0);
  32413. if (peer != 0)
  32414. {
  32415. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32416. {
  32417. // some kinds of peer can't change their always-on-top status, so
  32418. // for these, we'll need to create a new window
  32419. const int oldFlags = peer->getStyleFlags();
  32420. removeFromDesktop();
  32421. addToDesktop (oldFlags);
  32422. }
  32423. }
  32424. }
  32425. if (shouldStayOnTop)
  32426. toFront (false);
  32427. internalHierarchyChanged();
  32428. }
  32429. }
  32430. bool Component::isAlwaysOnTop() const throw()
  32431. {
  32432. return flags.alwaysOnTopFlag;
  32433. }
  32434. int Component::proportionOfWidth (const float proportion) const throw()
  32435. {
  32436. return roundToInt (proportion * bounds.getWidth());
  32437. }
  32438. int Component::proportionOfHeight (const float proportion) const throw()
  32439. {
  32440. return roundToInt (proportion * bounds.getHeight());
  32441. }
  32442. int Component::getParentWidth() const throw()
  32443. {
  32444. return (parentComponent != 0) ? parentComponent->getWidth()
  32445. : getParentMonitorArea().getWidth();
  32446. }
  32447. int Component::getParentHeight() const throw()
  32448. {
  32449. return (parentComponent != 0) ? parentComponent->getHeight()
  32450. : getParentMonitorArea().getHeight();
  32451. }
  32452. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32453. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32454. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32455. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32456. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32457. {
  32458. return ComponentHelpers::convertCoordinate (this, source, point);
  32459. }
  32460. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32461. {
  32462. return ComponentHelpers::convertCoordinate (this, source, area);
  32463. }
  32464. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32465. {
  32466. return ComponentHelpers::convertCoordinate (0, this, point);
  32467. }
  32468. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32469. {
  32470. return ComponentHelpers::convertCoordinate (0, this, area);
  32471. }
  32472. /* Deprecated methods... */
  32473. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32474. {
  32475. return localPointToGlobal (relativePosition);
  32476. }
  32477. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32478. {
  32479. return getLocalPoint (0, screenPosition);
  32480. }
  32481. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32482. {
  32483. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32484. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32485. }
  32486. void Component::setBounds (const int x, const int y, int w, int h)
  32487. {
  32488. // if component methods are being called from threads other than the message
  32489. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32490. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32491. if (w < 0) w = 0;
  32492. if (h < 0) h = 0;
  32493. const bool wasResized = (getWidth() != w || getHeight() != h);
  32494. const bool wasMoved = (getX() != x || getY() != y);
  32495. #if JUCE_DEBUG
  32496. // It's a very bad idea to try to resize a window during its paint() method!
  32497. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32498. #endif
  32499. if (wasMoved || wasResized)
  32500. {
  32501. const bool showing = isShowing();
  32502. if (showing)
  32503. {
  32504. // send a fake mouse move to trigger enter/exit messages if needed..
  32505. sendFakeMouseMove();
  32506. if (! flags.hasHeavyweightPeerFlag)
  32507. repaintParent();
  32508. }
  32509. bounds.setBounds (x, y, w, h);
  32510. if (showing)
  32511. {
  32512. if (wasResized)
  32513. repaint();
  32514. else if (! flags.hasHeavyweightPeerFlag)
  32515. repaintParent();
  32516. }
  32517. if (flags.hasHeavyweightPeerFlag)
  32518. {
  32519. ComponentPeer* const peer = getPeer();
  32520. if (peer != 0)
  32521. {
  32522. if (wasMoved && wasResized)
  32523. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32524. else if (wasMoved)
  32525. peer->setPosition (getX(), getY());
  32526. else if (wasResized)
  32527. peer->setSize (getWidth(), getHeight());
  32528. }
  32529. }
  32530. sendMovedResizedMessages (wasMoved, wasResized);
  32531. }
  32532. }
  32533. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32534. {
  32535. BailOutChecker checker (this);
  32536. if (wasMoved)
  32537. {
  32538. moved();
  32539. if (checker.shouldBailOut())
  32540. return;
  32541. }
  32542. if (wasResized)
  32543. {
  32544. resized();
  32545. if (checker.shouldBailOut())
  32546. return;
  32547. for (int i = childComponentList.size(); --i >= 0;)
  32548. {
  32549. childComponentList.getUnchecked(i)->parentSizeChanged();
  32550. if (checker.shouldBailOut())
  32551. return;
  32552. i = jmin (i, childComponentList.size());
  32553. }
  32554. }
  32555. if (parentComponent != 0)
  32556. parentComponent->childBoundsChanged (this);
  32557. if (! checker.shouldBailOut())
  32558. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32559. *this, wasMoved, wasResized);
  32560. }
  32561. void Component::setSize (const int w, const int h)
  32562. {
  32563. setBounds (getX(), getY(), w, h);
  32564. }
  32565. void Component::setTopLeftPosition (const int x, const int y)
  32566. {
  32567. setBounds (x, y, getWidth(), getHeight());
  32568. }
  32569. void Component::setTopRightPosition (const int x, const int y)
  32570. {
  32571. setTopLeftPosition (x - getWidth(), y);
  32572. }
  32573. void Component::setBounds (const Rectangle<int>& r)
  32574. {
  32575. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32576. }
  32577. void Component::setBounds (const RelativeRectangle& newBounds)
  32578. {
  32579. newBounds.applyToComponent (*this);
  32580. }
  32581. void Component::setBoundsRelative (const float x, const float y,
  32582. const float w, const float h)
  32583. {
  32584. const int pw = getParentWidth();
  32585. const int ph = getParentHeight();
  32586. setBounds (roundToInt (x * pw),
  32587. roundToInt (y * ph),
  32588. roundToInt (w * pw),
  32589. roundToInt (h * ph));
  32590. }
  32591. void Component::setCentrePosition (const int x, const int y)
  32592. {
  32593. setTopLeftPosition (x - getWidth() / 2,
  32594. y - getHeight() / 2);
  32595. }
  32596. void Component::setCentreRelative (const float x, const float y)
  32597. {
  32598. setCentrePosition (roundToInt (getParentWidth() * x),
  32599. roundToInt (getParentHeight() * y));
  32600. }
  32601. void Component::centreWithSize (const int width, const int height)
  32602. {
  32603. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32604. setBounds (parentArea.getCentreX() - width / 2,
  32605. parentArea.getCentreY() - height / 2,
  32606. width, height);
  32607. }
  32608. void Component::setBoundsInset (const BorderSize<int>& borders)
  32609. {
  32610. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32611. }
  32612. void Component::setBoundsToFit (int x, int y, int width, int height,
  32613. const Justification& justification,
  32614. const bool onlyReduceInSize)
  32615. {
  32616. // it's no good calling this method unless both the component and
  32617. // target rectangle have a finite size.
  32618. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32619. if (getWidth() > 0 && getHeight() > 0
  32620. && width > 0 && height > 0)
  32621. {
  32622. int newW, newH;
  32623. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32624. {
  32625. newW = getWidth();
  32626. newH = getHeight();
  32627. }
  32628. else
  32629. {
  32630. const double imageRatio = getHeight() / (double) getWidth();
  32631. const double targetRatio = height / (double) width;
  32632. if (imageRatio <= targetRatio)
  32633. {
  32634. newW = width;
  32635. newH = jmin (height, roundToInt (newW * imageRatio));
  32636. }
  32637. else
  32638. {
  32639. newH = height;
  32640. newW = jmin (width, roundToInt (newH / imageRatio));
  32641. }
  32642. }
  32643. if (newW > 0 && newH > 0)
  32644. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32645. Rectangle<int> (x, y, width, height)));
  32646. }
  32647. }
  32648. bool Component::isTransformed() const throw()
  32649. {
  32650. return affineTransform != 0;
  32651. }
  32652. void Component::setTransform (const AffineTransform& newTransform)
  32653. {
  32654. // If you pass in a transform with no inverse, the component will have no dimensions,
  32655. // and there will be all sorts of maths errors when converting coordinates.
  32656. jassert (! newTransform.isSingularity());
  32657. if (newTransform.isIdentity())
  32658. {
  32659. if (affineTransform != 0)
  32660. {
  32661. repaint();
  32662. affineTransform = 0;
  32663. repaint();
  32664. sendMovedResizedMessages (false, false);
  32665. }
  32666. }
  32667. else if (affineTransform == 0)
  32668. {
  32669. repaint();
  32670. affineTransform = new AffineTransform (newTransform);
  32671. repaint();
  32672. sendMovedResizedMessages (false, false);
  32673. }
  32674. else if (*affineTransform != newTransform)
  32675. {
  32676. repaint();
  32677. *affineTransform = newTransform;
  32678. repaint();
  32679. sendMovedResizedMessages (false, false);
  32680. }
  32681. }
  32682. const AffineTransform Component::getTransform() const
  32683. {
  32684. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32685. }
  32686. bool Component::hitTest (int x, int y)
  32687. {
  32688. if (! flags.ignoresMouseClicksFlag)
  32689. return true;
  32690. if (flags.allowChildMouseClicksFlag)
  32691. {
  32692. for (int i = getNumChildComponents(); --i >= 0;)
  32693. {
  32694. Component& child = *getChildComponent (i);
  32695. if (child.isVisible()
  32696. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32697. return true;
  32698. }
  32699. }
  32700. return false;
  32701. }
  32702. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32703. const bool allowClicksOnChildComponents) throw()
  32704. {
  32705. flags.ignoresMouseClicksFlag = ! allowClicks;
  32706. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32707. }
  32708. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32709. bool& allowsClicksOnChildComponents) const throw()
  32710. {
  32711. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32712. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32713. }
  32714. bool Component::contains (const Point<int>& point)
  32715. {
  32716. if (ComponentHelpers::hitTest (*this, point))
  32717. {
  32718. if (parentComponent != 0)
  32719. {
  32720. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32721. }
  32722. else if (flags.hasHeavyweightPeerFlag)
  32723. {
  32724. const ComponentPeer* const peer = getPeer();
  32725. if (peer != 0)
  32726. return peer->contains (point, true);
  32727. }
  32728. }
  32729. return false;
  32730. }
  32731. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32732. {
  32733. if (! contains (point))
  32734. return false;
  32735. Component* const top = getTopLevelComponent();
  32736. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32737. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32738. }
  32739. Component* Component::getComponentAt (const Point<int>& position)
  32740. {
  32741. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32742. {
  32743. for (int i = childComponentList.size(); --i >= 0;)
  32744. {
  32745. Component* child = childComponentList.getUnchecked(i);
  32746. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32747. if (child != 0)
  32748. return child;
  32749. }
  32750. return this;
  32751. }
  32752. return 0;
  32753. }
  32754. Component* Component::getComponentAt (const int x, const int y)
  32755. {
  32756. return getComponentAt (Point<int> (x, y));
  32757. }
  32758. void Component::addChildComponent (Component* const child, int zOrder)
  32759. {
  32760. // if component methods are being called from threads other than the message
  32761. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32762. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32763. if (child != 0 && child->parentComponent != this)
  32764. {
  32765. if (child->parentComponent != 0)
  32766. child->parentComponent->removeChildComponent (child);
  32767. else
  32768. child->removeFromDesktop();
  32769. child->parentComponent = this;
  32770. if (child->isVisible())
  32771. child->repaintParent();
  32772. if (! child->isAlwaysOnTop())
  32773. {
  32774. if (zOrder < 0 || zOrder > childComponentList.size())
  32775. zOrder = childComponentList.size();
  32776. while (zOrder > 0)
  32777. {
  32778. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32779. break;
  32780. --zOrder;
  32781. }
  32782. }
  32783. childComponentList.insert (zOrder, child);
  32784. child->internalHierarchyChanged();
  32785. internalChildrenChanged();
  32786. }
  32787. }
  32788. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32789. {
  32790. if (child != 0)
  32791. {
  32792. child->setVisible (true);
  32793. addChildComponent (child, zOrder);
  32794. }
  32795. }
  32796. void Component::removeChildComponent (Component* const child)
  32797. {
  32798. removeChildComponent (childComponentList.indexOf (child), true, true);
  32799. }
  32800. Component* Component::removeChildComponent (const int index)
  32801. {
  32802. return removeChildComponent (index, true, true);
  32803. }
  32804. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32805. {
  32806. // if component methods are being called from threads other than the message
  32807. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32808. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32809. Component* const child = childComponentList [index];
  32810. if (child != 0)
  32811. {
  32812. sendParentEvents = sendParentEvents && child->isShowing();
  32813. if (sendParentEvents)
  32814. {
  32815. sendFakeMouseMove();
  32816. child->repaintParent();
  32817. }
  32818. childComponentList.remove (index);
  32819. child->parentComponent = 0;
  32820. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32821. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32822. {
  32823. if (sendParentEvents)
  32824. {
  32825. const WeakReference<Component> thisPointer (this);
  32826. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32827. if (thisPointer == 0)
  32828. return child;
  32829. grabKeyboardFocus();
  32830. }
  32831. else
  32832. {
  32833. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32834. }
  32835. }
  32836. if (sendChildEvents)
  32837. child->internalHierarchyChanged();
  32838. if (sendParentEvents)
  32839. internalChildrenChanged();
  32840. }
  32841. return child;
  32842. }
  32843. void Component::removeAllChildren()
  32844. {
  32845. while (childComponentList.size() > 0)
  32846. removeChildComponent (childComponentList.size() - 1);
  32847. }
  32848. void Component::deleteAllChildren()
  32849. {
  32850. while (childComponentList.size() > 0)
  32851. delete (removeChildComponent (childComponentList.size() - 1));
  32852. }
  32853. int Component::getNumChildComponents() const throw()
  32854. {
  32855. return childComponentList.size();
  32856. }
  32857. Component* Component::getChildComponent (const int index) const throw()
  32858. {
  32859. return childComponentList [index];
  32860. }
  32861. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32862. {
  32863. return childComponentList.indexOf (const_cast <Component*> (child));
  32864. }
  32865. Component* Component::getTopLevelComponent() const throw()
  32866. {
  32867. const Component* comp = this;
  32868. while (comp->parentComponent != 0)
  32869. comp = comp->parentComponent;
  32870. return const_cast <Component*> (comp);
  32871. }
  32872. bool Component::isParentOf (const Component* possibleChild) const throw()
  32873. {
  32874. while (possibleChild != 0)
  32875. {
  32876. possibleChild = possibleChild->parentComponent;
  32877. if (possibleChild == this)
  32878. return true;
  32879. }
  32880. return false;
  32881. }
  32882. void Component::parentHierarchyChanged()
  32883. {
  32884. }
  32885. void Component::childrenChanged()
  32886. {
  32887. }
  32888. void Component::internalChildrenChanged()
  32889. {
  32890. if (componentListeners.isEmpty())
  32891. {
  32892. childrenChanged();
  32893. }
  32894. else
  32895. {
  32896. BailOutChecker checker (this);
  32897. childrenChanged();
  32898. if (! checker.shouldBailOut())
  32899. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32900. }
  32901. }
  32902. void Component::internalHierarchyChanged()
  32903. {
  32904. BailOutChecker checker (this);
  32905. parentHierarchyChanged();
  32906. if (checker.shouldBailOut())
  32907. return;
  32908. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32909. if (checker.shouldBailOut())
  32910. return;
  32911. for (int i = childComponentList.size(); --i >= 0;)
  32912. {
  32913. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32914. if (checker.shouldBailOut())
  32915. {
  32916. // you really shouldn't delete the parent component during a callback telling you
  32917. // that it's changed..
  32918. jassertfalse;
  32919. return;
  32920. }
  32921. i = jmin (i, childComponentList.size());
  32922. }
  32923. }
  32924. #if JUCE_MODAL_LOOPS_PERMITTED
  32925. int Component::runModalLoop()
  32926. {
  32927. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32928. {
  32929. // use a callback so this can be called from non-gui threads
  32930. return (int) (pointer_sized_int) MessageManager::getInstance()
  32931. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32932. }
  32933. if (! isCurrentlyModal())
  32934. enterModalState (true);
  32935. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32936. }
  32937. #endif
  32938. class ModalAutoDeleteCallback : public ModalComponentManager::Callback
  32939. {
  32940. public:
  32941. ModalAutoDeleteCallback (Component* const comp_)
  32942. : comp (comp_)
  32943. {}
  32944. void modalStateFinished (int)
  32945. {
  32946. delete comp.get();
  32947. }
  32948. private:
  32949. WeakReference<Component> comp;
  32950. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModalAutoDeleteCallback);
  32951. };
  32952. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  32953. ModalComponentManager::Callback* callback,
  32954. const bool deleteWhenDismissed)
  32955. {
  32956. // if component methods are being called from threads other than the message
  32957. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32958. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32959. // Check for an attempt to make a component modal when it already is!
  32960. // This can cause nasty problems..
  32961. jassert (! flags.currentlyModalFlag);
  32962. if (! isCurrentlyModal())
  32963. {
  32964. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  32965. mcm->startModal (this);
  32966. mcm->attachCallback (this, callback);
  32967. if (deleteWhenDismissed)
  32968. mcm->attachCallback (this, new ModalAutoDeleteCallback (this));
  32969. flags.currentlyModalFlag = true;
  32970. setVisible (true);
  32971. if (shouldTakeKeyboardFocus)
  32972. grabKeyboardFocus();
  32973. }
  32974. }
  32975. void Component::exitModalState (const int returnValue)
  32976. {
  32977. if (flags.currentlyModalFlag)
  32978. {
  32979. if (MessageManager::getInstance()->isThisTheMessageThread())
  32980. {
  32981. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32982. flags.currentlyModalFlag = false;
  32983. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32984. }
  32985. else
  32986. {
  32987. class ExitModalStateMessage : public CallbackMessage
  32988. {
  32989. public:
  32990. ExitModalStateMessage (Component* const target_, const int result_)
  32991. : target (target_), result (result_) {}
  32992. void messageCallback()
  32993. {
  32994. if (target.get() != 0) // (get() required for VS2003 bug)
  32995. target->exitModalState (result);
  32996. }
  32997. private:
  32998. WeakReference<Component> target;
  32999. int result;
  33000. };
  33001. (new ExitModalStateMessage (this, returnValue))->post();
  33002. }
  33003. }
  33004. }
  33005. bool Component::isCurrentlyModal() const throw()
  33006. {
  33007. return flags.currentlyModalFlag
  33008. && getCurrentlyModalComponent() == this;
  33009. }
  33010. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33011. {
  33012. Component* const mc = getCurrentlyModalComponent();
  33013. return mc != 0
  33014. && mc != this
  33015. && (! mc->isParentOf (this))
  33016. && ! mc->canModalEventBeSentToComponent (this);
  33017. }
  33018. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33019. {
  33020. return ModalComponentManager::getInstance()->getNumModalComponents();
  33021. }
  33022. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33023. {
  33024. return ModalComponentManager::getInstance()->getModalComponent (index);
  33025. }
  33026. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33027. {
  33028. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33029. }
  33030. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33031. {
  33032. return flags.bringToFrontOnClickFlag;
  33033. }
  33034. void Component::setMouseCursor (const MouseCursor& newCursor)
  33035. {
  33036. if (cursor != newCursor)
  33037. {
  33038. cursor = newCursor;
  33039. if (flags.visibleFlag)
  33040. updateMouseCursor();
  33041. }
  33042. }
  33043. const MouseCursor Component::getMouseCursor()
  33044. {
  33045. return cursor;
  33046. }
  33047. void Component::updateMouseCursor() const
  33048. {
  33049. sendFakeMouseMove();
  33050. }
  33051. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33052. {
  33053. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33054. }
  33055. void Component::setAlpha (const float newAlpha)
  33056. {
  33057. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33058. if (componentTransparency != newIntAlpha)
  33059. {
  33060. componentTransparency = newIntAlpha;
  33061. if (flags.hasHeavyweightPeerFlag)
  33062. {
  33063. ComponentPeer* const peer = getPeer();
  33064. if (peer != 0)
  33065. peer->setAlpha (newAlpha);
  33066. }
  33067. else
  33068. {
  33069. repaint();
  33070. }
  33071. }
  33072. }
  33073. float Component::getAlpha() const
  33074. {
  33075. return (255 - componentTransparency) / 255.0f;
  33076. }
  33077. void Component::repaintParent()
  33078. {
  33079. if (flags.visibleFlag)
  33080. internalRepaint (0, 0, getWidth(), getHeight());
  33081. }
  33082. void Component::repaint()
  33083. {
  33084. repaint (0, 0, getWidth(), getHeight());
  33085. }
  33086. void Component::repaint (const int x, const int y,
  33087. const int w, const int h)
  33088. {
  33089. bufferedImage = Image::null;
  33090. if (flags.visibleFlag)
  33091. internalRepaint (x, y, w, h);
  33092. }
  33093. void Component::repaint (const Rectangle<int>& area)
  33094. {
  33095. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33096. }
  33097. void Component::internalRepaint (int x, int y, int w, int h)
  33098. {
  33099. // if component methods are being called from threads other than the message
  33100. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33101. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33102. if (x < 0)
  33103. {
  33104. w += x;
  33105. x = 0;
  33106. }
  33107. if (x + w > getWidth())
  33108. w = getWidth() - x;
  33109. if (w > 0)
  33110. {
  33111. if (y < 0)
  33112. {
  33113. h += y;
  33114. y = 0;
  33115. }
  33116. if (y + h > getHeight())
  33117. h = getHeight() - y;
  33118. if (h > 0)
  33119. {
  33120. if (parentComponent != 0)
  33121. {
  33122. if (parentComponent->flags.visibleFlag)
  33123. {
  33124. if (affineTransform == 0)
  33125. {
  33126. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33127. }
  33128. else
  33129. {
  33130. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33131. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33132. }
  33133. }
  33134. }
  33135. else if (flags.hasHeavyweightPeerFlag)
  33136. {
  33137. ComponentPeer* const peer = getPeer();
  33138. if (peer != 0)
  33139. peer->repaint (Rectangle<int> (x, y, w, h));
  33140. }
  33141. }
  33142. }
  33143. }
  33144. void Component::paintComponent (Graphics& g)
  33145. {
  33146. if (flags.bufferToImageFlag)
  33147. {
  33148. if (bufferedImage.isNull())
  33149. {
  33150. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33151. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33152. Graphics imG (bufferedImage);
  33153. paint (imG);
  33154. }
  33155. g.setColour (Colours::black.withAlpha (getAlpha()));
  33156. g.drawImageAt (bufferedImage, 0, 0);
  33157. }
  33158. else
  33159. {
  33160. paint (g);
  33161. }
  33162. }
  33163. void Component::paintWithinParentContext (Graphics& g)
  33164. {
  33165. g.setOrigin (getX(), getY());
  33166. paintEntireComponent (g, false);
  33167. }
  33168. void Component::paintComponentAndChildren (Graphics& g)
  33169. {
  33170. const Rectangle<int> clipBounds (g.getClipBounds());
  33171. if (flags.dontClipGraphicsFlag)
  33172. {
  33173. paintComponent (g);
  33174. }
  33175. else
  33176. {
  33177. g.saveState();
  33178. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33179. if (! g.isClipEmpty())
  33180. paintComponent (g);
  33181. g.restoreState();
  33182. }
  33183. for (int i = 0; i < childComponentList.size(); ++i)
  33184. {
  33185. Component& child = *childComponentList.getUnchecked (i);
  33186. if (child.isVisible())
  33187. {
  33188. if (child.affineTransform != 0)
  33189. {
  33190. g.saveState();
  33191. g.addTransform (*child.affineTransform);
  33192. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33193. child.paintWithinParentContext (g);
  33194. g.restoreState();
  33195. }
  33196. else if (clipBounds.intersects (child.getBounds()))
  33197. {
  33198. g.saveState();
  33199. if (child.flags.dontClipGraphicsFlag)
  33200. {
  33201. child.paintWithinParentContext (g);
  33202. }
  33203. else if (g.reduceClipRegion (child.getBounds()))
  33204. {
  33205. bool nothingClipped = true;
  33206. for (int j = i + 1; j < childComponentList.size(); ++j)
  33207. {
  33208. const Component& sibling = *childComponentList.getUnchecked (j);
  33209. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33210. {
  33211. nothingClipped = false;
  33212. g.excludeClipRegion (sibling.getBounds());
  33213. }
  33214. }
  33215. if (nothingClipped || ! g.isClipEmpty())
  33216. child.paintWithinParentContext (g);
  33217. }
  33218. g.restoreState();
  33219. }
  33220. }
  33221. }
  33222. g.saveState();
  33223. paintOverChildren (g);
  33224. g.restoreState();
  33225. }
  33226. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33227. {
  33228. jassert (! g.isClipEmpty());
  33229. #if JUCE_DEBUG
  33230. flags.isInsidePaintCall = true;
  33231. #endif
  33232. if (effect != 0)
  33233. {
  33234. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33235. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33236. {
  33237. Graphics g2 (effectImage);
  33238. paintComponentAndChildren (g2);
  33239. }
  33240. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33241. }
  33242. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33243. {
  33244. if (componentTransparency < 255)
  33245. {
  33246. g.beginTransparencyLayer (getAlpha());
  33247. paintComponentAndChildren (g);
  33248. g.endTransparencyLayer();
  33249. }
  33250. }
  33251. else
  33252. {
  33253. paintComponentAndChildren (g);
  33254. }
  33255. #if JUCE_DEBUG
  33256. flags.isInsidePaintCall = false;
  33257. #endif
  33258. }
  33259. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33260. {
  33261. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33262. }
  33263. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33264. const bool clipImageToComponentBounds)
  33265. {
  33266. Rectangle<int> r (areaToGrab);
  33267. if (clipImageToComponentBounds)
  33268. r = r.getIntersection (getLocalBounds());
  33269. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33270. jmax (1, r.getWidth()),
  33271. jmax (1, r.getHeight()),
  33272. true);
  33273. Graphics imageContext (componentImage);
  33274. imageContext.setOrigin (-r.getX(), -r.getY());
  33275. paintEntireComponent (imageContext, true);
  33276. return componentImage;
  33277. }
  33278. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33279. {
  33280. if (effect != newEffect)
  33281. {
  33282. effect = newEffect;
  33283. repaint();
  33284. }
  33285. }
  33286. LookAndFeel& Component::getLookAndFeel() const throw()
  33287. {
  33288. const Component* c = this;
  33289. do
  33290. {
  33291. if (c->lookAndFeel != 0)
  33292. return *(c->lookAndFeel);
  33293. c = c->parentComponent;
  33294. }
  33295. while (c != 0);
  33296. return LookAndFeel::getDefaultLookAndFeel();
  33297. }
  33298. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33299. {
  33300. if (lookAndFeel != newLookAndFeel)
  33301. {
  33302. lookAndFeel = newLookAndFeel;
  33303. sendLookAndFeelChange();
  33304. }
  33305. }
  33306. void Component::lookAndFeelChanged()
  33307. {
  33308. }
  33309. void Component::sendLookAndFeelChange()
  33310. {
  33311. repaint();
  33312. WeakReference<Component> safePointer (this);
  33313. lookAndFeelChanged();
  33314. if (safePointer != 0)
  33315. {
  33316. for (int i = childComponentList.size(); --i >= 0;)
  33317. {
  33318. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33319. if (safePointer == 0)
  33320. return;
  33321. i = jmin (i, childComponentList.size());
  33322. }
  33323. }
  33324. }
  33325. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33326. {
  33327. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33328. if (v != 0)
  33329. return Colour ((int) *v);
  33330. if (inheritFromParent && parentComponent != 0)
  33331. return parentComponent->findColour (colourId, true);
  33332. return getLookAndFeel().findColour (colourId);
  33333. }
  33334. bool Component::isColourSpecified (const int colourId) const
  33335. {
  33336. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33337. }
  33338. void Component::removeColour (const int colourId)
  33339. {
  33340. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33341. colourChanged();
  33342. }
  33343. void Component::setColour (const int colourId, const Colour& colour)
  33344. {
  33345. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33346. colourChanged();
  33347. }
  33348. void Component::copyAllExplicitColoursTo (Component& target) const
  33349. {
  33350. bool changed = false;
  33351. for (int i = properties.size(); --i >= 0;)
  33352. {
  33353. const Identifier name (properties.getName(i));
  33354. if (name.toString().startsWith ("jcclr_"))
  33355. if (target.properties.set (name, properties [name]))
  33356. changed = true;
  33357. }
  33358. if (changed)
  33359. target.colourChanged();
  33360. }
  33361. void Component::colourChanged()
  33362. {
  33363. }
  33364. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33365. {
  33366. return 0;
  33367. }
  33368. Component::Positioner::Positioner (Component& component_) throw()
  33369. : component (component_)
  33370. {
  33371. }
  33372. Component::Positioner* Component::getPositioner() const throw()
  33373. {
  33374. return positioner;
  33375. }
  33376. void Component::setPositioner (Positioner* newPositioner)
  33377. {
  33378. // You can only assign a positioner to the component that it was created for!
  33379. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33380. positioner = newPositioner;
  33381. }
  33382. const Rectangle<int> Component::getLocalBounds() const throw()
  33383. {
  33384. return Rectangle<int> (getWidth(), getHeight());
  33385. }
  33386. const Rectangle<int> Component::getBoundsInParent() const throw()
  33387. {
  33388. return affineTransform == 0 ? bounds
  33389. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33390. }
  33391. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33392. {
  33393. result.clear();
  33394. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33395. if (! unclipped.isEmpty())
  33396. {
  33397. result.add (unclipped);
  33398. if (includeSiblings)
  33399. {
  33400. const Component* const c = getTopLevelComponent();
  33401. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33402. c->getLocalBounds(), this);
  33403. }
  33404. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33405. result.consolidate();
  33406. }
  33407. }
  33408. void Component::mouseEnter (const MouseEvent&)
  33409. {
  33410. // base class does nothing
  33411. }
  33412. void Component::mouseExit (const MouseEvent&)
  33413. {
  33414. // base class does nothing
  33415. }
  33416. void Component::mouseDown (const MouseEvent&)
  33417. {
  33418. // base class does nothing
  33419. }
  33420. void Component::mouseUp (const MouseEvent&)
  33421. {
  33422. // base class does nothing
  33423. }
  33424. void Component::mouseDrag (const MouseEvent&)
  33425. {
  33426. // base class does nothing
  33427. }
  33428. void Component::mouseMove (const MouseEvent&)
  33429. {
  33430. // base class does nothing
  33431. }
  33432. void Component::mouseDoubleClick (const MouseEvent&)
  33433. {
  33434. // base class does nothing
  33435. }
  33436. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33437. {
  33438. // the base class just passes this event up to its parent..
  33439. if (parentComponent != 0)
  33440. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33441. wheelIncrementX, wheelIncrementY);
  33442. }
  33443. void Component::resized()
  33444. {
  33445. // base class does nothing
  33446. }
  33447. void Component::moved()
  33448. {
  33449. // base class does nothing
  33450. }
  33451. void Component::childBoundsChanged (Component*)
  33452. {
  33453. // base class does nothing
  33454. }
  33455. void Component::parentSizeChanged()
  33456. {
  33457. // base class does nothing
  33458. }
  33459. void Component::addComponentListener (ComponentListener* const newListener)
  33460. {
  33461. // if component methods are being called from threads other than the message
  33462. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33463. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33464. componentListeners.add (newListener);
  33465. }
  33466. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33467. {
  33468. componentListeners.remove (listenerToRemove);
  33469. }
  33470. void Component::inputAttemptWhenModal()
  33471. {
  33472. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33473. getLookAndFeel().playAlertSound();
  33474. }
  33475. bool Component::canModalEventBeSentToComponent (const Component*)
  33476. {
  33477. return false;
  33478. }
  33479. void Component::internalModalInputAttempt()
  33480. {
  33481. Component* const current = getCurrentlyModalComponent();
  33482. if (current != 0)
  33483. current->inputAttemptWhenModal();
  33484. }
  33485. void Component::paint (Graphics&)
  33486. {
  33487. // all painting is done in the subclasses
  33488. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33489. }
  33490. void Component::paintOverChildren (Graphics&)
  33491. {
  33492. // all painting is done in the subclasses
  33493. }
  33494. void Component::postCommandMessage (const int commandId)
  33495. {
  33496. class CustomCommandMessage : public CallbackMessage
  33497. {
  33498. public:
  33499. CustomCommandMessage (Component* const target_, const int commandId_)
  33500. : target (target_), commandId (commandId_) {}
  33501. void messageCallback()
  33502. {
  33503. if (target.get() != 0) // (get() required for VS2003 bug)
  33504. target->handleCommandMessage (commandId);
  33505. }
  33506. private:
  33507. WeakReference<Component> target;
  33508. int commandId;
  33509. };
  33510. (new CustomCommandMessage (this, commandId))->post();
  33511. }
  33512. void Component::handleCommandMessage (int)
  33513. {
  33514. // used by subclasses
  33515. }
  33516. void Component::addMouseListener (MouseListener* const newListener,
  33517. const bool wantsEventsForAllNestedChildComponents)
  33518. {
  33519. // if component methods are being called from threads other than the message
  33520. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33521. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33522. // If you register a component as a mouselistener for itself, it'll receive all the events
  33523. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33524. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33525. if (mouseListeners == 0)
  33526. mouseListeners = new MouseListenerList();
  33527. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33528. }
  33529. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33530. {
  33531. // if component methods are being called from threads other than the message
  33532. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33533. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33534. if (mouseListeners != 0)
  33535. mouseListeners->removeListener (listenerToRemove);
  33536. }
  33537. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33538. {
  33539. if (isCurrentlyBlockedByAnotherModalComponent())
  33540. {
  33541. // if something else is modal, always just show a normal mouse cursor
  33542. source.showMouseCursor (MouseCursor::NormalCursor);
  33543. return;
  33544. }
  33545. if (! flags.mouseInsideFlag)
  33546. {
  33547. flags.mouseInsideFlag = true;
  33548. flags.mouseOverFlag = true;
  33549. flags.mouseDownFlag = false;
  33550. BailOutChecker checker (this);
  33551. if (flags.repaintOnMouseActivityFlag)
  33552. repaint();
  33553. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33554. this, this, time, relativePos, time, 0, false);
  33555. mouseEnter (me);
  33556. if (checker.shouldBailOut())
  33557. return;
  33558. Desktop& desktop = Desktop::getInstance();
  33559. desktop.resetTimer();
  33560. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33561. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33562. }
  33563. }
  33564. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33565. {
  33566. BailOutChecker checker (this);
  33567. if (flags.mouseDownFlag)
  33568. {
  33569. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33570. if (checker.shouldBailOut())
  33571. return;
  33572. }
  33573. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33574. {
  33575. flags.mouseInsideFlag = false;
  33576. flags.mouseOverFlag = false;
  33577. flags.mouseDownFlag = false;
  33578. if (flags.repaintOnMouseActivityFlag)
  33579. repaint();
  33580. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33581. this, this, time, relativePos, time, 0, false);
  33582. mouseExit (me);
  33583. if (checker.shouldBailOut())
  33584. return;
  33585. Desktop& desktop = Desktop::getInstance();
  33586. desktop.resetTimer();
  33587. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33588. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33589. }
  33590. }
  33591. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33592. {
  33593. Desktop& desktop = Desktop::getInstance();
  33594. BailOutChecker checker (this);
  33595. if (isCurrentlyBlockedByAnotherModalComponent())
  33596. {
  33597. internalModalInputAttempt();
  33598. if (checker.shouldBailOut())
  33599. return;
  33600. // If processing the input attempt has exited the modal loop, we'll allow the event
  33601. // to be delivered..
  33602. if (isCurrentlyBlockedByAnotherModalComponent())
  33603. {
  33604. // allow blocked mouse-events to go to global listeners..
  33605. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33606. this, this, time, relativePos, time,
  33607. source.getNumberOfMultipleClicks(), false);
  33608. desktop.resetTimer();
  33609. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33610. return;
  33611. }
  33612. }
  33613. {
  33614. Component* c = this;
  33615. while (c != 0)
  33616. {
  33617. if (c->isBroughtToFrontOnMouseClick())
  33618. {
  33619. c->toFront (true);
  33620. if (checker.shouldBailOut())
  33621. return;
  33622. }
  33623. c = c->parentComponent;
  33624. }
  33625. }
  33626. if (! flags.dontFocusOnMouseClickFlag)
  33627. {
  33628. grabFocusInternal (focusChangedByMouseClick);
  33629. if (checker.shouldBailOut())
  33630. return;
  33631. }
  33632. flags.mouseDownFlag = true;
  33633. flags.mouseOverFlag = true;
  33634. if (flags.repaintOnMouseActivityFlag)
  33635. repaint();
  33636. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33637. this, this, time, relativePos, time,
  33638. source.getNumberOfMultipleClicks(), false);
  33639. mouseDown (me);
  33640. if (checker.shouldBailOut())
  33641. return;
  33642. desktop.resetTimer();
  33643. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33644. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33645. }
  33646. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33647. {
  33648. if (flags.mouseDownFlag)
  33649. {
  33650. flags.mouseDownFlag = false;
  33651. BailOutChecker checker (this);
  33652. if (flags.repaintOnMouseActivityFlag)
  33653. repaint();
  33654. const MouseEvent me (source, relativePos,
  33655. oldModifiers, this, this, time,
  33656. getLocalPoint (0, source.getLastMouseDownPosition()),
  33657. source.getLastMouseDownTime(),
  33658. source.getNumberOfMultipleClicks(),
  33659. source.hasMouseMovedSignificantlySincePressed());
  33660. mouseUp (me);
  33661. if (checker.shouldBailOut())
  33662. return;
  33663. Desktop& desktop = Desktop::getInstance();
  33664. desktop.resetTimer();
  33665. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33666. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33667. if (checker.shouldBailOut())
  33668. return;
  33669. // check for double-click
  33670. if (me.getNumberOfClicks() >= 2)
  33671. {
  33672. mouseDoubleClick (me);
  33673. if (checker.shouldBailOut())
  33674. return;
  33675. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33676. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33677. }
  33678. }
  33679. }
  33680. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33681. {
  33682. if (flags.mouseDownFlag)
  33683. {
  33684. flags.mouseOverFlag = reallyContains (relativePos, false);
  33685. BailOutChecker checker (this);
  33686. const MouseEvent me (source, relativePos,
  33687. source.getCurrentModifiers(), this, this, time,
  33688. getLocalPoint (0, source.getLastMouseDownPosition()),
  33689. source.getLastMouseDownTime(),
  33690. source.getNumberOfMultipleClicks(),
  33691. source.hasMouseMovedSignificantlySincePressed());
  33692. mouseDrag (me);
  33693. if (checker.shouldBailOut())
  33694. return;
  33695. Desktop& desktop = Desktop::getInstance();
  33696. desktop.resetTimer();
  33697. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33698. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33699. }
  33700. }
  33701. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33702. {
  33703. Desktop& desktop = Desktop::getInstance();
  33704. BailOutChecker checker (this);
  33705. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33706. this, this, time, relativePos, time, 0, false);
  33707. if (isCurrentlyBlockedByAnotherModalComponent())
  33708. {
  33709. // allow blocked mouse-events to go to global listeners..
  33710. desktop.sendMouseMove();
  33711. }
  33712. else
  33713. {
  33714. flags.mouseOverFlag = true;
  33715. mouseMove (me);
  33716. if (checker.shouldBailOut())
  33717. return;
  33718. desktop.resetTimer();
  33719. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33720. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33721. }
  33722. }
  33723. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33724. const Time& time, const float amountX, const float amountY)
  33725. {
  33726. Desktop& desktop = Desktop::getInstance();
  33727. BailOutChecker checker (this);
  33728. const float wheelIncrementX = amountX / 256.0f;
  33729. const float wheelIncrementY = amountY / 256.0f;
  33730. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33731. this, this, time, relativePos, time, 0, false);
  33732. if (isCurrentlyBlockedByAnotherModalComponent())
  33733. {
  33734. // allow blocked mouse-events to go to global listeners..
  33735. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33736. }
  33737. else
  33738. {
  33739. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33740. if (checker.shouldBailOut())
  33741. return;
  33742. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33743. if (! checker.shouldBailOut())
  33744. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33745. }
  33746. }
  33747. void Component::sendFakeMouseMove() const
  33748. {
  33749. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33750. if (! mainMouse.isDragging())
  33751. mainMouse.triggerFakeMove();
  33752. }
  33753. void Component::beginDragAutoRepeat (const int interval)
  33754. {
  33755. Desktop::getInstance().beginDragAutoRepeat (interval);
  33756. }
  33757. void Component::broughtToFront()
  33758. {
  33759. }
  33760. void Component::internalBroughtToFront()
  33761. {
  33762. if (flags.hasHeavyweightPeerFlag)
  33763. Desktop::getInstance().componentBroughtToFront (this);
  33764. BailOutChecker checker (this);
  33765. broughtToFront();
  33766. if (checker.shouldBailOut())
  33767. return;
  33768. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33769. if (checker.shouldBailOut())
  33770. return;
  33771. // When brought to the front and there's a modal component blocking this one,
  33772. // we need to bring the modal one to the front instead..
  33773. Component* const cm = getCurrentlyModalComponent();
  33774. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33775. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33776. }
  33777. void Component::focusGained (FocusChangeType)
  33778. {
  33779. // base class does nothing
  33780. }
  33781. void Component::internalFocusGain (const FocusChangeType cause)
  33782. {
  33783. internalFocusGain (cause, WeakReference<Component> (this));
  33784. }
  33785. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33786. {
  33787. focusGained (cause);
  33788. if (safePointer != 0)
  33789. internalChildFocusChange (cause, safePointer);
  33790. }
  33791. void Component::focusLost (FocusChangeType)
  33792. {
  33793. // base class does nothing
  33794. }
  33795. void Component::internalFocusLoss (const FocusChangeType cause)
  33796. {
  33797. WeakReference<Component> safePointer (this);
  33798. focusLost (focusChangedDirectly);
  33799. if (safePointer != 0)
  33800. internalChildFocusChange (cause, safePointer);
  33801. }
  33802. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33803. {
  33804. // base class does nothing
  33805. }
  33806. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33807. {
  33808. const bool childIsNowFocused = hasKeyboardFocus (true);
  33809. if (flags.childCompFocusedFlag != childIsNowFocused)
  33810. {
  33811. flags.childCompFocusedFlag = childIsNowFocused;
  33812. focusOfChildComponentChanged (cause);
  33813. if (safePointer == 0)
  33814. return;
  33815. }
  33816. if (parentComponent != 0)
  33817. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33818. }
  33819. bool Component::isEnabled() const throw()
  33820. {
  33821. return (! flags.isDisabledFlag)
  33822. && (parentComponent == 0 || parentComponent->isEnabled());
  33823. }
  33824. void Component::setEnabled (const bool shouldBeEnabled)
  33825. {
  33826. if (flags.isDisabledFlag == shouldBeEnabled)
  33827. {
  33828. flags.isDisabledFlag = ! shouldBeEnabled;
  33829. // if any parent components are disabled, setting our flag won't make a difference,
  33830. // so no need to send a change message
  33831. if (parentComponent == 0 || parentComponent->isEnabled())
  33832. sendEnablementChangeMessage();
  33833. }
  33834. }
  33835. void Component::sendEnablementChangeMessage()
  33836. {
  33837. WeakReference<Component> safePointer (this);
  33838. enablementChanged();
  33839. if (safePointer == 0)
  33840. return;
  33841. for (int i = getNumChildComponents(); --i >= 0;)
  33842. {
  33843. Component* const c = getChildComponent (i);
  33844. if (c != 0)
  33845. {
  33846. c->sendEnablementChangeMessage();
  33847. if (safePointer == 0)
  33848. return;
  33849. }
  33850. }
  33851. }
  33852. void Component::enablementChanged()
  33853. {
  33854. }
  33855. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33856. {
  33857. flags.wantsFocusFlag = wantsFocus;
  33858. }
  33859. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33860. {
  33861. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33862. }
  33863. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33864. {
  33865. return ! flags.dontFocusOnMouseClickFlag;
  33866. }
  33867. bool Component::getWantsKeyboardFocus() const throw()
  33868. {
  33869. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33870. }
  33871. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33872. {
  33873. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33874. }
  33875. bool Component::isFocusContainer() const throw()
  33876. {
  33877. return flags.isFocusContainerFlag;
  33878. }
  33879. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33880. int Component::getExplicitFocusOrder() const
  33881. {
  33882. return properties [juce_explicitFocusOrderId];
  33883. }
  33884. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33885. {
  33886. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33887. }
  33888. KeyboardFocusTraverser* Component::createFocusTraverser()
  33889. {
  33890. if (flags.isFocusContainerFlag || parentComponent == 0)
  33891. return new KeyboardFocusTraverser();
  33892. return parentComponent->createFocusTraverser();
  33893. }
  33894. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33895. {
  33896. // give the focus to this component
  33897. if (currentlyFocusedComponent != this)
  33898. {
  33899. // get the focus onto our desktop window
  33900. ComponentPeer* const peer = getPeer();
  33901. if (peer != 0)
  33902. {
  33903. WeakReference<Component> safePointer (this);
  33904. peer->grabFocus();
  33905. if (peer->isFocused() && currentlyFocusedComponent != this)
  33906. {
  33907. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33908. currentlyFocusedComponent = this;
  33909. Desktop::getInstance().triggerFocusCallback();
  33910. // call this after setting currentlyFocusedComponent so that the one that's
  33911. // losing it has a chance to see where focus is going
  33912. if (componentLosingFocus != 0)
  33913. componentLosingFocus->internalFocusLoss (cause);
  33914. if (currentlyFocusedComponent == this)
  33915. internalFocusGain (cause, safePointer);
  33916. }
  33917. }
  33918. }
  33919. }
  33920. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33921. {
  33922. if (isShowing())
  33923. {
  33924. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33925. {
  33926. takeKeyboardFocus (cause);
  33927. }
  33928. else
  33929. {
  33930. if (isParentOf (currentlyFocusedComponent)
  33931. && currentlyFocusedComponent->isShowing())
  33932. {
  33933. // do nothing if the focused component is actually a child of ours..
  33934. }
  33935. else
  33936. {
  33937. // find the default child component..
  33938. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33939. if (traverser != 0)
  33940. {
  33941. Component* const defaultComp = traverser->getDefaultComponent (this);
  33942. traverser = 0;
  33943. if (defaultComp != 0)
  33944. {
  33945. defaultComp->grabFocusInternal (cause, false);
  33946. return;
  33947. }
  33948. }
  33949. if (canTryParent && parentComponent != 0)
  33950. {
  33951. // if no children want it and we're allowed to try our parent comp,
  33952. // then pass up to parent, which will try our siblings.
  33953. parentComponent->grabFocusInternal (cause, true);
  33954. }
  33955. }
  33956. }
  33957. }
  33958. }
  33959. void Component::grabKeyboardFocus()
  33960. {
  33961. // if component methods are being called from threads other than the message
  33962. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33963. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33964. grabFocusInternal (focusChangedDirectly);
  33965. }
  33966. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33967. {
  33968. // if component methods are being called from threads other than the message
  33969. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33970. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33971. if (parentComponent != 0)
  33972. {
  33973. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33974. if (traverser != 0)
  33975. {
  33976. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33977. : traverser->getPreviousComponent (this);
  33978. traverser = 0;
  33979. if (nextComp != 0)
  33980. {
  33981. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33982. {
  33983. WeakReference<Component> nextCompPointer (nextComp);
  33984. internalModalInputAttempt();
  33985. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33986. return;
  33987. }
  33988. nextComp->grabFocusInternal (focusChangedByTabKey);
  33989. return;
  33990. }
  33991. }
  33992. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  33993. }
  33994. }
  33995. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33996. {
  33997. return (currentlyFocusedComponent == this)
  33998. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33999. }
  34000. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34001. {
  34002. return currentlyFocusedComponent;
  34003. }
  34004. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34005. {
  34006. Component* const componentLosingFocus = currentlyFocusedComponent;
  34007. currentlyFocusedComponent = 0;
  34008. if (sendFocusLossEvent && componentLosingFocus != 0)
  34009. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34010. Desktop::getInstance().triggerFocusCallback();
  34011. }
  34012. bool Component::isMouseOver (const bool includeChildren) const
  34013. {
  34014. if (flags.mouseOverFlag)
  34015. return true;
  34016. if (includeChildren)
  34017. {
  34018. Desktop& desktop = Desktop::getInstance();
  34019. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34020. {
  34021. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34022. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34023. return true;
  34024. }
  34025. }
  34026. return false;
  34027. }
  34028. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34029. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34030. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34031. {
  34032. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34033. }
  34034. const Point<int> Component::getMouseXYRelative() const
  34035. {
  34036. return getLocalPoint (0, Desktop::getMousePosition());
  34037. }
  34038. const Rectangle<int> Component::getParentMonitorArea() const
  34039. {
  34040. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34041. }
  34042. void Component::addKeyListener (KeyListener* const newListener)
  34043. {
  34044. if (keyListeners == 0)
  34045. keyListeners = new Array <KeyListener*>();
  34046. keyListeners->addIfNotAlreadyThere (newListener);
  34047. }
  34048. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34049. {
  34050. if (keyListeners != 0)
  34051. keyListeners->removeValue (listenerToRemove);
  34052. }
  34053. bool Component::keyPressed (const KeyPress&)
  34054. {
  34055. return false;
  34056. }
  34057. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34058. {
  34059. return false;
  34060. }
  34061. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34062. {
  34063. if (parentComponent != 0)
  34064. parentComponent->modifierKeysChanged (modifiers);
  34065. }
  34066. void Component::internalModifierKeysChanged()
  34067. {
  34068. sendFakeMouseMove();
  34069. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34070. }
  34071. ComponentPeer* Component::getPeer() const
  34072. {
  34073. if (flags.hasHeavyweightPeerFlag)
  34074. return ComponentPeer::getPeerFor (this);
  34075. else if (parentComponent == 0)
  34076. return 0;
  34077. return parentComponent->getPeer();
  34078. }
  34079. Component::BailOutChecker::BailOutChecker (Component* const component)
  34080. : safePointer (component)
  34081. {
  34082. jassert (component != 0);
  34083. }
  34084. bool Component::BailOutChecker::shouldBailOut() const throw()
  34085. {
  34086. return safePointer == 0;
  34087. }
  34088. END_JUCE_NAMESPACE
  34089. /*** End of inlined file: juce_Component.cpp ***/
  34090. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34091. BEGIN_JUCE_NAMESPACE
  34092. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34093. void ComponentListener::componentBroughtToFront (Component&) {}
  34094. void ComponentListener::componentVisibilityChanged (Component&) {}
  34095. void ComponentListener::componentChildrenChanged (Component&) {}
  34096. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34097. void ComponentListener::componentNameChanged (Component&) {}
  34098. void ComponentListener::componentBeingDeleted (Component&) {}
  34099. END_JUCE_NAMESPACE
  34100. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34101. /*** Start of inlined file: juce_Desktop.cpp ***/
  34102. BEGIN_JUCE_NAMESPACE
  34103. Desktop::Desktop()
  34104. : mouseClickCounter (0),
  34105. kioskModeComponent (0),
  34106. allowedOrientations (allOrientations)
  34107. {
  34108. createMouseInputSources();
  34109. refreshMonitorSizes();
  34110. }
  34111. Desktop::~Desktop()
  34112. {
  34113. jassert (instance == this);
  34114. instance = 0;
  34115. // doh! If you don't delete all your windows before exiting, you're going to
  34116. // be leaking memory!
  34117. jassert (desktopComponents.size() == 0);
  34118. }
  34119. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34120. {
  34121. if (instance == 0)
  34122. instance = new Desktop();
  34123. return *instance;
  34124. }
  34125. Desktop* Desktop::instance = 0;
  34126. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34127. const bool clipToWorkArea);
  34128. void Desktop::refreshMonitorSizes()
  34129. {
  34130. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34131. oldClipped.swapWithArray (monitorCoordsClipped);
  34132. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34133. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34134. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34135. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34136. if (oldClipped != monitorCoordsClipped
  34137. || oldUnclipped != monitorCoordsUnclipped)
  34138. {
  34139. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34140. {
  34141. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34142. if (p != 0)
  34143. p->handleScreenSizeChange();
  34144. }
  34145. }
  34146. }
  34147. int Desktop::getNumDisplayMonitors() const throw()
  34148. {
  34149. return monitorCoordsClipped.size();
  34150. }
  34151. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34152. {
  34153. return clippedToWorkArea ? monitorCoordsClipped [index]
  34154. : monitorCoordsUnclipped [index];
  34155. }
  34156. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34157. {
  34158. RectangleList rl;
  34159. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34160. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34161. return rl;
  34162. }
  34163. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34164. {
  34165. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34166. }
  34167. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34168. {
  34169. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34170. double bestDistance = 1.0e10;
  34171. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34172. {
  34173. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34174. if (rect.contains (position))
  34175. return rect;
  34176. const double distance = rect.getCentre().getDistanceFrom (position);
  34177. if (distance < bestDistance)
  34178. {
  34179. bestDistance = distance;
  34180. best = rect;
  34181. }
  34182. }
  34183. return best;
  34184. }
  34185. int Desktop::getNumComponents() const throw()
  34186. {
  34187. return desktopComponents.size();
  34188. }
  34189. Component* Desktop::getComponent (const int index) const throw()
  34190. {
  34191. return desktopComponents [index];
  34192. }
  34193. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34194. {
  34195. for (int i = desktopComponents.size(); --i >= 0;)
  34196. {
  34197. Component* const c = desktopComponents.getUnchecked(i);
  34198. if (c->isVisible())
  34199. {
  34200. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34201. if (c->contains (relative))
  34202. return c->getComponentAt (relative);
  34203. }
  34204. }
  34205. return 0;
  34206. }
  34207. void Desktop::addDesktopComponent (Component* const c)
  34208. {
  34209. jassert (c != 0);
  34210. jassert (! desktopComponents.contains (c));
  34211. desktopComponents.addIfNotAlreadyThere (c);
  34212. }
  34213. void Desktop::removeDesktopComponent (Component* const c)
  34214. {
  34215. desktopComponents.removeValue (c);
  34216. }
  34217. void Desktop::componentBroughtToFront (Component* const c)
  34218. {
  34219. const int index = desktopComponents.indexOf (c);
  34220. jassert (index >= 0);
  34221. if (index >= 0)
  34222. {
  34223. int newIndex = -1;
  34224. if (! c->isAlwaysOnTop())
  34225. {
  34226. newIndex = desktopComponents.size();
  34227. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34228. --newIndex;
  34229. --newIndex;
  34230. }
  34231. desktopComponents.move (index, newIndex);
  34232. }
  34233. }
  34234. const Point<int> Desktop::getMousePosition()
  34235. {
  34236. return getInstance().getMainMouseSource().getScreenPosition();
  34237. }
  34238. const Point<int> Desktop::getLastMouseDownPosition()
  34239. {
  34240. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34241. }
  34242. int Desktop::getMouseButtonClickCounter()
  34243. {
  34244. return getInstance().mouseClickCounter;
  34245. }
  34246. void Desktop::incrementMouseClickCounter() throw()
  34247. {
  34248. ++mouseClickCounter;
  34249. }
  34250. int Desktop::getNumDraggingMouseSources() const throw()
  34251. {
  34252. int num = 0;
  34253. for (int i = mouseSources.size(); --i >= 0;)
  34254. if (mouseSources.getUnchecked(i)->isDragging())
  34255. ++num;
  34256. return num;
  34257. }
  34258. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34259. {
  34260. int num = 0;
  34261. for (int i = mouseSources.size(); --i >= 0;)
  34262. {
  34263. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34264. if (mi->isDragging())
  34265. {
  34266. if (index == num)
  34267. return mi;
  34268. ++num;
  34269. }
  34270. }
  34271. return 0;
  34272. }
  34273. class MouseDragAutoRepeater : public Timer
  34274. {
  34275. public:
  34276. MouseDragAutoRepeater() {}
  34277. void timerCallback()
  34278. {
  34279. Desktop& desktop = Desktop::getInstance();
  34280. int numMiceDown = 0;
  34281. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34282. {
  34283. MouseInputSource* const source = desktop.getMouseSource(i);
  34284. if (source->isDragging())
  34285. {
  34286. source->triggerFakeMove();
  34287. ++numMiceDown;
  34288. }
  34289. }
  34290. if (numMiceDown == 0)
  34291. desktop.beginDragAutoRepeat (0);
  34292. }
  34293. private:
  34294. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34295. };
  34296. void Desktop::beginDragAutoRepeat (const int interval)
  34297. {
  34298. if (interval > 0)
  34299. {
  34300. if (dragRepeater == 0)
  34301. dragRepeater = new MouseDragAutoRepeater();
  34302. if (dragRepeater->getTimerInterval() != interval)
  34303. dragRepeater->startTimer (interval);
  34304. }
  34305. else
  34306. {
  34307. dragRepeater = 0;
  34308. }
  34309. }
  34310. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34311. {
  34312. focusListeners.add (listener);
  34313. }
  34314. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34315. {
  34316. focusListeners.remove (listener);
  34317. }
  34318. void Desktop::triggerFocusCallback()
  34319. {
  34320. triggerAsyncUpdate();
  34321. }
  34322. void Desktop::handleAsyncUpdate()
  34323. {
  34324. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34325. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34326. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34327. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34328. }
  34329. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34330. {
  34331. mouseListeners.add (listener);
  34332. resetTimer();
  34333. }
  34334. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34335. {
  34336. mouseListeners.remove (listener);
  34337. resetTimer();
  34338. }
  34339. void Desktop::timerCallback()
  34340. {
  34341. if (lastFakeMouseMove != getMousePosition())
  34342. sendMouseMove();
  34343. }
  34344. void Desktop::sendMouseMove()
  34345. {
  34346. if (! mouseListeners.isEmpty())
  34347. {
  34348. startTimer (20);
  34349. lastFakeMouseMove = getMousePosition();
  34350. Component* const target = findComponentAt (lastFakeMouseMove);
  34351. if (target != 0)
  34352. {
  34353. Component::BailOutChecker checker (target);
  34354. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34355. const Time now (Time::getCurrentTime());
  34356. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34357. target, target, now, pos, now, 0, false);
  34358. if (me.mods.isAnyMouseButtonDown())
  34359. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34360. else
  34361. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34362. }
  34363. }
  34364. }
  34365. void Desktop::resetTimer()
  34366. {
  34367. if (mouseListeners.size() == 0)
  34368. stopTimer();
  34369. else
  34370. startTimer (100);
  34371. lastFakeMouseMove = getMousePosition();
  34372. }
  34373. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34374. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34375. {
  34376. if (kioskModeComponent != componentToUse)
  34377. {
  34378. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34379. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34380. if (kioskModeComponent != 0)
  34381. {
  34382. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34383. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34384. }
  34385. kioskModeComponent = componentToUse;
  34386. if (kioskModeComponent != 0)
  34387. {
  34388. // Only components that are already on the desktop can be put into kiosk mode!
  34389. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34390. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34391. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34392. }
  34393. }
  34394. }
  34395. void Desktop::setOrientationsEnabled (const int newOrientations)
  34396. {
  34397. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34398. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34399. allowedOrientations = newOrientations;
  34400. }
  34401. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34402. {
  34403. // Make sure you only pass one valid flag in here...
  34404. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34405. return (allowedOrientations & orientation) != 0;
  34406. }
  34407. END_JUCE_NAMESPACE
  34408. /*** End of inlined file: juce_Desktop.cpp ***/
  34409. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34410. BEGIN_JUCE_NAMESPACE
  34411. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34412. {
  34413. public:
  34414. ModalItem (Component* const comp)
  34415. : ComponentMovementWatcher (comp),
  34416. component (comp), returnValue (0), isActive (true)
  34417. {
  34418. jassert (comp != 0);
  34419. }
  34420. void componentMovedOrResized (bool, bool) {}
  34421. void componentPeerChanged()
  34422. {
  34423. if (! component->isShowing())
  34424. cancel();
  34425. }
  34426. void componentVisibilityChanged()
  34427. {
  34428. if (! component->isShowing())
  34429. cancel();
  34430. }
  34431. void componentBeingDeleted (Component& comp)
  34432. {
  34433. ComponentMovementWatcher::componentBeingDeleted (comp);
  34434. if (component == &comp || comp.isParentOf (component))
  34435. cancel();
  34436. }
  34437. void cancel()
  34438. {
  34439. if (isActive)
  34440. {
  34441. isActive = false;
  34442. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34443. }
  34444. }
  34445. Component* component;
  34446. OwnedArray<Callback> callbacks;
  34447. int returnValue;
  34448. bool isActive;
  34449. private:
  34450. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34451. };
  34452. ModalComponentManager::ModalComponentManager()
  34453. {
  34454. }
  34455. ModalComponentManager::~ModalComponentManager()
  34456. {
  34457. clearSingletonInstance();
  34458. }
  34459. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34460. void ModalComponentManager::startModal (Component* component)
  34461. {
  34462. if (component != 0)
  34463. stack.add (new ModalItem (component));
  34464. }
  34465. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34466. {
  34467. if (callback != 0)
  34468. {
  34469. ScopedPointer<Callback> callbackDeleter (callback);
  34470. for (int i = stack.size(); --i >= 0;)
  34471. {
  34472. ModalItem* const item = stack.getUnchecked(i);
  34473. if (item->component == component)
  34474. {
  34475. item->callbacks.add (callback);
  34476. callbackDeleter.release();
  34477. break;
  34478. }
  34479. }
  34480. }
  34481. }
  34482. void ModalComponentManager::endModal (Component* component)
  34483. {
  34484. for (int i = stack.size(); --i >= 0;)
  34485. {
  34486. ModalItem* const item = stack.getUnchecked(i);
  34487. if (item->component == component)
  34488. item->cancel();
  34489. }
  34490. }
  34491. void ModalComponentManager::endModal (Component* component, int returnValue)
  34492. {
  34493. for (int i = stack.size(); --i >= 0;)
  34494. {
  34495. ModalItem* const item = stack.getUnchecked(i);
  34496. if (item->component == component)
  34497. {
  34498. item->returnValue = returnValue;
  34499. item->cancel();
  34500. }
  34501. }
  34502. }
  34503. int ModalComponentManager::getNumModalComponents() const
  34504. {
  34505. int n = 0;
  34506. for (int i = 0; i < stack.size(); ++i)
  34507. if (stack.getUnchecked(i)->isActive)
  34508. ++n;
  34509. return n;
  34510. }
  34511. Component* ModalComponentManager::getModalComponent (const int index) const
  34512. {
  34513. int n = 0;
  34514. for (int i = stack.size(); --i >= 0;)
  34515. {
  34516. const ModalItem* const item = stack.getUnchecked(i);
  34517. if (item->isActive)
  34518. if (n++ == index)
  34519. return item->component;
  34520. }
  34521. return 0;
  34522. }
  34523. bool ModalComponentManager::isModal (Component* const comp) const
  34524. {
  34525. for (int i = stack.size(); --i >= 0;)
  34526. {
  34527. const ModalItem* const item = stack.getUnchecked(i);
  34528. if (item->isActive && item->component == comp)
  34529. return true;
  34530. }
  34531. return false;
  34532. }
  34533. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34534. {
  34535. return comp == getModalComponent (0);
  34536. }
  34537. void ModalComponentManager::handleAsyncUpdate()
  34538. {
  34539. for (int i = stack.size(); --i >= 0;)
  34540. {
  34541. const ModalItem* const item = stack.getUnchecked(i);
  34542. if (! item->isActive)
  34543. {
  34544. ScopedPointer<ModalItem> item (stack.removeAndReturn (i));
  34545. for (int j = item->callbacks.size(); --j >= 0;)
  34546. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34547. }
  34548. }
  34549. }
  34550. void ModalComponentManager::bringModalComponentsToFront()
  34551. {
  34552. ComponentPeer* lastOne = 0;
  34553. for (int i = 0; i < getNumModalComponents(); ++i)
  34554. {
  34555. Component* const c = getModalComponent (i);
  34556. if (c == 0)
  34557. break;
  34558. ComponentPeer* peer = c->getPeer();
  34559. if (peer != 0 && peer != lastOne)
  34560. {
  34561. if (lastOne == 0)
  34562. {
  34563. peer->toFront (true);
  34564. peer->grabFocus();
  34565. }
  34566. else
  34567. peer->toBehind (lastOne);
  34568. lastOne = peer;
  34569. }
  34570. }
  34571. }
  34572. #if JUCE_MODAL_LOOPS_PERMITTED
  34573. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34574. {
  34575. public:
  34576. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34577. void modalStateFinished (int returnValue)
  34578. {
  34579. finished = true;
  34580. value = returnValue;
  34581. }
  34582. private:
  34583. int& value;
  34584. bool& finished;
  34585. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34586. };
  34587. int ModalComponentManager::runEventLoopForCurrentComponent()
  34588. {
  34589. // This can only be run from the message thread!
  34590. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34591. Component* currentlyModal = getModalComponent (0);
  34592. if (currentlyModal == 0)
  34593. return 0;
  34594. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34595. int returnValue = 0;
  34596. bool finished = false;
  34597. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34598. JUCE_TRY
  34599. {
  34600. while (! finished)
  34601. {
  34602. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34603. break;
  34604. }
  34605. }
  34606. JUCE_CATCH_EXCEPTION
  34607. if (prevFocused != 0)
  34608. prevFocused->grabKeyboardFocus();
  34609. return returnValue;
  34610. }
  34611. #endif
  34612. END_JUCE_NAMESPACE
  34613. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34614. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34615. BEGIN_JUCE_NAMESPACE
  34616. ArrowButton::ArrowButton (const String& name,
  34617. float arrowDirectionInRadians,
  34618. const Colour& arrowColour)
  34619. : Button (name),
  34620. colour (arrowColour)
  34621. {
  34622. path.lineTo (0.0f, 1.0f);
  34623. path.lineTo (1.0f, 0.5f);
  34624. path.closeSubPath();
  34625. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34626. 0.5f, 0.5f));
  34627. setComponentEffect (&shadow);
  34628. buttonStateChanged();
  34629. }
  34630. ArrowButton::~ArrowButton()
  34631. {
  34632. }
  34633. void ArrowButton::paintButton (Graphics& g,
  34634. bool /*isMouseOverButton*/,
  34635. bool /*isButtonDown*/)
  34636. {
  34637. g.setColour (colour);
  34638. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34639. (float) offset,
  34640. (float) (getWidth() - 3),
  34641. (float) (getHeight() - 3),
  34642. false));
  34643. }
  34644. void ArrowButton::buttonStateChanged()
  34645. {
  34646. offset = (isDown()) ? 1 : 0;
  34647. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34648. 0.3f, -1, 0);
  34649. }
  34650. END_JUCE_NAMESPACE
  34651. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34652. /*** Start of inlined file: juce_Button.cpp ***/
  34653. BEGIN_JUCE_NAMESPACE
  34654. class Button::RepeatTimer : public Timer
  34655. {
  34656. public:
  34657. RepeatTimer (Button& owner_) : owner (owner_) {}
  34658. void timerCallback() { owner.repeatTimerCallback(); }
  34659. private:
  34660. Button& owner;
  34661. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34662. };
  34663. Button::Button (const String& name)
  34664. : Component (name),
  34665. text (name),
  34666. buttonPressTime (0),
  34667. lastRepeatTime (0),
  34668. commandManagerToUse (0),
  34669. autoRepeatDelay (-1),
  34670. autoRepeatSpeed (0),
  34671. autoRepeatMinimumDelay (-1),
  34672. radioGroupId (0),
  34673. commandID (0),
  34674. connectedEdgeFlags (0),
  34675. buttonState (buttonNormal),
  34676. lastToggleState (false),
  34677. clickTogglesState (false),
  34678. needsToRelease (false),
  34679. needsRepainting (false),
  34680. isKeyDown (false),
  34681. triggerOnMouseDown (false),
  34682. generateTooltip (false)
  34683. {
  34684. setWantsKeyboardFocus (true);
  34685. isOn.addListener (this);
  34686. }
  34687. Button::~Button()
  34688. {
  34689. isOn.removeListener (this);
  34690. if (commandManagerToUse != 0)
  34691. commandManagerToUse->removeListener (this);
  34692. repeatTimer = 0;
  34693. clearShortcuts();
  34694. }
  34695. void Button::setButtonText (const String& newText)
  34696. {
  34697. if (text != newText)
  34698. {
  34699. text = newText;
  34700. repaint();
  34701. }
  34702. }
  34703. void Button::setTooltip (const String& newTooltip)
  34704. {
  34705. SettableTooltipClient::setTooltip (newTooltip);
  34706. generateTooltip = false;
  34707. }
  34708. const String Button::getTooltip()
  34709. {
  34710. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34711. {
  34712. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34713. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34714. for (int i = 0; i < keyPresses.size(); ++i)
  34715. {
  34716. const String key (keyPresses.getReference(i).getTextDescription());
  34717. tt << " [";
  34718. if (key.length() == 1)
  34719. tt << TRANS("shortcut") << ": '" << key << "']";
  34720. else
  34721. tt << key << ']';
  34722. }
  34723. return tt;
  34724. }
  34725. return SettableTooltipClient::getTooltip();
  34726. }
  34727. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34728. {
  34729. if (connectedEdgeFlags != connectedEdgeFlags_)
  34730. {
  34731. connectedEdgeFlags = connectedEdgeFlags_;
  34732. repaint();
  34733. }
  34734. }
  34735. void Button::setToggleState (const bool shouldBeOn,
  34736. const bool sendChangeNotification)
  34737. {
  34738. if (shouldBeOn != lastToggleState)
  34739. {
  34740. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34741. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34742. lastToggleState = shouldBeOn;
  34743. repaint();
  34744. WeakReference<Component> deletionWatcher (this);
  34745. if (sendChangeNotification)
  34746. {
  34747. sendClickMessage (ModifierKeys());
  34748. if (deletionWatcher == 0)
  34749. return;
  34750. }
  34751. if (lastToggleState)
  34752. {
  34753. turnOffOtherButtonsInGroup (sendChangeNotification);
  34754. if (deletionWatcher == 0)
  34755. return;
  34756. }
  34757. sendStateMessage();
  34758. }
  34759. }
  34760. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34761. {
  34762. clickTogglesState = shouldToggle;
  34763. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34764. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34765. // it is that this button represents, and the button will update its state to reflect this
  34766. // in the applicationCommandListChanged() method.
  34767. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34768. }
  34769. bool Button::getClickingTogglesState() const throw()
  34770. {
  34771. return clickTogglesState;
  34772. }
  34773. void Button::valueChanged (Value& value)
  34774. {
  34775. if (value.refersToSameSourceAs (isOn))
  34776. setToggleState (isOn.getValue(), true);
  34777. }
  34778. void Button::setRadioGroupId (const int newGroupId)
  34779. {
  34780. if (radioGroupId != newGroupId)
  34781. {
  34782. radioGroupId = newGroupId;
  34783. if (lastToggleState)
  34784. turnOffOtherButtonsInGroup (true);
  34785. }
  34786. }
  34787. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34788. {
  34789. Component* const p = getParentComponent();
  34790. if (p != 0 && radioGroupId != 0)
  34791. {
  34792. WeakReference<Component> deletionWatcher (this);
  34793. for (int i = p->getNumChildComponents(); --i >= 0;)
  34794. {
  34795. Component* const c = p->getChildComponent (i);
  34796. if (c != this)
  34797. {
  34798. Button* const b = dynamic_cast <Button*> (c);
  34799. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34800. {
  34801. b->setToggleState (false, sendChangeNotification);
  34802. if (deletionWatcher == 0)
  34803. return;
  34804. }
  34805. }
  34806. }
  34807. }
  34808. }
  34809. void Button::enablementChanged()
  34810. {
  34811. updateState();
  34812. repaint();
  34813. }
  34814. Button::ButtonState Button::updateState()
  34815. {
  34816. return updateState (isMouseOver (true), isMouseButtonDown());
  34817. }
  34818. Button::ButtonState Button::updateState (const bool over, const bool down)
  34819. {
  34820. ButtonState newState = buttonNormal;
  34821. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34822. {
  34823. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34824. newState = buttonDown;
  34825. else if (over)
  34826. newState = buttonOver;
  34827. }
  34828. setState (newState);
  34829. return newState;
  34830. }
  34831. void Button::setState (const ButtonState newState)
  34832. {
  34833. if (buttonState != newState)
  34834. {
  34835. buttonState = newState;
  34836. repaint();
  34837. if (buttonState == buttonDown)
  34838. {
  34839. buttonPressTime = Time::getApproximateMillisecondCounter();
  34840. lastRepeatTime = 0;
  34841. }
  34842. sendStateMessage();
  34843. }
  34844. }
  34845. bool Button::isDown() const throw()
  34846. {
  34847. return buttonState == buttonDown;
  34848. }
  34849. bool Button::isOver() const throw()
  34850. {
  34851. return buttonState != buttonNormal;
  34852. }
  34853. void Button::buttonStateChanged()
  34854. {
  34855. }
  34856. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34857. {
  34858. const uint32 now = Time::getApproximateMillisecondCounter();
  34859. return now > buttonPressTime ? now - buttonPressTime : 0;
  34860. }
  34861. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34862. {
  34863. triggerOnMouseDown = isTriggeredOnMouseDown;
  34864. }
  34865. void Button::clicked()
  34866. {
  34867. }
  34868. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34869. {
  34870. clicked();
  34871. }
  34872. static const int clickMessageId = 0x2f3f4f99;
  34873. void Button::triggerClick()
  34874. {
  34875. postCommandMessage (clickMessageId);
  34876. }
  34877. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34878. {
  34879. if (clickTogglesState)
  34880. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34881. sendClickMessage (modifiers);
  34882. }
  34883. void Button::flashButtonState()
  34884. {
  34885. if (isEnabled())
  34886. {
  34887. needsToRelease = true;
  34888. setState (buttonDown);
  34889. getRepeatTimer().startTimer (100);
  34890. }
  34891. }
  34892. void Button::handleCommandMessage (int commandId)
  34893. {
  34894. if (commandId == clickMessageId)
  34895. {
  34896. if (isEnabled())
  34897. {
  34898. flashButtonState();
  34899. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34900. }
  34901. }
  34902. else
  34903. {
  34904. Component::handleCommandMessage (commandId);
  34905. }
  34906. }
  34907. void Button::addListener (ButtonListener* const newListener)
  34908. {
  34909. buttonListeners.add (newListener);
  34910. }
  34911. void Button::removeListener (ButtonListener* const listener)
  34912. {
  34913. buttonListeners.remove (listener);
  34914. }
  34915. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34916. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34917. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34918. {
  34919. Component::BailOutChecker checker (this);
  34920. if (commandManagerToUse != 0 && commandID != 0)
  34921. {
  34922. ApplicationCommandTarget::InvocationInfo info (commandID);
  34923. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34924. info.originatingComponent = this;
  34925. commandManagerToUse->invoke (info, true);
  34926. }
  34927. clicked (modifiers);
  34928. if (! checker.shouldBailOut())
  34929. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34930. }
  34931. void Button::sendStateMessage()
  34932. {
  34933. Component::BailOutChecker checker (this);
  34934. buttonStateChanged();
  34935. if (! checker.shouldBailOut())
  34936. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34937. }
  34938. void Button::paint (Graphics& g)
  34939. {
  34940. if (needsToRelease && isEnabled())
  34941. {
  34942. needsToRelease = false;
  34943. needsRepainting = true;
  34944. }
  34945. paintButton (g, isOver(), isDown());
  34946. }
  34947. void Button::mouseEnter (const MouseEvent&)
  34948. {
  34949. updateState (true, false);
  34950. }
  34951. void Button::mouseExit (const MouseEvent&)
  34952. {
  34953. updateState (false, false);
  34954. }
  34955. void Button::mouseDown (const MouseEvent& e)
  34956. {
  34957. updateState (true, true);
  34958. if (isDown())
  34959. {
  34960. if (autoRepeatDelay >= 0)
  34961. getRepeatTimer().startTimer (autoRepeatDelay);
  34962. if (triggerOnMouseDown)
  34963. internalClickCallback (e.mods);
  34964. }
  34965. }
  34966. void Button::mouseUp (const MouseEvent& e)
  34967. {
  34968. const bool wasDown = isDown();
  34969. updateState (isMouseOver(), false);
  34970. if (wasDown && isOver() && ! triggerOnMouseDown)
  34971. internalClickCallback (e.mods);
  34972. }
  34973. void Button::mouseDrag (const MouseEvent&)
  34974. {
  34975. const ButtonState oldState = buttonState;
  34976. updateState (isMouseOver(), true);
  34977. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34978. getRepeatTimer().startTimer (autoRepeatSpeed);
  34979. }
  34980. void Button::focusGained (FocusChangeType)
  34981. {
  34982. updateState();
  34983. repaint();
  34984. }
  34985. void Button::focusLost (FocusChangeType)
  34986. {
  34987. updateState();
  34988. repaint();
  34989. }
  34990. void Button::visibilityChanged()
  34991. {
  34992. needsToRelease = false;
  34993. updateState();
  34994. }
  34995. void Button::parentHierarchyChanged()
  34996. {
  34997. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34998. if (newKeySource != keySource.get())
  34999. {
  35000. if (keySource != 0)
  35001. keySource->removeKeyListener (this);
  35002. keySource = newKeySource;
  35003. if (keySource != 0)
  35004. keySource->addKeyListener (this);
  35005. }
  35006. }
  35007. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35008. const int commandID_,
  35009. const bool generateTooltip_)
  35010. {
  35011. commandID = commandID_;
  35012. generateTooltip = generateTooltip_;
  35013. if (commandManagerToUse != commandManagerToUse_)
  35014. {
  35015. if (commandManagerToUse != 0)
  35016. commandManagerToUse->removeListener (this);
  35017. commandManagerToUse = commandManagerToUse_;
  35018. if (commandManagerToUse != 0)
  35019. commandManagerToUse->addListener (this);
  35020. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35021. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35022. // it is that this button represents, and the button will update its state to reflect this
  35023. // in the applicationCommandListChanged() method.
  35024. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35025. }
  35026. if (commandManagerToUse != 0)
  35027. applicationCommandListChanged();
  35028. else
  35029. setEnabled (true);
  35030. }
  35031. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35032. {
  35033. if (info.commandID == commandID
  35034. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35035. {
  35036. flashButtonState();
  35037. }
  35038. }
  35039. void Button::applicationCommandListChanged()
  35040. {
  35041. if (commandManagerToUse != 0)
  35042. {
  35043. ApplicationCommandInfo info (0);
  35044. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35045. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35046. if (target != 0)
  35047. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35048. }
  35049. }
  35050. void Button::addShortcut (const KeyPress& key)
  35051. {
  35052. if (key.isValid())
  35053. {
  35054. jassert (! isRegisteredForShortcut (key)); // already registered!
  35055. shortcuts.add (key);
  35056. parentHierarchyChanged();
  35057. }
  35058. }
  35059. void Button::clearShortcuts()
  35060. {
  35061. shortcuts.clear();
  35062. parentHierarchyChanged();
  35063. }
  35064. bool Button::isShortcutPressed() const
  35065. {
  35066. if (! isCurrentlyBlockedByAnotherModalComponent())
  35067. {
  35068. for (int i = shortcuts.size(); --i >= 0;)
  35069. if (shortcuts.getReference(i).isCurrentlyDown())
  35070. return true;
  35071. }
  35072. return false;
  35073. }
  35074. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35075. {
  35076. for (int i = shortcuts.size(); --i >= 0;)
  35077. if (key == shortcuts.getReference(i))
  35078. return true;
  35079. return false;
  35080. }
  35081. bool Button::keyStateChanged (const bool, Component*)
  35082. {
  35083. if (! isEnabled())
  35084. return false;
  35085. const bool wasDown = isKeyDown;
  35086. isKeyDown = isShortcutPressed();
  35087. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35088. getRepeatTimer().startTimer (autoRepeatDelay);
  35089. updateState();
  35090. if (isEnabled() && wasDown && ! isKeyDown)
  35091. {
  35092. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35093. // (return immediately - this button may now have been deleted)
  35094. return true;
  35095. }
  35096. return wasDown || isKeyDown;
  35097. }
  35098. bool Button::keyPressed (const KeyPress&, Component*)
  35099. {
  35100. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35101. return isShortcutPressed();
  35102. }
  35103. bool Button::keyPressed (const KeyPress& key)
  35104. {
  35105. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35106. {
  35107. triggerClick();
  35108. return true;
  35109. }
  35110. return false;
  35111. }
  35112. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35113. const int repeatMillisecs,
  35114. const int minimumDelayInMillisecs) throw()
  35115. {
  35116. autoRepeatDelay = initialDelayMillisecs;
  35117. autoRepeatSpeed = repeatMillisecs;
  35118. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35119. }
  35120. void Button::repeatTimerCallback()
  35121. {
  35122. if (needsRepainting)
  35123. {
  35124. getRepeatTimer().stopTimer();
  35125. updateState();
  35126. needsRepainting = false;
  35127. }
  35128. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35129. {
  35130. int repeatSpeed = autoRepeatSpeed;
  35131. if (autoRepeatMinimumDelay >= 0)
  35132. {
  35133. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35134. timeHeldDown *= timeHeldDown;
  35135. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35136. }
  35137. repeatSpeed = jmax (1, repeatSpeed);
  35138. const uint32 now = Time::getMillisecondCounter();
  35139. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35140. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35141. repeatSpeed = jmax (1, repeatSpeed / 2);
  35142. lastRepeatTime = now;
  35143. getRepeatTimer().startTimer (repeatSpeed);
  35144. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35145. }
  35146. else if (! needsToRelease)
  35147. {
  35148. getRepeatTimer().stopTimer();
  35149. }
  35150. }
  35151. Button::RepeatTimer& Button::getRepeatTimer()
  35152. {
  35153. if (repeatTimer == 0)
  35154. repeatTimer = new RepeatTimer (*this);
  35155. return *repeatTimer;
  35156. }
  35157. END_JUCE_NAMESPACE
  35158. /*** End of inlined file: juce_Button.cpp ***/
  35159. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35160. BEGIN_JUCE_NAMESPACE
  35161. DrawableButton::DrawableButton (const String& name,
  35162. const DrawableButton::ButtonStyle buttonStyle)
  35163. : Button (name),
  35164. style (buttonStyle),
  35165. currentImage (0),
  35166. edgeIndent (3)
  35167. {
  35168. if (buttonStyle == ImageOnButtonBackground)
  35169. {
  35170. backgroundOff = Colour (0xffbbbbff);
  35171. backgroundOn = Colour (0xff3333ff);
  35172. }
  35173. else
  35174. {
  35175. backgroundOff = Colours::transparentBlack;
  35176. backgroundOn = Colour (0xaabbbbff);
  35177. }
  35178. }
  35179. DrawableButton::~DrawableButton()
  35180. {
  35181. }
  35182. void DrawableButton::setImages (const Drawable* normal,
  35183. const Drawable* over,
  35184. const Drawable* down,
  35185. const Drawable* disabled,
  35186. const Drawable* normalOn,
  35187. const Drawable* overOn,
  35188. const Drawable* downOn,
  35189. const Drawable* disabledOn)
  35190. {
  35191. jassert (normal != 0); // you really need to give it at least a normal image..
  35192. if (normal != 0) normalImage = normal->createCopy();
  35193. if (over != 0) overImage = over->createCopy();
  35194. if (down != 0) downImage = down->createCopy();
  35195. if (disabled != 0) disabledImage = disabled->createCopy();
  35196. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35197. if (overOn != 0) overImageOn = overOn->createCopy();
  35198. if (downOn != 0) downImageOn = downOn->createCopy();
  35199. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35200. buttonStateChanged();
  35201. }
  35202. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35203. {
  35204. if (style != newStyle)
  35205. {
  35206. style = newStyle;
  35207. buttonStateChanged();
  35208. }
  35209. }
  35210. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35211. const Colour& toggledOnColour)
  35212. {
  35213. if (backgroundOff != toggledOffColour
  35214. || backgroundOn != toggledOnColour)
  35215. {
  35216. backgroundOff = toggledOffColour;
  35217. backgroundOn = toggledOnColour;
  35218. repaint();
  35219. }
  35220. }
  35221. const Colour& DrawableButton::getBackgroundColour() const throw()
  35222. {
  35223. return getToggleState() ? backgroundOn
  35224. : backgroundOff;
  35225. }
  35226. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35227. {
  35228. edgeIndent = numPixelsIndent;
  35229. repaint();
  35230. resized();
  35231. }
  35232. void DrawableButton::resized()
  35233. {
  35234. Button::resized();
  35235. if (currentImage != 0)
  35236. {
  35237. if (style == ImageRaw)
  35238. {
  35239. currentImage->setOriginWithOriginalSize (Point<float>());
  35240. }
  35241. else
  35242. {
  35243. Rectangle<int> imageSpace;
  35244. if (style == ImageOnButtonBackground)
  35245. {
  35246. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35247. }
  35248. else
  35249. {
  35250. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35251. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35252. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35253. imageSpace.setBounds (indentX, indentY,
  35254. getWidth() - indentX * 2,
  35255. getHeight() - indentY * 2 - textH);
  35256. }
  35257. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35258. }
  35259. }
  35260. }
  35261. void DrawableButton::buttonStateChanged()
  35262. {
  35263. repaint();
  35264. Drawable* imageToDraw = 0;
  35265. float opacity = 1.0f;
  35266. if (isEnabled())
  35267. {
  35268. imageToDraw = getCurrentImage();
  35269. }
  35270. else
  35271. {
  35272. imageToDraw = getToggleState() ? disabledImageOn
  35273. : disabledImage;
  35274. if (imageToDraw == 0)
  35275. {
  35276. opacity = 0.4f;
  35277. imageToDraw = getNormalImage();
  35278. }
  35279. }
  35280. if (imageToDraw != currentImage)
  35281. {
  35282. removeChildComponent (currentImage);
  35283. currentImage = imageToDraw;
  35284. if (currentImage != 0)
  35285. {
  35286. currentImage->setInterceptsMouseClicks (false, false);
  35287. addAndMakeVisible (currentImage);
  35288. DrawableButton::resized();
  35289. }
  35290. }
  35291. if (currentImage != 0)
  35292. currentImage->setAlpha (opacity);
  35293. }
  35294. void DrawableButton::paintButton (Graphics& g,
  35295. bool isMouseOverButton,
  35296. bool isButtonDown)
  35297. {
  35298. if (style == ImageOnButtonBackground)
  35299. {
  35300. getLookAndFeel().drawButtonBackground (g, *this,
  35301. getBackgroundColour(),
  35302. isMouseOverButton,
  35303. isButtonDown);
  35304. }
  35305. else
  35306. {
  35307. g.fillAll (getBackgroundColour());
  35308. const int textH = (style == ImageAboveTextLabel)
  35309. ? jmin (16, proportionOfHeight (0.25f))
  35310. : 0;
  35311. if (textH > 0)
  35312. {
  35313. g.setFont ((float) textH);
  35314. g.setColour (findColour (DrawableButton::textColourId)
  35315. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35316. g.drawFittedText (getButtonText(),
  35317. 2, getHeight() - textH - 1,
  35318. getWidth() - 4, textH,
  35319. Justification::centred, 1);
  35320. }
  35321. }
  35322. }
  35323. Drawable* DrawableButton::getCurrentImage() const throw()
  35324. {
  35325. if (isDown())
  35326. return getDownImage();
  35327. if (isOver())
  35328. return getOverImage();
  35329. return getNormalImage();
  35330. }
  35331. Drawable* DrawableButton::getNormalImage() const throw()
  35332. {
  35333. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35334. : normalImage;
  35335. }
  35336. Drawable* DrawableButton::getOverImage() const throw()
  35337. {
  35338. Drawable* d = normalImage;
  35339. if (getToggleState())
  35340. {
  35341. if (overImageOn != 0)
  35342. d = overImageOn;
  35343. else if (normalImageOn != 0)
  35344. d = normalImageOn;
  35345. else if (overImage != 0)
  35346. d = overImage;
  35347. }
  35348. else
  35349. {
  35350. if (overImage != 0)
  35351. d = overImage;
  35352. }
  35353. return d;
  35354. }
  35355. Drawable* DrawableButton::getDownImage() const throw()
  35356. {
  35357. Drawable* d = normalImage;
  35358. if (getToggleState())
  35359. {
  35360. if (downImageOn != 0)
  35361. d = downImageOn;
  35362. else if (overImageOn != 0)
  35363. d = overImageOn;
  35364. else if (normalImageOn != 0)
  35365. d = normalImageOn;
  35366. else if (downImage != 0)
  35367. d = downImage;
  35368. else
  35369. d = getOverImage();
  35370. }
  35371. else
  35372. {
  35373. if (downImage != 0)
  35374. d = downImage;
  35375. else
  35376. d = getOverImage();
  35377. }
  35378. return d;
  35379. }
  35380. END_JUCE_NAMESPACE
  35381. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35382. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35383. BEGIN_JUCE_NAMESPACE
  35384. HyperlinkButton::HyperlinkButton (const String& linkText,
  35385. const URL& linkURL)
  35386. : Button (linkText),
  35387. url (linkURL),
  35388. font (14.0f, Font::underlined),
  35389. resizeFont (true),
  35390. justification (Justification::centred)
  35391. {
  35392. setMouseCursor (MouseCursor::PointingHandCursor);
  35393. setTooltip (linkURL.toString (false));
  35394. }
  35395. HyperlinkButton::~HyperlinkButton()
  35396. {
  35397. }
  35398. void HyperlinkButton::setFont (const Font& newFont,
  35399. const bool resizeToMatchComponentHeight,
  35400. const Justification& justificationType)
  35401. {
  35402. font = newFont;
  35403. resizeFont = resizeToMatchComponentHeight;
  35404. justification = justificationType;
  35405. repaint();
  35406. }
  35407. void HyperlinkButton::setURL (const URL& newURL) throw()
  35408. {
  35409. url = newURL;
  35410. setTooltip (newURL.toString (false));
  35411. }
  35412. const Font HyperlinkButton::getFontToUse() const
  35413. {
  35414. Font f (font);
  35415. if (resizeFont)
  35416. f.setHeight (getHeight() * 0.7f);
  35417. return f;
  35418. }
  35419. void HyperlinkButton::changeWidthToFitText()
  35420. {
  35421. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35422. }
  35423. void HyperlinkButton::colourChanged()
  35424. {
  35425. repaint();
  35426. }
  35427. void HyperlinkButton::clicked()
  35428. {
  35429. if (url.isWellFormed())
  35430. url.launchInDefaultBrowser();
  35431. }
  35432. void HyperlinkButton::paintButton (Graphics& g,
  35433. bool isMouseOverButton,
  35434. bool isButtonDown)
  35435. {
  35436. const Colour textColour (findColour (textColourId));
  35437. if (isEnabled())
  35438. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35439. : textColour);
  35440. else
  35441. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35442. g.setFont (getFontToUse());
  35443. g.drawText (getButtonText(),
  35444. 2, 0, getWidth() - 2, getHeight(),
  35445. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35446. true);
  35447. }
  35448. END_JUCE_NAMESPACE
  35449. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35450. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35451. BEGIN_JUCE_NAMESPACE
  35452. ImageButton::ImageButton (const String& text_)
  35453. : Button (text_),
  35454. scaleImageToFit (true),
  35455. preserveProportions (true),
  35456. alphaThreshold (0),
  35457. imageX (0),
  35458. imageY (0),
  35459. imageW (0),
  35460. imageH (0),
  35461. normalImage (0),
  35462. overImage (0),
  35463. downImage (0)
  35464. {
  35465. }
  35466. ImageButton::~ImageButton()
  35467. {
  35468. }
  35469. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35470. const bool rescaleImagesWhenButtonSizeChanges,
  35471. const bool preserveImageProportions,
  35472. const Image& normalImage_,
  35473. const float imageOpacityWhenNormal,
  35474. const Colour& overlayColourWhenNormal,
  35475. const Image& overImage_,
  35476. const float imageOpacityWhenOver,
  35477. const Colour& overlayColourWhenOver,
  35478. const Image& downImage_,
  35479. const float imageOpacityWhenDown,
  35480. const Colour& overlayColourWhenDown,
  35481. const float hitTestAlphaThreshold)
  35482. {
  35483. normalImage = normalImage_;
  35484. overImage = overImage_;
  35485. downImage = downImage_;
  35486. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35487. {
  35488. imageW = normalImage.getWidth();
  35489. imageH = normalImage.getHeight();
  35490. setSize (imageW, imageH);
  35491. }
  35492. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35493. preserveProportions = preserveImageProportions;
  35494. normalOpacity = imageOpacityWhenNormal;
  35495. normalOverlay = overlayColourWhenNormal;
  35496. overOpacity = imageOpacityWhenOver;
  35497. overOverlay = overlayColourWhenOver;
  35498. downOpacity = imageOpacityWhenDown;
  35499. downOverlay = overlayColourWhenDown;
  35500. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35501. repaint();
  35502. }
  35503. const Image ImageButton::getCurrentImage() const
  35504. {
  35505. if (isDown() || getToggleState())
  35506. return getDownImage();
  35507. if (isOver())
  35508. return getOverImage();
  35509. return getNormalImage();
  35510. }
  35511. const Image ImageButton::getNormalImage() const
  35512. {
  35513. return normalImage;
  35514. }
  35515. const Image ImageButton::getOverImage() const
  35516. {
  35517. return overImage.isValid() ? overImage
  35518. : normalImage;
  35519. }
  35520. const Image ImageButton::getDownImage() const
  35521. {
  35522. return downImage.isValid() ? downImage
  35523. : getOverImage();
  35524. }
  35525. void ImageButton::paintButton (Graphics& g,
  35526. bool isMouseOverButton,
  35527. bool isButtonDown)
  35528. {
  35529. if (! isEnabled())
  35530. {
  35531. isMouseOverButton = false;
  35532. isButtonDown = false;
  35533. }
  35534. Image im (getCurrentImage());
  35535. if (im.isValid())
  35536. {
  35537. const int iw = im.getWidth();
  35538. const int ih = im.getHeight();
  35539. imageW = getWidth();
  35540. imageH = getHeight();
  35541. imageX = (imageW - iw) >> 1;
  35542. imageY = (imageH - ih) >> 1;
  35543. if (scaleImageToFit)
  35544. {
  35545. if (preserveProportions)
  35546. {
  35547. int newW, newH;
  35548. const float imRatio = ih / (float)iw;
  35549. const float destRatio = imageH / (float)imageW;
  35550. if (imRatio > destRatio)
  35551. {
  35552. newW = roundToInt (imageH / imRatio);
  35553. newH = imageH;
  35554. }
  35555. else
  35556. {
  35557. newW = imageW;
  35558. newH = roundToInt (imageW * imRatio);
  35559. }
  35560. imageX = (imageW - newW) / 2;
  35561. imageY = (imageH - newH) / 2;
  35562. imageW = newW;
  35563. imageH = newH;
  35564. }
  35565. else
  35566. {
  35567. imageX = 0;
  35568. imageY = 0;
  35569. }
  35570. }
  35571. if (! scaleImageToFit)
  35572. {
  35573. imageW = iw;
  35574. imageH = ih;
  35575. }
  35576. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35577. isButtonDown ? downOverlay
  35578. : (isMouseOverButton ? overOverlay
  35579. : normalOverlay),
  35580. isButtonDown ? downOpacity
  35581. : (isMouseOverButton ? overOpacity
  35582. : normalOpacity),
  35583. *this);
  35584. }
  35585. }
  35586. bool ImageButton::hitTest (int x, int y)
  35587. {
  35588. if (alphaThreshold == 0)
  35589. return true;
  35590. Image im (getCurrentImage());
  35591. return im.isNull() || (imageW > 0 && imageH > 0
  35592. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35593. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35594. }
  35595. END_JUCE_NAMESPACE
  35596. /*** End of inlined file: juce_ImageButton.cpp ***/
  35597. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35598. BEGIN_JUCE_NAMESPACE
  35599. ShapeButton::ShapeButton (const String& text_,
  35600. const Colour& normalColour_,
  35601. const Colour& overColour_,
  35602. const Colour& downColour_)
  35603. : Button (text_),
  35604. normalColour (normalColour_),
  35605. overColour (overColour_),
  35606. downColour (downColour_),
  35607. maintainShapeProportions (false),
  35608. outlineWidth (0.0f)
  35609. {
  35610. }
  35611. ShapeButton::~ShapeButton()
  35612. {
  35613. }
  35614. void ShapeButton::setColours (const Colour& newNormalColour,
  35615. const Colour& newOverColour,
  35616. const Colour& newDownColour)
  35617. {
  35618. normalColour = newNormalColour;
  35619. overColour = newOverColour;
  35620. downColour = newDownColour;
  35621. }
  35622. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35623. const float newOutlineWidth)
  35624. {
  35625. outlineColour = newOutlineColour;
  35626. outlineWidth = newOutlineWidth;
  35627. }
  35628. void ShapeButton::setShape (const Path& newShape,
  35629. const bool resizeNowToFitThisShape,
  35630. const bool maintainShapeProportions_,
  35631. const bool hasShadow)
  35632. {
  35633. shape = newShape;
  35634. maintainShapeProportions = maintainShapeProportions_;
  35635. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35636. setComponentEffect ((hasShadow) ? &shadow : 0);
  35637. if (resizeNowToFitThisShape)
  35638. {
  35639. Rectangle<float> bounds (shape.getBounds());
  35640. if (hasShadow)
  35641. bounds.expand (4.0f, 4.0f);
  35642. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35643. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35644. 1 + (int) (bounds.getHeight() + outlineWidth));
  35645. }
  35646. }
  35647. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35648. {
  35649. if (! isEnabled())
  35650. {
  35651. isMouseOverButton = false;
  35652. isButtonDown = false;
  35653. }
  35654. g.setColour ((isButtonDown) ? downColour
  35655. : (isMouseOverButton) ? overColour
  35656. : normalColour);
  35657. int w = getWidth();
  35658. int h = getHeight();
  35659. if (getComponentEffect() != 0)
  35660. {
  35661. w -= 4;
  35662. h -= 4;
  35663. }
  35664. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35665. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35666. w - offset - outlineWidth,
  35667. h - offset - outlineWidth,
  35668. maintainShapeProportions));
  35669. g.fillPath (shape, trans);
  35670. if (outlineWidth > 0.0f)
  35671. {
  35672. g.setColour (outlineColour);
  35673. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35674. }
  35675. }
  35676. END_JUCE_NAMESPACE
  35677. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35678. /*** Start of inlined file: juce_TextButton.cpp ***/
  35679. BEGIN_JUCE_NAMESPACE
  35680. TextButton::TextButton (const String& name,
  35681. const String& toolTip)
  35682. : Button (name)
  35683. {
  35684. setTooltip (toolTip);
  35685. }
  35686. TextButton::~TextButton()
  35687. {
  35688. }
  35689. void TextButton::paintButton (Graphics& g,
  35690. bool isMouseOverButton,
  35691. bool isButtonDown)
  35692. {
  35693. getLookAndFeel().drawButtonBackground (g, *this,
  35694. findColour (getToggleState() ? buttonOnColourId
  35695. : buttonColourId),
  35696. isMouseOverButton,
  35697. isButtonDown);
  35698. getLookAndFeel().drawButtonText (g, *this,
  35699. isMouseOverButton,
  35700. isButtonDown);
  35701. }
  35702. void TextButton::colourChanged()
  35703. {
  35704. repaint();
  35705. }
  35706. const Font TextButton::getFont()
  35707. {
  35708. return Font (jmin (15.0f, getHeight() * 0.6f));
  35709. }
  35710. void TextButton::changeWidthToFitText (const int newHeight)
  35711. {
  35712. if (newHeight >= 0)
  35713. setSize (jmax (1, getWidth()), newHeight);
  35714. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35715. getHeight());
  35716. }
  35717. END_JUCE_NAMESPACE
  35718. /*** End of inlined file: juce_TextButton.cpp ***/
  35719. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35720. BEGIN_JUCE_NAMESPACE
  35721. ToggleButton::ToggleButton (const String& buttonText)
  35722. : Button (buttonText)
  35723. {
  35724. setClickingTogglesState (true);
  35725. }
  35726. ToggleButton::~ToggleButton()
  35727. {
  35728. }
  35729. void ToggleButton::paintButton (Graphics& g,
  35730. bool isMouseOverButton,
  35731. bool isButtonDown)
  35732. {
  35733. getLookAndFeel().drawToggleButton (g, *this,
  35734. isMouseOverButton,
  35735. isButtonDown);
  35736. }
  35737. void ToggleButton::changeWidthToFitText()
  35738. {
  35739. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35740. }
  35741. void ToggleButton::colourChanged()
  35742. {
  35743. repaint();
  35744. }
  35745. END_JUCE_NAMESPACE
  35746. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35747. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35748. BEGIN_JUCE_NAMESPACE
  35749. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35750. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35751. : ToolbarItemComponent (itemId_, buttonText, true),
  35752. normalImage (normalImage_),
  35753. toggledOnImage (toggledOnImage_),
  35754. currentImage (0)
  35755. {
  35756. jassert (normalImage_ != 0);
  35757. }
  35758. ToolbarButton::~ToolbarButton()
  35759. {
  35760. }
  35761. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35762. {
  35763. preferredSize = minSize = maxSize = toolbarDepth;
  35764. return true;
  35765. }
  35766. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35767. {
  35768. }
  35769. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35770. {
  35771. buttonStateChanged();
  35772. }
  35773. void ToolbarButton::updateDrawable()
  35774. {
  35775. if (currentImage != 0)
  35776. {
  35777. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35778. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35779. }
  35780. }
  35781. void ToolbarButton::resized()
  35782. {
  35783. ToolbarItemComponent::resized();
  35784. updateDrawable();
  35785. }
  35786. void ToolbarButton::enablementChanged()
  35787. {
  35788. ToolbarItemComponent::enablementChanged();
  35789. updateDrawable();
  35790. }
  35791. void ToolbarButton::buttonStateChanged()
  35792. {
  35793. Drawable* d = normalImage;
  35794. if (getToggleState() && toggledOnImage != 0)
  35795. d = toggledOnImage;
  35796. if (d != currentImage)
  35797. {
  35798. removeChildComponent (currentImage);
  35799. currentImage = d;
  35800. if (d != 0)
  35801. {
  35802. enablementChanged();
  35803. addAndMakeVisible (d);
  35804. updateDrawable();
  35805. }
  35806. }
  35807. }
  35808. END_JUCE_NAMESPACE
  35809. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35810. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35811. BEGIN_JUCE_NAMESPACE
  35812. class CodeDocumentLine
  35813. {
  35814. public:
  35815. CodeDocumentLine (const String::CharPointerType& line_,
  35816. const int lineLength_,
  35817. const int numNewLineChars,
  35818. const int lineStartInFile_)
  35819. : line (line_, lineLength_),
  35820. lineStartInFile (lineStartInFile_),
  35821. lineLength (lineLength_),
  35822. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35823. {
  35824. }
  35825. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35826. {
  35827. String::CharPointerType t (text.getCharPointer());
  35828. int charNumInFile = 0;
  35829. bool finished = t.isEmpty();
  35830. while (! finished)
  35831. {
  35832. String::CharPointerType startOfLine (t);
  35833. int startOfLineInFile = charNumInFile;
  35834. int lineLength = 0;
  35835. int numNewLineChars = 0;
  35836. for (;;)
  35837. {
  35838. const juce_wchar c = t.getAndAdvance();
  35839. if (c == 0)
  35840. {
  35841. finished = true;
  35842. break;
  35843. }
  35844. ++charNumInFile;
  35845. ++lineLength;
  35846. if (c == '\r')
  35847. {
  35848. ++numNewLineChars;
  35849. if (*t == '\n')
  35850. {
  35851. ++t;
  35852. ++charNumInFile;
  35853. ++lineLength;
  35854. ++numNewLineChars;
  35855. }
  35856. break;
  35857. }
  35858. if (c == '\n')
  35859. {
  35860. ++numNewLineChars;
  35861. break;
  35862. }
  35863. }
  35864. newLines.add (new CodeDocumentLine (startOfLine, lineLength,
  35865. numNewLineChars, startOfLineInFile));
  35866. }
  35867. jassert (charNumInFile == text.length());
  35868. }
  35869. bool endsWithLineBreak() const throw()
  35870. {
  35871. return lineLengthWithoutNewLines != lineLength;
  35872. }
  35873. void updateLength() throw()
  35874. {
  35875. lineLengthWithoutNewLines = lineLength = line.length();
  35876. while (lineLengthWithoutNewLines > 0
  35877. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35878. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35879. {
  35880. --lineLengthWithoutNewLines;
  35881. }
  35882. }
  35883. String line;
  35884. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35885. };
  35886. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35887. : document (document_),
  35888. currentLine (document_->lines[0]),
  35889. line (0),
  35890. position (0)
  35891. {
  35892. }
  35893. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35894. : document (other.document),
  35895. currentLine (other.currentLine),
  35896. line (other.line),
  35897. position (other.position)
  35898. {
  35899. }
  35900. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35901. {
  35902. document = other.document;
  35903. currentLine = other.currentLine;
  35904. line = other.line;
  35905. position = other.position;
  35906. return *this;
  35907. }
  35908. CodeDocument::Iterator::~Iterator() throw()
  35909. {
  35910. }
  35911. juce_wchar CodeDocument::Iterator::nextChar()
  35912. {
  35913. if (currentLine == 0)
  35914. return 0;
  35915. jassert (currentLine == document->lines.getUnchecked (line));
  35916. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35917. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35918. {
  35919. ++line;
  35920. currentLine = document->lines [line];
  35921. }
  35922. return result;
  35923. }
  35924. void CodeDocument::Iterator::skip()
  35925. {
  35926. if (currentLine != 0)
  35927. {
  35928. jassert (currentLine == document->lines.getUnchecked (line));
  35929. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35930. {
  35931. ++line;
  35932. currentLine = document->lines [line];
  35933. }
  35934. }
  35935. }
  35936. void CodeDocument::Iterator::skipToEndOfLine()
  35937. {
  35938. if (currentLine != 0)
  35939. {
  35940. jassert (currentLine == document->lines.getUnchecked (line));
  35941. ++line;
  35942. currentLine = document->lines [line];
  35943. if (currentLine != 0)
  35944. position = currentLine->lineStartInFile;
  35945. else
  35946. position = document->getNumCharacters();
  35947. }
  35948. }
  35949. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35950. {
  35951. if (currentLine == 0)
  35952. return 0;
  35953. jassert (currentLine == document->lines.getUnchecked (line));
  35954. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35955. }
  35956. void CodeDocument::Iterator::skipWhitespace()
  35957. {
  35958. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35959. skip();
  35960. }
  35961. bool CodeDocument::Iterator::isEOF() const throw()
  35962. {
  35963. return currentLine == 0;
  35964. }
  35965. CodeDocument::Position::Position() throw()
  35966. : owner (0), characterPos (0), line (0),
  35967. indexInLine (0), positionMaintained (false)
  35968. {
  35969. }
  35970. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35971. const int line_, const int indexInLine_) throw()
  35972. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35973. characterPos (0), line (line_),
  35974. indexInLine (indexInLine_), positionMaintained (false)
  35975. {
  35976. setLineAndIndex (line_, indexInLine_);
  35977. }
  35978. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35979. const int characterPos_) throw()
  35980. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35981. positionMaintained (false)
  35982. {
  35983. setPosition (characterPos_);
  35984. }
  35985. CodeDocument::Position::Position (const Position& other) throw()
  35986. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35987. indexInLine (other.indexInLine), positionMaintained (false)
  35988. {
  35989. jassert (*this == other);
  35990. }
  35991. CodeDocument::Position::~Position()
  35992. {
  35993. setPositionMaintained (false);
  35994. }
  35995. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  35996. {
  35997. if (this != &other)
  35998. {
  35999. const bool wasPositionMaintained = positionMaintained;
  36000. if (owner != other.owner)
  36001. setPositionMaintained (false);
  36002. owner = other.owner;
  36003. line = other.line;
  36004. indexInLine = other.indexInLine;
  36005. characterPos = other.characterPos;
  36006. setPositionMaintained (wasPositionMaintained);
  36007. jassert (*this == other);
  36008. }
  36009. return *this;
  36010. }
  36011. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36012. {
  36013. jassert ((characterPos == other.characterPos)
  36014. == (line == other.line && indexInLine == other.indexInLine));
  36015. return characterPos == other.characterPos
  36016. && line == other.line
  36017. && indexInLine == other.indexInLine
  36018. && owner == other.owner;
  36019. }
  36020. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36021. {
  36022. return ! operator== (other);
  36023. }
  36024. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  36025. {
  36026. jassert (owner != 0);
  36027. if (owner->lines.size() == 0)
  36028. {
  36029. line = 0;
  36030. indexInLine = 0;
  36031. characterPos = 0;
  36032. }
  36033. else
  36034. {
  36035. if (newLineNum >= owner->lines.size())
  36036. {
  36037. line = owner->lines.size() - 1;
  36038. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36039. jassert (l != 0);
  36040. indexInLine = l->lineLengthWithoutNewLines;
  36041. characterPos = l->lineStartInFile + indexInLine;
  36042. }
  36043. else
  36044. {
  36045. line = jmax (0, newLineNum);
  36046. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36047. jassert (l != 0);
  36048. if (l->lineLengthWithoutNewLines > 0)
  36049. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36050. else
  36051. indexInLine = 0;
  36052. characterPos = l->lineStartInFile + indexInLine;
  36053. }
  36054. }
  36055. }
  36056. void CodeDocument::Position::setPosition (const int newPosition)
  36057. {
  36058. jassert (owner != 0);
  36059. line = 0;
  36060. indexInLine = 0;
  36061. characterPos = 0;
  36062. if (newPosition > 0)
  36063. {
  36064. int lineStart = 0;
  36065. int lineEnd = owner->lines.size();
  36066. for (;;)
  36067. {
  36068. if (lineEnd - lineStart < 4)
  36069. {
  36070. for (int i = lineStart; i < lineEnd; ++i)
  36071. {
  36072. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36073. int index = newPosition - l->lineStartInFile;
  36074. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36075. {
  36076. line = i;
  36077. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36078. characterPos = l->lineStartInFile + indexInLine;
  36079. }
  36080. }
  36081. break;
  36082. }
  36083. else
  36084. {
  36085. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36086. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36087. if (newPosition >= mid->lineStartInFile)
  36088. lineStart = midIndex;
  36089. else
  36090. lineEnd = midIndex;
  36091. }
  36092. }
  36093. }
  36094. }
  36095. void CodeDocument::Position::moveBy (int characterDelta)
  36096. {
  36097. jassert (owner != 0);
  36098. if (characterDelta == 1)
  36099. {
  36100. setPosition (getPosition());
  36101. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36102. if (line < owner->lines.size())
  36103. {
  36104. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36105. if (indexInLine + characterDelta < l->lineLength
  36106. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36107. ++characterDelta;
  36108. }
  36109. }
  36110. setPosition (characterPos + characterDelta);
  36111. }
  36112. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36113. {
  36114. CodeDocument::Position p (*this);
  36115. p.moveBy (characterDelta);
  36116. return p;
  36117. }
  36118. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36119. {
  36120. CodeDocument::Position p (*this);
  36121. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36122. return p;
  36123. }
  36124. const juce_wchar CodeDocument::Position::getCharacter() const
  36125. {
  36126. const CodeDocumentLine* const l = owner->lines [line];
  36127. return l == 0 ? 0 : l->line [getIndexInLine()];
  36128. }
  36129. const String CodeDocument::Position::getLineText() const
  36130. {
  36131. const CodeDocumentLine* const l = owner->lines [line];
  36132. return l == 0 ? String::empty : l->line;
  36133. }
  36134. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36135. {
  36136. if (isMaintained != positionMaintained)
  36137. {
  36138. positionMaintained = isMaintained;
  36139. if (owner != 0)
  36140. {
  36141. if (isMaintained)
  36142. {
  36143. jassert (! owner->positionsToMaintain.contains (this));
  36144. owner->positionsToMaintain.add (this);
  36145. }
  36146. else
  36147. {
  36148. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36149. jassert (owner->positionsToMaintain.contains (this));
  36150. owner->positionsToMaintain.removeValue (this);
  36151. }
  36152. }
  36153. }
  36154. }
  36155. CodeDocument::CodeDocument()
  36156. : undoManager (std::numeric_limits<int>::max(), 10000),
  36157. currentActionIndex (0),
  36158. indexOfSavedState (-1),
  36159. maximumLineLength (-1),
  36160. newLineChars ("\r\n")
  36161. {
  36162. }
  36163. CodeDocument::~CodeDocument()
  36164. {
  36165. }
  36166. const String CodeDocument::getAllContent() const
  36167. {
  36168. return getTextBetween (Position (this, 0),
  36169. Position (this, lines.size(), 0));
  36170. }
  36171. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36172. {
  36173. if (end.getPosition() <= start.getPosition())
  36174. return String::empty;
  36175. const int startLine = start.getLineNumber();
  36176. const int endLine = end.getLineNumber();
  36177. if (startLine == endLine)
  36178. {
  36179. CodeDocumentLine* const line = lines [startLine];
  36180. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36181. }
  36182. String result;
  36183. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36184. String::Concatenator concatenator (result);
  36185. const int maxLine = jmin (lines.size() - 1, endLine);
  36186. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36187. {
  36188. const CodeDocumentLine* line = lines.getUnchecked(i);
  36189. int len = line->lineLength;
  36190. if (i == startLine)
  36191. {
  36192. const int index = start.getIndexInLine();
  36193. concatenator.append (line->line.substring (index, len));
  36194. }
  36195. else if (i == endLine)
  36196. {
  36197. len = end.getIndexInLine();
  36198. concatenator.append (line->line.substring (0, len));
  36199. }
  36200. else
  36201. {
  36202. concatenator.append (line->line);
  36203. }
  36204. }
  36205. return result;
  36206. }
  36207. int CodeDocument::getNumCharacters() const throw()
  36208. {
  36209. const CodeDocumentLine* const lastLine = lines.getLast();
  36210. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36211. }
  36212. const String CodeDocument::getLine (const int lineIndex) const throw()
  36213. {
  36214. const CodeDocumentLine* const line = lines [lineIndex];
  36215. return (line == 0) ? String::empty : line->line;
  36216. }
  36217. int CodeDocument::getMaximumLineLength() throw()
  36218. {
  36219. if (maximumLineLength < 0)
  36220. {
  36221. maximumLineLength = 0;
  36222. for (int i = lines.size(); --i >= 0;)
  36223. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36224. }
  36225. return maximumLineLength;
  36226. }
  36227. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36228. {
  36229. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36230. }
  36231. void CodeDocument::insertText (const Position& position, const String& text)
  36232. {
  36233. insert (text, position.getPosition(), true);
  36234. }
  36235. void CodeDocument::replaceAllContent (const String& newContent)
  36236. {
  36237. remove (0, getNumCharacters(), true);
  36238. insert (newContent, 0, true);
  36239. }
  36240. bool CodeDocument::loadFromStream (InputStream& stream)
  36241. {
  36242. replaceAllContent (stream.readEntireStreamAsString());
  36243. setSavePoint();
  36244. clearUndoHistory();
  36245. return true;
  36246. }
  36247. bool CodeDocument::writeToStream (OutputStream& stream)
  36248. {
  36249. for (int i = 0; i < lines.size(); ++i)
  36250. {
  36251. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36252. const char* utf8 = temp.toUTF8();
  36253. if (! stream.write (utf8, (int) strlen (utf8)))
  36254. return false;
  36255. }
  36256. return true;
  36257. }
  36258. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36259. {
  36260. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36261. newLineChars = newLineChars_;
  36262. }
  36263. void CodeDocument::newTransaction()
  36264. {
  36265. undoManager.beginNewTransaction (String::empty);
  36266. }
  36267. void CodeDocument::undo()
  36268. {
  36269. newTransaction();
  36270. undoManager.undo();
  36271. }
  36272. void CodeDocument::redo()
  36273. {
  36274. undoManager.redo();
  36275. }
  36276. void CodeDocument::clearUndoHistory()
  36277. {
  36278. undoManager.clearUndoHistory();
  36279. }
  36280. void CodeDocument::setSavePoint() throw()
  36281. {
  36282. indexOfSavedState = currentActionIndex;
  36283. }
  36284. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36285. {
  36286. return currentActionIndex != indexOfSavedState;
  36287. }
  36288. namespace CodeDocumentHelpers
  36289. {
  36290. int getCharacterType (const juce_wchar character) throw()
  36291. {
  36292. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36293. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36294. }
  36295. }
  36296. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36297. {
  36298. Position p (position);
  36299. const int maxDistance = 256;
  36300. int i = 0;
  36301. while (i < maxDistance
  36302. && CharacterFunctions::isWhitespace (p.getCharacter())
  36303. && (i == 0 || (p.getCharacter() != '\n'
  36304. && p.getCharacter() != '\r')))
  36305. {
  36306. ++i;
  36307. p.moveBy (1);
  36308. }
  36309. if (i == 0)
  36310. {
  36311. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36312. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36313. {
  36314. ++i;
  36315. p.moveBy (1);
  36316. }
  36317. while (i < maxDistance
  36318. && CharacterFunctions::isWhitespace (p.getCharacter())
  36319. && (i == 0 || (p.getCharacter() != '\n'
  36320. && p.getCharacter() != '\r')))
  36321. {
  36322. ++i;
  36323. p.moveBy (1);
  36324. }
  36325. }
  36326. return p;
  36327. }
  36328. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36329. {
  36330. Position p (position);
  36331. const int maxDistance = 256;
  36332. int i = 0;
  36333. bool stoppedAtLineStart = false;
  36334. while (i < maxDistance)
  36335. {
  36336. const juce_wchar c = p.movedBy (-1).getCharacter();
  36337. if (c == '\r' || c == '\n')
  36338. {
  36339. stoppedAtLineStart = true;
  36340. if (i > 0)
  36341. break;
  36342. }
  36343. if (! CharacterFunctions::isWhitespace (c))
  36344. break;
  36345. p.moveBy (-1);
  36346. ++i;
  36347. }
  36348. if (i < maxDistance && ! stoppedAtLineStart)
  36349. {
  36350. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36351. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36352. {
  36353. p.moveBy (-1);
  36354. ++i;
  36355. }
  36356. }
  36357. return p;
  36358. }
  36359. void CodeDocument::checkLastLineStatus()
  36360. {
  36361. while (lines.size() > 0
  36362. && lines.getLast()->lineLength == 0
  36363. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36364. {
  36365. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36366. lines.removeLast();
  36367. }
  36368. const CodeDocumentLine* const lastLine = lines.getLast();
  36369. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36370. {
  36371. // check that there's an empty line at the end if the preceding one ends in a newline..
  36372. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36373. }
  36374. }
  36375. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36376. {
  36377. listeners.add (listener);
  36378. }
  36379. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36380. {
  36381. listeners.remove (listener);
  36382. }
  36383. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36384. {
  36385. Position startPos (this, startLine, 0);
  36386. Position endPos (this, endLine, 0);
  36387. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36388. }
  36389. class CodeDocumentInsertAction : public UndoableAction
  36390. {
  36391. public:
  36392. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36393. : owner (owner_),
  36394. text (text_),
  36395. insertPos (insertPos_)
  36396. {
  36397. }
  36398. bool perform()
  36399. {
  36400. owner.currentActionIndex++;
  36401. owner.insert (text, insertPos, false);
  36402. return true;
  36403. }
  36404. bool undo()
  36405. {
  36406. owner.currentActionIndex--;
  36407. owner.remove (insertPos, insertPos + text.length(), false);
  36408. return true;
  36409. }
  36410. int getSizeInUnits() { return text.length() + 32; }
  36411. private:
  36412. CodeDocument& owner;
  36413. const String text;
  36414. int insertPos;
  36415. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36416. };
  36417. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36418. {
  36419. if (text.isEmpty())
  36420. return;
  36421. if (undoable)
  36422. {
  36423. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36424. }
  36425. else
  36426. {
  36427. Position pos (this, insertPos);
  36428. const int firstAffectedLine = pos.getLineNumber();
  36429. int lastAffectedLine = firstAffectedLine + 1;
  36430. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36431. String textInsideOriginalLine (text);
  36432. if (firstLine != 0)
  36433. {
  36434. const int index = pos.getIndexInLine();
  36435. textInsideOriginalLine = firstLine->line.substring (0, index)
  36436. + textInsideOriginalLine
  36437. + firstLine->line.substring (index);
  36438. }
  36439. maximumLineLength = -1;
  36440. Array <CodeDocumentLine*> newLines;
  36441. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36442. jassert (newLines.size() > 0);
  36443. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36444. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36445. lines.set (firstAffectedLine, newFirstLine);
  36446. if (newLines.size() > 1)
  36447. {
  36448. for (int i = 1; i < newLines.size(); ++i)
  36449. {
  36450. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36451. lines.insert (firstAffectedLine + i, l);
  36452. }
  36453. lastAffectedLine = lines.size();
  36454. }
  36455. int i, lineStart = newFirstLine->lineStartInFile;
  36456. for (i = firstAffectedLine; i < lines.size(); ++i)
  36457. {
  36458. CodeDocumentLine* const l = lines.getUnchecked (i);
  36459. l->lineStartInFile = lineStart;
  36460. lineStart += l->lineLength;
  36461. }
  36462. checkLastLineStatus();
  36463. const int newTextLength = text.length();
  36464. for (i = 0; i < positionsToMaintain.size(); ++i)
  36465. {
  36466. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36467. if (p->getPosition() >= insertPos)
  36468. p->setPosition (p->getPosition() + newTextLength);
  36469. }
  36470. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36471. }
  36472. }
  36473. class CodeDocumentDeleteAction : public UndoableAction
  36474. {
  36475. public:
  36476. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36477. : owner (owner_),
  36478. startPos (startPos_),
  36479. endPos (endPos_)
  36480. {
  36481. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36482. CodeDocument::Position (&owner, endPos));
  36483. }
  36484. bool perform()
  36485. {
  36486. owner.currentActionIndex++;
  36487. owner.remove (startPos, endPos, false);
  36488. return true;
  36489. }
  36490. bool undo()
  36491. {
  36492. owner.currentActionIndex--;
  36493. owner.insert (removedText, startPos, false);
  36494. return true;
  36495. }
  36496. int getSizeInUnits() { return removedText.length() + 32; }
  36497. private:
  36498. CodeDocument& owner;
  36499. int startPos, endPos;
  36500. String removedText;
  36501. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36502. };
  36503. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36504. {
  36505. if (endPos <= startPos)
  36506. return;
  36507. if (undoable)
  36508. {
  36509. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36510. }
  36511. else
  36512. {
  36513. Position startPosition (this, startPos);
  36514. Position endPosition (this, endPos);
  36515. maximumLineLength = -1;
  36516. const int firstAffectedLine = startPosition.getLineNumber();
  36517. const int endLine = endPosition.getLineNumber();
  36518. int lastAffectedLine = firstAffectedLine + 1;
  36519. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36520. if (firstAffectedLine == endLine)
  36521. {
  36522. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36523. + firstLine->line.substring (endPosition.getIndexInLine());
  36524. firstLine->updateLength();
  36525. }
  36526. else
  36527. {
  36528. lastAffectedLine = lines.size();
  36529. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36530. jassert (lastLine != 0);
  36531. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36532. + lastLine->line.substring (endPosition.getIndexInLine());
  36533. firstLine->updateLength();
  36534. int numLinesToRemove = endLine - firstAffectedLine;
  36535. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36536. }
  36537. int i;
  36538. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36539. {
  36540. CodeDocumentLine* const l = lines.getUnchecked (i);
  36541. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36542. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36543. }
  36544. checkLastLineStatus();
  36545. const int totalChars = getNumCharacters();
  36546. for (i = 0; i < positionsToMaintain.size(); ++i)
  36547. {
  36548. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36549. if (p->getPosition() > startPosition.getPosition())
  36550. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36551. if (p->getPosition() > totalChars)
  36552. p->setPosition (totalChars);
  36553. }
  36554. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36555. }
  36556. }
  36557. END_JUCE_NAMESPACE
  36558. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36559. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36560. BEGIN_JUCE_NAMESPACE
  36561. class CodeEditorComponent::CaretComponent : public Component,
  36562. public Timer
  36563. {
  36564. public:
  36565. CaretComponent (CodeEditorComponent& owner_)
  36566. : owner (owner_)
  36567. {
  36568. setAlwaysOnTop (true);
  36569. setInterceptsMouseClicks (false, false);
  36570. }
  36571. void paint (Graphics& g)
  36572. {
  36573. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36574. }
  36575. void timerCallback()
  36576. {
  36577. setVisible (shouldBeShown() && ! isVisible());
  36578. }
  36579. void updatePosition()
  36580. {
  36581. startTimer (400);
  36582. setVisible (shouldBeShown());
  36583. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36584. }
  36585. private:
  36586. CodeEditorComponent& owner;
  36587. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36588. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36589. };
  36590. class CodeEditorComponent::CodeEditorLine
  36591. {
  36592. public:
  36593. CodeEditorLine() throw()
  36594. : highlightColumnStart (0), highlightColumnEnd (0)
  36595. {
  36596. }
  36597. bool update (CodeDocument& document, int lineNum,
  36598. CodeDocument::Iterator& source,
  36599. CodeTokeniser* analyser, const int spacesPerTab,
  36600. const CodeDocument::Position& selectionStart,
  36601. const CodeDocument::Position& selectionEnd)
  36602. {
  36603. Array <SyntaxToken> newTokens;
  36604. newTokens.ensureStorageAllocated (8);
  36605. if (analyser == 0)
  36606. {
  36607. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36608. }
  36609. else if (lineNum < document.getNumLines())
  36610. {
  36611. const CodeDocument::Position pos (&document, lineNum, 0);
  36612. createTokens (pos.getPosition(), pos.getLineText(),
  36613. source, analyser, newTokens);
  36614. }
  36615. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36616. int newHighlightStart = 0;
  36617. int newHighlightEnd = 0;
  36618. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36619. {
  36620. const String line (document.getLine (lineNum));
  36621. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36622. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36623. line, spacesPerTab);
  36624. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36625. line, spacesPerTab);
  36626. }
  36627. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36628. {
  36629. highlightColumnStart = newHighlightStart;
  36630. highlightColumnEnd = newHighlightEnd;
  36631. }
  36632. else
  36633. {
  36634. if (tokens.size() == newTokens.size())
  36635. {
  36636. bool allTheSame = true;
  36637. for (int i = newTokens.size(); --i >= 0;)
  36638. {
  36639. if (tokens.getReference(i) != newTokens.getReference(i))
  36640. {
  36641. allTheSame = false;
  36642. break;
  36643. }
  36644. }
  36645. if (allTheSame)
  36646. return false;
  36647. }
  36648. }
  36649. tokens.swapWithArray (newTokens);
  36650. return true;
  36651. }
  36652. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36653. float x, const int y, const int baselineOffset, const int lineHeight,
  36654. const Colour& highlightColour) const
  36655. {
  36656. if (highlightColumnStart < highlightColumnEnd)
  36657. {
  36658. g.setColour (highlightColour);
  36659. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36660. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36661. }
  36662. int lastType = std::numeric_limits<int>::min();
  36663. for (int i = 0; i < tokens.size(); ++i)
  36664. {
  36665. SyntaxToken& token = tokens.getReference(i);
  36666. if (lastType != token.tokenType)
  36667. {
  36668. lastType = token.tokenType;
  36669. g.setColour (owner.getColourForTokenType (lastType));
  36670. }
  36671. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36672. if (i < tokens.size() - 1)
  36673. {
  36674. if (token.width < 0)
  36675. token.width = font.getStringWidthFloat (token.text);
  36676. x += token.width;
  36677. }
  36678. }
  36679. }
  36680. private:
  36681. struct SyntaxToken
  36682. {
  36683. SyntaxToken (const String& text_, const int type) throw()
  36684. : text (text_), tokenType (type), width (-1.0f)
  36685. {
  36686. }
  36687. bool operator!= (const SyntaxToken& other) const throw()
  36688. {
  36689. return text != other.text || tokenType != other.tokenType;
  36690. }
  36691. String text;
  36692. int tokenType;
  36693. float width;
  36694. };
  36695. Array <SyntaxToken> tokens;
  36696. int highlightColumnStart, highlightColumnEnd;
  36697. static void createTokens (int startPosition, const String& lineText,
  36698. CodeDocument::Iterator& source,
  36699. CodeTokeniser* analyser,
  36700. Array <SyntaxToken>& newTokens)
  36701. {
  36702. CodeDocument::Iterator lastIterator (source);
  36703. const int lineLength = lineText.length();
  36704. for (;;)
  36705. {
  36706. int tokenType = analyser->readNextToken (source);
  36707. int tokenStart = lastIterator.getPosition();
  36708. int tokenEnd = source.getPosition();
  36709. if (tokenEnd <= tokenStart)
  36710. break;
  36711. tokenEnd -= startPosition;
  36712. if (tokenEnd > 0)
  36713. {
  36714. tokenStart -= startPosition;
  36715. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36716. tokenType));
  36717. if (tokenEnd >= lineLength)
  36718. break;
  36719. }
  36720. lastIterator = source;
  36721. }
  36722. source = lastIterator;
  36723. }
  36724. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36725. {
  36726. int x = 0;
  36727. for (int i = 0; i < tokens.size(); ++i)
  36728. {
  36729. SyntaxToken& t = tokens.getReference(i);
  36730. for (;;)
  36731. {
  36732. int tabPos = t.text.indexOfChar ('\t');
  36733. if (tabPos < 0)
  36734. break;
  36735. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36736. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36737. }
  36738. x += t.text.length();
  36739. }
  36740. }
  36741. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36742. {
  36743. jassert (index <= line.length());
  36744. int col = 0;
  36745. for (int i = 0; i < index; ++i)
  36746. {
  36747. if (line[i] != '\t')
  36748. ++col;
  36749. else
  36750. col += spacesPerTab - (col % spacesPerTab);
  36751. }
  36752. return col;
  36753. }
  36754. };
  36755. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36756. CodeTokeniser* const codeTokeniser_)
  36757. : document (document_),
  36758. firstLineOnScreen (0),
  36759. gutter (5),
  36760. spacesPerTab (4),
  36761. lineHeight (0),
  36762. linesOnScreen (0),
  36763. columnsOnScreen (0),
  36764. scrollbarThickness (16),
  36765. columnToTryToMaintain (-1),
  36766. useSpacesForTabs (false),
  36767. xOffset (0),
  36768. verticalScrollBar (true),
  36769. horizontalScrollBar (false),
  36770. codeTokeniser (codeTokeniser_)
  36771. {
  36772. caretPos = CodeDocument::Position (&document_, 0, 0);
  36773. caretPos.setPositionMaintained (true);
  36774. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36775. selectionStart.setPositionMaintained (true);
  36776. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36777. selectionEnd.setPositionMaintained (true);
  36778. setOpaque (true);
  36779. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36780. setWantsKeyboardFocus (true);
  36781. addAndMakeVisible (&verticalScrollBar);
  36782. verticalScrollBar.setSingleStepSize (1.0);
  36783. addAndMakeVisible (&horizontalScrollBar);
  36784. horizontalScrollBar.setSingleStepSize (1.0);
  36785. addAndMakeVisible (caret = new CaretComponent (*this));
  36786. Font f (12.0f);
  36787. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36788. setFont (f);
  36789. resetToDefaultColours();
  36790. verticalScrollBar.addListener (this);
  36791. horizontalScrollBar.addListener (this);
  36792. document.addListener (this);
  36793. }
  36794. CodeEditorComponent::~CodeEditorComponent()
  36795. {
  36796. document.removeListener (this);
  36797. }
  36798. void CodeEditorComponent::loadContent (const String& newContent)
  36799. {
  36800. clearCachedIterators (0);
  36801. document.replaceAllContent (newContent);
  36802. document.clearUndoHistory();
  36803. document.setSavePoint();
  36804. caretPos.setPosition (0);
  36805. selectionStart.setPosition (0);
  36806. selectionEnd.setPosition (0);
  36807. scrollToLine (0);
  36808. }
  36809. bool CodeEditorComponent::isTextInputActive() const
  36810. {
  36811. return true;
  36812. }
  36813. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36814. const CodeDocument::Position& affectedTextEnd)
  36815. {
  36816. clearCachedIterators (affectedTextStart.getLineNumber());
  36817. triggerAsyncUpdate();
  36818. caret->updatePosition();
  36819. columnToTryToMaintain = -1;
  36820. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36821. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36822. deselectAll();
  36823. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36824. || caretPos.getPosition() < affectedTextStart.getPosition())
  36825. moveCaretTo (affectedTextStart, false);
  36826. updateScrollBars();
  36827. }
  36828. void CodeEditorComponent::resized()
  36829. {
  36830. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36831. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36832. lines.clear();
  36833. rebuildLineTokens();
  36834. caret->updatePosition();
  36835. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36836. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36837. updateScrollBars();
  36838. }
  36839. void CodeEditorComponent::paint (Graphics& g)
  36840. {
  36841. handleUpdateNowIfNeeded();
  36842. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36843. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36844. g.setFont (font);
  36845. const int baselineOffset = (int) font.getAscent();
  36846. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36847. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36848. const Rectangle<int> clip (g.getClipBounds());
  36849. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36850. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36851. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36852. {
  36853. lines.getUnchecked(j)->draw (*this, g, font,
  36854. (float) (gutter - xOffset * charWidth),
  36855. lineHeight * j, baselineOffset, lineHeight,
  36856. highlightColour);
  36857. }
  36858. }
  36859. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36860. {
  36861. if (scrollbarThickness != thickness)
  36862. {
  36863. scrollbarThickness = thickness;
  36864. resized();
  36865. }
  36866. }
  36867. void CodeEditorComponent::handleAsyncUpdate()
  36868. {
  36869. rebuildLineTokens();
  36870. }
  36871. void CodeEditorComponent::rebuildLineTokens()
  36872. {
  36873. cancelPendingUpdate();
  36874. const int numNeeded = linesOnScreen + 1;
  36875. int minLineToRepaint = numNeeded;
  36876. int maxLineToRepaint = 0;
  36877. if (numNeeded != lines.size())
  36878. {
  36879. lines.clear();
  36880. for (int i = numNeeded; --i >= 0;)
  36881. lines.add (new CodeEditorLine());
  36882. minLineToRepaint = 0;
  36883. maxLineToRepaint = numNeeded;
  36884. }
  36885. jassert (numNeeded == lines.size());
  36886. CodeDocument::Iterator source (&document);
  36887. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36888. for (int i = 0; i < numNeeded; ++i)
  36889. {
  36890. CodeEditorLine* const line = lines.getUnchecked(i);
  36891. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36892. selectionStart, selectionEnd))
  36893. {
  36894. minLineToRepaint = jmin (minLineToRepaint, i);
  36895. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36896. }
  36897. }
  36898. if (minLineToRepaint <= maxLineToRepaint)
  36899. {
  36900. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36901. verticalScrollBar.getX() - gutter,
  36902. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36903. }
  36904. }
  36905. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36906. {
  36907. caretPos = newPos;
  36908. columnToTryToMaintain = -1;
  36909. if (highlighting)
  36910. {
  36911. if (dragType == notDragging)
  36912. {
  36913. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36914. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36915. dragType = draggingSelectionStart;
  36916. else
  36917. dragType = draggingSelectionEnd;
  36918. }
  36919. if (dragType == draggingSelectionStart)
  36920. {
  36921. selectionStart = caretPos;
  36922. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36923. {
  36924. const CodeDocument::Position temp (selectionStart);
  36925. selectionStart = selectionEnd;
  36926. selectionEnd = temp;
  36927. dragType = draggingSelectionEnd;
  36928. }
  36929. }
  36930. else
  36931. {
  36932. selectionEnd = caretPos;
  36933. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36934. {
  36935. const CodeDocument::Position temp (selectionStart);
  36936. selectionStart = selectionEnd;
  36937. selectionEnd = temp;
  36938. dragType = draggingSelectionStart;
  36939. }
  36940. }
  36941. triggerAsyncUpdate();
  36942. }
  36943. else
  36944. {
  36945. deselectAll();
  36946. }
  36947. caret->updatePosition();
  36948. scrollToKeepCaretOnScreen();
  36949. updateScrollBars();
  36950. }
  36951. void CodeEditorComponent::deselectAll()
  36952. {
  36953. if (selectionStart != selectionEnd)
  36954. triggerAsyncUpdate();
  36955. selectionStart = caretPos;
  36956. selectionEnd = caretPos;
  36957. }
  36958. void CodeEditorComponent::updateScrollBars()
  36959. {
  36960. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36961. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36962. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36963. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36964. }
  36965. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36966. {
  36967. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36968. newFirstLineOnScreen);
  36969. if (newFirstLineOnScreen != firstLineOnScreen)
  36970. {
  36971. firstLineOnScreen = newFirstLineOnScreen;
  36972. caret->updatePosition();
  36973. updateCachedIterators (firstLineOnScreen);
  36974. triggerAsyncUpdate();
  36975. }
  36976. }
  36977. void CodeEditorComponent::scrollToColumnInternal (double column)
  36978. {
  36979. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36980. if (xOffset != newOffset)
  36981. {
  36982. xOffset = newOffset;
  36983. caret->updatePosition();
  36984. repaint();
  36985. }
  36986. }
  36987. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36988. {
  36989. scrollToLineInternal (newFirstLineOnScreen);
  36990. updateScrollBars();
  36991. }
  36992. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36993. {
  36994. scrollToColumnInternal (newFirstColumnOnScreen);
  36995. updateScrollBars();
  36996. }
  36997. void CodeEditorComponent::scrollBy (int deltaLines)
  36998. {
  36999. scrollToLine (firstLineOnScreen + deltaLines);
  37000. }
  37001. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37002. {
  37003. if (caretPos.getLineNumber() < firstLineOnScreen)
  37004. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37005. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37006. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37007. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37008. if (column >= xOffset + columnsOnScreen - 1)
  37009. scrollToColumn (column + 1 - columnsOnScreen);
  37010. else if (column < xOffset)
  37011. scrollToColumn (column);
  37012. }
  37013. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37014. {
  37015. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37016. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37017. roundToInt (charWidth),
  37018. lineHeight);
  37019. }
  37020. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37021. {
  37022. const int line = y / lineHeight + firstLineOnScreen;
  37023. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37024. const int index = columnToIndex (line, column);
  37025. return CodeDocument::Position (&document, line, index);
  37026. }
  37027. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37028. {
  37029. document.deleteSection (selectionStart, selectionEnd);
  37030. if (newText.isNotEmpty())
  37031. document.insertText (caretPos, newText);
  37032. scrollToKeepCaretOnScreen();
  37033. }
  37034. void CodeEditorComponent::insertTabAtCaret()
  37035. {
  37036. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37037. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37038. {
  37039. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37040. }
  37041. if (useSpacesForTabs)
  37042. {
  37043. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37044. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37045. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37046. }
  37047. else
  37048. {
  37049. insertTextAtCaret ("\t");
  37050. }
  37051. }
  37052. void CodeEditorComponent::cut()
  37053. {
  37054. insertTextAtCaret (String::empty);
  37055. }
  37056. void CodeEditorComponent::copy()
  37057. {
  37058. newTransaction();
  37059. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37060. if (selection.isNotEmpty())
  37061. SystemClipboard::copyTextToClipboard (selection);
  37062. }
  37063. void CodeEditorComponent::copyThenCut()
  37064. {
  37065. copy();
  37066. cut();
  37067. newTransaction();
  37068. }
  37069. void CodeEditorComponent::paste()
  37070. {
  37071. newTransaction();
  37072. const String clip (SystemClipboard::getTextFromClipboard());
  37073. if (clip.isNotEmpty())
  37074. insertTextAtCaret (clip);
  37075. newTransaction();
  37076. }
  37077. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37078. {
  37079. newTransaction();
  37080. if (moveInWholeWordSteps)
  37081. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37082. else
  37083. moveCaretTo (caretPos.movedBy (-1), selecting);
  37084. }
  37085. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37086. {
  37087. newTransaction();
  37088. if (moveInWholeWordSteps)
  37089. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37090. else
  37091. moveCaretTo (caretPos.movedBy (1), selecting);
  37092. }
  37093. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37094. {
  37095. CodeDocument::Position pos (caretPos);
  37096. const int newLineNum = pos.getLineNumber() + delta;
  37097. if (columnToTryToMaintain < 0)
  37098. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37099. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37100. const int colToMaintain = columnToTryToMaintain;
  37101. moveCaretTo (pos, selecting);
  37102. columnToTryToMaintain = colToMaintain;
  37103. }
  37104. void CodeEditorComponent::cursorDown (const bool selecting)
  37105. {
  37106. newTransaction();
  37107. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37108. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37109. else
  37110. moveLineDelta (1, selecting);
  37111. }
  37112. void CodeEditorComponent::cursorUp (const bool selecting)
  37113. {
  37114. newTransaction();
  37115. if (caretPos.getLineNumber() == 0)
  37116. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37117. else
  37118. moveLineDelta (-1, selecting);
  37119. }
  37120. void CodeEditorComponent::pageDown (const bool selecting)
  37121. {
  37122. newTransaction();
  37123. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37124. moveLineDelta (linesOnScreen, selecting);
  37125. }
  37126. void CodeEditorComponent::pageUp (const bool selecting)
  37127. {
  37128. newTransaction();
  37129. scrollBy (-linesOnScreen);
  37130. moveLineDelta (-linesOnScreen, selecting);
  37131. }
  37132. void CodeEditorComponent::scrollUp()
  37133. {
  37134. newTransaction();
  37135. scrollBy (1);
  37136. if (caretPos.getLineNumber() < firstLineOnScreen)
  37137. moveLineDelta (1, false);
  37138. }
  37139. void CodeEditorComponent::scrollDown()
  37140. {
  37141. newTransaction();
  37142. scrollBy (-1);
  37143. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37144. moveLineDelta (-1, false);
  37145. }
  37146. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37147. {
  37148. newTransaction();
  37149. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37150. }
  37151. namespace CodeEditorHelpers
  37152. {
  37153. int findFirstNonWhitespaceChar (const String& line) throw()
  37154. {
  37155. const int len = line.length();
  37156. for (int i = 0; i < len; ++i)
  37157. if (! CharacterFunctions::isWhitespace (line [i]))
  37158. return i;
  37159. return 0;
  37160. }
  37161. }
  37162. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37163. {
  37164. newTransaction();
  37165. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37166. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37167. index = 0;
  37168. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37169. }
  37170. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37171. {
  37172. newTransaction();
  37173. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37174. }
  37175. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37176. {
  37177. newTransaction();
  37178. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37179. }
  37180. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37181. {
  37182. if (moveInWholeWordSteps)
  37183. {
  37184. cut(); // in case something is already highlighted
  37185. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37186. }
  37187. else
  37188. {
  37189. if (selectionStart == selectionEnd)
  37190. selectionStart.moveBy (-1);
  37191. }
  37192. cut();
  37193. }
  37194. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37195. {
  37196. if (moveInWholeWordSteps)
  37197. {
  37198. cut(); // in case something is already highlighted
  37199. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37200. }
  37201. else
  37202. {
  37203. if (selectionStart == selectionEnd)
  37204. selectionEnd.moveBy (1);
  37205. else
  37206. newTransaction();
  37207. }
  37208. cut();
  37209. }
  37210. void CodeEditorComponent::selectAll()
  37211. {
  37212. newTransaction();
  37213. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37214. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37215. }
  37216. void CodeEditorComponent::undo()
  37217. {
  37218. document.undo();
  37219. scrollToKeepCaretOnScreen();
  37220. }
  37221. void CodeEditorComponent::redo()
  37222. {
  37223. document.redo();
  37224. scrollToKeepCaretOnScreen();
  37225. }
  37226. void CodeEditorComponent::newTransaction()
  37227. {
  37228. document.newTransaction();
  37229. startTimer (600);
  37230. }
  37231. void CodeEditorComponent::timerCallback()
  37232. {
  37233. newTransaction();
  37234. }
  37235. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37236. {
  37237. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37238. }
  37239. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37240. {
  37241. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37242. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37243. }
  37244. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37245. {
  37246. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37247. CodeDocument::Position (&document, range.getEnd()));
  37248. }
  37249. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37250. {
  37251. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37252. const bool shiftDown = key.getModifiers().isShiftDown();
  37253. if (key.isKeyCode (KeyPress::leftKey))
  37254. {
  37255. cursorLeft (moveInWholeWordSteps, shiftDown);
  37256. }
  37257. else if (key.isKeyCode (KeyPress::rightKey))
  37258. {
  37259. cursorRight (moveInWholeWordSteps, shiftDown);
  37260. }
  37261. else if (key.isKeyCode (KeyPress::upKey))
  37262. {
  37263. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37264. scrollDown();
  37265. #if JUCE_MAC
  37266. else if (key.getModifiers().isCommandDown())
  37267. goToStartOfDocument (shiftDown);
  37268. #endif
  37269. else
  37270. cursorUp (shiftDown);
  37271. }
  37272. else if (key.isKeyCode (KeyPress::downKey))
  37273. {
  37274. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37275. scrollUp();
  37276. #if JUCE_MAC
  37277. else if (key.getModifiers().isCommandDown())
  37278. goToEndOfDocument (shiftDown);
  37279. #endif
  37280. else
  37281. cursorDown (shiftDown);
  37282. }
  37283. else if (key.isKeyCode (KeyPress::pageDownKey))
  37284. {
  37285. pageDown (shiftDown);
  37286. }
  37287. else if (key.isKeyCode (KeyPress::pageUpKey))
  37288. {
  37289. pageUp (shiftDown);
  37290. }
  37291. else if (key.isKeyCode (KeyPress::homeKey))
  37292. {
  37293. if (moveInWholeWordSteps)
  37294. goToStartOfDocument (shiftDown);
  37295. else
  37296. goToStartOfLine (shiftDown);
  37297. }
  37298. else if (key.isKeyCode (KeyPress::endKey))
  37299. {
  37300. if (moveInWholeWordSteps)
  37301. goToEndOfDocument (shiftDown);
  37302. else
  37303. goToEndOfLine (shiftDown);
  37304. }
  37305. else if (key.isKeyCode (KeyPress::backspaceKey))
  37306. {
  37307. backspace (moveInWholeWordSteps);
  37308. }
  37309. else if (key.isKeyCode (KeyPress::deleteKey))
  37310. {
  37311. deleteForward (moveInWholeWordSteps);
  37312. }
  37313. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37314. {
  37315. copy();
  37316. }
  37317. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37318. {
  37319. copyThenCut();
  37320. }
  37321. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37322. {
  37323. paste();
  37324. }
  37325. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37326. {
  37327. undo();
  37328. }
  37329. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37330. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37331. {
  37332. redo();
  37333. }
  37334. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37335. {
  37336. selectAll();
  37337. }
  37338. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37339. {
  37340. insertTabAtCaret();
  37341. }
  37342. else if (key == KeyPress::returnKey)
  37343. {
  37344. newTransaction();
  37345. insertTextAtCaret (document.getNewLineCharacters());
  37346. }
  37347. else if (key.isKeyCode (KeyPress::escapeKey))
  37348. {
  37349. newTransaction();
  37350. }
  37351. else if (key.getTextCharacter() >= ' ')
  37352. {
  37353. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37354. }
  37355. else
  37356. {
  37357. return false;
  37358. }
  37359. return true;
  37360. }
  37361. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37362. {
  37363. newTransaction();
  37364. dragType = notDragging;
  37365. if (! e.mods.isPopupMenu())
  37366. {
  37367. beginDragAutoRepeat (100);
  37368. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37369. }
  37370. else
  37371. {
  37372. /*PopupMenu m;
  37373. addPopupMenuItems (m, &e);
  37374. const int result = m.show();
  37375. if (result != 0)
  37376. performPopupMenuAction (result);
  37377. */
  37378. }
  37379. }
  37380. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37381. {
  37382. if (! e.mods.isPopupMenu())
  37383. moveCaretTo (getPositionAt (e.x, e.y), true);
  37384. }
  37385. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37386. {
  37387. newTransaction();
  37388. beginDragAutoRepeat (0);
  37389. dragType = notDragging;
  37390. }
  37391. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37392. {
  37393. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37394. CodeDocument::Position tokenEnd (tokenStart);
  37395. if (e.getNumberOfClicks() > 2)
  37396. {
  37397. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37398. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37399. }
  37400. else
  37401. {
  37402. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37403. tokenEnd.moveBy (1);
  37404. tokenStart = tokenEnd;
  37405. while (tokenStart.getIndexInLine() > 0
  37406. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37407. tokenStart.moveBy (-1);
  37408. }
  37409. moveCaretTo (tokenEnd, false);
  37410. moveCaretTo (tokenStart, true);
  37411. }
  37412. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37413. {
  37414. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37415. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37416. {
  37417. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37418. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37419. }
  37420. else
  37421. {
  37422. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37423. }
  37424. }
  37425. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37426. {
  37427. if (scrollBarThatHasMoved == &verticalScrollBar)
  37428. scrollToLineInternal ((int) newRangeStart);
  37429. else
  37430. scrollToColumnInternal (newRangeStart);
  37431. }
  37432. void CodeEditorComponent::focusGained (FocusChangeType)
  37433. {
  37434. caret->updatePosition();
  37435. }
  37436. void CodeEditorComponent::focusLost (FocusChangeType)
  37437. {
  37438. caret->updatePosition();
  37439. }
  37440. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37441. {
  37442. useSpacesForTabs = insertSpaces;
  37443. if (spacesPerTab != numSpaces)
  37444. {
  37445. spacesPerTab = numSpaces;
  37446. triggerAsyncUpdate();
  37447. }
  37448. }
  37449. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37450. {
  37451. const String line (document.getLine (lineNum));
  37452. jassert (index <= line.length());
  37453. int col = 0;
  37454. for (int i = 0; i < index; ++i)
  37455. {
  37456. if (line[i] != '\t')
  37457. ++col;
  37458. else
  37459. col += getTabSize() - (col % getTabSize());
  37460. }
  37461. return col;
  37462. }
  37463. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37464. {
  37465. const String line (document.getLine (lineNum));
  37466. const int lineLength = line.length();
  37467. int i, col = 0;
  37468. for (i = 0; i < lineLength; ++i)
  37469. {
  37470. if (line[i] != '\t')
  37471. ++col;
  37472. else
  37473. col += getTabSize() - (col % getTabSize());
  37474. if (col > column)
  37475. break;
  37476. }
  37477. return i;
  37478. }
  37479. void CodeEditorComponent::setFont (const Font& newFont)
  37480. {
  37481. font = newFont;
  37482. charWidth = font.getStringWidthFloat ("0");
  37483. lineHeight = roundToInt (font.getHeight());
  37484. resized();
  37485. }
  37486. void CodeEditorComponent::resetToDefaultColours()
  37487. {
  37488. coloursForTokenCategories.clear();
  37489. if (codeTokeniser != 0)
  37490. {
  37491. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37492. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37493. }
  37494. }
  37495. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37496. {
  37497. jassert (tokenType < 256);
  37498. while (coloursForTokenCategories.size() < tokenType)
  37499. coloursForTokenCategories.add (Colours::black);
  37500. coloursForTokenCategories.set (tokenType, colour);
  37501. repaint();
  37502. }
  37503. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37504. {
  37505. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37506. return findColour (CodeEditorComponent::defaultTextColourId);
  37507. return coloursForTokenCategories.getReference (tokenType);
  37508. }
  37509. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37510. {
  37511. int i;
  37512. for (i = cachedIterators.size(); --i >= 0;)
  37513. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37514. break;
  37515. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37516. }
  37517. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37518. {
  37519. const int maxNumCachedPositions = 5000;
  37520. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37521. if (cachedIterators.size() == 0)
  37522. cachedIterators.add (new CodeDocument::Iterator (&document));
  37523. if (codeTokeniser == 0)
  37524. return;
  37525. for (;;)
  37526. {
  37527. CodeDocument::Iterator* last = cachedIterators.getLast();
  37528. if (last->getLine() >= maxLineNum)
  37529. break;
  37530. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37531. cachedIterators.add (t);
  37532. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37533. for (;;)
  37534. {
  37535. codeTokeniser->readNextToken (*t);
  37536. if (t->getLine() >= targetLine)
  37537. break;
  37538. if (t->isEOF())
  37539. return;
  37540. }
  37541. }
  37542. }
  37543. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37544. {
  37545. if (codeTokeniser == 0)
  37546. return;
  37547. for (int i = cachedIterators.size(); --i >= 0;)
  37548. {
  37549. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37550. if (t->getPosition() <= position)
  37551. {
  37552. source = *t;
  37553. break;
  37554. }
  37555. }
  37556. while (source.getPosition() < position)
  37557. {
  37558. const CodeDocument::Iterator original (source);
  37559. codeTokeniser->readNextToken (source);
  37560. if (source.getPosition() > position || source.isEOF())
  37561. {
  37562. source = original;
  37563. break;
  37564. }
  37565. }
  37566. }
  37567. END_JUCE_NAMESPACE
  37568. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37569. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37570. BEGIN_JUCE_NAMESPACE
  37571. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37572. {
  37573. }
  37574. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37575. {
  37576. }
  37577. namespace CppTokeniser
  37578. {
  37579. bool isIdentifierStart (const juce_wchar c) throw()
  37580. {
  37581. return CharacterFunctions::isLetter (c)
  37582. || c == '_' || c == '@';
  37583. }
  37584. bool isIdentifierBody (const juce_wchar c) throw()
  37585. {
  37586. return CharacterFunctions::isLetterOrDigit (c)
  37587. || c == '_' || c == '@';
  37588. }
  37589. bool isReservedKeyword (String::CharPointerType token, const int tokenLength) throw()
  37590. {
  37591. static const char* const keywords2Char[] =
  37592. { "if", "do", "or", "id", 0 };
  37593. static const char* const keywords3Char[] =
  37594. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37595. static const char* const keywords4Char[] =
  37596. { "bool", "void", "this", "true", "long", "else", "char",
  37597. "enum", "case", "goto", "auto", 0 };
  37598. static const char* const keywords5Char[] =
  37599. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37600. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37601. static const char* const keywords6Char[] =
  37602. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37603. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37604. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37605. static const char* const keywordsOther[] =
  37606. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37607. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37608. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37609. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37610. "@private", "@property", "@protected", "@class", 0 };
  37611. const char* const* k;
  37612. switch (tokenLength)
  37613. {
  37614. case 2: k = keywords2Char; break;
  37615. case 3: k = keywords3Char; break;
  37616. case 4: k = keywords4Char; break;
  37617. case 5: k = keywords5Char; break;
  37618. case 6: k = keywords6Char; break;
  37619. default:
  37620. if (tokenLength < 2 || tokenLength > 16)
  37621. return false;
  37622. k = keywordsOther;
  37623. break;
  37624. }
  37625. int i = 0;
  37626. while (k[i] != 0)
  37627. {
  37628. if (token.compare (CharPointer_ASCII (k[i])) == 0)
  37629. return true;
  37630. ++i;
  37631. }
  37632. return false;
  37633. }
  37634. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37635. {
  37636. int tokenLength = 0;
  37637. juce_wchar possibleIdentifier [19];
  37638. while (isIdentifierBody (source.peekNextChar()))
  37639. {
  37640. const juce_wchar c = source.nextChar();
  37641. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37642. possibleIdentifier [tokenLength] = c;
  37643. ++tokenLength;
  37644. }
  37645. if (tokenLength > 1 && tokenLength <= 16)
  37646. {
  37647. possibleIdentifier [tokenLength] = 0;
  37648. if (isReservedKeyword (CharPointer_UTF32 (possibleIdentifier), tokenLength))
  37649. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37650. }
  37651. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37652. }
  37653. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37654. {
  37655. const juce_wchar c = source.peekNextChar();
  37656. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37657. source.skip();
  37658. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37659. return false;
  37660. return true;
  37661. }
  37662. bool isHexDigit (const juce_wchar c) throw()
  37663. {
  37664. return (c >= '0' && c <= '9')
  37665. || (c >= 'a' && c <= 'f')
  37666. || (c >= 'A' && c <= 'F');
  37667. }
  37668. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37669. {
  37670. if (source.nextChar() != '0')
  37671. return false;
  37672. juce_wchar c = source.nextChar();
  37673. if (c != 'x' && c != 'X')
  37674. return false;
  37675. int numDigits = 0;
  37676. while (isHexDigit (source.peekNextChar()))
  37677. {
  37678. ++numDigits;
  37679. source.skip();
  37680. }
  37681. if (numDigits == 0)
  37682. return false;
  37683. return skipNumberSuffix (source);
  37684. }
  37685. bool isOctalDigit (const juce_wchar c) throw()
  37686. {
  37687. return c >= '0' && c <= '7';
  37688. }
  37689. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37690. {
  37691. if (source.nextChar() != '0')
  37692. return false;
  37693. if (! isOctalDigit (source.nextChar()))
  37694. return false;
  37695. while (isOctalDigit (source.peekNextChar()))
  37696. source.skip();
  37697. return skipNumberSuffix (source);
  37698. }
  37699. bool isDecimalDigit (const juce_wchar c) throw()
  37700. {
  37701. return c >= '0' && c <= '9';
  37702. }
  37703. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37704. {
  37705. int numChars = 0;
  37706. while (isDecimalDigit (source.peekNextChar()))
  37707. {
  37708. ++numChars;
  37709. source.skip();
  37710. }
  37711. if (numChars == 0)
  37712. return false;
  37713. return skipNumberSuffix (source);
  37714. }
  37715. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37716. {
  37717. int numDigits = 0;
  37718. while (isDecimalDigit (source.peekNextChar()))
  37719. {
  37720. source.skip();
  37721. ++numDigits;
  37722. }
  37723. const bool hasPoint = (source.peekNextChar() == '.');
  37724. if (hasPoint)
  37725. {
  37726. source.skip();
  37727. while (isDecimalDigit (source.peekNextChar()))
  37728. {
  37729. source.skip();
  37730. ++numDigits;
  37731. }
  37732. }
  37733. if (numDigits == 0)
  37734. return false;
  37735. juce_wchar c = source.peekNextChar();
  37736. const bool hasExponent = (c == 'e' || c == 'E');
  37737. if (hasExponent)
  37738. {
  37739. source.skip();
  37740. c = source.peekNextChar();
  37741. if (c == '+' || c == '-')
  37742. source.skip();
  37743. int numExpDigits = 0;
  37744. while (isDecimalDigit (source.peekNextChar()))
  37745. {
  37746. source.skip();
  37747. ++numExpDigits;
  37748. }
  37749. if (numExpDigits == 0)
  37750. return false;
  37751. }
  37752. c = source.peekNextChar();
  37753. if (c == 'f' || c == 'F')
  37754. source.skip();
  37755. else if (! (hasExponent || hasPoint))
  37756. return false;
  37757. return true;
  37758. }
  37759. int parseNumber (CodeDocument::Iterator& source)
  37760. {
  37761. const CodeDocument::Iterator original (source);
  37762. if (parseFloatLiteral (source))
  37763. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37764. source = original;
  37765. if (parseHexLiteral (source))
  37766. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37767. source = original;
  37768. if (parseOctalLiteral (source))
  37769. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37770. source = original;
  37771. if (parseDecimalLiteral (source))
  37772. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37773. source = original;
  37774. source.skip();
  37775. return CPlusPlusCodeTokeniser::tokenType_error;
  37776. }
  37777. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37778. {
  37779. const juce_wchar quote = source.nextChar();
  37780. for (;;)
  37781. {
  37782. const juce_wchar c = source.nextChar();
  37783. if (c == quote || c == 0)
  37784. break;
  37785. if (c == '\\')
  37786. source.skip();
  37787. }
  37788. }
  37789. void skipComment (CodeDocument::Iterator& source) throw()
  37790. {
  37791. bool lastWasStar = false;
  37792. for (;;)
  37793. {
  37794. const juce_wchar c = source.nextChar();
  37795. if (c == 0 || (c == '/' && lastWasStar))
  37796. break;
  37797. lastWasStar = (c == '*');
  37798. }
  37799. }
  37800. }
  37801. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37802. {
  37803. int result = tokenType_error;
  37804. source.skipWhitespace();
  37805. juce_wchar firstChar = source.peekNextChar();
  37806. switch (firstChar)
  37807. {
  37808. case 0:
  37809. source.skip();
  37810. break;
  37811. case '0':
  37812. case '1':
  37813. case '2':
  37814. case '3':
  37815. case '4':
  37816. case '5':
  37817. case '6':
  37818. case '7':
  37819. case '8':
  37820. case '9':
  37821. result = CppTokeniser::parseNumber (source);
  37822. break;
  37823. case '.':
  37824. result = CppTokeniser::parseNumber (source);
  37825. if (result == tokenType_error)
  37826. result = tokenType_punctuation;
  37827. break;
  37828. case ',':
  37829. case ';':
  37830. case ':':
  37831. source.skip();
  37832. result = tokenType_punctuation;
  37833. break;
  37834. case '(':
  37835. case ')':
  37836. case '{':
  37837. case '}':
  37838. case '[':
  37839. case ']':
  37840. source.skip();
  37841. result = tokenType_bracket;
  37842. break;
  37843. case '"':
  37844. case '\'':
  37845. CppTokeniser::skipQuotedString (source);
  37846. result = tokenType_stringLiteral;
  37847. break;
  37848. case '+':
  37849. result = tokenType_operator;
  37850. source.skip();
  37851. if (source.peekNextChar() == '+')
  37852. source.skip();
  37853. else if (source.peekNextChar() == '=')
  37854. source.skip();
  37855. break;
  37856. case '-':
  37857. source.skip();
  37858. result = CppTokeniser::parseNumber (source);
  37859. if (result == tokenType_error)
  37860. {
  37861. result = tokenType_operator;
  37862. if (source.peekNextChar() == '-')
  37863. source.skip();
  37864. else if (source.peekNextChar() == '=')
  37865. source.skip();
  37866. }
  37867. break;
  37868. case '*':
  37869. case '%':
  37870. case '=':
  37871. case '!':
  37872. result = tokenType_operator;
  37873. source.skip();
  37874. if (source.peekNextChar() == '=')
  37875. source.skip();
  37876. break;
  37877. case '/':
  37878. result = tokenType_operator;
  37879. source.skip();
  37880. if (source.peekNextChar() == '=')
  37881. {
  37882. source.skip();
  37883. }
  37884. else if (source.peekNextChar() == '/')
  37885. {
  37886. result = tokenType_comment;
  37887. source.skipToEndOfLine();
  37888. }
  37889. else if (source.peekNextChar() == '*')
  37890. {
  37891. source.skip();
  37892. result = tokenType_comment;
  37893. CppTokeniser::skipComment (source);
  37894. }
  37895. break;
  37896. case '?':
  37897. case '~':
  37898. source.skip();
  37899. result = tokenType_operator;
  37900. break;
  37901. case '<':
  37902. source.skip();
  37903. result = tokenType_operator;
  37904. if (source.peekNextChar() == '=')
  37905. {
  37906. source.skip();
  37907. }
  37908. else if (source.peekNextChar() == '<')
  37909. {
  37910. source.skip();
  37911. if (source.peekNextChar() == '=')
  37912. source.skip();
  37913. }
  37914. break;
  37915. case '>':
  37916. source.skip();
  37917. result = tokenType_operator;
  37918. if (source.peekNextChar() == '=')
  37919. {
  37920. source.skip();
  37921. }
  37922. else if (source.peekNextChar() == '<')
  37923. {
  37924. source.skip();
  37925. if (source.peekNextChar() == '=')
  37926. source.skip();
  37927. }
  37928. break;
  37929. case '|':
  37930. source.skip();
  37931. result = tokenType_operator;
  37932. if (source.peekNextChar() == '=')
  37933. {
  37934. source.skip();
  37935. }
  37936. else if (source.peekNextChar() == '|')
  37937. {
  37938. source.skip();
  37939. if (source.peekNextChar() == '=')
  37940. source.skip();
  37941. }
  37942. break;
  37943. case '&':
  37944. source.skip();
  37945. result = tokenType_operator;
  37946. if (source.peekNextChar() == '=')
  37947. {
  37948. source.skip();
  37949. }
  37950. else if (source.peekNextChar() == '&')
  37951. {
  37952. source.skip();
  37953. if (source.peekNextChar() == '=')
  37954. source.skip();
  37955. }
  37956. break;
  37957. case '^':
  37958. source.skip();
  37959. result = tokenType_operator;
  37960. if (source.peekNextChar() == '=')
  37961. {
  37962. source.skip();
  37963. }
  37964. else if (source.peekNextChar() == '^')
  37965. {
  37966. source.skip();
  37967. if (source.peekNextChar() == '=')
  37968. source.skip();
  37969. }
  37970. break;
  37971. case '#':
  37972. result = tokenType_preprocessor;
  37973. source.skipToEndOfLine();
  37974. break;
  37975. default:
  37976. if (CppTokeniser::isIdentifierStart (firstChar))
  37977. result = CppTokeniser::parseIdentifier (source);
  37978. else
  37979. source.skip();
  37980. break;
  37981. }
  37982. return result;
  37983. }
  37984. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37985. {
  37986. const char* const types[] =
  37987. {
  37988. "Error",
  37989. "Comment",
  37990. "C++ keyword",
  37991. "Identifier",
  37992. "Integer literal",
  37993. "Float literal",
  37994. "String literal",
  37995. "Operator",
  37996. "Bracket",
  37997. "Punctuation",
  37998. "Preprocessor line",
  37999. 0
  38000. };
  38001. return StringArray (types);
  38002. }
  38003. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38004. {
  38005. const uint32 colours[] =
  38006. {
  38007. 0xffcc0000, // error
  38008. 0xff00aa00, // comment
  38009. 0xff0000cc, // keyword
  38010. 0xff000000, // identifier
  38011. 0xff880000, // int literal
  38012. 0xff885500, // float literal
  38013. 0xff990099, // string literal
  38014. 0xff225500, // operator
  38015. 0xff000055, // bracket
  38016. 0xff004400, // punctuation
  38017. 0xff660000 // preprocessor
  38018. };
  38019. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38020. return Colour (colours [tokenType]);
  38021. return Colours::black;
  38022. }
  38023. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38024. {
  38025. return CppTokeniser::isReservedKeyword (token.getCharPointer(), token.length());
  38026. }
  38027. END_JUCE_NAMESPACE
  38028. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38029. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38030. BEGIN_JUCE_NAMESPACE
  38031. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38032. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38033. {
  38034. }
  38035. bool ComboBox::ItemInfo::isSeparator() const throw()
  38036. {
  38037. return name.isEmpty();
  38038. }
  38039. bool ComboBox::ItemInfo::isRealItem() const throw()
  38040. {
  38041. return ! (isHeading || name.isEmpty());
  38042. }
  38043. ComboBox::ComboBox (const String& name)
  38044. : Component (name),
  38045. lastCurrentId (0),
  38046. isButtonDown (false),
  38047. separatorPending (false),
  38048. menuActive (false),
  38049. noChoicesMessage (TRANS("(no choices)"))
  38050. {
  38051. setRepaintsOnMouseActivity (true);
  38052. lookAndFeelChanged();
  38053. currentId.addListener (this);
  38054. }
  38055. ComboBox::~ComboBox()
  38056. {
  38057. currentId.removeListener (this);
  38058. if (menuActive)
  38059. PopupMenu::dismissAllActiveMenus();
  38060. label = 0;
  38061. }
  38062. void ComboBox::setEditableText (const bool isEditable)
  38063. {
  38064. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38065. {
  38066. label->setEditable (isEditable, isEditable, false);
  38067. setWantsKeyboardFocus (! isEditable);
  38068. resized();
  38069. }
  38070. }
  38071. bool ComboBox::isTextEditable() const throw()
  38072. {
  38073. return label->isEditable();
  38074. }
  38075. void ComboBox::setJustificationType (const Justification& justification)
  38076. {
  38077. label->setJustificationType (justification);
  38078. }
  38079. const Justification ComboBox::getJustificationType() const throw()
  38080. {
  38081. return label->getJustificationType();
  38082. }
  38083. void ComboBox::setTooltip (const String& newTooltip)
  38084. {
  38085. SettableTooltipClient::setTooltip (newTooltip);
  38086. label->setTooltip (newTooltip);
  38087. }
  38088. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38089. {
  38090. // you can't add empty strings to the list..
  38091. jassert (newItemText.isNotEmpty());
  38092. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38093. jassert (newItemId != 0);
  38094. // you shouldn't use duplicate item IDs!
  38095. jassert (getItemForId (newItemId) == 0);
  38096. if (newItemText.isNotEmpty() && newItemId != 0)
  38097. {
  38098. if (separatorPending)
  38099. {
  38100. separatorPending = false;
  38101. items.add (new ItemInfo (String::empty, 0, false, false));
  38102. }
  38103. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38104. }
  38105. }
  38106. void ComboBox::addSeparator()
  38107. {
  38108. separatorPending = (items.size() > 0);
  38109. }
  38110. void ComboBox::addSectionHeading (const String& headingName)
  38111. {
  38112. // you can't add empty strings to the list..
  38113. jassert (headingName.isNotEmpty());
  38114. if (headingName.isNotEmpty())
  38115. {
  38116. if (separatorPending)
  38117. {
  38118. separatorPending = false;
  38119. items.add (new ItemInfo (String::empty, 0, false, false));
  38120. }
  38121. items.add (new ItemInfo (headingName, 0, true, true));
  38122. }
  38123. }
  38124. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38125. {
  38126. ItemInfo* const item = getItemForId (itemId);
  38127. if (item != 0)
  38128. item->isEnabled = shouldBeEnabled;
  38129. }
  38130. bool ComboBox::isItemEnabled (int itemId) const throw()
  38131. {
  38132. const ItemInfo* const item = getItemForId (itemId);
  38133. return item != 0 && item->isEnabled;
  38134. }
  38135. void ComboBox::changeItemText (const int itemId, const String& newText)
  38136. {
  38137. ItemInfo* const item = getItemForId (itemId);
  38138. jassert (item != 0);
  38139. if (item != 0)
  38140. item->name = newText;
  38141. }
  38142. void ComboBox::clear (const bool dontSendChangeMessage)
  38143. {
  38144. items.clear();
  38145. separatorPending = false;
  38146. if (! label->isEditable())
  38147. setSelectedItemIndex (-1, dontSendChangeMessage);
  38148. }
  38149. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38150. {
  38151. if (itemId != 0)
  38152. {
  38153. for (int i = items.size(); --i >= 0;)
  38154. if (items.getUnchecked(i)->itemId == itemId)
  38155. return items.getUnchecked(i);
  38156. }
  38157. return 0;
  38158. }
  38159. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38160. {
  38161. for (int n = 0, i = 0; i < items.size(); ++i)
  38162. {
  38163. ItemInfo* const item = items.getUnchecked(i);
  38164. if (item->isRealItem())
  38165. if (n++ == index)
  38166. return item;
  38167. }
  38168. return 0;
  38169. }
  38170. int ComboBox::getNumItems() const throw()
  38171. {
  38172. int n = 0;
  38173. for (int i = items.size(); --i >= 0;)
  38174. if (items.getUnchecked(i)->isRealItem())
  38175. ++n;
  38176. return n;
  38177. }
  38178. const String ComboBox::getItemText (const int index) const
  38179. {
  38180. const ItemInfo* const item = getItemForIndex (index);
  38181. return item != 0 ? item->name : String::empty;
  38182. }
  38183. int ComboBox::getItemId (const int index) const throw()
  38184. {
  38185. const ItemInfo* const item = getItemForIndex (index);
  38186. return item != 0 ? item->itemId : 0;
  38187. }
  38188. int ComboBox::indexOfItemId (const int itemId) const throw()
  38189. {
  38190. for (int n = 0, i = 0; i < items.size(); ++i)
  38191. {
  38192. const ItemInfo* const item = items.getUnchecked(i);
  38193. if (item->isRealItem())
  38194. {
  38195. if (item->itemId == itemId)
  38196. return n;
  38197. ++n;
  38198. }
  38199. }
  38200. return -1;
  38201. }
  38202. int ComboBox::getSelectedItemIndex() const
  38203. {
  38204. int index = indexOfItemId (currentId.getValue());
  38205. if (getText() != getItemText (index))
  38206. index = -1;
  38207. return index;
  38208. }
  38209. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38210. {
  38211. setSelectedId (getItemId (index), dontSendChangeMessage);
  38212. }
  38213. int ComboBox::getSelectedId() const throw()
  38214. {
  38215. const ItemInfo* const item = getItemForId (currentId.getValue());
  38216. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38217. }
  38218. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38219. {
  38220. const ItemInfo* const item = getItemForId (newItemId);
  38221. const String newItemText (item != 0 ? item->name : String::empty);
  38222. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38223. {
  38224. if (! dontSendChangeMessage)
  38225. triggerAsyncUpdate();
  38226. label->setText (newItemText, false);
  38227. lastCurrentId = newItemId;
  38228. currentId = newItemId;
  38229. repaint(); // for the benefit of the 'none selected' text
  38230. }
  38231. }
  38232. bool ComboBox::selectIfEnabled (const int index)
  38233. {
  38234. const ItemInfo* const item = getItemForIndex (index);
  38235. if (item != 0 && item->isEnabled)
  38236. {
  38237. setSelectedItemIndex (index);
  38238. return true;
  38239. }
  38240. return false;
  38241. }
  38242. void ComboBox::valueChanged (Value&)
  38243. {
  38244. if (lastCurrentId != (int) currentId.getValue())
  38245. setSelectedId (currentId.getValue(), false);
  38246. }
  38247. const String ComboBox::getText() const
  38248. {
  38249. return label->getText();
  38250. }
  38251. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38252. {
  38253. for (int i = items.size(); --i >= 0;)
  38254. {
  38255. const ItemInfo* const item = items.getUnchecked(i);
  38256. if (item->isRealItem()
  38257. && item->name == newText)
  38258. {
  38259. setSelectedId (item->itemId, dontSendChangeMessage);
  38260. return;
  38261. }
  38262. }
  38263. lastCurrentId = 0;
  38264. currentId = 0;
  38265. if (label->getText() != newText)
  38266. {
  38267. label->setText (newText, false);
  38268. if (! dontSendChangeMessage)
  38269. triggerAsyncUpdate();
  38270. }
  38271. repaint();
  38272. }
  38273. void ComboBox::showEditor()
  38274. {
  38275. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38276. label->showEditor();
  38277. }
  38278. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38279. {
  38280. if (textWhenNothingSelected != newMessage)
  38281. {
  38282. textWhenNothingSelected = newMessage;
  38283. repaint();
  38284. }
  38285. }
  38286. const String ComboBox::getTextWhenNothingSelected() const
  38287. {
  38288. return textWhenNothingSelected;
  38289. }
  38290. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38291. {
  38292. noChoicesMessage = newMessage;
  38293. }
  38294. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38295. {
  38296. return noChoicesMessage;
  38297. }
  38298. void ComboBox::paint (Graphics& g)
  38299. {
  38300. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38301. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38302. *this);
  38303. if (textWhenNothingSelected.isNotEmpty()
  38304. && label->getText().isEmpty()
  38305. && ! label->isBeingEdited())
  38306. {
  38307. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38308. g.setFont (label->getFont());
  38309. g.drawFittedText (textWhenNothingSelected,
  38310. label->getX() + 2, label->getY() + 1,
  38311. label->getWidth() - 4, label->getHeight() - 2,
  38312. label->getJustificationType(),
  38313. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38314. }
  38315. }
  38316. void ComboBox::resized()
  38317. {
  38318. if (getHeight() > 0 && getWidth() > 0)
  38319. getLookAndFeel().positionComboBoxText (*this, *label);
  38320. }
  38321. void ComboBox::enablementChanged()
  38322. {
  38323. repaint();
  38324. }
  38325. void ComboBox::lookAndFeelChanged()
  38326. {
  38327. repaint();
  38328. {
  38329. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38330. jassert (newLabel != 0);
  38331. if (label != 0)
  38332. {
  38333. newLabel->setEditable (label->isEditable());
  38334. newLabel->setJustificationType (label->getJustificationType());
  38335. newLabel->setTooltip (label->getTooltip());
  38336. newLabel->setText (label->getText(), false);
  38337. }
  38338. label = newLabel;
  38339. }
  38340. addAndMakeVisible (label);
  38341. label->addListener (this);
  38342. label->addMouseListener (this, false);
  38343. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38344. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38345. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38346. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38347. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38348. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38349. resized();
  38350. }
  38351. void ComboBox::colourChanged()
  38352. {
  38353. lookAndFeelChanged();
  38354. }
  38355. bool ComboBox::keyPressed (const KeyPress& key)
  38356. {
  38357. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38358. {
  38359. int index = getSelectedItemIndex() - 1;
  38360. while (index >= 0 && ! selectIfEnabled (index))
  38361. --index;
  38362. return true;
  38363. }
  38364. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38365. {
  38366. int index = getSelectedItemIndex() + 1;
  38367. while (index < getNumItems() && ! selectIfEnabled (index))
  38368. ++index;
  38369. return true;
  38370. }
  38371. else if (key.isKeyCode (KeyPress::returnKey))
  38372. {
  38373. showPopup();
  38374. return true;
  38375. }
  38376. return false;
  38377. }
  38378. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38379. {
  38380. // only forward key events that aren't used by this component
  38381. return isKeyDown
  38382. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38383. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38384. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38385. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38386. }
  38387. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38388. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38389. void ComboBox::labelTextChanged (Label*)
  38390. {
  38391. triggerAsyncUpdate();
  38392. }
  38393. void ComboBox::popupMenuFinishedCallback (int result, ComboBox* box)
  38394. {
  38395. if (box != 0)
  38396. {
  38397. box->menuActive = false;
  38398. if (result != 0)
  38399. box->setSelectedId (result);
  38400. }
  38401. }
  38402. void ComboBox::showPopup()
  38403. {
  38404. if (! menuActive)
  38405. {
  38406. const int selectedId = getSelectedId();
  38407. PopupMenu menu;
  38408. menu.setLookAndFeel (&getLookAndFeel());
  38409. for (int i = 0; i < items.size(); ++i)
  38410. {
  38411. const ItemInfo* const item = items.getUnchecked(i);
  38412. if (item->isSeparator())
  38413. menu.addSeparator();
  38414. else if (item->isHeading)
  38415. menu.addSectionHeader (item->name);
  38416. else
  38417. menu.addItem (item->itemId, item->name,
  38418. item->isEnabled, item->itemId == selectedId);
  38419. }
  38420. if (items.size() == 0)
  38421. menu.addItem (1, noChoicesMessage, false);
  38422. menuActive = true;
  38423. menu.showMenuAsync (PopupMenu::Options().withTargetComponent (this)
  38424. .withItemThatMustBeVisible (selectedId)
  38425. .withMinimumWidth (getWidth())
  38426. .withMaximumNumColumns (1)
  38427. .withStandardItemHeight (jlimit (12, 24, getHeight())),
  38428. ModalCallbackFunction::forComponent (popupMenuFinishedCallback, this));
  38429. }
  38430. }
  38431. void ComboBox::mouseDown (const MouseEvent& e)
  38432. {
  38433. beginDragAutoRepeat (300);
  38434. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38435. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38436. showPopup();
  38437. }
  38438. void ComboBox::mouseDrag (const MouseEvent& e)
  38439. {
  38440. beginDragAutoRepeat (50);
  38441. if (isButtonDown && ! e.mouseWasClicked())
  38442. showPopup();
  38443. }
  38444. void ComboBox::mouseUp (const MouseEvent& e2)
  38445. {
  38446. if (isButtonDown)
  38447. {
  38448. isButtonDown = false;
  38449. repaint();
  38450. const MouseEvent e (e2.getEventRelativeTo (this));
  38451. if (reallyContains (e.getPosition(), true)
  38452. && (e2.eventComponent == this || ! label->isEditable()))
  38453. {
  38454. showPopup();
  38455. }
  38456. }
  38457. }
  38458. void ComboBox::addListener (ComboBoxListener* const listener)
  38459. {
  38460. listeners.add (listener);
  38461. }
  38462. void ComboBox::removeListener (ComboBoxListener* const listener)
  38463. {
  38464. listeners.remove (listener);
  38465. }
  38466. void ComboBox::handleAsyncUpdate()
  38467. {
  38468. Component::BailOutChecker checker (this);
  38469. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38470. }
  38471. END_JUCE_NAMESPACE
  38472. /*** End of inlined file: juce_ComboBox.cpp ***/
  38473. /*** Start of inlined file: juce_Label.cpp ***/
  38474. BEGIN_JUCE_NAMESPACE
  38475. Label::Label (const String& componentName,
  38476. const String& labelText)
  38477. : Component (componentName),
  38478. textValue (labelText),
  38479. lastTextValue (labelText),
  38480. font (15.0f),
  38481. justification (Justification::centredLeft),
  38482. ownerComponent (0),
  38483. horizontalBorderSize (5),
  38484. verticalBorderSize (1),
  38485. minimumHorizontalScale (0.7f),
  38486. editSingleClick (false),
  38487. editDoubleClick (false),
  38488. lossOfFocusDiscardsChanges (false)
  38489. {
  38490. setColour (TextEditor::textColourId, Colours::black);
  38491. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38492. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38493. textValue.addListener (this);
  38494. }
  38495. Label::~Label()
  38496. {
  38497. textValue.removeListener (this);
  38498. if (ownerComponent != 0)
  38499. ownerComponent->removeComponentListener (this);
  38500. editor = 0;
  38501. }
  38502. void Label::setText (const String& newText,
  38503. const bool broadcastChangeMessage)
  38504. {
  38505. hideEditor (true);
  38506. if (lastTextValue != newText)
  38507. {
  38508. lastTextValue = newText;
  38509. textValue = newText;
  38510. repaint();
  38511. textWasChanged();
  38512. if (ownerComponent != 0)
  38513. componentMovedOrResized (*ownerComponent, true, true);
  38514. if (broadcastChangeMessage)
  38515. callChangeListeners();
  38516. }
  38517. }
  38518. const String Label::getText (const bool returnActiveEditorContents) const
  38519. {
  38520. return (returnActiveEditorContents && isBeingEdited())
  38521. ? editor->getText()
  38522. : textValue.toString();
  38523. }
  38524. void Label::valueChanged (Value&)
  38525. {
  38526. if (lastTextValue != textValue.toString())
  38527. setText (textValue.toString(), true);
  38528. }
  38529. void Label::setFont (const Font& newFont)
  38530. {
  38531. if (font != newFont)
  38532. {
  38533. font = newFont;
  38534. repaint();
  38535. }
  38536. }
  38537. const Font& Label::getFont() const throw()
  38538. {
  38539. return font;
  38540. }
  38541. void Label::setEditable (const bool editOnSingleClick,
  38542. const bool editOnDoubleClick,
  38543. const bool lossOfFocusDiscardsChanges_)
  38544. {
  38545. editSingleClick = editOnSingleClick;
  38546. editDoubleClick = editOnDoubleClick;
  38547. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38548. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38549. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38550. }
  38551. void Label::setJustificationType (const Justification& newJustification)
  38552. {
  38553. if (justification != newJustification)
  38554. {
  38555. justification = newJustification;
  38556. repaint();
  38557. }
  38558. }
  38559. void Label::setBorderSize (int h, int v)
  38560. {
  38561. if (horizontalBorderSize != h || verticalBorderSize != v)
  38562. {
  38563. horizontalBorderSize = h;
  38564. verticalBorderSize = v;
  38565. repaint();
  38566. }
  38567. }
  38568. Component* Label::getAttachedComponent() const
  38569. {
  38570. return static_cast<Component*> (ownerComponent);
  38571. }
  38572. void Label::attachToComponent (Component* owner,
  38573. const bool onLeft)
  38574. {
  38575. if (ownerComponent != 0)
  38576. ownerComponent->removeComponentListener (this);
  38577. ownerComponent = owner;
  38578. leftOfOwnerComp = onLeft;
  38579. if (ownerComponent != 0)
  38580. {
  38581. setVisible (owner->isVisible());
  38582. ownerComponent->addComponentListener (this);
  38583. componentParentHierarchyChanged (*ownerComponent);
  38584. componentMovedOrResized (*ownerComponent, true, true);
  38585. }
  38586. }
  38587. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38588. {
  38589. if (leftOfOwnerComp)
  38590. {
  38591. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38592. component.getHeight());
  38593. setTopRightPosition (component.getX(), component.getY());
  38594. }
  38595. else
  38596. {
  38597. setSize (component.getWidth(),
  38598. 8 + roundToInt (getFont().getHeight()));
  38599. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38600. }
  38601. }
  38602. void Label::componentParentHierarchyChanged (Component& component)
  38603. {
  38604. if (component.getParentComponent() != 0)
  38605. component.getParentComponent()->addChildComponent (this);
  38606. }
  38607. void Label::componentVisibilityChanged (Component& component)
  38608. {
  38609. setVisible (component.isVisible());
  38610. }
  38611. void Label::textWasEdited()
  38612. {
  38613. }
  38614. void Label::textWasChanged()
  38615. {
  38616. }
  38617. void Label::showEditor()
  38618. {
  38619. if (editor == 0)
  38620. {
  38621. addAndMakeVisible (editor = createEditorComponent());
  38622. editor->setText (getText(), false);
  38623. editor->addListener (this);
  38624. editor->grabKeyboardFocus();
  38625. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38626. editor->addListener (this);
  38627. resized();
  38628. repaint();
  38629. editorShown (editor);
  38630. enterModalState (false);
  38631. editor->grabKeyboardFocus();
  38632. }
  38633. }
  38634. void Label::editorShown (TextEditor*)
  38635. {
  38636. }
  38637. void Label::editorAboutToBeHidden (TextEditor*)
  38638. {
  38639. }
  38640. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38641. {
  38642. const String newText (ed.getText());
  38643. if (textValue.toString() != newText)
  38644. {
  38645. lastTextValue = newText;
  38646. textValue = newText;
  38647. repaint();
  38648. textWasChanged();
  38649. if (ownerComponent != 0)
  38650. componentMovedOrResized (*ownerComponent, true, true);
  38651. return true;
  38652. }
  38653. return false;
  38654. }
  38655. void Label::hideEditor (const bool discardCurrentEditorContents)
  38656. {
  38657. if (editor != 0)
  38658. {
  38659. WeakReference<Component> deletionChecker (this);
  38660. ScopedPointer<TextEditor> outgoingEditor (editor);
  38661. editorAboutToBeHidden (outgoingEditor);
  38662. const bool changed = (! discardCurrentEditorContents)
  38663. && updateFromTextEditorContents (*outgoingEditor);
  38664. outgoingEditor = 0;
  38665. repaint();
  38666. if (changed)
  38667. textWasEdited();
  38668. if (deletionChecker != 0)
  38669. exitModalState (0);
  38670. if (changed && deletionChecker != 0)
  38671. callChangeListeners();
  38672. }
  38673. }
  38674. void Label::inputAttemptWhenModal()
  38675. {
  38676. if (editor != 0)
  38677. {
  38678. if (lossOfFocusDiscardsChanges)
  38679. textEditorEscapeKeyPressed (*editor);
  38680. else
  38681. textEditorReturnKeyPressed (*editor);
  38682. }
  38683. }
  38684. bool Label::isBeingEdited() const throw()
  38685. {
  38686. return editor != 0;
  38687. }
  38688. TextEditor* Label::createEditorComponent()
  38689. {
  38690. TextEditor* const ed = new TextEditor (getName());
  38691. ed->setFont (font);
  38692. // copy these colours from our own settings..
  38693. const int cols[] = { TextEditor::backgroundColourId,
  38694. TextEditor::textColourId,
  38695. TextEditor::highlightColourId,
  38696. TextEditor::highlightedTextColourId,
  38697. TextEditor::caretColourId,
  38698. TextEditor::outlineColourId,
  38699. TextEditor::focusedOutlineColourId,
  38700. TextEditor::shadowColourId };
  38701. for (int i = 0; i < numElementsInArray (cols); ++i)
  38702. ed->setColour (cols[i], findColour (cols[i]));
  38703. return ed;
  38704. }
  38705. void Label::paint (Graphics& g)
  38706. {
  38707. getLookAndFeel().drawLabel (g, *this);
  38708. }
  38709. void Label::mouseUp (const MouseEvent& e)
  38710. {
  38711. if (editSingleClick
  38712. && e.mouseWasClicked()
  38713. && contains (e.getPosition())
  38714. && ! e.mods.isPopupMenu())
  38715. {
  38716. showEditor();
  38717. }
  38718. }
  38719. void Label::mouseDoubleClick (const MouseEvent& e)
  38720. {
  38721. if (editDoubleClick && ! e.mods.isPopupMenu())
  38722. showEditor();
  38723. }
  38724. void Label::resized()
  38725. {
  38726. if (editor != 0)
  38727. editor->setBoundsInset (BorderSize<int> (0));
  38728. }
  38729. void Label::focusGained (FocusChangeType cause)
  38730. {
  38731. if (editSingleClick && cause == focusChangedByTabKey)
  38732. showEditor();
  38733. }
  38734. void Label::enablementChanged()
  38735. {
  38736. repaint();
  38737. }
  38738. void Label::colourChanged()
  38739. {
  38740. repaint();
  38741. }
  38742. void Label::setMinimumHorizontalScale (const float newScale)
  38743. {
  38744. if (minimumHorizontalScale != newScale)
  38745. {
  38746. minimumHorizontalScale = newScale;
  38747. repaint();
  38748. }
  38749. }
  38750. // We'll use a custom focus traverser here to make sure focus goes from the
  38751. // text editor to another component rather than back to the label itself.
  38752. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38753. {
  38754. public:
  38755. LabelKeyboardFocusTraverser() {}
  38756. Component* getNextComponent (Component* current)
  38757. {
  38758. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38759. ? current->getParentComponent() : current);
  38760. }
  38761. Component* getPreviousComponent (Component* current)
  38762. {
  38763. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38764. ? current->getParentComponent() : current);
  38765. }
  38766. };
  38767. KeyboardFocusTraverser* Label::createFocusTraverser()
  38768. {
  38769. return new LabelKeyboardFocusTraverser();
  38770. }
  38771. void Label::addListener (LabelListener* const listener)
  38772. {
  38773. listeners.add (listener);
  38774. }
  38775. void Label::removeListener (LabelListener* const listener)
  38776. {
  38777. listeners.remove (listener);
  38778. }
  38779. void Label::callChangeListeners()
  38780. {
  38781. Component::BailOutChecker checker (this);
  38782. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38783. }
  38784. void Label::textEditorTextChanged (TextEditor& ed)
  38785. {
  38786. if (editor != 0)
  38787. {
  38788. jassert (&ed == editor);
  38789. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38790. {
  38791. if (lossOfFocusDiscardsChanges)
  38792. textEditorEscapeKeyPressed (ed);
  38793. else
  38794. textEditorReturnKeyPressed (ed);
  38795. }
  38796. }
  38797. }
  38798. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38799. {
  38800. if (editor != 0)
  38801. {
  38802. jassert (&ed == editor);
  38803. const bool changed = updateFromTextEditorContents (ed);
  38804. hideEditor (true);
  38805. if (changed)
  38806. {
  38807. WeakReference<Component> deletionChecker (this);
  38808. textWasEdited();
  38809. if (deletionChecker != 0)
  38810. callChangeListeners();
  38811. }
  38812. }
  38813. }
  38814. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38815. {
  38816. if (editor != 0)
  38817. {
  38818. jassert (&ed == editor);
  38819. (void) ed;
  38820. editor->setText (textValue.toString(), false);
  38821. hideEditor (true);
  38822. }
  38823. }
  38824. void Label::textEditorFocusLost (TextEditor& ed)
  38825. {
  38826. textEditorTextChanged (ed);
  38827. }
  38828. END_JUCE_NAMESPACE
  38829. /*** End of inlined file: juce_Label.cpp ***/
  38830. /*** Start of inlined file: juce_ListBox.cpp ***/
  38831. BEGIN_JUCE_NAMESPACE
  38832. class ListBoxRowComponent : public Component,
  38833. public TooltipClient
  38834. {
  38835. public:
  38836. ListBoxRowComponent (ListBox& owner_)
  38837. : owner (owner_), row (-1),
  38838. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38839. {
  38840. }
  38841. void paint (Graphics& g)
  38842. {
  38843. if (owner.getModel() != 0)
  38844. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38845. }
  38846. void update (const int row_, const bool selected_)
  38847. {
  38848. if (row != row_ || selected != selected_)
  38849. {
  38850. repaint();
  38851. row = row_;
  38852. selected = selected_;
  38853. }
  38854. if (owner.getModel() != 0)
  38855. {
  38856. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38857. if (customComponent != 0)
  38858. {
  38859. addAndMakeVisible (customComponent);
  38860. customComponent->setBounds (getLocalBounds());
  38861. }
  38862. }
  38863. }
  38864. void mouseDown (const MouseEvent& e)
  38865. {
  38866. isDragging = false;
  38867. selectRowOnMouseUp = false;
  38868. if (isEnabled())
  38869. {
  38870. if (! selected)
  38871. {
  38872. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38873. if (owner.getModel() != 0)
  38874. owner.getModel()->listBoxItemClicked (row, e);
  38875. }
  38876. else
  38877. {
  38878. selectRowOnMouseUp = true;
  38879. }
  38880. }
  38881. }
  38882. void mouseUp (const MouseEvent& e)
  38883. {
  38884. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38885. {
  38886. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38887. if (owner.getModel() != 0)
  38888. owner.getModel()->listBoxItemClicked (row, e);
  38889. }
  38890. }
  38891. void mouseDoubleClick (const MouseEvent& e)
  38892. {
  38893. if (owner.getModel() != 0 && isEnabled())
  38894. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38895. }
  38896. void mouseDrag (const MouseEvent& e)
  38897. {
  38898. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38899. {
  38900. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38901. if (selectedRows.size() > 0)
  38902. {
  38903. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38904. if (dragDescription.isNotEmpty())
  38905. {
  38906. isDragging = true;
  38907. owner.startDragAndDrop (e, dragDescription);
  38908. }
  38909. }
  38910. }
  38911. }
  38912. void resized()
  38913. {
  38914. if (customComponent != 0)
  38915. customComponent->setBounds (getLocalBounds());
  38916. }
  38917. const String getTooltip()
  38918. {
  38919. if (owner.getModel() != 0)
  38920. return owner.getModel()->getTooltipForRow (row);
  38921. return String::empty;
  38922. }
  38923. ScopedPointer<Component> customComponent;
  38924. private:
  38925. ListBox& owner;
  38926. int row;
  38927. bool selected, isDragging, selectRowOnMouseUp;
  38928. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38929. };
  38930. class ListViewport : public Viewport
  38931. {
  38932. public:
  38933. ListViewport (ListBox& owner_)
  38934. : owner (owner_)
  38935. {
  38936. setWantsKeyboardFocus (false);
  38937. Component* const content = new Component();
  38938. setViewedComponent (content);
  38939. content->addMouseListener (this, false);
  38940. content->setWantsKeyboardFocus (false);
  38941. }
  38942. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38943. {
  38944. return rows [row % jmax (1, rows.size())];
  38945. }
  38946. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38947. {
  38948. return (row >= firstIndex && row < firstIndex + rows.size())
  38949. ? getComponentForRow (row) : 0;
  38950. }
  38951. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38952. {
  38953. const int index = getIndexOfChildComponent (rowComponent);
  38954. const int num = rows.size();
  38955. for (int i = num; --i >= 0;)
  38956. if (((firstIndex + i) % jmax (1, num)) == index)
  38957. return firstIndex + i;
  38958. return -1;
  38959. }
  38960. void visibleAreaChanged (const Rectangle<int>&)
  38961. {
  38962. updateVisibleArea (true);
  38963. if (owner.getModel() != 0)
  38964. owner.getModel()->listWasScrolled();
  38965. }
  38966. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38967. {
  38968. hasUpdated = false;
  38969. const int newX = getViewedComponent()->getX();
  38970. int newY = getViewedComponent()->getY();
  38971. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38972. const int newH = owner.totalItems * owner.getRowHeight();
  38973. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38974. newY = getMaximumVisibleHeight() - newH;
  38975. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38976. if (makeSureItUpdatesContent && ! hasUpdated)
  38977. updateContents();
  38978. }
  38979. void updateContents()
  38980. {
  38981. hasUpdated = true;
  38982. const int rowHeight = owner.getRowHeight();
  38983. if (rowHeight > 0)
  38984. {
  38985. const int y = getViewPositionY();
  38986. const int w = getViewedComponent()->getWidth();
  38987. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38988. rows.removeRange (numNeeded, rows.size());
  38989. while (numNeeded > rows.size())
  38990. {
  38991. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  38992. rows.add (newRow);
  38993. getViewedComponent()->addAndMakeVisible (newRow);
  38994. }
  38995. firstIndex = y / rowHeight;
  38996. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38997. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38998. for (int i = 0; i < numNeeded; ++i)
  38999. {
  39000. const int row = i + firstIndex;
  39001. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39002. if (rowComp != 0)
  39003. {
  39004. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39005. rowComp->update (row, owner.isRowSelected (row));
  39006. }
  39007. }
  39008. }
  39009. if (owner.headerComponent != 0)
  39010. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39011. owner.outlineThickness,
  39012. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39013. getViewedComponent()->getWidth()),
  39014. owner.headerComponent->getHeight());
  39015. }
  39016. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39017. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39018. {
  39019. hasUpdated = false;
  39020. if (row < firstWholeIndex && ! dontScroll)
  39021. {
  39022. setViewPosition (getViewPositionX(), row * rowHeight);
  39023. }
  39024. else if (row >= lastWholeIndex && ! dontScroll)
  39025. {
  39026. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39027. if (row >= lastRowSelected + rowsOnScreen
  39028. && rowsOnScreen < totalItems - 1
  39029. && ! isMouseClick)
  39030. {
  39031. setViewPosition (getViewPositionX(),
  39032. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39033. }
  39034. else
  39035. {
  39036. setViewPosition (getViewPositionX(),
  39037. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39038. }
  39039. }
  39040. if (! hasUpdated)
  39041. updateContents();
  39042. }
  39043. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39044. {
  39045. if (row < firstWholeIndex)
  39046. {
  39047. setViewPosition (getViewPositionX(), row * rowHeight);
  39048. }
  39049. else if (row >= lastWholeIndex)
  39050. {
  39051. setViewPosition (getViewPositionX(),
  39052. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39053. }
  39054. }
  39055. void paint (Graphics& g)
  39056. {
  39057. if (isOpaque())
  39058. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39059. }
  39060. bool keyPressed (const KeyPress& key)
  39061. {
  39062. if (key.isKeyCode (KeyPress::upKey)
  39063. || key.isKeyCode (KeyPress::downKey)
  39064. || key.isKeyCode (KeyPress::pageUpKey)
  39065. || key.isKeyCode (KeyPress::pageDownKey)
  39066. || key.isKeyCode (KeyPress::homeKey)
  39067. || key.isKeyCode (KeyPress::endKey))
  39068. {
  39069. // we want to avoid these keypresses going to the viewport, and instead allow
  39070. // them to pass up to our listbox..
  39071. return false;
  39072. }
  39073. return Viewport::keyPressed (key);
  39074. }
  39075. private:
  39076. ListBox& owner;
  39077. OwnedArray<ListBoxRowComponent> rows;
  39078. int firstIndex, firstWholeIndex, lastWholeIndex;
  39079. bool hasUpdated;
  39080. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39081. };
  39082. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39083. : Component (name),
  39084. model (model_),
  39085. totalItems (0),
  39086. rowHeight (22),
  39087. minimumRowWidth (0),
  39088. outlineThickness (0),
  39089. lastRowSelected (-1),
  39090. mouseMoveSelects (false),
  39091. multipleSelection (false),
  39092. hasDoneInitialUpdate (false)
  39093. {
  39094. addAndMakeVisible (viewport = new ListViewport (*this));
  39095. setWantsKeyboardFocus (true);
  39096. colourChanged();
  39097. }
  39098. ListBox::~ListBox()
  39099. {
  39100. headerComponent = 0;
  39101. viewport = 0;
  39102. }
  39103. void ListBox::setModel (ListBoxModel* const newModel)
  39104. {
  39105. if (model != newModel)
  39106. {
  39107. model = newModel;
  39108. repaint();
  39109. updateContent();
  39110. }
  39111. }
  39112. void ListBox::setMultipleSelectionEnabled (bool b)
  39113. {
  39114. multipleSelection = b;
  39115. }
  39116. void ListBox::setMouseMoveSelectsRows (bool b)
  39117. {
  39118. mouseMoveSelects = b;
  39119. if (b)
  39120. addMouseListener (this, true);
  39121. }
  39122. void ListBox::paint (Graphics& g)
  39123. {
  39124. if (! hasDoneInitialUpdate)
  39125. updateContent();
  39126. g.fillAll (findColour (backgroundColourId));
  39127. }
  39128. void ListBox::paintOverChildren (Graphics& g)
  39129. {
  39130. if (outlineThickness > 0)
  39131. {
  39132. g.setColour (findColour (outlineColourId));
  39133. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39134. }
  39135. }
  39136. void ListBox::resized()
  39137. {
  39138. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39139. outlineThickness, outlineThickness, outlineThickness));
  39140. viewport->setSingleStepSizes (20, getRowHeight());
  39141. viewport->updateVisibleArea (false);
  39142. }
  39143. void ListBox::visibilityChanged()
  39144. {
  39145. viewport->updateVisibleArea (true);
  39146. }
  39147. Viewport* ListBox::getViewport() const throw()
  39148. {
  39149. return viewport;
  39150. }
  39151. void ListBox::updateContent()
  39152. {
  39153. hasDoneInitialUpdate = true;
  39154. totalItems = (model != 0) ? model->getNumRows() : 0;
  39155. bool selectionChanged = false;
  39156. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  39157. {
  39158. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39159. lastRowSelected = getSelectedRow (0);
  39160. selectionChanged = true;
  39161. }
  39162. viewport->updateVisibleArea (isVisible());
  39163. viewport->resized();
  39164. if (selectionChanged && model != 0)
  39165. model->selectedRowsChanged (lastRowSelected);
  39166. }
  39167. void ListBox::selectRow (const int row,
  39168. bool dontScroll,
  39169. bool deselectOthersFirst)
  39170. {
  39171. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39172. }
  39173. void ListBox::selectRowInternal (const int row,
  39174. bool dontScroll,
  39175. bool deselectOthersFirst,
  39176. bool isMouseClick)
  39177. {
  39178. if (! multipleSelection)
  39179. deselectOthersFirst = true;
  39180. if ((! isRowSelected (row))
  39181. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39182. {
  39183. if (isPositiveAndBelow (row, totalItems))
  39184. {
  39185. if (deselectOthersFirst)
  39186. selected.clear();
  39187. selected.addRange (Range<int> (row, row + 1));
  39188. if (getHeight() == 0 || getWidth() == 0)
  39189. dontScroll = true;
  39190. viewport->selectRow (row, getRowHeight(), dontScroll,
  39191. lastRowSelected, totalItems, isMouseClick);
  39192. lastRowSelected = row;
  39193. model->selectedRowsChanged (row);
  39194. }
  39195. else
  39196. {
  39197. if (deselectOthersFirst)
  39198. deselectAllRows();
  39199. }
  39200. }
  39201. }
  39202. void ListBox::deselectRow (const int row)
  39203. {
  39204. if (selected.contains (row))
  39205. {
  39206. selected.removeRange (Range <int> (row, row + 1));
  39207. if (row == lastRowSelected)
  39208. lastRowSelected = getSelectedRow (0);
  39209. viewport->updateContents();
  39210. model->selectedRowsChanged (lastRowSelected);
  39211. }
  39212. }
  39213. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39214. const bool sendNotificationEventToModel)
  39215. {
  39216. selected = setOfRowsToBeSelected;
  39217. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39218. if (! isRowSelected (lastRowSelected))
  39219. lastRowSelected = getSelectedRow (0);
  39220. viewport->updateContents();
  39221. if ((model != 0) && sendNotificationEventToModel)
  39222. model->selectedRowsChanged (lastRowSelected);
  39223. }
  39224. const SparseSet<int> ListBox::getSelectedRows() const
  39225. {
  39226. return selected;
  39227. }
  39228. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39229. {
  39230. if (multipleSelection && (firstRow != lastRow))
  39231. {
  39232. const int numRows = totalItems - 1;
  39233. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39234. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39235. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39236. jmax (firstRow, lastRow) + 1));
  39237. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39238. }
  39239. selectRowInternal (lastRow, false, false, true);
  39240. }
  39241. void ListBox::flipRowSelection (const int row)
  39242. {
  39243. if (isRowSelected (row))
  39244. deselectRow (row);
  39245. else
  39246. selectRowInternal (row, false, false, true);
  39247. }
  39248. void ListBox::deselectAllRows()
  39249. {
  39250. if (! selected.isEmpty())
  39251. {
  39252. selected.clear();
  39253. lastRowSelected = -1;
  39254. viewport->updateContents();
  39255. if (model != 0)
  39256. model->selectedRowsChanged (lastRowSelected);
  39257. }
  39258. }
  39259. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39260. const ModifierKeys& mods,
  39261. const bool isMouseUpEvent)
  39262. {
  39263. if (multipleSelection && mods.isCommandDown())
  39264. {
  39265. flipRowSelection (row);
  39266. }
  39267. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39268. {
  39269. selectRangeOfRows (lastRowSelected, row);
  39270. }
  39271. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39272. {
  39273. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39274. }
  39275. }
  39276. int ListBox::getNumSelectedRows() const
  39277. {
  39278. return selected.size();
  39279. }
  39280. int ListBox::getSelectedRow (const int index) const
  39281. {
  39282. return (isPositiveAndBelow (index, selected.size()))
  39283. ? selected [index] : -1;
  39284. }
  39285. bool ListBox::isRowSelected (const int row) const
  39286. {
  39287. return selected.contains (row);
  39288. }
  39289. int ListBox::getLastRowSelected() const
  39290. {
  39291. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39292. }
  39293. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39294. {
  39295. if (isPositiveAndBelow (x, getWidth()))
  39296. {
  39297. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39298. if (isPositiveAndBelow (row, totalItems))
  39299. return row;
  39300. }
  39301. return -1;
  39302. }
  39303. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39304. {
  39305. if (isPositiveAndBelow (x, getWidth()))
  39306. {
  39307. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39308. return jlimit (0, totalItems, row);
  39309. }
  39310. return -1;
  39311. }
  39312. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39313. {
  39314. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39315. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39316. }
  39317. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39318. {
  39319. return viewport->getRowNumberOfComponent (rowComponent);
  39320. }
  39321. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39322. const bool relativeToComponentTopLeft) const throw()
  39323. {
  39324. int y = viewport->getY() + rowHeight * rowNumber;
  39325. if (relativeToComponentTopLeft)
  39326. y -= viewport->getViewPositionY();
  39327. return Rectangle<int> (viewport->getX(), y,
  39328. viewport->getViewedComponent()->getWidth(), rowHeight);
  39329. }
  39330. void ListBox::setVerticalPosition (const double proportion)
  39331. {
  39332. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39333. viewport->setViewPosition (viewport->getViewPositionX(),
  39334. jmax (0, roundToInt (proportion * offscreen)));
  39335. }
  39336. double ListBox::getVerticalPosition() const
  39337. {
  39338. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39339. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39340. : 0;
  39341. }
  39342. int ListBox::getVisibleRowWidth() const throw()
  39343. {
  39344. return viewport->getViewWidth();
  39345. }
  39346. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39347. {
  39348. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39349. }
  39350. bool ListBox::keyPressed (const KeyPress& key)
  39351. {
  39352. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39353. const bool multiple = multipleSelection
  39354. && (lastRowSelected >= 0)
  39355. && (key.getModifiers().isShiftDown()
  39356. || key.getModifiers().isCtrlDown()
  39357. || key.getModifiers().isCommandDown());
  39358. if (key.isKeyCode (KeyPress::upKey))
  39359. {
  39360. if (multiple)
  39361. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39362. else
  39363. selectRow (jmax (0, lastRowSelected - 1));
  39364. }
  39365. else if (key.isKeyCode (KeyPress::returnKey)
  39366. && isRowSelected (lastRowSelected))
  39367. {
  39368. if (model != 0)
  39369. model->returnKeyPressed (lastRowSelected);
  39370. }
  39371. else if (key.isKeyCode (KeyPress::pageUpKey))
  39372. {
  39373. if (multiple)
  39374. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39375. else
  39376. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39377. }
  39378. else if (key.isKeyCode (KeyPress::pageDownKey))
  39379. {
  39380. if (multiple)
  39381. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39382. else
  39383. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39384. }
  39385. else if (key.isKeyCode (KeyPress::homeKey))
  39386. {
  39387. if (multiple && key.getModifiers().isShiftDown())
  39388. selectRangeOfRows (lastRowSelected, 0);
  39389. else
  39390. selectRow (0);
  39391. }
  39392. else if (key.isKeyCode (KeyPress::endKey))
  39393. {
  39394. if (multiple && key.getModifiers().isShiftDown())
  39395. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39396. else
  39397. selectRow (totalItems - 1);
  39398. }
  39399. else if (key.isKeyCode (KeyPress::downKey))
  39400. {
  39401. if (multiple)
  39402. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39403. else
  39404. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39405. }
  39406. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39407. && isRowSelected (lastRowSelected))
  39408. {
  39409. if (model != 0)
  39410. model->deleteKeyPressed (lastRowSelected);
  39411. }
  39412. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39413. {
  39414. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39415. }
  39416. else
  39417. {
  39418. return false;
  39419. }
  39420. return true;
  39421. }
  39422. bool ListBox::keyStateChanged (const bool isKeyDown)
  39423. {
  39424. return isKeyDown
  39425. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39426. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39427. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39428. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39429. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39430. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39431. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39432. }
  39433. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39434. {
  39435. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39436. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39437. }
  39438. void ListBox::mouseMove (const MouseEvent& e)
  39439. {
  39440. if (mouseMoveSelects)
  39441. {
  39442. const MouseEvent e2 (e.getEventRelativeTo (this));
  39443. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39444. }
  39445. }
  39446. void ListBox::mouseExit (const MouseEvent& e)
  39447. {
  39448. mouseMove (e);
  39449. }
  39450. void ListBox::mouseUp (const MouseEvent& e)
  39451. {
  39452. if (e.mouseWasClicked() && model != 0)
  39453. model->backgroundClicked();
  39454. }
  39455. void ListBox::setRowHeight (const int newHeight)
  39456. {
  39457. rowHeight = jmax (1, newHeight);
  39458. viewport->setSingleStepSizes (20, rowHeight);
  39459. updateContent();
  39460. }
  39461. int ListBox::getNumRowsOnScreen() const throw()
  39462. {
  39463. return viewport->getMaximumVisibleHeight() / rowHeight;
  39464. }
  39465. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39466. {
  39467. minimumRowWidth = newMinimumWidth;
  39468. updateContent();
  39469. }
  39470. int ListBox::getVisibleContentWidth() const throw()
  39471. {
  39472. return viewport->getMaximumVisibleWidth();
  39473. }
  39474. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39475. {
  39476. return viewport->getVerticalScrollBar();
  39477. }
  39478. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39479. {
  39480. return viewport->getHorizontalScrollBar();
  39481. }
  39482. void ListBox::colourChanged()
  39483. {
  39484. setOpaque (findColour (backgroundColourId).isOpaque());
  39485. viewport->setOpaque (isOpaque());
  39486. repaint();
  39487. }
  39488. void ListBox::setOutlineThickness (const int outlineThickness_)
  39489. {
  39490. outlineThickness = outlineThickness_;
  39491. resized();
  39492. }
  39493. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39494. {
  39495. if (headerComponent != newHeaderComponent)
  39496. {
  39497. headerComponent = newHeaderComponent;
  39498. addAndMakeVisible (newHeaderComponent);
  39499. ListBox::resized();
  39500. }
  39501. }
  39502. void ListBox::repaintRow (const int rowNumber) throw()
  39503. {
  39504. repaint (getRowPosition (rowNumber, true));
  39505. }
  39506. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39507. {
  39508. Rectangle<int> imageArea;
  39509. const int firstRow = getRowContainingPosition (0, 0);
  39510. int i;
  39511. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39512. {
  39513. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39514. if (rowComp != 0 && isRowSelected (firstRow + i))
  39515. {
  39516. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39517. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39518. imageArea = imageArea.getUnion (rowRect);
  39519. }
  39520. }
  39521. imageArea = imageArea.getIntersection (getLocalBounds());
  39522. imageX = imageArea.getX();
  39523. imageY = imageArea.getY();
  39524. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39525. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39526. {
  39527. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39528. if (rowComp != 0 && isRowSelected (firstRow + i))
  39529. {
  39530. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39531. Graphics g (snapshot);
  39532. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39533. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39534. {
  39535. g.beginTransparencyLayer (0.6f);
  39536. rowComp->paintEntireComponent (g, false);
  39537. g.endTransparencyLayer();
  39538. }
  39539. }
  39540. }
  39541. return snapshot;
  39542. }
  39543. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39544. {
  39545. DragAndDropContainer* const dragContainer
  39546. = DragAndDropContainer::findParentDragContainerFor (this);
  39547. if (dragContainer != 0)
  39548. {
  39549. int x, y;
  39550. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39551. MouseEvent e2 (e.getEventRelativeTo (this));
  39552. const Point<int> p (x - e2.x, y - e2.y);
  39553. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39554. }
  39555. else
  39556. {
  39557. // to be able to do a drag-and-drop operation, the listbox needs to
  39558. // be inside a component which is also a DragAndDropContainer.
  39559. jassertfalse;
  39560. }
  39561. }
  39562. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39563. {
  39564. (void) existingComponentToUpdate;
  39565. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39566. return 0;
  39567. }
  39568. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39569. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39570. void ListBoxModel::backgroundClicked() {}
  39571. void ListBoxModel::selectedRowsChanged (int) {}
  39572. void ListBoxModel::deleteKeyPressed (int) {}
  39573. void ListBoxModel::returnKeyPressed (int) {}
  39574. void ListBoxModel::listWasScrolled() {}
  39575. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39576. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39577. END_JUCE_NAMESPACE
  39578. /*** End of inlined file: juce_ListBox.cpp ***/
  39579. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39580. BEGIN_JUCE_NAMESPACE
  39581. ProgressBar::ProgressBar (double& progress_)
  39582. : progress (progress_),
  39583. displayPercentage (true),
  39584. lastCallbackTime (0)
  39585. {
  39586. currentValue = jlimit (0.0, 1.0, progress);
  39587. }
  39588. ProgressBar::~ProgressBar()
  39589. {
  39590. }
  39591. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39592. {
  39593. displayPercentage = shouldDisplayPercentage;
  39594. repaint();
  39595. }
  39596. void ProgressBar::setTextToDisplay (const String& text)
  39597. {
  39598. displayPercentage = false;
  39599. displayedMessage = text;
  39600. }
  39601. void ProgressBar::lookAndFeelChanged()
  39602. {
  39603. setOpaque (findColour (backgroundColourId).isOpaque());
  39604. }
  39605. void ProgressBar::colourChanged()
  39606. {
  39607. lookAndFeelChanged();
  39608. }
  39609. void ProgressBar::paint (Graphics& g)
  39610. {
  39611. String text;
  39612. if (displayPercentage)
  39613. {
  39614. if (currentValue >= 0 && currentValue <= 1.0)
  39615. text << roundToInt (currentValue * 100.0) << '%';
  39616. }
  39617. else
  39618. {
  39619. text = displayedMessage;
  39620. }
  39621. getLookAndFeel().drawProgressBar (g, *this,
  39622. getWidth(), getHeight(),
  39623. currentValue, text);
  39624. }
  39625. void ProgressBar::visibilityChanged()
  39626. {
  39627. if (isVisible())
  39628. startTimer (30);
  39629. else
  39630. stopTimer();
  39631. }
  39632. void ProgressBar::timerCallback()
  39633. {
  39634. double newProgress = progress;
  39635. const uint32 now = Time::getMillisecondCounter();
  39636. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39637. lastCallbackTime = now;
  39638. if (currentValue != newProgress
  39639. || newProgress < 0 || newProgress >= 1.0
  39640. || currentMessage != displayedMessage)
  39641. {
  39642. if (currentValue < newProgress
  39643. && newProgress >= 0 && newProgress < 1.0
  39644. && currentValue >= 0 && currentValue < 1.0)
  39645. {
  39646. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39647. newProgress);
  39648. }
  39649. currentValue = newProgress;
  39650. currentMessage = displayedMessage;
  39651. repaint();
  39652. }
  39653. }
  39654. END_JUCE_NAMESPACE
  39655. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39656. /*** Start of inlined file: juce_Slider.cpp ***/
  39657. BEGIN_JUCE_NAMESPACE
  39658. class SliderPopupDisplayComponent : public BubbleComponent
  39659. {
  39660. public:
  39661. SliderPopupDisplayComponent (Slider* const owner_)
  39662. : owner (owner_),
  39663. font (15.0f, Font::bold)
  39664. {
  39665. setAlwaysOnTop (true);
  39666. }
  39667. void paintContent (Graphics& g, int w, int h)
  39668. {
  39669. g.setFont (font);
  39670. g.setColour (Colours::black);
  39671. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39672. }
  39673. void getContentSize (int& w, int& h)
  39674. {
  39675. w = font.getStringWidth (text) + 18;
  39676. h = (int) (font.getHeight() * 1.6f);
  39677. }
  39678. void updatePosition (const String& newText)
  39679. {
  39680. if (text != newText)
  39681. {
  39682. text = newText;
  39683. repaint();
  39684. }
  39685. BubbleComponent::setPosition (owner);
  39686. }
  39687. private:
  39688. Slider* owner;
  39689. Font font;
  39690. String text;
  39691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39692. };
  39693. Slider::Slider (const String& name)
  39694. : Component (name),
  39695. lastCurrentValue (0),
  39696. lastValueMin (0),
  39697. lastValueMax (0),
  39698. minimum (0),
  39699. maximum (10),
  39700. interval (0),
  39701. skewFactor (1.0),
  39702. velocityModeSensitivity (1.0),
  39703. velocityModeOffset (0.0),
  39704. velocityModeThreshold (1),
  39705. rotaryStart (float_Pi * 1.2f),
  39706. rotaryEnd (float_Pi * 2.8f),
  39707. numDecimalPlaces (7),
  39708. sliderRegionStart (0),
  39709. sliderRegionSize (1),
  39710. sliderBeingDragged (-1),
  39711. pixelsForFullDragExtent (250),
  39712. style (LinearHorizontal),
  39713. textBoxPos (TextBoxLeft),
  39714. textBoxWidth (80),
  39715. textBoxHeight (20),
  39716. incDecButtonMode (incDecButtonsNotDraggable),
  39717. editableText (true),
  39718. doubleClickToValue (false),
  39719. isVelocityBased (false),
  39720. userKeyOverridesVelocity (true),
  39721. rotaryStop (true),
  39722. incDecButtonsSideBySide (false),
  39723. sendChangeOnlyOnRelease (false),
  39724. popupDisplayEnabled (false),
  39725. menuEnabled (false),
  39726. menuShown (false),
  39727. scrollWheelEnabled (true),
  39728. snapsToMousePos (true),
  39729. popupDisplay (0),
  39730. parentForPopupDisplay (0)
  39731. {
  39732. setWantsKeyboardFocus (false);
  39733. setRepaintsOnMouseActivity (true);
  39734. lookAndFeelChanged();
  39735. updateText();
  39736. currentValue.addListener (this);
  39737. valueMin.addListener (this);
  39738. valueMax.addListener (this);
  39739. }
  39740. Slider::~Slider()
  39741. {
  39742. currentValue.removeListener (this);
  39743. valueMin.removeListener (this);
  39744. valueMax.removeListener (this);
  39745. popupDisplay = 0;
  39746. }
  39747. void Slider::handleAsyncUpdate()
  39748. {
  39749. cancelPendingUpdate();
  39750. Component::BailOutChecker checker (this);
  39751. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39752. }
  39753. void Slider::sendDragStart()
  39754. {
  39755. startedDragging();
  39756. Component::BailOutChecker checker (this);
  39757. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39758. }
  39759. void Slider::sendDragEnd()
  39760. {
  39761. stoppedDragging();
  39762. sliderBeingDragged = -1;
  39763. Component::BailOutChecker checker (this);
  39764. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39765. }
  39766. void Slider::addListener (SliderListener* const listener)
  39767. {
  39768. listeners.add (listener);
  39769. }
  39770. void Slider::removeListener (SliderListener* const listener)
  39771. {
  39772. listeners.remove (listener);
  39773. }
  39774. void Slider::setSliderStyle (const SliderStyle newStyle)
  39775. {
  39776. if (style != newStyle)
  39777. {
  39778. style = newStyle;
  39779. repaint();
  39780. lookAndFeelChanged();
  39781. }
  39782. }
  39783. void Slider::setRotaryParameters (const float startAngleRadians,
  39784. const float endAngleRadians,
  39785. const bool stopAtEnd)
  39786. {
  39787. // make sure the values are sensible..
  39788. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39789. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39790. jassert (rotaryStart < rotaryEnd);
  39791. rotaryStart = startAngleRadians;
  39792. rotaryEnd = endAngleRadians;
  39793. rotaryStop = stopAtEnd;
  39794. }
  39795. void Slider::setVelocityBasedMode (const bool velBased)
  39796. {
  39797. isVelocityBased = velBased;
  39798. }
  39799. void Slider::setVelocityModeParameters (const double sensitivity,
  39800. const int threshold,
  39801. const double offset,
  39802. const bool userCanPressKeyToSwapMode)
  39803. {
  39804. jassert (threshold >= 0);
  39805. jassert (sensitivity > 0);
  39806. jassert (offset >= 0);
  39807. velocityModeSensitivity = sensitivity;
  39808. velocityModeOffset = offset;
  39809. velocityModeThreshold = threshold;
  39810. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39811. }
  39812. void Slider::setSkewFactor (const double factor)
  39813. {
  39814. skewFactor = factor;
  39815. }
  39816. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39817. {
  39818. if (maximum > minimum)
  39819. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39820. / (maximum - minimum));
  39821. }
  39822. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39823. {
  39824. jassert (distanceForFullScaleDrag > 0);
  39825. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39826. }
  39827. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39828. {
  39829. if (incDecButtonMode != mode)
  39830. {
  39831. incDecButtonMode = mode;
  39832. lookAndFeelChanged();
  39833. }
  39834. }
  39835. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39836. const bool isReadOnly,
  39837. const int textEntryBoxWidth,
  39838. const int textEntryBoxHeight)
  39839. {
  39840. if (textBoxPos != newPosition
  39841. || editableText != (! isReadOnly)
  39842. || textBoxWidth != textEntryBoxWidth
  39843. || textBoxHeight != textEntryBoxHeight)
  39844. {
  39845. textBoxPos = newPosition;
  39846. editableText = ! isReadOnly;
  39847. textBoxWidth = textEntryBoxWidth;
  39848. textBoxHeight = textEntryBoxHeight;
  39849. repaint();
  39850. lookAndFeelChanged();
  39851. }
  39852. }
  39853. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39854. {
  39855. editableText = shouldBeEditable;
  39856. if (valueBox != 0)
  39857. valueBox->setEditable (shouldBeEditable && isEnabled());
  39858. }
  39859. void Slider::showTextBox()
  39860. {
  39861. jassert (editableText); // this should probably be avoided in read-only sliders.
  39862. if (valueBox != 0)
  39863. valueBox->showEditor();
  39864. }
  39865. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39866. {
  39867. if (valueBox != 0)
  39868. {
  39869. valueBox->hideEditor (discardCurrentEditorContents);
  39870. if (discardCurrentEditorContents)
  39871. updateText();
  39872. }
  39873. }
  39874. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39875. {
  39876. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39877. }
  39878. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39879. {
  39880. snapsToMousePos = shouldSnapToMouse;
  39881. }
  39882. void Slider::setPopupDisplayEnabled (const bool enabled,
  39883. Component* const parentComponentToUse)
  39884. {
  39885. popupDisplayEnabled = enabled;
  39886. parentForPopupDisplay = parentComponentToUse;
  39887. }
  39888. void Slider::colourChanged()
  39889. {
  39890. lookAndFeelChanged();
  39891. }
  39892. void Slider::lookAndFeelChanged()
  39893. {
  39894. LookAndFeel& lf = getLookAndFeel();
  39895. if (textBoxPos != NoTextBox)
  39896. {
  39897. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39898. : getTextFromValue (currentValue.getValue()));
  39899. valueBox = 0;
  39900. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39901. valueBox->setWantsKeyboardFocus (false);
  39902. valueBox->setText (previousTextBoxContent, false);
  39903. valueBox->setEditable (editableText && isEnabled());
  39904. valueBox->addListener (this);
  39905. if (style == LinearBar)
  39906. valueBox->addMouseListener (this, false);
  39907. valueBox->setTooltip (getTooltip());
  39908. }
  39909. else
  39910. {
  39911. valueBox = 0;
  39912. }
  39913. if (style == IncDecButtons)
  39914. {
  39915. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39916. incButton->addListener (this);
  39917. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39918. decButton->addListener (this);
  39919. if (incDecButtonMode != incDecButtonsNotDraggable)
  39920. {
  39921. incButton->addMouseListener (this, false);
  39922. decButton->addMouseListener (this, false);
  39923. }
  39924. else
  39925. {
  39926. incButton->setRepeatSpeed (300, 100, 20);
  39927. incButton->addMouseListener (decButton, false);
  39928. decButton->setRepeatSpeed (300, 100, 20);
  39929. decButton->addMouseListener (incButton, false);
  39930. }
  39931. incButton->setTooltip (getTooltip());
  39932. decButton->setTooltip (getTooltip());
  39933. }
  39934. else
  39935. {
  39936. incButton = 0;
  39937. decButton = 0;
  39938. }
  39939. setComponentEffect (lf.getSliderEffect());
  39940. resized();
  39941. repaint();
  39942. }
  39943. void Slider::setRange (const double newMin,
  39944. const double newMax,
  39945. const double newInt)
  39946. {
  39947. if (minimum != newMin
  39948. || maximum != newMax
  39949. || interval != newInt)
  39950. {
  39951. minimum = newMin;
  39952. maximum = newMax;
  39953. interval = newInt;
  39954. // figure out the number of DPs needed to display all values at this
  39955. // interval setting.
  39956. numDecimalPlaces = 7;
  39957. if (newInt != 0)
  39958. {
  39959. int v = abs ((int) (newInt * 10000000));
  39960. while ((v % 10) == 0)
  39961. {
  39962. --numDecimalPlaces;
  39963. v /= 10;
  39964. }
  39965. }
  39966. // keep the current values inside the new range..
  39967. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39968. {
  39969. setValue (getValue(), false, false);
  39970. }
  39971. else
  39972. {
  39973. setMinValue (getMinValue(), false, false);
  39974. setMaxValue (getMaxValue(), false, false);
  39975. }
  39976. updateText();
  39977. }
  39978. }
  39979. void Slider::triggerChangeMessage (const bool synchronous)
  39980. {
  39981. if (synchronous)
  39982. handleAsyncUpdate();
  39983. else
  39984. triggerAsyncUpdate();
  39985. valueChanged();
  39986. }
  39987. void Slider::valueChanged (Value& value)
  39988. {
  39989. if (value.refersToSameSourceAs (currentValue))
  39990. {
  39991. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39992. setValue (currentValue.getValue(), false, false);
  39993. }
  39994. else if (value.refersToSameSourceAs (valueMin))
  39995. setMinValue (valueMin.getValue(), false, false, true);
  39996. else if (value.refersToSameSourceAs (valueMax))
  39997. setMaxValue (valueMax.getValue(), false, false, true);
  39998. }
  39999. double Slider::getValue() const
  40000. {
  40001. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40002. // methods to get the two values.
  40003. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40004. return currentValue.getValue();
  40005. }
  40006. void Slider::setValue (double newValue,
  40007. const bool sendUpdateMessage,
  40008. const bool sendMessageSynchronously)
  40009. {
  40010. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40011. // methods to set the two values.
  40012. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40013. newValue = constrainedValue (newValue);
  40014. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40015. {
  40016. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40017. newValue = jlimit ((double) valueMin.getValue(),
  40018. (double) valueMax.getValue(),
  40019. newValue);
  40020. }
  40021. if (newValue != lastCurrentValue)
  40022. {
  40023. if (valueBox != 0)
  40024. valueBox->hideEditor (true);
  40025. lastCurrentValue = newValue;
  40026. currentValue = newValue;
  40027. updateText();
  40028. repaint();
  40029. if (popupDisplay != 0)
  40030. {
  40031. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40032. ->updatePosition (getTextFromValue (newValue));
  40033. popupDisplay->repaint();
  40034. }
  40035. if (sendUpdateMessage)
  40036. triggerChangeMessage (sendMessageSynchronously);
  40037. }
  40038. }
  40039. double Slider::getMinValue() const
  40040. {
  40041. // The minimum value only applies to sliders that are in two- or three-value mode.
  40042. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40043. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40044. return valueMin.getValue();
  40045. }
  40046. double Slider::getMaxValue() const
  40047. {
  40048. // The maximum value only applies to sliders that are in two- or three-value mode.
  40049. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40050. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40051. return valueMax.getValue();
  40052. }
  40053. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40054. {
  40055. // The minimum value only applies to sliders that are in two- or three-value mode.
  40056. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40057. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40058. newValue = constrainedValue (newValue);
  40059. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40060. {
  40061. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40062. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40063. newValue = jmin ((double) valueMax.getValue(), newValue);
  40064. }
  40065. else
  40066. {
  40067. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40068. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40069. newValue = jmin (lastCurrentValue, newValue);
  40070. }
  40071. if (lastValueMin != newValue)
  40072. {
  40073. lastValueMin = newValue;
  40074. valueMin = newValue;
  40075. repaint();
  40076. if (popupDisplay != 0)
  40077. {
  40078. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40079. ->updatePosition (getTextFromValue (newValue));
  40080. popupDisplay->repaint();
  40081. }
  40082. if (sendUpdateMessage)
  40083. triggerChangeMessage (sendMessageSynchronously);
  40084. }
  40085. }
  40086. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40087. {
  40088. // The maximum value only applies to sliders that are in two- or three-value mode.
  40089. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40090. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40091. newValue = constrainedValue (newValue);
  40092. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40093. {
  40094. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40095. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40096. newValue = jmax ((double) valueMin.getValue(), newValue);
  40097. }
  40098. else
  40099. {
  40100. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40101. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40102. newValue = jmax (lastCurrentValue, newValue);
  40103. }
  40104. if (lastValueMax != newValue)
  40105. {
  40106. lastValueMax = newValue;
  40107. valueMax = newValue;
  40108. repaint();
  40109. if (popupDisplay != 0)
  40110. {
  40111. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40112. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40113. popupDisplay->repaint();
  40114. }
  40115. if (sendUpdateMessage)
  40116. triggerChangeMessage (sendMessageSynchronously);
  40117. }
  40118. }
  40119. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, bool sendUpdateMessage, bool sendMessageSynchronously)
  40120. {
  40121. // The maximum value only applies to sliders that are in two- or three-value mode.
  40122. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40123. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40124. if (newMaxValue < newMinValue)
  40125. swapVariables (newMaxValue, newMinValue);
  40126. newMinValue = constrainedValue (newMinValue);
  40127. newMaxValue = constrainedValue (newMaxValue);
  40128. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  40129. {
  40130. lastValueMax = newMaxValue;
  40131. lastValueMin = newMinValue;
  40132. valueMin = newMinValue;
  40133. valueMax = newMaxValue;
  40134. repaint();
  40135. if (sendUpdateMessage)
  40136. triggerChangeMessage (sendMessageSynchronously);
  40137. }
  40138. }
  40139. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40140. const double valueToSetOnDoubleClick)
  40141. {
  40142. doubleClickToValue = isDoubleClickEnabled;
  40143. doubleClickReturnValue = valueToSetOnDoubleClick;
  40144. }
  40145. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40146. {
  40147. isEnabled_ = doubleClickToValue;
  40148. return doubleClickReturnValue;
  40149. }
  40150. void Slider::updateText()
  40151. {
  40152. if (valueBox != 0)
  40153. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40154. }
  40155. void Slider::setTextValueSuffix (const String& suffix)
  40156. {
  40157. if (textSuffix != suffix)
  40158. {
  40159. textSuffix = suffix;
  40160. updateText();
  40161. }
  40162. }
  40163. const String Slider::getTextValueSuffix() const
  40164. {
  40165. return textSuffix;
  40166. }
  40167. const String Slider::getTextFromValue (double v)
  40168. {
  40169. if (getNumDecimalPlacesToDisplay() > 0)
  40170. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40171. else
  40172. return String (roundToInt (v)) + getTextValueSuffix();
  40173. }
  40174. double Slider::getValueFromText (const String& text)
  40175. {
  40176. String t (text.trimStart());
  40177. if (t.endsWith (textSuffix))
  40178. t = t.substring (0, t.length() - textSuffix.length());
  40179. while (t.startsWithChar ('+'))
  40180. t = t.substring (1).trimStart();
  40181. return t.initialSectionContainingOnly ("0123456789.,-")
  40182. .getDoubleValue();
  40183. }
  40184. double Slider::proportionOfLengthToValue (double proportion)
  40185. {
  40186. if (skewFactor != 1.0 && proportion > 0.0)
  40187. proportion = exp (log (proportion) / skewFactor);
  40188. return minimum + (maximum - minimum) * proportion;
  40189. }
  40190. double Slider::valueToProportionOfLength (double value)
  40191. {
  40192. const double n = (value - minimum) / (maximum - minimum);
  40193. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40194. }
  40195. double Slider::snapValue (double attemptedValue, const bool)
  40196. {
  40197. return attemptedValue;
  40198. }
  40199. void Slider::startedDragging()
  40200. {
  40201. }
  40202. void Slider::stoppedDragging()
  40203. {
  40204. }
  40205. void Slider::valueChanged()
  40206. {
  40207. }
  40208. void Slider::enablementChanged()
  40209. {
  40210. repaint();
  40211. }
  40212. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40213. {
  40214. menuEnabled = menuEnabled_;
  40215. }
  40216. void Slider::setScrollWheelEnabled (const bool enabled)
  40217. {
  40218. scrollWheelEnabled = enabled;
  40219. }
  40220. void Slider::labelTextChanged (Label* label)
  40221. {
  40222. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40223. if (newValue != (double) currentValue.getValue())
  40224. {
  40225. sendDragStart();
  40226. setValue (newValue, true, true);
  40227. sendDragEnd();
  40228. }
  40229. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40230. }
  40231. void Slider::buttonClicked (Button* button)
  40232. {
  40233. if (style == IncDecButtons)
  40234. {
  40235. sendDragStart();
  40236. if (button == incButton)
  40237. setValue (snapValue (getValue() + interval, false), true, true);
  40238. else if (button == decButton)
  40239. setValue (snapValue (getValue() - interval, false), true, true);
  40240. sendDragEnd();
  40241. }
  40242. }
  40243. double Slider::constrainedValue (double value) const
  40244. {
  40245. if (interval > 0)
  40246. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40247. if (value <= minimum || maximum <= minimum)
  40248. value = minimum;
  40249. else if (value >= maximum)
  40250. value = maximum;
  40251. return value;
  40252. }
  40253. float Slider::getLinearSliderPos (const double value)
  40254. {
  40255. double sliderPosProportional;
  40256. if (maximum > minimum)
  40257. {
  40258. if (value < minimum)
  40259. {
  40260. sliderPosProportional = 0.0;
  40261. }
  40262. else if (value > maximum)
  40263. {
  40264. sliderPosProportional = 1.0;
  40265. }
  40266. else
  40267. {
  40268. sliderPosProportional = valueToProportionOfLength (value);
  40269. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40270. }
  40271. }
  40272. else
  40273. {
  40274. sliderPosProportional = 0.5;
  40275. }
  40276. if (isVertical() || style == IncDecButtons)
  40277. sliderPosProportional = 1.0 - sliderPosProportional;
  40278. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40279. }
  40280. bool Slider::isHorizontal() const
  40281. {
  40282. return style == LinearHorizontal
  40283. || style == LinearBar
  40284. || style == TwoValueHorizontal
  40285. || style == ThreeValueHorizontal;
  40286. }
  40287. bool Slider::isVertical() const
  40288. {
  40289. return style == LinearVertical
  40290. || style == TwoValueVertical
  40291. || style == ThreeValueVertical;
  40292. }
  40293. bool Slider::incDecDragDirectionIsHorizontal() const
  40294. {
  40295. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40296. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40297. }
  40298. float Slider::getPositionOfValue (const double value)
  40299. {
  40300. if (isHorizontal() || isVertical())
  40301. {
  40302. return getLinearSliderPos (value);
  40303. }
  40304. else
  40305. {
  40306. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40307. return 0.0f;
  40308. }
  40309. }
  40310. void Slider::paint (Graphics& g)
  40311. {
  40312. if (style != IncDecButtons)
  40313. {
  40314. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40315. {
  40316. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40317. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40318. getLookAndFeel().drawRotarySlider (g,
  40319. sliderRect.getX(),
  40320. sliderRect.getY(),
  40321. sliderRect.getWidth(),
  40322. sliderRect.getHeight(),
  40323. sliderPos,
  40324. rotaryStart, rotaryEnd,
  40325. *this);
  40326. }
  40327. else
  40328. {
  40329. getLookAndFeel().drawLinearSlider (g,
  40330. sliderRect.getX(),
  40331. sliderRect.getY(),
  40332. sliderRect.getWidth(),
  40333. sliderRect.getHeight(),
  40334. getLinearSliderPos (lastCurrentValue),
  40335. getLinearSliderPos (lastValueMin),
  40336. getLinearSliderPos (lastValueMax),
  40337. style,
  40338. *this);
  40339. }
  40340. if (style == LinearBar && valueBox == 0)
  40341. {
  40342. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40343. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40344. }
  40345. }
  40346. }
  40347. void Slider::resized()
  40348. {
  40349. int minXSpace = 0;
  40350. int minYSpace = 0;
  40351. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40352. minXSpace = 30;
  40353. else
  40354. minYSpace = 15;
  40355. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40356. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40357. if (style == LinearBar)
  40358. {
  40359. if (valueBox != 0)
  40360. valueBox->setBounds (getLocalBounds());
  40361. }
  40362. else
  40363. {
  40364. if (textBoxPos == NoTextBox)
  40365. {
  40366. sliderRect = getLocalBounds();
  40367. }
  40368. else if (textBoxPos == TextBoxLeft)
  40369. {
  40370. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40371. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40372. }
  40373. else if (textBoxPos == TextBoxRight)
  40374. {
  40375. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40376. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40377. }
  40378. else if (textBoxPos == TextBoxAbove)
  40379. {
  40380. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40381. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40382. }
  40383. else if (textBoxPos == TextBoxBelow)
  40384. {
  40385. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40386. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40387. }
  40388. }
  40389. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40390. if (style == LinearBar)
  40391. {
  40392. const int barIndent = 1;
  40393. sliderRegionStart = barIndent;
  40394. sliderRegionSize = getWidth() - barIndent * 2;
  40395. sliderRect.setBounds (sliderRegionStart, barIndent,
  40396. sliderRegionSize, getHeight() - barIndent * 2);
  40397. }
  40398. else if (isHorizontal())
  40399. {
  40400. sliderRegionStart = sliderRect.getX() + indent;
  40401. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40402. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40403. sliderRegionSize, sliderRect.getHeight());
  40404. }
  40405. else if (isVertical())
  40406. {
  40407. sliderRegionStart = sliderRect.getY() + indent;
  40408. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40409. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40410. sliderRect.getWidth(), sliderRegionSize);
  40411. }
  40412. else
  40413. {
  40414. sliderRegionStart = 0;
  40415. sliderRegionSize = 100;
  40416. }
  40417. if (style == IncDecButtons)
  40418. {
  40419. Rectangle<int> buttonRect (sliderRect);
  40420. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40421. buttonRect.expand (-2, 0);
  40422. else
  40423. buttonRect.expand (0, -2);
  40424. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40425. if (incDecButtonsSideBySide)
  40426. {
  40427. decButton->setBounds (buttonRect.getX(),
  40428. buttonRect.getY(),
  40429. buttonRect.getWidth() / 2,
  40430. buttonRect.getHeight());
  40431. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40432. incButton->setBounds (buttonRect.getCentreX(),
  40433. buttonRect.getY(),
  40434. buttonRect.getWidth() / 2,
  40435. buttonRect.getHeight());
  40436. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40437. }
  40438. else
  40439. {
  40440. incButton->setBounds (buttonRect.getX(),
  40441. buttonRect.getY(),
  40442. buttonRect.getWidth(),
  40443. buttonRect.getHeight() / 2);
  40444. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40445. decButton->setBounds (buttonRect.getX(),
  40446. buttonRect.getCentreY(),
  40447. buttonRect.getWidth(),
  40448. buttonRect.getHeight() / 2);
  40449. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40450. }
  40451. }
  40452. }
  40453. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40454. {
  40455. repaint();
  40456. }
  40457. static void sliderMenuCallback (int result, Slider* slider)
  40458. {
  40459. if (slider != 0)
  40460. {
  40461. switch (result)
  40462. {
  40463. case 1: slider->setVelocityBasedMode (! slider->getVelocityBasedMode()); break;
  40464. case 2: slider->setSliderStyle (Slider::Rotary); break;
  40465. case 3: slider->setSliderStyle (Slider::RotaryHorizontalDrag); break;
  40466. case 4: slider->setSliderStyle (Slider::RotaryVerticalDrag); break;
  40467. default: break;
  40468. }
  40469. }
  40470. }
  40471. void Slider::mouseDown (const MouseEvent& e)
  40472. {
  40473. mouseWasHidden = false;
  40474. incDecDragged = false;
  40475. mouseXWhenLastDragged = e.x;
  40476. mouseYWhenLastDragged = e.y;
  40477. mouseDragStartX = e.getMouseDownX();
  40478. mouseDragStartY = e.getMouseDownY();
  40479. if (isEnabled())
  40480. {
  40481. if (e.mods.isPopupMenu() && menuEnabled)
  40482. {
  40483. menuShown = true;
  40484. PopupMenu m;
  40485. m.setLookAndFeel (&getLookAndFeel());
  40486. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40487. m.addSeparator();
  40488. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40489. {
  40490. PopupMenu rotaryMenu;
  40491. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40492. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40493. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40494. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40495. }
  40496. m.showMenuAsync (PopupMenu::Options(),
  40497. ModalCallbackFunction::forComponent (sliderMenuCallback, this));
  40498. }
  40499. else if (maximum > minimum)
  40500. {
  40501. menuShown = false;
  40502. if (valueBox != 0)
  40503. valueBox->hideEditor (true);
  40504. sliderBeingDragged = 0;
  40505. if (style == TwoValueHorizontal
  40506. || style == TwoValueVertical
  40507. || style == ThreeValueHorizontal
  40508. || style == ThreeValueVertical)
  40509. {
  40510. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40511. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40512. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40513. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40514. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40515. {
  40516. if (maxPosDistance <= minPosDistance)
  40517. sliderBeingDragged = 2;
  40518. else
  40519. sliderBeingDragged = 1;
  40520. }
  40521. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40522. {
  40523. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40524. sliderBeingDragged = 1;
  40525. else if (normalPosDistance >= maxPosDistance)
  40526. sliderBeingDragged = 2;
  40527. }
  40528. }
  40529. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40530. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40531. * valueToProportionOfLength (currentValue.getValue());
  40532. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40533. : ((sliderBeingDragged == 1) ? valueMin
  40534. : currentValue)).getValue();
  40535. valueOnMouseDown = valueWhenLastDragged;
  40536. if (popupDisplayEnabled)
  40537. {
  40538. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40539. popupDisplay = popup;
  40540. if (parentForPopupDisplay != 0)
  40541. {
  40542. parentForPopupDisplay->addChildComponent (popup);
  40543. }
  40544. else
  40545. {
  40546. popup->addToDesktop (0);
  40547. }
  40548. popup->setVisible (true);
  40549. }
  40550. sendDragStart();
  40551. mouseDrag (e);
  40552. }
  40553. }
  40554. }
  40555. void Slider::mouseUp (const MouseEvent&)
  40556. {
  40557. if (isEnabled()
  40558. && (! menuShown)
  40559. && (maximum > minimum)
  40560. && (style != IncDecButtons || incDecDragged))
  40561. {
  40562. restoreMouseIfHidden();
  40563. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40564. triggerChangeMessage (false);
  40565. sendDragEnd();
  40566. popupDisplay = 0;
  40567. if (style == IncDecButtons)
  40568. {
  40569. incButton->setState (Button::buttonNormal);
  40570. decButton->setState (Button::buttonNormal);
  40571. }
  40572. }
  40573. }
  40574. void Slider::restoreMouseIfHidden()
  40575. {
  40576. if (mouseWasHidden)
  40577. {
  40578. mouseWasHidden = false;
  40579. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40580. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40581. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40582. : ((sliderBeingDragged == 1) ? getMinValue()
  40583. : (double) currentValue.getValue());
  40584. Point<int> mousePos;
  40585. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40586. {
  40587. mousePos = Desktop::getLastMouseDownPosition();
  40588. if (style == RotaryHorizontalDrag)
  40589. {
  40590. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40591. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40592. }
  40593. else
  40594. {
  40595. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40596. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40597. }
  40598. }
  40599. else
  40600. {
  40601. const int pixelPos = (int) getLinearSliderPos (pos);
  40602. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40603. isVertical() ? pixelPos : (getHeight() / 2)));
  40604. }
  40605. Desktop::setMousePosition (mousePos);
  40606. }
  40607. }
  40608. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40609. {
  40610. if (isEnabled()
  40611. && style != IncDecButtons
  40612. && style != Rotary
  40613. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40614. {
  40615. restoreMouseIfHidden();
  40616. }
  40617. }
  40618. namespace SliderHelpers
  40619. {
  40620. double smallestAngleBetween (double a1, double a2) throw()
  40621. {
  40622. return jmin (std::abs (a1 - a2),
  40623. std::abs (a1 + double_Pi * 2.0 - a2),
  40624. std::abs (a2 + double_Pi * 2.0 - a1));
  40625. }
  40626. }
  40627. void Slider::mouseDrag (const MouseEvent& e)
  40628. {
  40629. if (isEnabled()
  40630. && (! menuShown)
  40631. && (maximum > minimum))
  40632. {
  40633. if (style == Rotary)
  40634. {
  40635. int dx = e.x - sliderRect.getCentreX();
  40636. int dy = e.y - sliderRect.getCentreY();
  40637. if (dx * dx + dy * dy > 25)
  40638. {
  40639. double angle = std::atan2 ((double) dx, (double) -dy);
  40640. while (angle < 0.0)
  40641. angle += double_Pi * 2.0;
  40642. if (rotaryStop && ! e.mouseWasClicked())
  40643. {
  40644. if (std::abs (angle - lastAngle) > double_Pi)
  40645. {
  40646. if (angle >= lastAngle)
  40647. angle -= double_Pi * 2.0;
  40648. else
  40649. angle += double_Pi * 2.0;
  40650. }
  40651. if (angle >= lastAngle)
  40652. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40653. else
  40654. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40655. }
  40656. else
  40657. {
  40658. while (angle < rotaryStart)
  40659. angle += double_Pi * 2.0;
  40660. if (angle > rotaryEnd)
  40661. {
  40662. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40663. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40664. angle = rotaryStart;
  40665. else
  40666. angle = rotaryEnd;
  40667. }
  40668. }
  40669. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40670. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40671. lastAngle = angle;
  40672. }
  40673. }
  40674. else
  40675. {
  40676. if (style == LinearBar && e.mouseWasClicked()
  40677. && valueBox != 0 && valueBox->isEditable())
  40678. return;
  40679. if (style == IncDecButtons && ! incDecDragged)
  40680. {
  40681. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40682. return;
  40683. incDecDragged = true;
  40684. mouseDragStartX = e.x;
  40685. mouseDragStartY = e.y;
  40686. }
  40687. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40688. : false))
  40689. || ((maximum - minimum) / sliderRegionSize < interval))
  40690. {
  40691. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40692. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40693. if (style == RotaryHorizontalDrag
  40694. || style == RotaryVerticalDrag
  40695. || style == IncDecButtons
  40696. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40697. && ! snapsToMousePos))
  40698. {
  40699. const int mouseDiff = (style == RotaryHorizontalDrag
  40700. || style == LinearHorizontal
  40701. || style == LinearBar
  40702. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40703. ? e.x - mouseDragStartX
  40704. : mouseDragStartY - e.y;
  40705. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40706. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40707. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40708. if (style == IncDecButtons)
  40709. {
  40710. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40711. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40712. }
  40713. }
  40714. else
  40715. {
  40716. if (isVertical())
  40717. scaledMousePos = 1.0 - scaledMousePos;
  40718. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40719. }
  40720. }
  40721. else
  40722. {
  40723. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40724. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40725. ? e.x - mouseXWhenLastDragged
  40726. : e.y - mouseYWhenLastDragged;
  40727. const double maxSpeed = jmax (200, sliderRegionSize);
  40728. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40729. if (speed != 0)
  40730. {
  40731. speed = 0.2 * velocityModeSensitivity
  40732. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40733. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40734. / maxSpeed))));
  40735. if (mouseDiff < 0)
  40736. speed = -speed;
  40737. if (isVertical() || style == RotaryVerticalDrag
  40738. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40739. speed = -speed;
  40740. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40741. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40742. e.source.enableUnboundedMouseMovement (true, false);
  40743. mouseWasHidden = true;
  40744. }
  40745. }
  40746. }
  40747. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40748. if (sliderBeingDragged == 0)
  40749. {
  40750. setValue (snapValue (valueWhenLastDragged, true),
  40751. ! sendChangeOnlyOnRelease, true);
  40752. }
  40753. else if (sliderBeingDragged == 1)
  40754. {
  40755. setMinValue (snapValue (valueWhenLastDragged, true),
  40756. ! sendChangeOnlyOnRelease, false, true);
  40757. if (e.mods.isShiftDown())
  40758. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40759. else
  40760. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40761. }
  40762. else
  40763. {
  40764. jassert (sliderBeingDragged == 2);
  40765. setMaxValue (snapValue (valueWhenLastDragged, true),
  40766. ! sendChangeOnlyOnRelease, false, true);
  40767. if (e.mods.isShiftDown())
  40768. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40769. else
  40770. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40771. }
  40772. mouseXWhenLastDragged = e.x;
  40773. mouseYWhenLastDragged = e.y;
  40774. }
  40775. }
  40776. void Slider::mouseDoubleClick (const MouseEvent&)
  40777. {
  40778. if (doubleClickToValue
  40779. && isEnabled()
  40780. && style != IncDecButtons
  40781. && minimum <= doubleClickReturnValue
  40782. && maximum >= doubleClickReturnValue)
  40783. {
  40784. sendDragStart();
  40785. setValue (doubleClickReturnValue, true, true);
  40786. sendDragEnd();
  40787. }
  40788. }
  40789. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40790. {
  40791. if (scrollWheelEnabled && isEnabled()
  40792. && style != TwoValueHorizontal
  40793. && style != TwoValueVertical)
  40794. {
  40795. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40796. {
  40797. if (valueBox != 0)
  40798. valueBox->hideEditor (false);
  40799. const double value = (double) currentValue.getValue();
  40800. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40801. const double currentPos = valueToProportionOfLength (value);
  40802. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40803. double delta = (newValue != value)
  40804. ? jmax (std::abs (newValue - value), interval) : 0;
  40805. if (value > newValue)
  40806. delta = -delta;
  40807. sendDragStart();
  40808. setValue (snapValue (value + delta, false), true, true);
  40809. sendDragEnd();
  40810. }
  40811. }
  40812. else
  40813. {
  40814. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40815. }
  40816. }
  40817. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40818. {
  40819. }
  40820. void SliderListener::sliderDragEnded (Slider*)
  40821. {
  40822. }
  40823. END_JUCE_NAMESPACE
  40824. /*** End of inlined file: juce_Slider.cpp ***/
  40825. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40826. BEGIN_JUCE_NAMESPACE
  40827. class DragOverlayComp : public Component
  40828. {
  40829. public:
  40830. DragOverlayComp (const Image& image_)
  40831. : image (image_)
  40832. {
  40833. image.duplicateIfShared();
  40834. image.multiplyAllAlphas (0.8f);
  40835. setAlwaysOnTop (true);
  40836. }
  40837. void paint (Graphics& g)
  40838. {
  40839. g.drawImageAt (image, 0, 0);
  40840. }
  40841. private:
  40842. Image image;
  40843. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40844. };
  40845. TableHeaderComponent::TableHeaderComponent()
  40846. : columnsChanged (false),
  40847. columnsResized (false),
  40848. sortChanged (false),
  40849. menuActive (true),
  40850. stretchToFit (false),
  40851. columnIdBeingResized (0),
  40852. columnIdBeingDragged (0),
  40853. columnIdUnderMouse (0),
  40854. lastDeliberateWidth (0)
  40855. {
  40856. }
  40857. TableHeaderComponent::~TableHeaderComponent()
  40858. {
  40859. dragOverlayComp = 0;
  40860. }
  40861. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40862. {
  40863. menuActive = hasMenu;
  40864. }
  40865. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40866. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40867. {
  40868. if (onlyCountVisibleColumns)
  40869. {
  40870. int num = 0;
  40871. for (int i = columns.size(); --i >= 0;)
  40872. if (columns.getUnchecked(i)->isVisible())
  40873. ++num;
  40874. return num;
  40875. }
  40876. else
  40877. {
  40878. return columns.size();
  40879. }
  40880. }
  40881. const String TableHeaderComponent::getColumnName (const int columnId) const
  40882. {
  40883. const ColumnInfo* const ci = getInfoForId (columnId);
  40884. return ci != 0 ? ci->name : String::empty;
  40885. }
  40886. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40887. {
  40888. ColumnInfo* const ci = getInfoForId (columnId);
  40889. if (ci != 0 && ci->name != newName)
  40890. {
  40891. ci->name = newName;
  40892. sendColumnsChanged();
  40893. }
  40894. }
  40895. void TableHeaderComponent::addColumn (const String& columnName,
  40896. const int columnId,
  40897. const int width,
  40898. const int minimumWidth,
  40899. const int maximumWidth,
  40900. const int propertyFlags,
  40901. const int insertIndex)
  40902. {
  40903. // can't have a duplicate or null ID!
  40904. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40905. jassert (width > 0);
  40906. ColumnInfo* const ci = new ColumnInfo();
  40907. ci->name = columnName;
  40908. ci->id = columnId;
  40909. ci->width = width;
  40910. ci->lastDeliberateWidth = width;
  40911. ci->minimumWidth = minimumWidth;
  40912. ci->maximumWidth = maximumWidth;
  40913. if (ci->maximumWidth < 0)
  40914. ci->maximumWidth = std::numeric_limits<int>::max();
  40915. jassert (ci->maximumWidth >= ci->minimumWidth);
  40916. ci->propertyFlags = propertyFlags;
  40917. columns.insert (insertIndex, ci);
  40918. sendColumnsChanged();
  40919. }
  40920. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40921. {
  40922. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40923. if (index >= 0)
  40924. {
  40925. columns.remove (index);
  40926. sortChanged = true;
  40927. sendColumnsChanged();
  40928. }
  40929. }
  40930. void TableHeaderComponent::removeAllColumns()
  40931. {
  40932. if (columns.size() > 0)
  40933. {
  40934. columns.clear();
  40935. sendColumnsChanged();
  40936. }
  40937. }
  40938. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40939. {
  40940. const int currentIndex = getIndexOfColumnId (columnId, false);
  40941. newIndex = visibleIndexToTotalIndex (newIndex);
  40942. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40943. {
  40944. columns.move (currentIndex, newIndex);
  40945. sendColumnsChanged();
  40946. }
  40947. }
  40948. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40949. {
  40950. const ColumnInfo* const ci = getInfoForId (columnId);
  40951. return ci != 0 ? ci->width : 0;
  40952. }
  40953. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40954. {
  40955. ColumnInfo* const ci = getInfoForId (columnId);
  40956. if (ci != 0 && ci->width != newWidth)
  40957. {
  40958. const int numColumns = getNumColumns (true);
  40959. ci->lastDeliberateWidth = ci->width
  40960. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40961. if (stretchToFit)
  40962. {
  40963. const int index = getIndexOfColumnId (columnId, true) + 1;
  40964. if (isPositiveAndBelow (index, numColumns))
  40965. {
  40966. const int x = getColumnPosition (index).getX();
  40967. if (lastDeliberateWidth == 0)
  40968. lastDeliberateWidth = getTotalWidth();
  40969. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40970. }
  40971. }
  40972. repaint();
  40973. columnsResized = true;
  40974. triggerAsyncUpdate();
  40975. }
  40976. }
  40977. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40978. {
  40979. int n = 0;
  40980. for (int i = 0; i < columns.size(); ++i)
  40981. {
  40982. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40983. {
  40984. if (columns.getUnchecked(i)->id == columnId)
  40985. return n;
  40986. ++n;
  40987. }
  40988. }
  40989. return -1;
  40990. }
  40991. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40992. {
  40993. if (onlyCountVisibleColumns)
  40994. index = visibleIndexToTotalIndex (index);
  40995. const ColumnInfo* const ci = columns [index];
  40996. return (ci != 0) ? ci->id : 0;
  40997. }
  40998. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40999. {
  41000. int x = 0, width = 0, n = 0;
  41001. for (int i = 0; i < columns.size(); ++i)
  41002. {
  41003. x += width;
  41004. if (columns.getUnchecked(i)->isVisible())
  41005. {
  41006. width = columns.getUnchecked(i)->width;
  41007. if (n++ == index)
  41008. break;
  41009. }
  41010. else
  41011. {
  41012. width = 0;
  41013. }
  41014. }
  41015. return Rectangle<int> (x, 0, width, getHeight());
  41016. }
  41017. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41018. {
  41019. if (xToFind >= 0)
  41020. {
  41021. int x = 0;
  41022. for (int i = 0; i < columns.size(); ++i)
  41023. {
  41024. const ColumnInfo* const ci = columns.getUnchecked(i);
  41025. if (ci->isVisible())
  41026. {
  41027. x += ci->width;
  41028. if (xToFind < x)
  41029. return ci->id;
  41030. }
  41031. }
  41032. }
  41033. return 0;
  41034. }
  41035. int TableHeaderComponent::getTotalWidth() const
  41036. {
  41037. int w = 0;
  41038. for (int i = columns.size(); --i >= 0;)
  41039. if (columns.getUnchecked(i)->isVisible())
  41040. w += columns.getUnchecked(i)->width;
  41041. return w;
  41042. }
  41043. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41044. {
  41045. stretchToFit = shouldStretchToFit;
  41046. lastDeliberateWidth = getTotalWidth();
  41047. resized();
  41048. }
  41049. bool TableHeaderComponent::isStretchToFitActive() const
  41050. {
  41051. return stretchToFit;
  41052. }
  41053. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41054. {
  41055. if (stretchToFit && getWidth() > 0
  41056. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41057. {
  41058. lastDeliberateWidth = targetTotalWidth;
  41059. resizeColumnsToFit (0, targetTotalWidth);
  41060. }
  41061. }
  41062. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41063. {
  41064. targetTotalWidth = jmax (targetTotalWidth, 0);
  41065. StretchableObjectResizer sor;
  41066. int i;
  41067. for (i = firstColumnIndex; i < columns.size(); ++i)
  41068. {
  41069. ColumnInfo* const ci = columns.getUnchecked(i);
  41070. if (ci->isVisible())
  41071. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41072. }
  41073. sor.resizeToFit (targetTotalWidth);
  41074. int visIndex = 0;
  41075. for (i = firstColumnIndex; i < columns.size(); ++i)
  41076. {
  41077. ColumnInfo* const ci = columns.getUnchecked(i);
  41078. if (ci->isVisible())
  41079. {
  41080. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41081. (int) std::floor (sor.getItemSize (visIndex++)));
  41082. if (newWidth != ci->width)
  41083. {
  41084. ci->width = newWidth;
  41085. repaint();
  41086. columnsResized = true;
  41087. triggerAsyncUpdate();
  41088. }
  41089. }
  41090. }
  41091. }
  41092. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41093. {
  41094. ColumnInfo* const ci = getInfoForId (columnId);
  41095. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41096. {
  41097. if (shouldBeVisible)
  41098. ci->propertyFlags |= visible;
  41099. else
  41100. ci->propertyFlags &= ~visible;
  41101. sendColumnsChanged();
  41102. resized();
  41103. }
  41104. }
  41105. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41106. {
  41107. const ColumnInfo* const ci = getInfoForId (columnId);
  41108. return ci != 0 && ci->isVisible();
  41109. }
  41110. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41111. {
  41112. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41113. {
  41114. for (int i = columns.size(); --i >= 0;)
  41115. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41116. ColumnInfo* const ci = getInfoForId (columnId);
  41117. if (ci != 0)
  41118. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41119. reSortTable();
  41120. }
  41121. }
  41122. int TableHeaderComponent::getSortColumnId() const
  41123. {
  41124. for (int i = columns.size(); --i >= 0;)
  41125. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41126. return columns.getUnchecked(i)->id;
  41127. return 0;
  41128. }
  41129. bool TableHeaderComponent::isSortedForwards() const
  41130. {
  41131. for (int i = columns.size(); --i >= 0;)
  41132. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41133. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41134. return true;
  41135. }
  41136. void TableHeaderComponent::reSortTable()
  41137. {
  41138. sortChanged = true;
  41139. repaint();
  41140. triggerAsyncUpdate();
  41141. }
  41142. const String TableHeaderComponent::toString() const
  41143. {
  41144. String s;
  41145. XmlElement doc ("TABLELAYOUT");
  41146. doc.setAttribute ("sortedCol", getSortColumnId());
  41147. doc.setAttribute ("sortForwards", isSortedForwards());
  41148. for (int i = 0; i < columns.size(); ++i)
  41149. {
  41150. const ColumnInfo* const ci = columns.getUnchecked (i);
  41151. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41152. e->setAttribute ("id", ci->id);
  41153. e->setAttribute ("visible", ci->isVisible());
  41154. e->setAttribute ("width", ci->width);
  41155. }
  41156. return doc.createDocument (String::empty, true, false);
  41157. }
  41158. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41159. {
  41160. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41161. int index = 0;
  41162. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41163. {
  41164. forEachXmlChildElement (*storedXml, col)
  41165. {
  41166. const int tabId = col->getIntAttribute ("id");
  41167. ColumnInfo* const ci = getInfoForId (tabId);
  41168. if (ci != 0)
  41169. {
  41170. columns.move (columns.indexOf (ci), index);
  41171. ci->width = col->getIntAttribute ("width");
  41172. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41173. }
  41174. ++index;
  41175. }
  41176. columnsResized = true;
  41177. sendColumnsChanged();
  41178. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41179. storedXml->getBoolAttribute ("sortForwards", true));
  41180. }
  41181. }
  41182. void TableHeaderComponent::addListener (Listener* const newListener)
  41183. {
  41184. listeners.addIfNotAlreadyThere (newListener);
  41185. }
  41186. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41187. {
  41188. listeners.removeValue (listenerToRemove);
  41189. }
  41190. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41191. {
  41192. const ColumnInfo* const ci = getInfoForId (columnId);
  41193. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41194. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41195. }
  41196. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41197. {
  41198. for (int i = 0; i < columns.size(); ++i)
  41199. {
  41200. const ColumnInfo* const ci = columns.getUnchecked(i);
  41201. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41202. menu.addItem (ci->id, ci->name,
  41203. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41204. isColumnVisible (ci->id));
  41205. }
  41206. }
  41207. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41208. {
  41209. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41210. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41211. }
  41212. void TableHeaderComponent::paint (Graphics& g)
  41213. {
  41214. LookAndFeel& lf = getLookAndFeel();
  41215. lf.drawTableHeaderBackground (g, *this);
  41216. const Rectangle<int> clip (g.getClipBounds());
  41217. int x = 0;
  41218. for (int i = 0; i < columns.size(); ++i)
  41219. {
  41220. const ColumnInfo* const ci = columns.getUnchecked(i);
  41221. if (ci->isVisible())
  41222. {
  41223. if (x + ci->width > clip.getX()
  41224. && (ci->id != columnIdBeingDragged
  41225. || dragOverlayComp == 0
  41226. || ! dragOverlayComp->isVisible()))
  41227. {
  41228. Graphics::ScopedSaveState ss (g);
  41229. g.setOrigin (x, 0);
  41230. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41231. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41232. ci->id == columnIdUnderMouse,
  41233. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41234. ci->propertyFlags);
  41235. }
  41236. x += ci->width;
  41237. if (x >= clip.getRight())
  41238. break;
  41239. }
  41240. }
  41241. }
  41242. void TableHeaderComponent::resized()
  41243. {
  41244. }
  41245. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41246. {
  41247. updateColumnUnderMouse (e.x, e.y);
  41248. }
  41249. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41250. {
  41251. updateColumnUnderMouse (e.x, e.y);
  41252. }
  41253. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41254. {
  41255. updateColumnUnderMouse (e.x, e.y);
  41256. }
  41257. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41258. {
  41259. repaint();
  41260. columnIdBeingResized = 0;
  41261. columnIdBeingDragged = 0;
  41262. if (columnIdUnderMouse != 0)
  41263. {
  41264. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41265. if (e.mods.isPopupMenu())
  41266. columnClicked (columnIdUnderMouse, e.mods);
  41267. }
  41268. if (menuActive && e.mods.isPopupMenu())
  41269. showColumnChooserMenu (columnIdUnderMouse);
  41270. }
  41271. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41272. {
  41273. if (columnIdBeingResized == 0
  41274. && columnIdBeingDragged == 0
  41275. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41276. {
  41277. dragOverlayComp = 0;
  41278. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41279. if (columnIdBeingResized != 0)
  41280. {
  41281. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41282. initialColumnWidth = ci->width;
  41283. }
  41284. else
  41285. {
  41286. beginDrag (e);
  41287. }
  41288. }
  41289. if (columnIdBeingResized != 0)
  41290. {
  41291. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41292. if (ci != 0)
  41293. {
  41294. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41295. initialColumnWidth + e.getDistanceFromDragStartX());
  41296. if (stretchToFit)
  41297. {
  41298. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41299. int minWidthOnRight = 0;
  41300. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41301. if (columns.getUnchecked (i)->isVisible())
  41302. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41303. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41304. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41305. }
  41306. setColumnWidth (columnIdBeingResized, w);
  41307. }
  41308. }
  41309. else if (columnIdBeingDragged != 0)
  41310. {
  41311. if (e.y >= -50 && e.y < getHeight() + 50)
  41312. {
  41313. if (dragOverlayComp != 0)
  41314. {
  41315. dragOverlayComp->setVisible (true);
  41316. dragOverlayComp->setBounds (jlimit (0,
  41317. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41318. e.x - draggingColumnOffset),
  41319. 0,
  41320. dragOverlayComp->getWidth(),
  41321. getHeight());
  41322. for (int i = columns.size(); --i >= 0;)
  41323. {
  41324. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41325. int newIndex = currentIndex;
  41326. if (newIndex > 0)
  41327. {
  41328. // if the previous column isn't draggable, we can't move our column
  41329. // past it, because that'd change the undraggable column's position..
  41330. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41331. if ((previous->propertyFlags & draggable) != 0)
  41332. {
  41333. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41334. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41335. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41336. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41337. {
  41338. --newIndex;
  41339. }
  41340. }
  41341. }
  41342. if (newIndex < columns.size() - 1)
  41343. {
  41344. // if the next column isn't draggable, we can't move our column
  41345. // past it, because that'd change the undraggable column's position..
  41346. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41347. if ((nextCol->propertyFlags & draggable) != 0)
  41348. {
  41349. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41350. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41351. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41352. > abs (dragOverlayComp->getRight() - rightOfNext))
  41353. {
  41354. ++newIndex;
  41355. }
  41356. }
  41357. }
  41358. if (newIndex != currentIndex)
  41359. moveColumn (columnIdBeingDragged, newIndex);
  41360. else
  41361. break;
  41362. }
  41363. }
  41364. }
  41365. else
  41366. {
  41367. endDrag (draggingColumnOriginalIndex);
  41368. }
  41369. }
  41370. }
  41371. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41372. {
  41373. if (columnIdBeingDragged == 0)
  41374. {
  41375. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41376. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41377. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41378. {
  41379. columnIdBeingDragged = 0;
  41380. }
  41381. else
  41382. {
  41383. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41384. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41385. const int temp = columnIdBeingDragged;
  41386. columnIdBeingDragged = 0;
  41387. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41388. columnIdBeingDragged = temp;
  41389. dragOverlayComp->setBounds (columnRect);
  41390. for (int i = listeners.size(); --i >= 0;)
  41391. {
  41392. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41393. i = jmin (i, listeners.size() - 1);
  41394. }
  41395. }
  41396. }
  41397. }
  41398. void TableHeaderComponent::endDrag (const int finalIndex)
  41399. {
  41400. if (columnIdBeingDragged != 0)
  41401. {
  41402. moveColumn (columnIdBeingDragged, finalIndex);
  41403. columnIdBeingDragged = 0;
  41404. repaint();
  41405. for (int i = listeners.size(); --i >= 0;)
  41406. {
  41407. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41408. i = jmin (i, listeners.size() - 1);
  41409. }
  41410. }
  41411. }
  41412. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41413. {
  41414. mouseDrag (e);
  41415. for (int i = columns.size(); --i >= 0;)
  41416. if (columns.getUnchecked (i)->isVisible())
  41417. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41418. columnIdBeingResized = 0;
  41419. repaint();
  41420. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41421. updateColumnUnderMouse (e.x, e.y);
  41422. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41423. columnClicked (columnIdUnderMouse, e.mods);
  41424. dragOverlayComp = 0;
  41425. }
  41426. const MouseCursor TableHeaderComponent::getMouseCursor()
  41427. {
  41428. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41429. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41430. return Component::getMouseCursor();
  41431. }
  41432. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41433. {
  41434. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41435. }
  41436. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41437. {
  41438. for (int i = columns.size(); --i >= 0;)
  41439. if (columns.getUnchecked(i)->id == id)
  41440. return columns.getUnchecked(i);
  41441. return 0;
  41442. }
  41443. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41444. {
  41445. int n = 0;
  41446. for (int i = 0; i < columns.size(); ++i)
  41447. {
  41448. if (columns.getUnchecked(i)->isVisible())
  41449. {
  41450. if (n == visibleIndex)
  41451. return i;
  41452. ++n;
  41453. }
  41454. }
  41455. return -1;
  41456. }
  41457. void TableHeaderComponent::sendColumnsChanged()
  41458. {
  41459. if (stretchToFit && lastDeliberateWidth > 0)
  41460. resizeAllColumnsToFit (lastDeliberateWidth);
  41461. repaint();
  41462. columnsChanged = true;
  41463. triggerAsyncUpdate();
  41464. }
  41465. void TableHeaderComponent::handleAsyncUpdate()
  41466. {
  41467. const bool changed = columnsChanged || sortChanged;
  41468. const bool sized = columnsResized || changed;
  41469. const bool sorted = sortChanged;
  41470. columnsChanged = false;
  41471. columnsResized = false;
  41472. sortChanged = false;
  41473. if (sorted)
  41474. {
  41475. for (int i = listeners.size(); --i >= 0;)
  41476. {
  41477. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41478. i = jmin (i, listeners.size() - 1);
  41479. }
  41480. }
  41481. if (changed)
  41482. {
  41483. for (int i = listeners.size(); --i >= 0;)
  41484. {
  41485. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41486. i = jmin (i, listeners.size() - 1);
  41487. }
  41488. }
  41489. if (sized)
  41490. {
  41491. for (int i = listeners.size(); --i >= 0;)
  41492. {
  41493. listeners.getUnchecked(i)->tableColumnsResized (this);
  41494. i = jmin (i, listeners.size() - 1);
  41495. }
  41496. }
  41497. }
  41498. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41499. {
  41500. if (isPositiveAndBelow (mouseX, getWidth()))
  41501. {
  41502. const int draggableDistance = 3;
  41503. int x = 0;
  41504. for (int i = 0; i < columns.size(); ++i)
  41505. {
  41506. const ColumnInfo* const ci = columns.getUnchecked(i);
  41507. if (ci->isVisible())
  41508. {
  41509. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41510. && (ci->propertyFlags & resizable) != 0)
  41511. return ci->id;
  41512. x += ci->width;
  41513. }
  41514. }
  41515. }
  41516. return 0;
  41517. }
  41518. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41519. {
  41520. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41521. ? getColumnIdAtX (x) : 0;
  41522. if (newCol != columnIdUnderMouse)
  41523. {
  41524. columnIdUnderMouse = newCol;
  41525. repaint();
  41526. }
  41527. }
  41528. static void tableHeaderMenuCallback (int result, TableHeaderComponent* tableHeader, int columnIdClicked)
  41529. {
  41530. if (tableHeader != 0 && result != 0)
  41531. tableHeader->reactToMenuItem (result, columnIdClicked);
  41532. }
  41533. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41534. {
  41535. PopupMenu m;
  41536. addMenuItems (m, columnIdClicked);
  41537. if (m.getNumItems() > 0)
  41538. {
  41539. m.setLookAndFeel (&getLookAndFeel());
  41540. m.showMenuAsync (PopupMenu::Options(),
  41541. ModalCallbackFunction::forComponent (tableHeaderMenuCallback, this, columnIdClicked));
  41542. }
  41543. }
  41544. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41545. {
  41546. }
  41547. END_JUCE_NAMESPACE
  41548. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41549. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41550. BEGIN_JUCE_NAMESPACE
  41551. class TableListRowComp : public Component,
  41552. public TooltipClient
  41553. {
  41554. public:
  41555. TableListRowComp (TableListBox& owner_)
  41556. : owner (owner_), row (-1), isSelected (false)
  41557. {
  41558. }
  41559. void paint (Graphics& g)
  41560. {
  41561. TableListBoxModel* const model = owner.getModel();
  41562. if (model != 0)
  41563. {
  41564. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41565. const TableHeaderComponent& header = owner.getHeader();
  41566. const int numColumns = header.getNumColumns (true);
  41567. for (int i = 0; i < numColumns; ++i)
  41568. {
  41569. if (columnComponents[i] == 0)
  41570. {
  41571. const int columnId = header.getColumnIdOfIndex (i, true);
  41572. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41573. Graphics::ScopedSaveState ss (g);
  41574. g.reduceClipRegion (columnRect);
  41575. g.setOrigin (columnRect.getX(), 0);
  41576. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41577. }
  41578. }
  41579. }
  41580. }
  41581. void update (const int newRow, const bool isNowSelected)
  41582. {
  41583. jassert (newRow >= 0);
  41584. if (newRow != row || isNowSelected != isSelected)
  41585. {
  41586. row = newRow;
  41587. isSelected = isNowSelected;
  41588. repaint();
  41589. }
  41590. TableListBoxModel* const model = owner.getModel();
  41591. if (model != 0 && row < owner.getNumRows())
  41592. {
  41593. const Identifier columnProperty ("_tableColumnId");
  41594. const int numColumns = owner.getHeader().getNumColumns (true);
  41595. for (int i = 0; i < numColumns; ++i)
  41596. {
  41597. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41598. Component* comp = columnComponents[i];
  41599. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41600. {
  41601. columnComponents.set (i, 0);
  41602. comp = 0;
  41603. }
  41604. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41605. columnComponents.set (i, comp, false);
  41606. if (comp != 0)
  41607. {
  41608. comp->getProperties().set (columnProperty, columnId);
  41609. addAndMakeVisible (comp);
  41610. resizeCustomComp (i);
  41611. }
  41612. }
  41613. columnComponents.removeRange (numColumns, columnComponents.size());
  41614. }
  41615. else
  41616. {
  41617. columnComponents.clear();
  41618. }
  41619. }
  41620. void resized()
  41621. {
  41622. for (int i = columnComponents.size(); --i >= 0;)
  41623. resizeCustomComp (i);
  41624. }
  41625. void resizeCustomComp (const int index)
  41626. {
  41627. Component* const c = columnComponents.getUnchecked (index);
  41628. if (c != 0)
  41629. c->setBounds (owner.getHeader().getColumnPosition (index)
  41630. .withY (0).withHeight (getHeight()));
  41631. }
  41632. void mouseDown (const MouseEvent& e)
  41633. {
  41634. isDragging = false;
  41635. selectRowOnMouseUp = false;
  41636. if (isEnabled())
  41637. {
  41638. if (! isSelected)
  41639. {
  41640. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41641. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41642. if (columnId != 0 && owner.getModel() != 0)
  41643. owner.getModel()->cellClicked (row, columnId, e);
  41644. }
  41645. else
  41646. {
  41647. selectRowOnMouseUp = true;
  41648. }
  41649. }
  41650. }
  41651. void mouseDrag (const MouseEvent& e)
  41652. {
  41653. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41654. {
  41655. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41656. if (selectedRows.size() > 0)
  41657. {
  41658. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41659. if (dragDescription.isNotEmpty())
  41660. {
  41661. isDragging = true;
  41662. owner.startDragAndDrop (e, dragDescription);
  41663. }
  41664. }
  41665. }
  41666. }
  41667. void mouseUp (const MouseEvent& e)
  41668. {
  41669. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41670. {
  41671. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41672. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41673. if (columnId != 0 && owner.getModel() != 0)
  41674. owner.getModel()->cellClicked (row, columnId, e);
  41675. }
  41676. }
  41677. void mouseDoubleClick (const MouseEvent& e)
  41678. {
  41679. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41680. if (columnId != 0 && owner.getModel() != 0)
  41681. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41682. }
  41683. const String getTooltip()
  41684. {
  41685. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41686. if (columnId != 0 && owner.getModel() != 0)
  41687. return owner.getModel()->getCellTooltip (row, columnId);
  41688. return String::empty;
  41689. }
  41690. Component* findChildComponentForColumn (const int columnId) const
  41691. {
  41692. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41693. }
  41694. private:
  41695. TableListBox& owner;
  41696. OwnedArray<Component> columnComponents;
  41697. int row;
  41698. bool isSelected, isDragging, selectRowOnMouseUp;
  41699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41700. };
  41701. class TableListBoxHeader : public TableHeaderComponent
  41702. {
  41703. public:
  41704. TableListBoxHeader (TableListBox& owner_)
  41705. : owner (owner_)
  41706. {
  41707. }
  41708. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41709. {
  41710. if (owner.isAutoSizeMenuOptionShown())
  41711. {
  41712. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41713. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41714. menu.addSeparator();
  41715. }
  41716. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41717. }
  41718. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41719. {
  41720. switch (menuReturnId)
  41721. {
  41722. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41723. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41724. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41725. }
  41726. }
  41727. private:
  41728. TableListBox& owner;
  41729. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41730. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41731. };
  41732. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41733. : ListBox (name, 0),
  41734. header (0), model (model_),
  41735. autoSizeOptionsShown (true)
  41736. {
  41737. ListBox::model = this;
  41738. setHeader (new TableListBoxHeader (*this));
  41739. }
  41740. TableListBox::~TableListBox()
  41741. {
  41742. header = 0;
  41743. }
  41744. void TableListBox::setModel (TableListBoxModel* const newModel)
  41745. {
  41746. if (model != newModel)
  41747. {
  41748. model = newModel;
  41749. updateContent();
  41750. }
  41751. }
  41752. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41753. {
  41754. jassert (newHeader != 0); // you need to supply a real header for a table!
  41755. Rectangle<int> newBounds (0, 0, 100, 28);
  41756. if (header != 0)
  41757. newBounds = header->getBounds();
  41758. header = newHeader;
  41759. header->setBounds (newBounds);
  41760. setHeaderComponent (header);
  41761. header->addListener (this);
  41762. }
  41763. int TableListBox::getHeaderHeight() const
  41764. {
  41765. return header->getHeight();
  41766. }
  41767. void TableListBox::setHeaderHeight (const int newHeight)
  41768. {
  41769. header->setSize (header->getWidth(), newHeight);
  41770. resized();
  41771. }
  41772. void TableListBox::autoSizeColumn (const int columnId)
  41773. {
  41774. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41775. if (width > 0)
  41776. header->setColumnWidth (columnId, width);
  41777. }
  41778. void TableListBox::autoSizeAllColumns()
  41779. {
  41780. for (int i = 0; i < header->getNumColumns (true); ++i)
  41781. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41782. }
  41783. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41784. {
  41785. autoSizeOptionsShown = shouldBeShown;
  41786. }
  41787. bool TableListBox::isAutoSizeMenuOptionShown() const
  41788. {
  41789. return autoSizeOptionsShown;
  41790. }
  41791. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41792. const bool relativeToComponentTopLeft) const
  41793. {
  41794. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41795. if (relativeToComponentTopLeft)
  41796. headerCell.translate (header->getX(), 0);
  41797. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41798. .withX (headerCell.getX())
  41799. .withWidth (headerCell.getWidth());
  41800. }
  41801. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41802. {
  41803. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41804. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41805. }
  41806. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41807. {
  41808. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41809. if (scrollbar != 0)
  41810. {
  41811. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41812. double x = scrollbar->getCurrentRangeStart();
  41813. const double w = scrollbar->getCurrentRangeSize();
  41814. if (pos.getX() < x)
  41815. x = pos.getX();
  41816. else if (pos.getRight() > x + w)
  41817. x += jmax (0.0, pos.getRight() - (x + w));
  41818. scrollbar->setCurrentRangeStart (x);
  41819. }
  41820. }
  41821. int TableListBox::getNumRows()
  41822. {
  41823. return model != 0 ? model->getNumRows() : 0;
  41824. }
  41825. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41826. {
  41827. }
  41828. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41829. {
  41830. if (existingComponentToUpdate == 0)
  41831. existingComponentToUpdate = new TableListRowComp (*this);
  41832. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41833. return existingComponentToUpdate;
  41834. }
  41835. void TableListBox::selectedRowsChanged (int row)
  41836. {
  41837. if (model != 0)
  41838. model->selectedRowsChanged (row);
  41839. }
  41840. void TableListBox::deleteKeyPressed (int row)
  41841. {
  41842. if (model != 0)
  41843. model->deleteKeyPressed (row);
  41844. }
  41845. void TableListBox::returnKeyPressed (int row)
  41846. {
  41847. if (model != 0)
  41848. model->returnKeyPressed (row);
  41849. }
  41850. void TableListBox::backgroundClicked()
  41851. {
  41852. if (model != 0)
  41853. model->backgroundClicked();
  41854. }
  41855. void TableListBox::listWasScrolled()
  41856. {
  41857. if (model != 0)
  41858. model->listWasScrolled();
  41859. }
  41860. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41861. {
  41862. setMinimumContentWidth (header->getTotalWidth());
  41863. repaint();
  41864. updateColumnComponents();
  41865. }
  41866. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41867. {
  41868. setMinimumContentWidth (header->getTotalWidth());
  41869. repaint();
  41870. updateColumnComponents();
  41871. }
  41872. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41873. {
  41874. if (model != 0)
  41875. model->sortOrderChanged (header->getSortColumnId(),
  41876. header->isSortedForwards());
  41877. }
  41878. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41879. {
  41880. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41881. repaint();
  41882. }
  41883. void TableListBox::resized()
  41884. {
  41885. ListBox::resized();
  41886. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41887. setMinimumContentWidth (header->getTotalWidth());
  41888. }
  41889. void TableListBox::updateColumnComponents() const
  41890. {
  41891. const int firstRow = getRowContainingPosition (0, 0);
  41892. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41893. {
  41894. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41895. if (rowComp != 0)
  41896. rowComp->resized();
  41897. }
  41898. }
  41899. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41900. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41901. void TableListBoxModel::backgroundClicked() {}
  41902. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41903. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41904. void TableListBoxModel::selectedRowsChanged (int) {}
  41905. void TableListBoxModel::deleteKeyPressed (int) {}
  41906. void TableListBoxModel::returnKeyPressed (int) {}
  41907. void TableListBoxModel::listWasScrolled() {}
  41908. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41909. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41910. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41911. {
  41912. (void) existingComponentToUpdate;
  41913. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41914. return 0;
  41915. }
  41916. END_JUCE_NAMESPACE
  41917. /*** End of inlined file: juce_TableListBox.cpp ***/
  41918. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41919. BEGIN_JUCE_NAMESPACE
  41920. // a word or space that can't be broken down any further
  41921. struct TextAtom
  41922. {
  41923. String atomText;
  41924. float width;
  41925. int numChars;
  41926. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41927. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41928. const String getText (const juce_wchar passwordCharacter) const
  41929. {
  41930. if (passwordCharacter == 0)
  41931. return atomText;
  41932. else
  41933. return String::repeatedString (String::charToString (passwordCharacter),
  41934. atomText.length());
  41935. }
  41936. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41937. {
  41938. if (passwordCharacter == 0)
  41939. return atomText.substring (0, numChars);
  41940. else if (isNewLine())
  41941. return String::empty;
  41942. else
  41943. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41944. }
  41945. };
  41946. // a run of text with a single font and colour
  41947. class TextEditor::UniformTextSection
  41948. {
  41949. public:
  41950. UniformTextSection (const String& text,
  41951. const Font& font_,
  41952. const Colour& colour_,
  41953. const juce_wchar passwordCharacter)
  41954. : font (font_),
  41955. colour (colour_)
  41956. {
  41957. initialiseAtoms (text, passwordCharacter);
  41958. }
  41959. UniformTextSection (const UniformTextSection& other)
  41960. : font (other.font),
  41961. colour (other.colour)
  41962. {
  41963. atoms.ensureStorageAllocated (other.atoms.size());
  41964. for (int i = 0; i < other.atoms.size(); ++i)
  41965. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41966. }
  41967. ~UniformTextSection()
  41968. {
  41969. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41970. }
  41971. void clear()
  41972. {
  41973. for (int i = atoms.size(); --i >= 0;)
  41974. delete getAtom(i);
  41975. atoms.clear();
  41976. }
  41977. int getNumAtoms() const
  41978. {
  41979. return atoms.size();
  41980. }
  41981. TextAtom* getAtom (const int index) const throw()
  41982. {
  41983. return atoms.getUnchecked (index);
  41984. }
  41985. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41986. {
  41987. if (other.atoms.size() > 0)
  41988. {
  41989. TextAtom* const lastAtom = atoms.getLast();
  41990. int i = 0;
  41991. if (lastAtom != 0)
  41992. {
  41993. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41994. {
  41995. TextAtom* const first = other.getAtom(0);
  41996. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41997. {
  41998. lastAtom->atomText += first->atomText;
  41999. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42000. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42001. delete first;
  42002. ++i;
  42003. }
  42004. }
  42005. }
  42006. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42007. while (i < other.atoms.size())
  42008. {
  42009. atoms.add (other.getAtom(i));
  42010. ++i;
  42011. }
  42012. }
  42013. }
  42014. UniformTextSection* split (const int indexToBreakAt,
  42015. const juce_wchar passwordCharacter)
  42016. {
  42017. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42018. font, colour,
  42019. passwordCharacter);
  42020. int index = 0;
  42021. for (int i = 0; i < atoms.size(); ++i)
  42022. {
  42023. TextAtom* const atom = getAtom(i);
  42024. const int nextIndex = index + atom->numChars;
  42025. if (index == indexToBreakAt)
  42026. {
  42027. int j;
  42028. for (j = i; j < atoms.size(); ++j)
  42029. section2->atoms.add (getAtom (j));
  42030. for (j = atoms.size(); --j >= i;)
  42031. atoms.remove (j);
  42032. break;
  42033. }
  42034. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42035. {
  42036. TextAtom* const secondAtom = new TextAtom();
  42037. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42038. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42039. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42040. section2->atoms.add (secondAtom);
  42041. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42042. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42043. atom->numChars = (uint16) (indexToBreakAt - index);
  42044. int j;
  42045. for (j = i + 1; j < atoms.size(); ++j)
  42046. section2->atoms.add (getAtom (j));
  42047. for (j = atoms.size(); --j > i;)
  42048. atoms.remove (j);
  42049. break;
  42050. }
  42051. index = nextIndex;
  42052. }
  42053. return section2;
  42054. }
  42055. void appendAllText (String::Concatenator& concatenator) const
  42056. {
  42057. for (int i = 0; i < atoms.size(); ++i)
  42058. concatenator.append (getAtom(i)->atomText);
  42059. }
  42060. void appendSubstring (String::Concatenator& concatenator,
  42061. const Range<int>& range) const
  42062. {
  42063. int index = 0;
  42064. for (int i = 0; i < atoms.size(); ++i)
  42065. {
  42066. const TextAtom* const atom = getAtom (i);
  42067. const int nextIndex = index + atom->numChars;
  42068. if (range.getStart() < nextIndex)
  42069. {
  42070. if (range.getEnd() <= index)
  42071. break;
  42072. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42073. if (! r.isEmpty())
  42074. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42075. }
  42076. index = nextIndex;
  42077. }
  42078. }
  42079. int getTotalLength() const
  42080. {
  42081. int total = 0;
  42082. for (int i = atoms.size(); --i >= 0;)
  42083. total += getAtom(i)->numChars;
  42084. return total;
  42085. }
  42086. void setFont (const Font& newFont,
  42087. const juce_wchar passwordCharacter)
  42088. {
  42089. if (font != newFont)
  42090. {
  42091. font = newFont;
  42092. for (int i = atoms.size(); --i >= 0;)
  42093. {
  42094. TextAtom* const atom = atoms.getUnchecked(i);
  42095. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42096. }
  42097. }
  42098. }
  42099. Font font;
  42100. Colour colour;
  42101. private:
  42102. Array <TextAtom*> atoms;
  42103. void initialiseAtoms (const String& textToParse,
  42104. const juce_wchar passwordCharacter)
  42105. {
  42106. String::CharPointerType text (textToParse.getCharPointer());
  42107. while (! text.isEmpty())
  42108. {
  42109. int numChars = 0;
  42110. String::CharPointerType start (text);
  42111. // create a whitespace atom unless it starts with non-ws
  42112. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  42113. {
  42114. do
  42115. {
  42116. ++text;
  42117. ++numChars;
  42118. }
  42119. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  42120. }
  42121. else
  42122. {
  42123. if (*text == '\r')
  42124. {
  42125. ++text;
  42126. ++numChars;
  42127. if (*text == '\n')
  42128. {
  42129. ++start;
  42130. ++text;
  42131. }
  42132. }
  42133. else if (*text == '\n')
  42134. {
  42135. ++text;
  42136. ++numChars;
  42137. }
  42138. else
  42139. {
  42140. while (! (text.isEmpty() || text.isWhitespace()))
  42141. {
  42142. ++text;
  42143. ++numChars;
  42144. }
  42145. }
  42146. }
  42147. TextAtom* const atom = new TextAtom();
  42148. atom->atomText = String (start, numChars);
  42149. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42150. atom->numChars = (uint16) numChars;
  42151. atoms.add (atom);
  42152. }
  42153. }
  42154. UniformTextSection& operator= (const UniformTextSection& other);
  42155. JUCE_LEAK_DETECTOR (UniformTextSection);
  42156. };
  42157. class TextEditor::Iterator
  42158. {
  42159. public:
  42160. Iterator (const Array <UniformTextSection*>& sections_,
  42161. const float wordWrapWidth_,
  42162. const juce_wchar passwordCharacter_)
  42163. : indexInText (0),
  42164. lineY (0),
  42165. lineHeight (0),
  42166. maxDescent (0),
  42167. atomX (0),
  42168. atomRight (0),
  42169. atom (0),
  42170. currentSection (0),
  42171. sections (sections_),
  42172. sectionIndex (0),
  42173. atomIndex (0),
  42174. wordWrapWidth (wordWrapWidth_),
  42175. passwordCharacter (passwordCharacter_)
  42176. {
  42177. jassert (wordWrapWidth_ > 0);
  42178. if (sections.size() > 0)
  42179. {
  42180. currentSection = sections.getUnchecked (sectionIndex);
  42181. if (currentSection != 0)
  42182. beginNewLine();
  42183. }
  42184. }
  42185. Iterator (const Iterator& other)
  42186. : indexInText (other.indexInText),
  42187. lineY (other.lineY),
  42188. lineHeight (other.lineHeight),
  42189. maxDescent (other.maxDescent),
  42190. atomX (other.atomX),
  42191. atomRight (other.atomRight),
  42192. atom (other.atom),
  42193. currentSection (other.currentSection),
  42194. sections (other.sections),
  42195. sectionIndex (other.sectionIndex),
  42196. atomIndex (other.atomIndex),
  42197. wordWrapWidth (other.wordWrapWidth),
  42198. passwordCharacter (other.passwordCharacter),
  42199. tempAtom (other.tempAtom)
  42200. {
  42201. }
  42202. bool next()
  42203. {
  42204. if (atom == &tempAtom)
  42205. {
  42206. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42207. if (numRemaining > 0)
  42208. {
  42209. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42210. atomX = 0;
  42211. if (tempAtom.numChars > 0)
  42212. lineY += lineHeight;
  42213. indexInText += tempAtom.numChars;
  42214. GlyphArrangement g;
  42215. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42216. int split;
  42217. for (split = 0; split < g.getNumGlyphs(); ++split)
  42218. if (shouldWrap (g.getGlyph (split).getRight()))
  42219. break;
  42220. if (split > 0 && split <= numRemaining)
  42221. {
  42222. tempAtom.numChars = (uint16) split;
  42223. tempAtom.width = g.getGlyph (split - 1).getRight();
  42224. atomRight = atomX + tempAtom.width;
  42225. return true;
  42226. }
  42227. }
  42228. }
  42229. bool forceNewLine = false;
  42230. if (sectionIndex >= sections.size())
  42231. {
  42232. moveToEndOfLastAtom();
  42233. return false;
  42234. }
  42235. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42236. {
  42237. if (atomIndex >= currentSection->getNumAtoms())
  42238. {
  42239. if (++sectionIndex >= sections.size())
  42240. {
  42241. moveToEndOfLastAtom();
  42242. return false;
  42243. }
  42244. atomIndex = 0;
  42245. currentSection = sections.getUnchecked (sectionIndex);
  42246. }
  42247. else
  42248. {
  42249. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42250. if (! lastAtom->isWhitespace())
  42251. {
  42252. // handle the case where the last atom in a section is actually part of the same
  42253. // word as the first atom of the next section...
  42254. float right = atomRight + lastAtom->width;
  42255. float lineHeight2 = lineHeight;
  42256. float maxDescent2 = maxDescent;
  42257. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42258. {
  42259. const UniformTextSection* const s = sections.getUnchecked (section);
  42260. if (s->getNumAtoms() == 0)
  42261. break;
  42262. const TextAtom* const nextAtom = s->getAtom (0);
  42263. if (nextAtom->isWhitespace())
  42264. break;
  42265. right += nextAtom->width;
  42266. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42267. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42268. if (shouldWrap (right))
  42269. {
  42270. lineHeight = lineHeight2;
  42271. maxDescent = maxDescent2;
  42272. forceNewLine = true;
  42273. break;
  42274. }
  42275. if (s->getNumAtoms() > 1)
  42276. break;
  42277. }
  42278. }
  42279. }
  42280. }
  42281. if (atom != 0)
  42282. {
  42283. atomX = atomRight;
  42284. indexInText += atom->numChars;
  42285. if (atom->isNewLine())
  42286. beginNewLine();
  42287. }
  42288. atom = currentSection->getAtom (atomIndex);
  42289. atomRight = atomX + atom->width;
  42290. ++atomIndex;
  42291. if (shouldWrap (atomRight) || forceNewLine)
  42292. {
  42293. if (atom->isWhitespace())
  42294. {
  42295. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42296. atomRight = jmin (atomRight, wordWrapWidth);
  42297. }
  42298. else
  42299. {
  42300. atomRight = atom->width;
  42301. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42302. {
  42303. tempAtom = *atom;
  42304. tempAtom.width = 0;
  42305. tempAtom.numChars = 0;
  42306. atom = &tempAtom;
  42307. if (atomX > 0)
  42308. beginNewLine();
  42309. return next();
  42310. }
  42311. beginNewLine();
  42312. return true;
  42313. }
  42314. }
  42315. return true;
  42316. }
  42317. void beginNewLine()
  42318. {
  42319. atomX = 0;
  42320. lineY += lineHeight;
  42321. int tempSectionIndex = sectionIndex;
  42322. int tempAtomIndex = atomIndex;
  42323. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42324. lineHeight = section->font.getHeight();
  42325. maxDescent = section->font.getDescent();
  42326. float x = (atom != 0) ? atom->width : 0;
  42327. while (! shouldWrap (x))
  42328. {
  42329. if (tempSectionIndex >= sections.size())
  42330. break;
  42331. bool checkSize = false;
  42332. if (tempAtomIndex >= section->getNumAtoms())
  42333. {
  42334. if (++tempSectionIndex >= sections.size())
  42335. break;
  42336. tempAtomIndex = 0;
  42337. section = sections.getUnchecked (tempSectionIndex);
  42338. checkSize = true;
  42339. }
  42340. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42341. if (nextAtom == 0)
  42342. break;
  42343. x += nextAtom->width;
  42344. if (shouldWrap (x) || nextAtom->isNewLine())
  42345. break;
  42346. if (checkSize)
  42347. {
  42348. lineHeight = jmax (lineHeight, section->font.getHeight());
  42349. maxDescent = jmax (maxDescent, section->font.getDescent());
  42350. }
  42351. ++tempAtomIndex;
  42352. }
  42353. }
  42354. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42355. {
  42356. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42357. {
  42358. if (lastSection != currentSection)
  42359. {
  42360. lastSection = currentSection;
  42361. g.setColour (currentSection->colour);
  42362. g.setFont (currentSection->font);
  42363. }
  42364. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42365. GlyphArrangement ga;
  42366. ga.addLineOfText (currentSection->font,
  42367. atom->getTrimmedText (passwordCharacter),
  42368. atomX,
  42369. (float) roundToInt (lineY + lineHeight - maxDescent));
  42370. ga.draw (g);
  42371. }
  42372. }
  42373. void drawSelection (Graphics& g,
  42374. const Range<int>& selection) const
  42375. {
  42376. const int startX = roundToInt (indexToX (selection.getStart()));
  42377. const int endX = roundToInt (indexToX (selection.getEnd()));
  42378. const int y = roundToInt (lineY);
  42379. const int nextY = roundToInt (lineY + lineHeight);
  42380. g.fillRect (startX, y, endX - startX, nextY - y);
  42381. }
  42382. void drawSelectedText (Graphics& g,
  42383. const Range<int>& selection,
  42384. const Colour& selectedTextColour) const
  42385. {
  42386. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42387. {
  42388. GlyphArrangement ga;
  42389. ga.addLineOfText (currentSection->font,
  42390. atom->getTrimmedText (passwordCharacter),
  42391. atomX,
  42392. (float) roundToInt (lineY + lineHeight - maxDescent));
  42393. if (selection.getEnd() < indexInText + atom->numChars)
  42394. {
  42395. GlyphArrangement ga2 (ga);
  42396. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42397. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42398. g.setColour (currentSection->colour);
  42399. ga2.draw (g);
  42400. }
  42401. if (selection.getStart() > indexInText)
  42402. {
  42403. GlyphArrangement ga2 (ga);
  42404. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42405. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42406. g.setColour (currentSection->colour);
  42407. ga2.draw (g);
  42408. }
  42409. g.setColour (selectedTextColour);
  42410. ga.draw (g);
  42411. }
  42412. }
  42413. float indexToX (const int indexToFind) const
  42414. {
  42415. if (indexToFind <= indexInText)
  42416. return atomX;
  42417. if (indexToFind >= indexInText + atom->numChars)
  42418. return atomRight;
  42419. GlyphArrangement g;
  42420. g.addLineOfText (currentSection->font,
  42421. atom->getText (passwordCharacter),
  42422. atomX, 0.0f);
  42423. if (indexToFind - indexInText >= g.getNumGlyphs())
  42424. return atomRight;
  42425. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42426. }
  42427. int xToIndex (const float xToFind) const
  42428. {
  42429. if (xToFind <= atomX || atom->isNewLine())
  42430. return indexInText;
  42431. if (xToFind >= atomRight)
  42432. return indexInText + atom->numChars;
  42433. GlyphArrangement g;
  42434. g.addLineOfText (currentSection->font,
  42435. atom->getText (passwordCharacter),
  42436. atomX, 0.0f);
  42437. int j;
  42438. for (j = 0; j < g.getNumGlyphs(); ++j)
  42439. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42440. break;
  42441. return indexInText + j;
  42442. }
  42443. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42444. {
  42445. while (next())
  42446. {
  42447. if (indexInText + atom->numChars > index)
  42448. {
  42449. cx = indexToX (index);
  42450. cy = lineY;
  42451. lineHeight_ = lineHeight;
  42452. return true;
  42453. }
  42454. }
  42455. cx = atomX;
  42456. cy = lineY;
  42457. lineHeight_ = lineHeight;
  42458. return false;
  42459. }
  42460. int indexInText;
  42461. float lineY, lineHeight, maxDescent;
  42462. float atomX, atomRight;
  42463. const TextAtom* atom;
  42464. const UniformTextSection* currentSection;
  42465. private:
  42466. const Array <UniformTextSection*>& sections;
  42467. int sectionIndex, atomIndex;
  42468. const float wordWrapWidth;
  42469. const juce_wchar passwordCharacter;
  42470. TextAtom tempAtom;
  42471. Iterator& operator= (const Iterator&);
  42472. void moveToEndOfLastAtom()
  42473. {
  42474. if (atom != 0)
  42475. {
  42476. atomX = atomRight;
  42477. if (atom->isNewLine())
  42478. {
  42479. atomX = 0.0f;
  42480. lineY += lineHeight;
  42481. }
  42482. }
  42483. }
  42484. bool shouldWrap (const float x) const
  42485. {
  42486. return (x - 0.0001f) >= wordWrapWidth;
  42487. }
  42488. JUCE_LEAK_DETECTOR (Iterator);
  42489. };
  42490. class TextEditor::InsertAction : public UndoableAction
  42491. {
  42492. public:
  42493. InsertAction (TextEditor& owner_,
  42494. const String& text_,
  42495. const int insertIndex_,
  42496. const Font& font_,
  42497. const Colour& colour_,
  42498. const int oldCaretPos_,
  42499. const int newCaretPos_)
  42500. : owner (owner_),
  42501. text (text_),
  42502. insertIndex (insertIndex_),
  42503. oldCaretPos (oldCaretPos_),
  42504. newCaretPos (newCaretPos_),
  42505. font (font_),
  42506. colour (colour_)
  42507. {
  42508. }
  42509. bool perform()
  42510. {
  42511. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42512. return true;
  42513. }
  42514. bool undo()
  42515. {
  42516. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42517. return true;
  42518. }
  42519. int getSizeInUnits()
  42520. {
  42521. return text.length() + 16;
  42522. }
  42523. private:
  42524. TextEditor& owner;
  42525. const String text;
  42526. const int insertIndex, oldCaretPos, newCaretPos;
  42527. const Font font;
  42528. const Colour colour;
  42529. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42530. };
  42531. class TextEditor::RemoveAction : public UndoableAction
  42532. {
  42533. public:
  42534. RemoveAction (TextEditor& owner_,
  42535. const Range<int> range_,
  42536. const int oldCaretPos_,
  42537. const int newCaretPos_,
  42538. const Array <UniformTextSection*>& removedSections_)
  42539. : owner (owner_),
  42540. range (range_),
  42541. oldCaretPos (oldCaretPos_),
  42542. newCaretPos (newCaretPos_),
  42543. removedSections (removedSections_)
  42544. {
  42545. }
  42546. ~RemoveAction()
  42547. {
  42548. for (int i = removedSections.size(); --i >= 0;)
  42549. {
  42550. UniformTextSection* const section = removedSections.getUnchecked (i);
  42551. section->clear();
  42552. delete section;
  42553. }
  42554. }
  42555. bool perform()
  42556. {
  42557. owner.remove (range, 0, newCaretPos);
  42558. return true;
  42559. }
  42560. bool undo()
  42561. {
  42562. owner.reinsert (range.getStart(), removedSections);
  42563. owner.moveCursorTo (oldCaretPos, false);
  42564. return true;
  42565. }
  42566. int getSizeInUnits()
  42567. {
  42568. int n = 0;
  42569. for (int i = removedSections.size(); --i >= 0;)
  42570. n += removedSections.getUnchecked (i)->getTotalLength();
  42571. return n + 16;
  42572. }
  42573. private:
  42574. TextEditor& owner;
  42575. const Range<int> range;
  42576. const int oldCaretPos, newCaretPos;
  42577. Array <UniformTextSection*> removedSections;
  42578. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42579. };
  42580. class TextEditor::TextHolderComponent : public Component,
  42581. public Timer,
  42582. public ValueListener
  42583. {
  42584. public:
  42585. TextHolderComponent (TextEditor& owner_)
  42586. : owner (owner_)
  42587. {
  42588. setWantsKeyboardFocus (false);
  42589. setInterceptsMouseClicks (false, true);
  42590. owner.getTextValue().addListener (this);
  42591. }
  42592. ~TextHolderComponent()
  42593. {
  42594. owner.getTextValue().removeListener (this);
  42595. }
  42596. void paint (Graphics& g)
  42597. {
  42598. owner.drawContent (g);
  42599. }
  42600. void timerCallback()
  42601. {
  42602. owner.timerCallbackInt();
  42603. }
  42604. const MouseCursor getMouseCursor()
  42605. {
  42606. return owner.getMouseCursor();
  42607. }
  42608. void valueChanged (Value&)
  42609. {
  42610. owner.textWasChangedByValue();
  42611. }
  42612. private:
  42613. TextEditor& owner;
  42614. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42615. };
  42616. class TextEditorViewport : public Viewport
  42617. {
  42618. public:
  42619. TextEditorViewport (TextEditor& owner_)
  42620. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42621. {
  42622. }
  42623. void visibleAreaChanged (const Rectangle<int>&)
  42624. {
  42625. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42626. // appear and disappear, causing the wrap width to change.
  42627. {
  42628. const float wordWrapWidth = owner.getWordWrapWidth();
  42629. if (wordWrapWidth != lastWordWrapWidth)
  42630. {
  42631. lastWordWrapWidth = wordWrapWidth;
  42632. rentrant = true;
  42633. owner.updateTextHolderSize();
  42634. rentrant = false;
  42635. }
  42636. }
  42637. }
  42638. private:
  42639. TextEditor& owner;
  42640. float lastWordWrapWidth;
  42641. bool rentrant;
  42642. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42643. };
  42644. namespace TextEditorDefs
  42645. {
  42646. const int flashSpeedIntervalMs = 380;
  42647. const int textChangeMessageId = 0x10003001;
  42648. const int returnKeyMessageId = 0x10003002;
  42649. const int escapeKeyMessageId = 0x10003003;
  42650. const int focusLossMessageId = 0x10003004;
  42651. const int maxActionsPerTransaction = 100;
  42652. int getCharacterCategory (const juce_wchar character)
  42653. {
  42654. return CharacterFunctions::isLetterOrDigit (character)
  42655. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42656. }
  42657. }
  42658. TextEditor::TextEditor (const String& name,
  42659. const juce_wchar passwordCharacter_)
  42660. : Component (name),
  42661. borderSize (1, 1, 1, 3),
  42662. readOnly (false),
  42663. multiline (false),
  42664. wordWrap (false),
  42665. returnKeyStartsNewLine (false),
  42666. caretVisible (true),
  42667. popupMenuEnabled (true),
  42668. selectAllTextWhenFocused (false),
  42669. scrollbarVisible (true),
  42670. wasFocused (false),
  42671. caretFlashState (true),
  42672. keepCursorOnScreen (true),
  42673. tabKeyUsed (false),
  42674. menuActive (false),
  42675. valueTextNeedsUpdating (false),
  42676. cursorX (0),
  42677. cursorY (0),
  42678. cursorHeight (0),
  42679. maxTextLength (0),
  42680. leftIndent (4),
  42681. topIndent (4),
  42682. lastTransactionTime (0),
  42683. currentFont (14.0f),
  42684. totalNumChars (0),
  42685. caretPosition (0),
  42686. passwordCharacter (passwordCharacter_),
  42687. dragType (notDragging)
  42688. {
  42689. setOpaque (true);
  42690. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42691. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42692. viewport->setWantsKeyboardFocus (false);
  42693. viewport->setScrollBarsShown (false, false);
  42694. setMouseCursor (MouseCursor::IBeamCursor);
  42695. setWantsKeyboardFocus (true);
  42696. }
  42697. TextEditor::~TextEditor()
  42698. {
  42699. textValue.referTo (Value());
  42700. clearInternal (0);
  42701. viewport = 0;
  42702. textHolder = 0;
  42703. }
  42704. void TextEditor::newTransaction()
  42705. {
  42706. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42707. undoManager.beginNewTransaction();
  42708. }
  42709. void TextEditor::doUndoRedo (const bool isRedo)
  42710. {
  42711. if (! isReadOnly())
  42712. {
  42713. if (isRedo ? undoManager.redo()
  42714. : undoManager.undo())
  42715. {
  42716. scrollToMakeSureCursorIsVisible();
  42717. repaint();
  42718. textChanged();
  42719. }
  42720. }
  42721. }
  42722. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42723. const bool shouldWordWrap)
  42724. {
  42725. if (multiline != shouldBeMultiLine
  42726. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42727. {
  42728. multiline = shouldBeMultiLine;
  42729. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42730. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42731. scrollbarVisible && multiline);
  42732. viewport->setViewPosition (0, 0);
  42733. resized();
  42734. scrollToMakeSureCursorIsVisible();
  42735. }
  42736. }
  42737. bool TextEditor::isMultiLine() const
  42738. {
  42739. return multiline;
  42740. }
  42741. void TextEditor::setScrollbarsShown (bool shown)
  42742. {
  42743. if (scrollbarVisible != shown)
  42744. {
  42745. scrollbarVisible = shown;
  42746. shown = shown && isMultiLine();
  42747. viewport->setScrollBarsShown (shown, shown);
  42748. }
  42749. }
  42750. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42751. {
  42752. if (readOnly != shouldBeReadOnly)
  42753. {
  42754. readOnly = shouldBeReadOnly;
  42755. enablementChanged();
  42756. }
  42757. }
  42758. bool TextEditor::isReadOnly() const
  42759. {
  42760. return readOnly || ! isEnabled();
  42761. }
  42762. bool TextEditor::isTextInputActive() const
  42763. {
  42764. return ! isReadOnly();
  42765. }
  42766. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42767. {
  42768. returnKeyStartsNewLine = shouldStartNewLine;
  42769. }
  42770. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42771. {
  42772. tabKeyUsed = shouldTabKeyBeUsed;
  42773. }
  42774. void TextEditor::setPopupMenuEnabled (const bool b)
  42775. {
  42776. popupMenuEnabled = b;
  42777. }
  42778. void TextEditor::setSelectAllWhenFocused (const bool b)
  42779. {
  42780. selectAllTextWhenFocused = b;
  42781. }
  42782. const Font TextEditor::getFont() const
  42783. {
  42784. return currentFont;
  42785. }
  42786. void TextEditor::setFont (const Font& newFont)
  42787. {
  42788. currentFont = newFont;
  42789. scrollToMakeSureCursorIsVisible();
  42790. }
  42791. void TextEditor::applyFontToAllText (const Font& newFont)
  42792. {
  42793. currentFont = newFont;
  42794. const Colour overallColour (findColour (textColourId));
  42795. for (int i = sections.size(); --i >= 0;)
  42796. {
  42797. UniformTextSection* const uts = sections.getUnchecked (i);
  42798. uts->setFont (newFont, passwordCharacter);
  42799. uts->colour = overallColour;
  42800. }
  42801. coalesceSimilarSections();
  42802. updateTextHolderSize();
  42803. scrollToMakeSureCursorIsVisible();
  42804. repaint();
  42805. }
  42806. void TextEditor::colourChanged()
  42807. {
  42808. setOpaque (findColour (backgroundColourId).isOpaque());
  42809. repaint();
  42810. }
  42811. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42812. {
  42813. caretVisible = shouldCaretBeVisible;
  42814. if (shouldCaretBeVisible)
  42815. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42816. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42817. : MouseCursor::NormalCursor);
  42818. }
  42819. void TextEditor::setInputRestrictions (const int maxLen,
  42820. const String& chars)
  42821. {
  42822. maxTextLength = jmax (0, maxLen);
  42823. allowedCharacters = chars;
  42824. }
  42825. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42826. {
  42827. textToShowWhenEmpty = text;
  42828. colourForTextWhenEmpty = colourToUse;
  42829. }
  42830. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42831. {
  42832. if (passwordCharacter != newPasswordCharacter)
  42833. {
  42834. passwordCharacter = newPasswordCharacter;
  42835. resized();
  42836. repaint();
  42837. }
  42838. }
  42839. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42840. {
  42841. viewport->setScrollBarThickness (newThicknessPixels);
  42842. }
  42843. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42844. {
  42845. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42846. }
  42847. void TextEditor::clear()
  42848. {
  42849. clearInternal (0);
  42850. updateTextHolderSize();
  42851. undoManager.clearUndoHistory();
  42852. }
  42853. void TextEditor::setText (const String& newText,
  42854. const bool sendTextChangeMessage)
  42855. {
  42856. const int newLength = newText.length();
  42857. if (newLength != getTotalNumChars() || getText() != newText)
  42858. {
  42859. const int oldCursorPos = caretPosition;
  42860. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42861. clearInternal (0);
  42862. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42863. // if you're adding text with line-feeds to a single-line text editor, it
  42864. // ain't gonna look right!
  42865. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42866. if (cursorWasAtEnd && ! isMultiLine())
  42867. moveCursorTo (getTotalNumChars(), false);
  42868. else
  42869. moveCursorTo (oldCursorPos, false);
  42870. if (sendTextChangeMessage)
  42871. textChanged();
  42872. updateTextHolderSize();
  42873. scrollToMakeSureCursorIsVisible();
  42874. undoManager.clearUndoHistory();
  42875. repaint();
  42876. }
  42877. }
  42878. Value& TextEditor::getTextValue()
  42879. {
  42880. if (valueTextNeedsUpdating)
  42881. {
  42882. valueTextNeedsUpdating = false;
  42883. textValue = getText();
  42884. }
  42885. return textValue;
  42886. }
  42887. void TextEditor::textWasChangedByValue()
  42888. {
  42889. if (textValue.getValueSource().getReferenceCount() > 1)
  42890. setText (textValue.getValue());
  42891. }
  42892. void TextEditor::textChanged()
  42893. {
  42894. updateTextHolderSize();
  42895. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42896. if (textValue.getValueSource().getReferenceCount() > 1)
  42897. {
  42898. valueTextNeedsUpdating = false;
  42899. textValue = getText();
  42900. }
  42901. }
  42902. void TextEditor::returnPressed()
  42903. {
  42904. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42905. }
  42906. void TextEditor::escapePressed()
  42907. {
  42908. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42909. }
  42910. void TextEditor::addListener (TextEditorListener* const newListener)
  42911. {
  42912. listeners.add (newListener);
  42913. }
  42914. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42915. {
  42916. listeners.remove (listenerToRemove);
  42917. }
  42918. void TextEditor::timerCallbackInt()
  42919. {
  42920. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42921. if (caretFlashState != newState)
  42922. {
  42923. caretFlashState = newState;
  42924. if (caretFlashState)
  42925. wasFocused = true;
  42926. if (caretVisible
  42927. && hasKeyboardFocus (false)
  42928. && ! isReadOnly())
  42929. {
  42930. repaintCaret();
  42931. }
  42932. }
  42933. const unsigned int now = Time::getApproximateMillisecondCounter();
  42934. if (now > lastTransactionTime + 200)
  42935. newTransaction();
  42936. }
  42937. void TextEditor::repaintCaret()
  42938. {
  42939. if (! findColour (caretColourId).isTransparent())
  42940. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42941. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42942. 4,
  42943. roundToInt (cursorHeight) + 2);
  42944. }
  42945. void TextEditor::repaintText (const Range<int>& range)
  42946. {
  42947. if (! range.isEmpty())
  42948. {
  42949. float x = 0, y = 0, lh = currentFont.getHeight();
  42950. const float wordWrapWidth = getWordWrapWidth();
  42951. if (wordWrapWidth > 0)
  42952. {
  42953. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42954. i.getCharPosition (range.getStart(), x, y, lh);
  42955. const int y1 = (int) y;
  42956. int y2;
  42957. if (range.getEnd() >= getTotalNumChars())
  42958. {
  42959. y2 = textHolder->getHeight();
  42960. }
  42961. else
  42962. {
  42963. i.getCharPosition (range.getEnd(), x, y, lh);
  42964. y2 = (int) (y + lh * 2.0f);
  42965. }
  42966. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42967. }
  42968. }
  42969. }
  42970. void TextEditor::moveCaret (int newCaretPos)
  42971. {
  42972. if (newCaretPos < 0)
  42973. newCaretPos = 0;
  42974. else if (newCaretPos > getTotalNumChars())
  42975. newCaretPos = getTotalNumChars();
  42976. if (newCaretPos != getCaretPosition())
  42977. {
  42978. repaintCaret();
  42979. caretFlashState = true;
  42980. caretPosition = newCaretPos;
  42981. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42982. scrollToMakeSureCursorIsVisible();
  42983. repaintCaret();
  42984. }
  42985. }
  42986. void TextEditor::setCaretPosition (const int newIndex)
  42987. {
  42988. moveCursorTo (newIndex, false);
  42989. }
  42990. int TextEditor::getCaretPosition() const
  42991. {
  42992. return caretPosition;
  42993. }
  42994. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42995. const int desiredCaretY)
  42996. {
  42997. updateCaretPosition();
  42998. int vx = roundToInt (cursorX) - desiredCaretX;
  42999. int vy = roundToInt (cursorY) - desiredCaretY;
  43000. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43001. {
  43002. vx += desiredCaretX - proportionOfWidth (0.2f);
  43003. }
  43004. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43005. {
  43006. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43007. }
  43008. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43009. if (! isMultiLine())
  43010. {
  43011. vy = viewport->getViewPositionY();
  43012. }
  43013. else
  43014. {
  43015. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43016. const int curH = roundToInt (cursorHeight);
  43017. if (desiredCaretY < 0)
  43018. {
  43019. vy = jmax (0, desiredCaretY + vy);
  43020. }
  43021. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43022. {
  43023. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43024. }
  43025. }
  43026. viewport->setViewPosition (vx, vy);
  43027. }
  43028. const Rectangle<int> TextEditor::getCaretRectangle()
  43029. {
  43030. updateCaretPosition();
  43031. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43032. roundToInt (cursorY) - viewport->getY(),
  43033. 1, roundToInt (cursorHeight));
  43034. }
  43035. float TextEditor::getWordWrapWidth() const
  43036. {
  43037. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43038. : 1.0e10f;
  43039. }
  43040. void TextEditor::updateTextHolderSize()
  43041. {
  43042. const float wordWrapWidth = getWordWrapWidth();
  43043. if (wordWrapWidth > 0)
  43044. {
  43045. float maxWidth = 0.0f;
  43046. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43047. while (i.next())
  43048. maxWidth = jmax (maxWidth, i.atomRight);
  43049. const int w = leftIndent + roundToInt (maxWidth);
  43050. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43051. currentFont.getHeight()));
  43052. textHolder->setSize (w + 1, h + 1);
  43053. }
  43054. }
  43055. int TextEditor::getTextWidth() const
  43056. {
  43057. return textHolder->getWidth();
  43058. }
  43059. int TextEditor::getTextHeight() const
  43060. {
  43061. return textHolder->getHeight();
  43062. }
  43063. void TextEditor::setIndents (const int newLeftIndent,
  43064. const int newTopIndent)
  43065. {
  43066. leftIndent = newLeftIndent;
  43067. topIndent = newTopIndent;
  43068. }
  43069. void TextEditor::setBorder (const BorderSize<int>& border)
  43070. {
  43071. borderSize = border;
  43072. resized();
  43073. }
  43074. const BorderSize<int> TextEditor::getBorder() const
  43075. {
  43076. return borderSize;
  43077. }
  43078. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43079. {
  43080. keepCursorOnScreen = shouldScrollToShowCursor;
  43081. }
  43082. void TextEditor::updateCaretPosition()
  43083. {
  43084. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43085. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43086. }
  43087. void TextEditor::scrollToMakeSureCursorIsVisible()
  43088. {
  43089. updateCaretPosition();
  43090. if (keepCursorOnScreen)
  43091. {
  43092. int x = viewport->getViewPositionX();
  43093. int y = viewport->getViewPositionY();
  43094. const int relativeCursorX = roundToInt (cursorX) - x;
  43095. const int relativeCursorY = roundToInt (cursorY) - y;
  43096. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43097. {
  43098. x += relativeCursorX - proportionOfWidth (0.2f);
  43099. }
  43100. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43101. {
  43102. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43103. }
  43104. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43105. if (! isMultiLine())
  43106. {
  43107. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43108. }
  43109. else
  43110. {
  43111. const int curH = roundToInt (cursorHeight);
  43112. if (relativeCursorY < 0)
  43113. {
  43114. y = jmax (0, relativeCursorY + y);
  43115. }
  43116. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43117. {
  43118. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43119. }
  43120. }
  43121. viewport->setViewPosition (x, y);
  43122. }
  43123. }
  43124. void TextEditor::moveCursorTo (const int newPosition,
  43125. const bool isSelecting)
  43126. {
  43127. if (isSelecting)
  43128. {
  43129. moveCaret (newPosition);
  43130. const Range<int> oldSelection (selection);
  43131. if (dragType == notDragging)
  43132. {
  43133. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43134. dragType = draggingSelectionStart;
  43135. else
  43136. dragType = draggingSelectionEnd;
  43137. }
  43138. if (dragType == draggingSelectionStart)
  43139. {
  43140. if (getCaretPosition() >= selection.getEnd())
  43141. dragType = draggingSelectionEnd;
  43142. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43143. }
  43144. else
  43145. {
  43146. if (getCaretPosition() < selection.getStart())
  43147. dragType = draggingSelectionStart;
  43148. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43149. }
  43150. repaintText (selection.getUnionWith (oldSelection));
  43151. }
  43152. else
  43153. {
  43154. dragType = notDragging;
  43155. repaintText (selection);
  43156. moveCaret (newPosition);
  43157. selection = Range<int>::emptyRange (getCaretPosition());
  43158. }
  43159. }
  43160. int TextEditor::getTextIndexAt (const int x,
  43161. const int y)
  43162. {
  43163. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43164. (float) (y + viewport->getViewPositionY() - topIndent));
  43165. }
  43166. void TextEditor::insertTextAtCaret (const String& newText_)
  43167. {
  43168. String newText (newText_);
  43169. if (allowedCharacters.isNotEmpty())
  43170. newText = newText.retainCharacters (allowedCharacters);
  43171. if (! isMultiLine())
  43172. newText = newText.replaceCharacters ("\r\n", " ");
  43173. else
  43174. newText = newText.replace ("\r\n", "\n");
  43175. const int newCaretPos = selection.getStart() + newText.length();
  43176. const int insertIndex = selection.getStart();
  43177. remove (selection, getUndoManager(),
  43178. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43179. if (maxTextLength > 0)
  43180. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43181. if (newText.isNotEmpty())
  43182. insert (newText,
  43183. insertIndex,
  43184. currentFont,
  43185. findColour (textColourId),
  43186. getUndoManager(),
  43187. newCaretPos);
  43188. textChanged();
  43189. }
  43190. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43191. {
  43192. moveCursorTo (newSelection.getStart(), false);
  43193. moveCursorTo (newSelection.getEnd(), true);
  43194. }
  43195. void TextEditor::copy()
  43196. {
  43197. if (passwordCharacter == 0)
  43198. {
  43199. const String selectedText (getHighlightedText());
  43200. if (selectedText.isNotEmpty())
  43201. SystemClipboard::copyTextToClipboard (selectedText);
  43202. }
  43203. }
  43204. void TextEditor::paste()
  43205. {
  43206. if (! isReadOnly())
  43207. {
  43208. const String clip (SystemClipboard::getTextFromClipboard());
  43209. if (clip.isNotEmpty())
  43210. insertTextAtCaret (clip);
  43211. }
  43212. }
  43213. void TextEditor::cut()
  43214. {
  43215. if (! isReadOnly())
  43216. {
  43217. moveCaret (selection.getEnd());
  43218. insertTextAtCaret (String::empty);
  43219. }
  43220. }
  43221. void TextEditor::drawContent (Graphics& g)
  43222. {
  43223. const float wordWrapWidth = getWordWrapWidth();
  43224. if (wordWrapWidth > 0)
  43225. {
  43226. g.setOrigin (leftIndent, topIndent);
  43227. const Rectangle<int> clip (g.getClipBounds());
  43228. Colour selectedTextColour;
  43229. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43230. while (i.lineY + 200.0 < clip.getY() && i.next())
  43231. {}
  43232. if (! selection.isEmpty())
  43233. {
  43234. g.setColour (findColour (highlightColourId)
  43235. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43236. selectedTextColour = findColour (highlightedTextColourId);
  43237. Iterator i2 (i);
  43238. while (i2.next() && i2.lineY < clip.getBottom())
  43239. {
  43240. if (i2.lineY + i2.lineHeight >= clip.getY()
  43241. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43242. {
  43243. i2.drawSelection (g, selection);
  43244. }
  43245. }
  43246. }
  43247. const UniformTextSection* lastSection = 0;
  43248. while (i.next() && i.lineY < clip.getBottom())
  43249. {
  43250. if (i.lineY + i.lineHeight >= clip.getY())
  43251. {
  43252. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43253. {
  43254. i.drawSelectedText (g, selection, selectedTextColour);
  43255. lastSection = 0;
  43256. }
  43257. else
  43258. {
  43259. i.draw (g, lastSection);
  43260. }
  43261. }
  43262. }
  43263. }
  43264. }
  43265. void TextEditor::paint (Graphics& g)
  43266. {
  43267. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43268. }
  43269. void TextEditor::paintOverChildren (Graphics& g)
  43270. {
  43271. if (caretFlashState
  43272. && hasKeyboardFocus (false)
  43273. && caretVisible
  43274. && ! isReadOnly())
  43275. {
  43276. g.setColour (findColour (caretColourId));
  43277. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43278. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43279. 2.0f, cursorHeight);
  43280. }
  43281. if (textToShowWhenEmpty.isNotEmpty()
  43282. && (! hasKeyboardFocus (false))
  43283. && getTotalNumChars() == 0)
  43284. {
  43285. g.setColour (colourForTextWhenEmpty);
  43286. g.setFont (getFont());
  43287. if (isMultiLine())
  43288. {
  43289. g.drawText (textToShowWhenEmpty,
  43290. 0, 0, getWidth(), getHeight(),
  43291. Justification::centred, true);
  43292. }
  43293. else
  43294. {
  43295. g.drawText (textToShowWhenEmpty,
  43296. leftIndent, topIndent,
  43297. viewport->getWidth() - leftIndent,
  43298. viewport->getHeight() - topIndent,
  43299. Justification::centredLeft, true);
  43300. }
  43301. }
  43302. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43303. }
  43304. static void textEditorMenuCallback (int menuResult, TextEditor* editor)
  43305. {
  43306. if (editor != 0 && menuResult != 0)
  43307. editor->performPopupMenuAction (menuResult);
  43308. }
  43309. void TextEditor::mouseDown (const MouseEvent& e)
  43310. {
  43311. beginDragAutoRepeat (100);
  43312. newTransaction();
  43313. if (wasFocused || ! selectAllTextWhenFocused)
  43314. {
  43315. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43316. {
  43317. moveCursorTo (getTextIndexAt (e.x, e.y),
  43318. e.mods.isShiftDown());
  43319. }
  43320. else
  43321. {
  43322. PopupMenu m;
  43323. m.setLookAndFeel (&getLookAndFeel());
  43324. addPopupMenuItems (m, &e);
  43325. m.showMenuAsync (PopupMenu::Options(),
  43326. ModalCallbackFunction::forComponent (textEditorMenuCallback, this));
  43327. }
  43328. }
  43329. }
  43330. void TextEditor::mouseDrag (const MouseEvent& e)
  43331. {
  43332. if (wasFocused || ! selectAllTextWhenFocused)
  43333. {
  43334. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43335. {
  43336. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43337. }
  43338. }
  43339. }
  43340. void TextEditor::mouseUp (const MouseEvent& e)
  43341. {
  43342. newTransaction();
  43343. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43344. if (wasFocused || ! selectAllTextWhenFocused)
  43345. {
  43346. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43347. {
  43348. moveCaret (getTextIndexAt (e.x, e.y));
  43349. }
  43350. }
  43351. wasFocused = true;
  43352. }
  43353. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43354. {
  43355. int tokenEnd = getTextIndexAt (e.x, e.y);
  43356. int tokenStart = tokenEnd;
  43357. if (e.getNumberOfClicks() > 3)
  43358. {
  43359. tokenStart = 0;
  43360. tokenEnd = getTotalNumChars();
  43361. }
  43362. else
  43363. {
  43364. const String t (getText());
  43365. const int totalLength = getTotalNumChars();
  43366. while (tokenEnd < totalLength)
  43367. {
  43368. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43369. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43370. ++tokenEnd;
  43371. else
  43372. break;
  43373. }
  43374. tokenStart = tokenEnd;
  43375. while (tokenStart > 0)
  43376. {
  43377. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43378. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43379. --tokenStart;
  43380. else
  43381. break;
  43382. }
  43383. if (e.getNumberOfClicks() > 2)
  43384. {
  43385. while (tokenEnd < totalLength)
  43386. {
  43387. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43388. ++tokenEnd;
  43389. else
  43390. break;
  43391. }
  43392. while (tokenStart > 0)
  43393. {
  43394. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43395. --tokenStart;
  43396. else
  43397. break;
  43398. }
  43399. }
  43400. }
  43401. moveCursorTo (tokenEnd, false);
  43402. moveCursorTo (tokenStart, true);
  43403. }
  43404. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43405. {
  43406. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43407. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43408. }
  43409. bool TextEditor::keyPressed (const KeyPress& key)
  43410. {
  43411. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43412. return false;
  43413. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43414. if (key.isKeyCode (KeyPress::leftKey)
  43415. || key.isKeyCode (KeyPress::upKey))
  43416. {
  43417. newTransaction();
  43418. int newPos;
  43419. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43420. newPos = indexAtPosition (cursorX, cursorY - 1);
  43421. else if (moveInWholeWordSteps)
  43422. newPos = findWordBreakBefore (getCaretPosition());
  43423. else
  43424. newPos = getCaretPosition() - 1;
  43425. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43426. }
  43427. else if (key.isKeyCode (KeyPress::rightKey)
  43428. || key.isKeyCode (KeyPress::downKey))
  43429. {
  43430. newTransaction();
  43431. int newPos;
  43432. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43433. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43434. else if (moveInWholeWordSteps)
  43435. newPos = findWordBreakAfter (getCaretPosition());
  43436. else
  43437. newPos = getCaretPosition() + 1;
  43438. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43439. }
  43440. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43441. {
  43442. newTransaction();
  43443. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43444. key.getModifiers().isShiftDown());
  43445. }
  43446. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43447. {
  43448. newTransaction();
  43449. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43450. key.getModifiers().isShiftDown());
  43451. }
  43452. else if (key.isKeyCode (KeyPress::homeKey))
  43453. {
  43454. newTransaction();
  43455. if (isMultiLine() && ! moveInWholeWordSteps)
  43456. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43457. key.getModifiers().isShiftDown());
  43458. else
  43459. moveCursorTo (0, key.getModifiers().isShiftDown());
  43460. }
  43461. else if (key.isKeyCode (KeyPress::endKey))
  43462. {
  43463. newTransaction();
  43464. if (isMultiLine() && ! moveInWholeWordSteps)
  43465. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43466. key.getModifiers().isShiftDown());
  43467. else
  43468. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43469. }
  43470. else if (key.isKeyCode (KeyPress::backspaceKey))
  43471. {
  43472. if (moveInWholeWordSteps)
  43473. {
  43474. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43475. }
  43476. else
  43477. {
  43478. if (selection.isEmpty() && selection.getStart() > 0)
  43479. selection.setStart (selection.getEnd() - 1);
  43480. }
  43481. cut();
  43482. }
  43483. else if (key.isKeyCode (KeyPress::deleteKey))
  43484. {
  43485. if (key.getModifiers().isShiftDown())
  43486. copy();
  43487. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43488. selection.setEnd (selection.getStart() + 1);
  43489. cut();
  43490. }
  43491. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43492. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43493. {
  43494. newTransaction();
  43495. copy();
  43496. }
  43497. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43498. {
  43499. newTransaction();
  43500. copy();
  43501. cut();
  43502. }
  43503. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43504. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43505. {
  43506. newTransaction();
  43507. paste();
  43508. }
  43509. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43510. {
  43511. newTransaction();
  43512. doUndoRedo (false);
  43513. }
  43514. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43515. {
  43516. newTransaction();
  43517. doUndoRedo (true);
  43518. }
  43519. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43520. {
  43521. newTransaction();
  43522. moveCursorTo (getTotalNumChars(), false);
  43523. moveCursorTo (0, true);
  43524. }
  43525. else if (key == KeyPress::returnKey)
  43526. {
  43527. newTransaction();
  43528. if (returnKeyStartsNewLine)
  43529. insertTextAtCaret ("\n");
  43530. else
  43531. returnPressed();
  43532. }
  43533. else if (key.isKeyCode (KeyPress::escapeKey))
  43534. {
  43535. newTransaction();
  43536. moveCursorTo (getCaretPosition(), false);
  43537. escapePressed();
  43538. }
  43539. else if (key.getTextCharacter() >= ' '
  43540. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43541. {
  43542. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43543. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43544. }
  43545. else
  43546. {
  43547. return false;
  43548. }
  43549. return true;
  43550. }
  43551. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43552. {
  43553. if (! isKeyDown)
  43554. return false;
  43555. #if JUCE_WINDOWS
  43556. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43557. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43558. #endif
  43559. // (overridden to avoid forwarding key events to the parent)
  43560. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43561. }
  43562. const int baseMenuItemID = 0x7fff0000;
  43563. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43564. {
  43565. const bool writable = ! isReadOnly();
  43566. if (passwordCharacter == 0)
  43567. {
  43568. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43569. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43570. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43571. }
  43572. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43573. m.addSeparator();
  43574. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43575. m.addSeparator();
  43576. if (getUndoManager() != 0)
  43577. {
  43578. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43579. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43580. }
  43581. }
  43582. void TextEditor::performPopupMenuAction (const int menuItemID)
  43583. {
  43584. switch (menuItemID)
  43585. {
  43586. case baseMenuItemID + 1:
  43587. copy();
  43588. cut();
  43589. break;
  43590. case baseMenuItemID + 2:
  43591. copy();
  43592. break;
  43593. case baseMenuItemID + 3:
  43594. paste();
  43595. break;
  43596. case baseMenuItemID + 4:
  43597. cut();
  43598. break;
  43599. case baseMenuItemID + 5:
  43600. moveCursorTo (getTotalNumChars(), false);
  43601. moveCursorTo (0, true);
  43602. break;
  43603. case baseMenuItemID + 6:
  43604. doUndoRedo (false);
  43605. break;
  43606. case baseMenuItemID + 7:
  43607. doUndoRedo (true);
  43608. break;
  43609. default:
  43610. break;
  43611. }
  43612. }
  43613. void TextEditor::focusGained (FocusChangeType)
  43614. {
  43615. newTransaction();
  43616. caretFlashState = true;
  43617. if (selectAllTextWhenFocused)
  43618. {
  43619. moveCursorTo (0, false);
  43620. moveCursorTo (getTotalNumChars(), true);
  43621. }
  43622. repaint();
  43623. if (caretVisible)
  43624. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43625. ComponentPeer* const peer = getPeer();
  43626. if (peer != 0 && ! isReadOnly())
  43627. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43628. }
  43629. void TextEditor::focusLost (FocusChangeType)
  43630. {
  43631. newTransaction();
  43632. wasFocused = false;
  43633. textHolder->stopTimer();
  43634. caretFlashState = false;
  43635. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43636. repaint();
  43637. }
  43638. void TextEditor::resized()
  43639. {
  43640. viewport->setBoundsInset (borderSize);
  43641. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43642. updateTextHolderSize();
  43643. if (! isMultiLine())
  43644. {
  43645. scrollToMakeSureCursorIsVisible();
  43646. }
  43647. else
  43648. {
  43649. updateCaretPosition();
  43650. }
  43651. }
  43652. void TextEditor::handleCommandMessage (const int commandId)
  43653. {
  43654. Component::BailOutChecker checker (this);
  43655. switch (commandId)
  43656. {
  43657. case TextEditorDefs::textChangeMessageId:
  43658. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43659. break;
  43660. case TextEditorDefs::returnKeyMessageId:
  43661. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43662. break;
  43663. case TextEditorDefs::escapeKeyMessageId:
  43664. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43665. break;
  43666. case TextEditorDefs::focusLossMessageId:
  43667. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43668. break;
  43669. default:
  43670. jassertfalse;
  43671. break;
  43672. }
  43673. }
  43674. void TextEditor::enablementChanged()
  43675. {
  43676. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43677. : MouseCursor::IBeamCursor);
  43678. repaint();
  43679. }
  43680. UndoManager* TextEditor::getUndoManager() throw()
  43681. {
  43682. return isReadOnly() ? 0 : &undoManager;
  43683. }
  43684. void TextEditor::clearInternal (UndoManager* const um)
  43685. {
  43686. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43687. }
  43688. void TextEditor::insert (const String& text,
  43689. const int insertIndex,
  43690. const Font& font,
  43691. const Colour& colour,
  43692. UndoManager* const um,
  43693. const int caretPositionToMoveTo)
  43694. {
  43695. if (text.isNotEmpty())
  43696. {
  43697. if (um != 0)
  43698. {
  43699. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43700. newTransaction();
  43701. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43702. caretPosition, caretPositionToMoveTo));
  43703. }
  43704. else
  43705. {
  43706. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43707. // a line gets moved due to word wrap
  43708. int index = 0;
  43709. int nextIndex = 0;
  43710. for (int i = 0; i < sections.size(); ++i)
  43711. {
  43712. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43713. if (insertIndex == index)
  43714. {
  43715. sections.insert (i, new UniformTextSection (text,
  43716. font, colour,
  43717. passwordCharacter));
  43718. break;
  43719. }
  43720. else if (insertIndex > index && insertIndex < nextIndex)
  43721. {
  43722. splitSection (i, insertIndex - index);
  43723. sections.insert (i + 1, new UniformTextSection (text,
  43724. font, colour,
  43725. passwordCharacter));
  43726. break;
  43727. }
  43728. index = nextIndex;
  43729. }
  43730. if (nextIndex == insertIndex)
  43731. sections.add (new UniformTextSection (text,
  43732. font, colour,
  43733. passwordCharacter));
  43734. coalesceSimilarSections();
  43735. totalNumChars = -1;
  43736. valueTextNeedsUpdating = true;
  43737. moveCursorTo (caretPositionToMoveTo, false);
  43738. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43739. }
  43740. }
  43741. }
  43742. void TextEditor::reinsert (const int insertIndex,
  43743. const Array <UniformTextSection*>& sectionsToInsert)
  43744. {
  43745. int index = 0;
  43746. int nextIndex = 0;
  43747. for (int i = 0; i < sections.size(); ++i)
  43748. {
  43749. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43750. if (insertIndex == index)
  43751. {
  43752. for (int j = sectionsToInsert.size(); --j >= 0;)
  43753. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43754. break;
  43755. }
  43756. else if (insertIndex > index && insertIndex < nextIndex)
  43757. {
  43758. splitSection (i, insertIndex - index);
  43759. for (int j = sectionsToInsert.size(); --j >= 0;)
  43760. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43761. break;
  43762. }
  43763. index = nextIndex;
  43764. }
  43765. if (nextIndex == insertIndex)
  43766. {
  43767. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43768. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43769. }
  43770. coalesceSimilarSections();
  43771. totalNumChars = -1;
  43772. valueTextNeedsUpdating = true;
  43773. }
  43774. void TextEditor::remove (const Range<int>& range,
  43775. UndoManager* const um,
  43776. const int caretPositionToMoveTo)
  43777. {
  43778. if (! range.isEmpty())
  43779. {
  43780. int index = 0;
  43781. for (int i = 0; i < sections.size(); ++i)
  43782. {
  43783. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43784. if (range.getStart() > index && range.getStart() < nextIndex)
  43785. {
  43786. splitSection (i, range.getStart() - index);
  43787. --i;
  43788. }
  43789. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43790. {
  43791. splitSection (i, range.getEnd() - index);
  43792. --i;
  43793. }
  43794. else
  43795. {
  43796. index = nextIndex;
  43797. if (index > range.getEnd())
  43798. break;
  43799. }
  43800. }
  43801. index = 0;
  43802. if (um != 0)
  43803. {
  43804. Array <UniformTextSection*> removedSections;
  43805. for (int i = 0; i < sections.size(); ++i)
  43806. {
  43807. if (range.getEnd() <= range.getStart())
  43808. break;
  43809. UniformTextSection* const section = sections.getUnchecked (i);
  43810. const int nextIndex = index + section->getTotalLength();
  43811. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43812. removedSections.add (new UniformTextSection (*section));
  43813. index = nextIndex;
  43814. }
  43815. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43816. newTransaction();
  43817. um->perform (new RemoveAction (*this, range, caretPosition,
  43818. caretPositionToMoveTo, removedSections));
  43819. }
  43820. else
  43821. {
  43822. Range<int> remainingRange (range);
  43823. for (int i = 0; i < sections.size(); ++i)
  43824. {
  43825. UniformTextSection* const section = sections.getUnchecked (i);
  43826. const int nextIndex = index + section->getTotalLength();
  43827. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43828. {
  43829. sections.remove(i);
  43830. section->clear();
  43831. delete section;
  43832. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43833. if (remainingRange.isEmpty())
  43834. break;
  43835. --i;
  43836. }
  43837. else
  43838. {
  43839. index = nextIndex;
  43840. }
  43841. }
  43842. coalesceSimilarSections();
  43843. totalNumChars = -1;
  43844. valueTextNeedsUpdating = true;
  43845. moveCursorTo (caretPositionToMoveTo, false);
  43846. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43847. }
  43848. }
  43849. }
  43850. const String TextEditor::getText() const
  43851. {
  43852. String t;
  43853. t.preallocateStorage (getTotalNumChars());
  43854. String::Concatenator concatenator (t);
  43855. for (int i = 0; i < sections.size(); ++i)
  43856. sections.getUnchecked (i)->appendAllText (concatenator);
  43857. return t;
  43858. }
  43859. const String TextEditor::getTextInRange (const Range<int>& range) const
  43860. {
  43861. String t;
  43862. if (! range.isEmpty())
  43863. {
  43864. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43865. String::Concatenator concatenator (t);
  43866. int index = 0;
  43867. for (int i = 0; i < sections.size(); ++i)
  43868. {
  43869. const UniformTextSection* const s = sections.getUnchecked (i);
  43870. const int nextIndex = index + s->getTotalLength();
  43871. if (range.getStart() < nextIndex)
  43872. {
  43873. if (range.getEnd() <= index)
  43874. break;
  43875. s->appendSubstring (concatenator, range - index);
  43876. }
  43877. index = nextIndex;
  43878. }
  43879. }
  43880. return t;
  43881. }
  43882. const String TextEditor::getHighlightedText() const
  43883. {
  43884. return getTextInRange (selection);
  43885. }
  43886. int TextEditor::getTotalNumChars() const
  43887. {
  43888. if (totalNumChars < 0)
  43889. {
  43890. totalNumChars = 0;
  43891. for (int i = sections.size(); --i >= 0;)
  43892. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43893. }
  43894. return totalNumChars;
  43895. }
  43896. bool TextEditor::isEmpty() const
  43897. {
  43898. return getTotalNumChars() == 0;
  43899. }
  43900. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43901. {
  43902. const float wordWrapWidth = getWordWrapWidth();
  43903. if (wordWrapWidth > 0 && sections.size() > 0)
  43904. {
  43905. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43906. i.getCharPosition (index, cx, cy, lineHeight);
  43907. }
  43908. else
  43909. {
  43910. cx = cy = 0;
  43911. lineHeight = currentFont.getHeight();
  43912. }
  43913. }
  43914. int TextEditor::indexAtPosition (const float x, const float y)
  43915. {
  43916. const float wordWrapWidth = getWordWrapWidth();
  43917. if (wordWrapWidth > 0)
  43918. {
  43919. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43920. while (i.next())
  43921. {
  43922. if (i.lineY + i.lineHeight > y)
  43923. {
  43924. if (i.lineY > y)
  43925. return jmax (0, i.indexInText - 1);
  43926. if (i.atomX >= x)
  43927. return i.indexInText;
  43928. if (x < i.atomRight)
  43929. return i.xToIndex (x);
  43930. }
  43931. }
  43932. }
  43933. return getTotalNumChars();
  43934. }
  43935. int TextEditor::findWordBreakAfter (const int position) const
  43936. {
  43937. const String t (getTextInRange (Range<int> (position, position + 512)));
  43938. const int totalLength = t.length();
  43939. int i = 0;
  43940. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43941. ++i;
  43942. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43943. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43944. ++i;
  43945. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43946. ++i;
  43947. return position + i;
  43948. }
  43949. int TextEditor::findWordBreakBefore (const int position) const
  43950. {
  43951. if (position <= 0)
  43952. return 0;
  43953. const int startOfBuffer = jmax (0, position - 512);
  43954. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43955. int i = position - startOfBuffer;
  43956. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43957. --i;
  43958. if (i > 0)
  43959. {
  43960. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43961. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43962. --i;
  43963. }
  43964. jassert (startOfBuffer + i >= 0);
  43965. return startOfBuffer + i;
  43966. }
  43967. void TextEditor::splitSection (const int sectionIndex,
  43968. const int charToSplitAt)
  43969. {
  43970. jassert (sections[sectionIndex] != 0);
  43971. sections.insert (sectionIndex + 1,
  43972. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43973. }
  43974. void TextEditor::coalesceSimilarSections()
  43975. {
  43976. for (int i = 0; i < sections.size() - 1; ++i)
  43977. {
  43978. UniformTextSection* const s1 = sections.getUnchecked (i);
  43979. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43980. if (s1->font == s2->font
  43981. && s1->colour == s2->colour)
  43982. {
  43983. s1->append (*s2, passwordCharacter);
  43984. sections.remove (i + 1);
  43985. delete s2;
  43986. --i;
  43987. }
  43988. }
  43989. }
  43990. void TextEditor::Listener::textEditorTextChanged (TextEditor&) {}
  43991. void TextEditor::Listener::textEditorReturnKeyPressed (TextEditor&) {}
  43992. void TextEditor::Listener::textEditorEscapeKeyPressed (TextEditor&) {}
  43993. void TextEditor::Listener::textEditorFocusLost (TextEditor&) {}
  43994. END_JUCE_NAMESPACE
  43995. /*** End of inlined file: juce_TextEditor.cpp ***/
  43996. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43997. BEGIN_JUCE_NAMESPACE
  43998. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43999. class ToolbarSpacerComp : public ToolbarItemComponent
  44000. {
  44001. public:
  44002. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44003. : ToolbarItemComponent (itemId_, String::empty, false),
  44004. fixedSize (fixedSize_),
  44005. drawBar (drawBar_)
  44006. {
  44007. }
  44008. ~ToolbarSpacerComp()
  44009. {
  44010. }
  44011. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44012. int& preferredSize, int& minSize, int& maxSize)
  44013. {
  44014. if (fixedSize <= 0)
  44015. {
  44016. preferredSize = toolbarThickness * 2;
  44017. minSize = 4;
  44018. maxSize = 32768;
  44019. }
  44020. else
  44021. {
  44022. maxSize = roundToInt (toolbarThickness * fixedSize);
  44023. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44024. preferredSize = maxSize;
  44025. if (getEditingMode() == editableOnPalette)
  44026. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44027. }
  44028. return true;
  44029. }
  44030. void paintButtonArea (Graphics&, int, int, bool, bool)
  44031. {
  44032. }
  44033. void contentAreaChanged (const Rectangle<int>&)
  44034. {
  44035. }
  44036. int getResizeOrder() const throw()
  44037. {
  44038. return fixedSize <= 0 ? 0 : 1;
  44039. }
  44040. void paint (Graphics& g)
  44041. {
  44042. const int w = getWidth();
  44043. const int h = getHeight();
  44044. if (drawBar)
  44045. {
  44046. g.setColour (findColour (Toolbar::separatorColourId, true));
  44047. const float thickness = 0.2f;
  44048. if (isToolbarVertical())
  44049. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44050. else
  44051. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44052. }
  44053. if (getEditingMode() != normalMode && ! drawBar)
  44054. {
  44055. g.setColour (findColour (Toolbar::separatorColourId, true));
  44056. const int indentX = jmin (2, (w - 3) / 2);
  44057. const int indentY = jmin (2, (h - 3) / 2);
  44058. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44059. if (fixedSize <= 0)
  44060. {
  44061. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44062. if (isToolbarVertical())
  44063. {
  44064. x1 = w * 0.5f;
  44065. y1 = h * 0.4f;
  44066. x2 = x1;
  44067. y2 = indentX * 2.0f;
  44068. x3 = x1;
  44069. y3 = h * 0.6f;
  44070. x4 = x1;
  44071. y4 = h - y2;
  44072. hw = w * 0.15f;
  44073. hl = w * 0.2f;
  44074. }
  44075. else
  44076. {
  44077. x1 = w * 0.4f;
  44078. y1 = h * 0.5f;
  44079. x2 = indentX * 2.0f;
  44080. y2 = y1;
  44081. x3 = w * 0.6f;
  44082. y3 = y1;
  44083. x4 = w - x2;
  44084. y4 = y1;
  44085. hw = h * 0.15f;
  44086. hl = h * 0.2f;
  44087. }
  44088. Path p;
  44089. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44090. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44091. g.fillPath (p);
  44092. }
  44093. }
  44094. }
  44095. private:
  44096. const float fixedSize;
  44097. const bool drawBar;
  44098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44099. };
  44100. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  44101. {
  44102. public:
  44103. MissingItemsComponent (Toolbar& owner_, const int height_)
  44104. : PopupMenu::CustomComponent (true),
  44105. owner (&owner_),
  44106. height (height_)
  44107. {
  44108. for (int i = owner_.items.size(); --i >= 0;)
  44109. {
  44110. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44111. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44112. {
  44113. oldIndexes.insert (0, i);
  44114. addAndMakeVisible (tc, 0);
  44115. }
  44116. }
  44117. layout (400);
  44118. }
  44119. ~MissingItemsComponent()
  44120. {
  44121. if (owner != 0)
  44122. {
  44123. for (int i = 0; i < getNumChildComponents(); ++i)
  44124. {
  44125. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44126. if (tc != 0)
  44127. {
  44128. tc->setVisible (false);
  44129. const int index = oldIndexes.remove (i);
  44130. owner->addChildComponent (tc, index);
  44131. --i;
  44132. }
  44133. }
  44134. owner->resized();
  44135. }
  44136. }
  44137. void layout (const int preferredWidth)
  44138. {
  44139. const int indent = 8;
  44140. int x = indent;
  44141. int y = indent;
  44142. int maxX = 0;
  44143. for (int i = 0; i < getNumChildComponents(); ++i)
  44144. {
  44145. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44146. if (tc != 0)
  44147. {
  44148. int preferredSize = 1, minSize = 1, maxSize = 1;
  44149. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44150. {
  44151. if (x + preferredSize > preferredWidth && x > indent)
  44152. {
  44153. x = indent;
  44154. y += height;
  44155. }
  44156. tc->setBounds (x, y, preferredSize, height);
  44157. x += preferredSize;
  44158. maxX = jmax (maxX, x);
  44159. }
  44160. }
  44161. }
  44162. setSize (maxX + 8, y + height + 8);
  44163. }
  44164. void getIdealSize (int& idealWidth, int& idealHeight)
  44165. {
  44166. idealWidth = getWidth();
  44167. idealHeight = getHeight();
  44168. }
  44169. private:
  44170. Component::SafePointer<Toolbar> owner;
  44171. const int height;
  44172. Array <int> oldIndexes;
  44173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44174. };
  44175. Toolbar::Toolbar()
  44176. : vertical (false),
  44177. isEditingActive (false),
  44178. toolbarStyle (Toolbar::iconsOnly)
  44179. {
  44180. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44181. missingItemsButton->setAlwaysOnTop (true);
  44182. missingItemsButton->addListener (this);
  44183. }
  44184. Toolbar::~Toolbar()
  44185. {
  44186. items.clear();
  44187. }
  44188. void Toolbar::setVertical (const bool shouldBeVertical)
  44189. {
  44190. if (vertical != shouldBeVertical)
  44191. {
  44192. vertical = shouldBeVertical;
  44193. resized();
  44194. }
  44195. }
  44196. void Toolbar::clear()
  44197. {
  44198. items.clear();
  44199. resized();
  44200. }
  44201. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44202. {
  44203. if (itemId == ToolbarItemFactory::separatorBarId)
  44204. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44205. else if (itemId == ToolbarItemFactory::spacerId)
  44206. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44207. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44208. return new ToolbarSpacerComp (itemId, 0, false);
  44209. return factory.createItem (itemId);
  44210. }
  44211. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44212. const int itemId,
  44213. const int insertIndex)
  44214. {
  44215. // An ID can't be zero - this might indicate a mistake somewhere?
  44216. jassert (itemId != 0);
  44217. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44218. if (tc != 0)
  44219. {
  44220. #if JUCE_DEBUG
  44221. Array <int> allowedIds;
  44222. factory.getAllToolbarItemIds (allowedIds);
  44223. // If your factory can create an item for a given ID, it must also return
  44224. // that ID from its getAllToolbarItemIds() method!
  44225. jassert (allowedIds.contains (itemId));
  44226. #endif
  44227. items.insert (insertIndex, tc);
  44228. addAndMakeVisible (tc, insertIndex);
  44229. }
  44230. }
  44231. void Toolbar::addItem (ToolbarItemFactory& factory,
  44232. const int itemId,
  44233. const int insertIndex)
  44234. {
  44235. addItemInternal (factory, itemId, insertIndex);
  44236. resized();
  44237. }
  44238. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44239. {
  44240. Array <int> ids;
  44241. factoryToUse.getDefaultItemSet (ids);
  44242. clear();
  44243. for (int i = 0; i < ids.size(); ++i)
  44244. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44245. resized();
  44246. }
  44247. void Toolbar::removeToolbarItem (const int itemIndex)
  44248. {
  44249. items.remove (itemIndex);
  44250. resized();
  44251. }
  44252. int Toolbar::getNumItems() const throw()
  44253. {
  44254. return items.size();
  44255. }
  44256. int Toolbar::getItemId (const int itemIndex) const throw()
  44257. {
  44258. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44259. return tc != 0 ? tc->getItemId() : 0;
  44260. }
  44261. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44262. {
  44263. return items [itemIndex];
  44264. }
  44265. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44266. {
  44267. for (;;)
  44268. {
  44269. index += delta;
  44270. ToolbarItemComponent* const tc = getItemComponent (index);
  44271. if (tc == 0)
  44272. break;
  44273. if (tc->isActive)
  44274. return tc;
  44275. }
  44276. return 0;
  44277. }
  44278. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44279. {
  44280. if (toolbarStyle != newStyle)
  44281. {
  44282. toolbarStyle = newStyle;
  44283. updateAllItemPositions (false);
  44284. }
  44285. }
  44286. const String Toolbar::toString() const
  44287. {
  44288. String s ("TB:");
  44289. for (int i = 0; i < getNumItems(); ++i)
  44290. s << getItemId(i) << ' ';
  44291. return s.trimEnd();
  44292. }
  44293. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44294. const String& savedVersion)
  44295. {
  44296. if (! savedVersion.startsWith ("TB:"))
  44297. return false;
  44298. StringArray tokens;
  44299. tokens.addTokens (savedVersion.substring (3), false);
  44300. clear();
  44301. for (int i = 0; i < tokens.size(); ++i)
  44302. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44303. resized();
  44304. return true;
  44305. }
  44306. void Toolbar::paint (Graphics& g)
  44307. {
  44308. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44309. }
  44310. int Toolbar::getThickness() const throw()
  44311. {
  44312. return vertical ? getWidth() : getHeight();
  44313. }
  44314. int Toolbar::getLength() const throw()
  44315. {
  44316. return vertical ? getHeight() : getWidth();
  44317. }
  44318. void Toolbar::setEditingActive (const bool active)
  44319. {
  44320. if (isEditingActive != active)
  44321. {
  44322. isEditingActive = active;
  44323. updateAllItemPositions (false);
  44324. }
  44325. }
  44326. void Toolbar::resized()
  44327. {
  44328. updateAllItemPositions (false);
  44329. }
  44330. void Toolbar::updateAllItemPositions (const bool animate)
  44331. {
  44332. if (getWidth() > 0 && getHeight() > 0)
  44333. {
  44334. StretchableObjectResizer resizer;
  44335. int i;
  44336. for (i = 0; i < items.size(); ++i)
  44337. {
  44338. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44339. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44340. : ToolbarItemComponent::normalMode);
  44341. tc->setStyle (toolbarStyle);
  44342. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44343. int preferredSize = 1, minSize = 1, maxSize = 1;
  44344. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44345. preferredSize, minSize, maxSize))
  44346. {
  44347. tc->isActive = true;
  44348. resizer.addItem (preferredSize, minSize, maxSize,
  44349. spacer != 0 ? spacer->getResizeOrder() : 2);
  44350. }
  44351. else
  44352. {
  44353. tc->isActive = false;
  44354. tc->setVisible (false);
  44355. }
  44356. }
  44357. resizer.resizeToFit (getLength());
  44358. int totalLength = 0;
  44359. for (i = 0; i < resizer.getNumItems(); ++i)
  44360. totalLength += (int) resizer.getItemSize (i);
  44361. const bool itemsOffTheEnd = totalLength > getLength();
  44362. const int extrasButtonSize = getThickness() / 2;
  44363. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44364. missingItemsButton->setVisible (itemsOffTheEnd);
  44365. missingItemsButton->setEnabled (! isEditingActive);
  44366. if (vertical)
  44367. missingItemsButton->setCentrePosition (getWidth() / 2,
  44368. getHeight() - 4 - extrasButtonSize / 2);
  44369. else
  44370. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44371. getHeight() / 2);
  44372. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44373. : missingItemsButton->getX()) - 4
  44374. : getLength();
  44375. int pos = 0, activeIndex = 0;
  44376. for (i = 0; i < items.size(); ++i)
  44377. {
  44378. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44379. if (tc->isActive)
  44380. {
  44381. const int size = (int) resizer.getItemSize (activeIndex++);
  44382. Rectangle<int> newBounds;
  44383. if (vertical)
  44384. newBounds.setBounds (0, pos, getWidth(), size);
  44385. else
  44386. newBounds.setBounds (pos, 0, size, getHeight());
  44387. if (animate)
  44388. {
  44389. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44390. }
  44391. else
  44392. {
  44393. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44394. tc->setBounds (newBounds);
  44395. }
  44396. pos += size;
  44397. tc->setVisible (pos <= maxLength
  44398. && ((! tc->isBeingDragged)
  44399. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44400. }
  44401. }
  44402. }
  44403. }
  44404. void Toolbar::buttonClicked (Button*)
  44405. {
  44406. jassert (missingItemsButton->isShowing());
  44407. if (missingItemsButton->isShowing())
  44408. {
  44409. PopupMenu m;
  44410. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44411. m.showMenuAsync (PopupMenu::Options().withTargetComponent (missingItemsButton), 0);
  44412. }
  44413. }
  44414. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44415. Component* /*sourceComponent*/)
  44416. {
  44417. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44418. }
  44419. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44420. {
  44421. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44422. if (tc != 0)
  44423. {
  44424. if (! items.contains (tc))
  44425. {
  44426. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44427. {
  44428. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44429. if (palette != 0)
  44430. palette->replaceComponent (tc);
  44431. }
  44432. else
  44433. {
  44434. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44435. }
  44436. items.add (tc);
  44437. addChildComponent (tc);
  44438. updateAllItemPositions (true);
  44439. }
  44440. for (int i = getNumItems(); --i >= 0;)
  44441. {
  44442. const int currentIndex = items.indexOf (tc);
  44443. int newIndex = currentIndex;
  44444. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44445. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44446. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44447. .getComponentDestination (getChildComponent (newIndex)));
  44448. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44449. if (prev != 0)
  44450. {
  44451. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44452. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44453. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44454. {
  44455. newIndex = getIndexOfChildComponent (prev);
  44456. }
  44457. }
  44458. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44459. if (next != 0)
  44460. {
  44461. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44462. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44463. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44464. {
  44465. newIndex = getIndexOfChildComponent (next) + 1;
  44466. }
  44467. }
  44468. if (newIndex == currentIndex)
  44469. break;
  44470. items.removeObject (tc, false);
  44471. removeChildComponent (tc);
  44472. addChildComponent (tc, newIndex);
  44473. items.insert (newIndex, tc);
  44474. updateAllItemPositions (true);
  44475. }
  44476. }
  44477. }
  44478. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44479. {
  44480. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44481. if (tc != 0 && isParentOf (tc))
  44482. {
  44483. items.removeObject (tc, false);
  44484. removeChildComponent (tc);
  44485. updateAllItemPositions (true);
  44486. }
  44487. }
  44488. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44489. {
  44490. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44491. if (tc != 0)
  44492. tc->setState (Button::buttonNormal);
  44493. }
  44494. void Toolbar::mouseDown (const MouseEvent&)
  44495. {
  44496. }
  44497. class ToolbarCustomisationDialog : public DialogWindow
  44498. {
  44499. public:
  44500. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44501. Toolbar* const toolbar_,
  44502. const int optionFlags)
  44503. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44504. toolbar (toolbar_)
  44505. {
  44506. setContentOwned (new CustomiserPanel (factory, toolbar, optionFlags), true);
  44507. setResizable (true, true);
  44508. setResizeLimits (400, 300, 1500, 1000);
  44509. positionNearBar();
  44510. }
  44511. ~ToolbarCustomisationDialog()
  44512. {
  44513. toolbar->setEditingActive (false);
  44514. }
  44515. void closeButtonPressed()
  44516. {
  44517. setVisible (false);
  44518. }
  44519. bool canModalEventBeSentToComponent (const Component* comp)
  44520. {
  44521. return toolbar->isParentOf (comp);
  44522. }
  44523. void positionNearBar()
  44524. {
  44525. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44526. const int tbx = toolbar->getScreenX();
  44527. const int tby = toolbar->getScreenY();
  44528. const int gap = 8;
  44529. int x, y;
  44530. if (toolbar->isVertical())
  44531. {
  44532. y = tby;
  44533. if (tbx > screenSize.getCentreX())
  44534. x = tbx - getWidth() - gap;
  44535. else
  44536. x = tbx + toolbar->getWidth() + gap;
  44537. }
  44538. else
  44539. {
  44540. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44541. if (tby > screenSize.getCentreY())
  44542. y = tby - getHeight() - gap;
  44543. else
  44544. y = tby + toolbar->getHeight() + gap;
  44545. }
  44546. setTopLeftPosition (x, y);
  44547. }
  44548. private:
  44549. Toolbar* const toolbar;
  44550. class CustomiserPanel : public Component,
  44551. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44552. private ButtonListener
  44553. {
  44554. public:
  44555. CustomiserPanel (ToolbarItemFactory& factory_,
  44556. Toolbar* const toolbar_,
  44557. const int optionFlags)
  44558. : factory (factory_),
  44559. toolbar (toolbar_),
  44560. palette (factory_, toolbar_),
  44561. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44562. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44563. defaultButton (TRANS ("Restore to default set of items"))
  44564. {
  44565. addAndMakeVisible (&palette);
  44566. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44567. | Toolbar::allowIconsWithTextChoice
  44568. | Toolbar::allowTextOnlyChoice)) != 0)
  44569. {
  44570. addAndMakeVisible (&styleBox);
  44571. styleBox.setEditableText (false);
  44572. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44573. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44574. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44575. int selectedStyle = 0;
  44576. switch (toolbar_->getStyle())
  44577. {
  44578. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44579. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44580. case Toolbar::textOnly: selectedStyle = 3; break;
  44581. }
  44582. styleBox.setSelectedId (selectedStyle);
  44583. styleBox.addListener (this);
  44584. }
  44585. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44586. {
  44587. addAndMakeVisible (&defaultButton);
  44588. defaultButton.addListener (this);
  44589. }
  44590. addAndMakeVisible (&instructions);
  44591. instructions.setFont (Font (13.0f));
  44592. setSize (500, 300);
  44593. }
  44594. void comboBoxChanged (ComboBox*)
  44595. {
  44596. switch (styleBox.getSelectedId())
  44597. {
  44598. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44599. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44600. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44601. }
  44602. palette.resized(); // to make it update the styles
  44603. }
  44604. void buttonClicked (Button*)
  44605. {
  44606. toolbar->addDefaultItems (factory);
  44607. }
  44608. void paint (Graphics& g)
  44609. {
  44610. Colour background;
  44611. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44612. if (dw != 0)
  44613. background = dw->getBackgroundColour();
  44614. g.setColour (background.contrasting().withAlpha (0.3f));
  44615. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44616. }
  44617. void resized()
  44618. {
  44619. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44620. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44621. defaultButton.changeWidthToFitText (22);
  44622. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44623. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44624. }
  44625. private:
  44626. ToolbarItemFactory& factory;
  44627. Toolbar* const toolbar;
  44628. ToolbarItemPalette palette;
  44629. Label instructions;
  44630. ComboBox styleBox;
  44631. TextButton defaultButton;
  44632. };
  44633. };
  44634. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44635. {
  44636. setEditingActive (true);
  44637. (new ToolbarCustomisationDialog (factory, this, optionFlags))
  44638. ->enterModalState (true, 0, true);
  44639. }
  44640. END_JUCE_NAMESPACE
  44641. /*** End of inlined file: juce_Toolbar.cpp ***/
  44642. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44643. BEGIN_JUCE_NAMESPACE
  44644. ToolbarItemFactory::ToolbarItemFactory()
  44645. {
  44646. }
  44647. ToolbarItemFactory::~ToolbarItemFactory()
  44648. {
  44649. }
  44650. class ItemDragAndDropOverlayComponent : public Component
  44651. {
  44652. public:
  44653. ItemDragAndDropOverlayComponent()
  44654. : isDragging (false)
  44655. {
  44656. setAlwaysOnTop (true);
  44657. setRepaintsOnMouseActivity (true);
  44658. setMouseCursor (MouseCursor::DraggingHandCursor);
  44659. }
  44660. void paint (Graphics& g)
  44661. {
  44662. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44663. if (isMouseOverOrDragging()
  44664. && tc != 0
  44665. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44666. {
  44667. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44668. g.drawRect (0, 0, getWidth(), getHeight(),
  44669. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44670. }
  44671. }
  44672. void mouseDown (const MouseEvent& e)
  44673. {
  44674. isDragging = false;
  44675. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44676. if (tc != 0)
  44677. {
  44678. tc->dragOffsetX = e.x;
  44679. tc->dragOffsetY = e.y;
  44680. }
  44681. }
  44682. void mouseDrag (const MouseEvent& e)
  44683. {
  44684. if (! (isDragging || e.mouseWasClicked()))
  44685. {
  44686. isDragging = true;
  44687. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44688. if (dnd != 0)
  44689. {
  44690. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44691. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44692. if (tc != 0)
  44693. {
  44694. tc->isBeingDragged = true;
  44695. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44696. tc->setVisible (false);
  44697. }
  44698. }
  44699. }
  44700. }
  44701. void mouseUp (const MouseEvent&)
  44702. {
  44703. isDragging = false;
  44704. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44705. if (tc != 0)
  44706. {
  44707. tc->isBeingDragged = false;
  44708. Toolbar* const tb = tc->getToolbar();
  44709. if (tb != 0)
  44710. tb->updateAllItemPositions (true);
  44711. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44712. delete tc;
  44713. }
  44714. }
  44715. void parentSizeChanged()
  44716. {
  44717. setBounds (0, 0, getParentWidth(), getParentHeight());
  44718. }
  44719. private:
  44720. bool isDragging;
  44721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44722. };
  44723. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44724. const String& labelText,
  44725. const bool isBeingUsedAsAButton_)
  44726. : Button (labelText),
  44727. itemId (itemId_),
  44728. mode (normalMode),
  44729. toolbarStyle (Toolbar::iconsOnly),
  44730. dragOffsetX (0),
  44731. dragOffsetY (0),
  44732. isActive (true),
  44733. isBeingDragged (false),
  44734. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44735. {
  44736. // Your item ID can't be 0!
  44737. jassert (itemId_ != 0);
  44738. }
  44739. ToolbarItemComponent::~ToolbarItemComponent()
  44740. {
  44741. overlayComp = 0;
  44742. }
  44743. Toolbar* ToolbarItemComponent::getToolbar() const
  44744. {
  44745. return dynamic_cast <Toolbar*> (getParentComponent());
  44746. }
  44747. bool ToolbarItemComponent::isToolbarVertical() const
  44748. {
  44749. const Toolbar* const t = getToolbar();
  44750. return t != 0 && t->isVertical();
  44751. }
  44752. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44753. {
  44754. if (toolbarStyle != newStyle)
  44755. {
  44756. toolbarStyle = newStyle;
  44757. repaint();
  44758. resized();
  44759. }
  44760. }
  44761. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44762. {
  44763. if (isBeingUsedAsAButton)
  44764. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44765. over, down, *this);
  44766. if (toolbarStyle != Toolbar::iconsOnly)
  44767. {
  44768. const int indent = contentArea.getX();
  44769. int y = indent;
  44770. int h = getHeight() - indent * 2;
  44771. if (toolbarStyle == Toolbar::iconsWithText)
  44772. {
  44773. y = contentArea.getBottom() + indent / 2;
  44774. h -= contentArea.getHeight();
  44775. }
  44776. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44777. getButtonText(), *this);
  44778. }
  44779. if (! contentArea.isEmpty())
  44780. {
  44781. Graphics::ScopedSaveState ss (g);
  44782. g.reduceClipRegion (contentArea);
  44783. g.setOrigin (contentArea.getX(), contentArea.getY());
  44784. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44785. }
  44786. }
  44787. void ToolbarItemComponent::resized()
  44788. {
  44789. if (toolbarStyle != Toolbar::textOnly)
  44790. {
  44791. const int indent = jmin (proportionOfWidth (0.08f),
  44792. proportionOfHeight (0.08f));
  44793. contentArea = Rectangle<int> (indent, indent,
  44794. getWidth() - indent * 2,
  44795. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44796. : (getHeight() - indent * 2));
  44797. }
  44798. else
  44799. {
  44800. contentArea = Rectangle<int>();
  44801. }
  44802. contentAreaChanged (contentArea);
  44803. }
  44804. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44805. {
  44806. if (mode != newMode)
  44807. {
  44808. mode = newMode;
  44809. repaint();
  44810. if (mode == normalMode)
  44811. {
  44812. overlayComp = 0;
  44813. }
  44814. else if (overlayComp == 0)
  44815. {
  44816. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44817. overlayComp->parentSizeChanged();
  44818. }
  44819. resized();
  44820. }
  44821. }
  44822. END_JUCE_NAMESPACE
  44823. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44824. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44825. BEGIN_JUCE_NAMESPACE
  44826. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44827. Toolbar* const toolbar_)
  44828. : factory (factory_),
  44829. toolbar (toolbar_)
  44830. {
  44831. Component* const itemHolder = new Component();
  44832. viewport.setViewedComponent (itemHolder);
  44833. Array <int> allIds;
  44834. factory.getAllToolbarItemIds (allIds);
  44835. for (int i = 0; i < allIds.size(); ++i)
  44836. addComponent (allIds.getUnchecked (i), -1);
  44837. addAndMakeVisible (&viewport);
  44838. }
  44839. ToolbarItemPalette::~ToolbarItemPalette()
  44840. {
  44841. }
  44842. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44843. {
  44844. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44845. jassert (tc != 0);
  44846. if (tc != 0)
  44847. {
  44848. items.insert (index, tc);
  44849. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44850. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44851. }
  44852. }
  44853. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44854. {
  44855. const int index = items.indexOf (comp);
  44856. jassert (index >= 0);
  44857. items.removeObject (comp, false);
  44858. addComponent (comp->getItemId(), index);
  44859. resized();
  44860. }
  44861. void ToolbarItemPalette::resized()
  44862. {
  44863. viewport.setBoundsInset (BorderSize<int> (1));
  44864. Component* const itemHolder = viewport.getViewedComponent();
  44865. const int indent = 8;
  44866. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44867. const int height = toolbar->getThickness();
  44868. int x = indent;
  44869. int y = indent;
  44870. int maxX = 0;
  44871. for (int i = 0; i < items.size(); ++i)
  44872. {
  44873. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44874. tc->setStyle (toolbar->getStyle());
  44875. int preferredSize = 1, minSize = 1, maxSize = 1;
  44876. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44877. {
  44878. if (x + preferredSize > preferredWidth && x > indent)
  44879. {
  44880. x = indent;
  44881. y += height;
  44882. }
  44883. tc->setBounds (x, y, preferredSize, height);
  44884. x += preferredSize + 8;
  44885. maxX = jmax (maxX, x);
  44886. }
  44887. }
  44888. itemHolder->setSize (maxX, y + height + 8);
  44889. }
  44890. END_JUCE_NAMESPACE
  44891. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44892. /*** Start of inlined file: juce_TreeView.cpp ***/
  44893. BEGIN_JUCE_NAMESPACE
  44894. class TreeViewContentComponent : public Component,
  44895. public TooltipClient
  44896. {
  44897. public:
  44898. TreeViewContentComponent (TreeView& owner_)
  44899. : owner (owner_),
  44900. buttonUnderMouse (0),
  44901. isDragging (false)
  44902. {
  44903. }
  44904. void mouseDown (const MouseEvent& e)
  44905. {
  44906. updateButtonUnderMouse (e);
  44907. isDragging = false;
  44908. needSelectionOnMouseUp = false;
  44909. Rectangle<int> pos;
  44910. TreeViewItem* const item = findItemAt (e.y, pos);
  44911. if (item == 0)
  44912. return;
  44913. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44914. // as selection clicks)
  44915. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44916. {
  44917. if (e.x >= pos.getX() - owner.getIndentSize())
  44918. item->setOpen (! item->isOpen());
  44919. // (clicks to the left of an open/close button are ignored)
  44920. }
  44921. else
  44922. {
  44923. // mouse-down inside the body of the item..
  44924. if (! owner.isMultiSelectEnabled())
  44925. item->setSelected (true, true);
  44926. else if (item->isSelected())
  44927. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44928. else
  44929. selectBasedOnModifiers (item, e.mods);
  44930. if (e.x >= pos.getX())
  44931. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44932. }
  44933. }
  44934. void mouseUp (const MouseEvent& e)
  44935. {
  44936. updateButtonUnderMouse (e);
  44937. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44938. {
  44939. Rectangle<int> pos;
  44940. TreeViewItem* const item = findItemAt (e.y, pos);
  44941. if (item != 0)
  44942. selectBasedOnModifiers (item, e.mods);
  44943. }
  44944. }
  44945. void mouseDoubleClick (const MouseEvent& e)
  44946. {
  44947. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44948. {
  44949. Rectangle<int> pos;
  44950. TreeViewItem* const item = findItemAt (e.y, pos);
  44951. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44952. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44953. }
  44954. }
  44955. void mouseDrag (const MouseEvent& e)
  44956. {
  44957. if (isEnabled()
  44958. && ! (isDragging || e.mouseWasClicked()
  44959. || e.getDistanceFromDragStart() < 5
  44960. || e.mods.isPopupMenu()))
  44961. {
  44962. isDragging = true;
  44963. Rectangle<int> pos;
  44964. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44965. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44966. {
  44967. const String dragDescription (item->getDragSourceDescription());
  44968. if (dragDescription.isNotEmpty())
  44969. {
  44970. DragAndDropContainer* const dragContainer
  44971. = DragAndDropContainer::findParentDragContainerFor (this);
  44972. if (dragContainer != 0)
  44973. {
  44974. pos.setSize (pos.getWidth(), item->itemHeight);
  44975. Image dragImage (Component::createComponentSnapshot (pos, true));
  44976. dragImage.multiplyAllAlphas (0.6f);
  44977. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44978. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44979. }
  44980. else
  44981. {
  44982. // to be able to do a drag-and-drop operation, the treeview needs to
  44983. // be inside a component which is also a DragAndDropContainer.
  44984. jassertfalse;
  44985. }
  44986. }
  44987. }
  44988. }
  44989. }
  44990. void mouseMove (const MouseEvent& e)
  44991. {
  44992. updateButtonUnderMouse (e);
  44993. }
  44994. void mouseExit (const MouseEvent& e)
  44995. {
  44996. updateButtonUnderMouse (e);
  44997. }
  44998. void paint (Graphics& g)
  44999. {
  45000. if (owner.rootItem != 0)
  45001. {
  45002. owner.handleAsyncUpdate();
  45003. if (! owner.rootItemVisible)
  45004. g.setOrigin (0, -owner.rootItem->itemHeight);
  45005. owner.rootItem->paintRecursively (g, getWidth());
  45006. }
  45007. }
  45008. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45009. {
  45010. if (owner.rootItem != 0)
  45011. {
  45012. owner.handleAsyncUpdate();
  45013. if (! owner.rootItemVisible)
  45014. y += owner.rootItem->itemHeight;
  45015. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45016. if (ti != 0)
  45017. itemPosition = ti->getItemPosition (false);
  45018. return ti;
  45019. }
  45020. return 0;
  45021. }
  45022. void updateComponents()
  45023. {
  45024. const int visibleTop = -getY();
  45025. const int visibleBottom = visibleTop + getParentHeight();
  45026. {
  45027. for (int i = items.size(); --i >= 0;)
  45028. items.getUnchecked(i)->shouldKeep = false;
  45029. }
  45030. {
  45031. TreeViewItem* item = owner.rootItem;
  45032. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45033. while (item != 0 && y < visibleBottom)
  45034. {
  45035. y += item->itemHeight;
  45036. if (y >= visibleTop)
  45037. {
  45038. RowItem* const ri = findItem (item->uid);
  45039. if (ri != 0)
  45040. {
  45041. ri->shouldKeep = true;
  45042. }
  45043. else
  45044. {
  45045. Component* const comp = item->createItemComponent();
  45046. if (comp != 0)
  45047. {
  45048. items.add (new RowItem (item, comp, item->uid));
  45049. addAndMakeVisible (comp);
  45050. }
  45051. }
  45052. }
  45053. item = item->getNextVisibleItem (true);
  45054. }
  45055. }
  45056. for (int i = items.size(); --i >= 0;)
  45057. {
  45058. RowItem* const ri = items.getUnchecked(i);
  45059. bool keep = false;
  45060. if (isParentOf (ri->component))
  45061. {
  45062. if (ri->shouldKeep)
  45063. {
  45064. Rectangle<int> pos (ri->item->getItemPosition (false));
  45065. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45066. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45067. {
  45068. keep = true;
  45069. ri->component->setBounds (pos);
  45070. }
  45071. }
  45072. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45073. {
  45074. keep = true;
  45075. ri->component->setSize (0, 0);
  45076. }
  45077. }
  45078. if (! keep)
  45079. items.remove (i);
  45080. }
  45081. }
  45082. void updateButtonUnderMouse (const MouseEvent& e)
  45083. {
  45084. TreeViewItem* newItem = 0;
  45085. if (owner.openCloseButtonsVisible)
  45086. {
  45087. Rectangle<int> pos;
  45088. TreeViewItem* item = findItemAt (e.y, pos);
  45089. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45090. {
  45091. newItem = item;
  45092. if (! newItem->mightContainSubItems())
  45093. newItem = 0;
  45094. }
  45095. }
  45096. if (buttonUnderMouse != newItem)
  45097. {
  45098. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45099. {
  45100. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45101. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45102. }
  45103. buttonUnderMouse = newItem;
  45104. if (buttonUnderMouse != 0)
  45105. {
  45106. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45107. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45108. }
  45109. }
  45110. }
  45111. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45112. {
  45113. return item == buttonUnderMouse;
  45114. }
  45115. void resized()
  45116. {
  45117. owner.itemsChanged();
  45118. }
  45119. const String getTooltip()
  45120. {
  45121. Rectangle<int> pos;
  45122. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45123. if (item != 0)
  45124. return item->getTooltip();
  45125. return owner.getTooltip();
  45126. }
  45127. private:
  45128. TreeView& owner;
  45129. struct RowItem
  45130. {
  45131. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45132. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45133. {
  45134. }
  45135. ~RowItem()
  45136. {
  45137. delete component.get();
  45138. }
  45139. WeakReference<Component> component;
  45140. TreeViewItem* item;
  45141. int uid;
  45142. bool shouldKeep;
  45143. };
  45144. OwnedArray <RowItem> items;
  45145. TreeViewItem* buttonUnderMouse;
  45146. bool isDragging, needSelectionOnMouseUp;
  45147. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45148. {
  45149. TreeViewItem* firstSelected = 0;
  45150. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45151. {
  45152. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45153. jassert (lastSelected != 0);
  45154. int rowStart = firstSelected->getRowNumberInTree();
  45155. int rowEnd = lastSelected->getRowNumberInTree();
  45156. if (rowStart > rowEnd)
  45157. swapVariables (rowStart, rowEnd);
  45158. int ourRow = item->getRowNumberInTree();
  45159. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45160. if (ourRow > otherEnd)
  45161. swapVariables (ourRow, otherEnd);
  45162. for (int i = ourRow; i <= otherEnd; ++i)
  45163. owner.getItemOnRow (i)->setSelected (true, false);
  45164. }
  45165. else
  45166. {
  45167. const bool cmd = modifiers.isCommandDown();
  45168. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45169. }
  45170. }
  45171. bool containsItem (TreeViewItem* const item) const throw()
  45172. {
  45173. for (int i = items.size(); --i >= 0;)
  45174. if (items.getUnchecked(i)->item == item)
  45175. return true;
  45176. return false;
  45177. }
  45178. RowItem* findItem (const int uid) const throw()
  45179. {
  45180. for (int i = items.size(); --i >= 0;)
  45181. {
  45182. RowItem* const ri = items.getUnchecked(i);
  45183. if (ri->uid == uid)
  45184. return ri;
  45185. }
  45186. return 0;
  45187. }
  45188. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45189. {
  45190. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45191. {
  45192. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45193. if (source->isDragging())
  45194. {
  45195. Component* const underMouse = source->getComponentUnderMouse();
  45196. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45197. return true;
  45198. }
  45199. }
  45200. return false;
  45201. }
  45202. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45203. };
  45204. class TreeView::TreeViewport : public Viewport
  45205. {
  45206. public:
  45207. TreeViewport() throw() : lastX (-1) {}
  45208. void updateComponents (const bool triggerResize = false)
  45209. {
  45210. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45211. if (tvc != 0)
  45212. {
  45213. if (triggerResize)
  45214. tvc->resized();
  45215. else
  45216. tvc->updateComponents();
  45217. }
  45218. repaint();
  45219. }
  45220. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45221. {
  45222. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45223. lastX = newVisibleArea.getX();
  45224. updateComponents (hasScrolledSideways);
  45225. }
  45226. private:
  45227. int lastX;
  45228. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45229. };
  45230. TreeView::TreeView (const String& componentName)
  45231. : Component (componentName),
  45232. rootItem (0),
  45233. indentSize (24),
  45234. defaultOpenness (false),
  45235. needsRecalculating (true),
  45236. rootItemVisible (true),
  45237. multiSelectEnabled (false),
  45238. openCloseButtonsVisible (true)
  45239. {
  45240. addAndMakeVisible (viewport = new TreeViewport());
  45241. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45242. viewport->setWantsKeyboardFocus (false);
  45243. setWantsKeyboardFocus (true);
  45244. }
  45245. TreeView::~TreeView()
  45246. {
  45247. if (rootItem != 0)
  45248. rootItem->setOwnerView (0);
  45249. }
  45250. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45251. {
  45252. if (rootItem != newRootItem)
  45253. {
  45254. if (newRootItem != 0)
  45255. {
  45256. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45257. if (newRootItem->ownerView != 0)
  45258. newRootItem->ownerView->setRootItem (0);
  45259. }
  45260. if (rootItem != 0)
  45261. rootItem->setOwnerView (0);
  45262. rootItem = newRootItem;
  45263. if (newRootItem != 0)
  45264. newRootItem->setOwnerView (this);
  45265. needsRecalculating = true;
  45266. handleAsyncUpdate();
  45267. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45268. {
  45269. rootItem->setOpen (false); // force a re-open
  45270. rootItem->setOpen (true);
  45271. }
  45272. }
  45273. }
  45274. void TreeView::deleteRootItem()
  45275. {
  45276. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45277. setRootItem (0);
  45278. }
  45279. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45280. {
  45281. rootItemVisible = shouldBeVisible;
  45282. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45283. {
  45284. rootItem->setOpen (false); // force a re-open
  45285. rootItem->setOpen (true);
  45286. }
  45287. itemsChanged();
  45288. }
  45289. void TreeView::colourChanged()
  45290. {
  45291. setOpaque (findColour (backgroundColourId).isOpaque());
  45292. repaint();
  45293. }
  45294. void TreeView::setIndentSize (const int newIndentSize)
  45295. {
  45296. if (indentSize != newIndentSize)
  45297. {
  45298. indentSize = newIndentSize;
  45299. resized();
  45300. }
  45301. }
  45302. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45303. {
  45304. if (defaultOpenness != isOpenByDefault)
  45305. {
  45306. defaultOpenness = isOpenByDefault;
  45307. itemsChanged();
  45308. }
  45309. }
  45310. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45311. {
  45312. multiSelectEnabled = canMultiSelect;
  45313. }
  45314. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45315. {
  45316. if (openCloseButtonsVisible != shouldBeVisible)
  45317. {
  45318. openCloseButtonsVisible = shouldBeVisible;
  45319. itemsChanged();
  45320. }
  45321. }
  45322. Viewport* TreeView::getViewport() const throw()
  45323. {
  45324. return viewport;
  45325. }
  45326. void TreeView::clearSelectedItems()
  45327. {
  45328. if (rootItem != 0)
  45329. rootItem->deselectAllRecursively();
  45330. }
  45331. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45332. {
  45333. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45334. }
  45335. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45336. {
  45337. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45338. }
  45339. int TreeView::getNumRowsInTree() const
  45340. {
  45341. if (rootItem != 0)
  45342. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45343. return 0;
  45344. }
  45345. TreeViewItem* TreeView::getItemOnRow (int index) const
  45346. {
  45347. if (! rootItemVisible)
  45348. ++index;
  45349. if (rootItem != 0 && index >= 0)
  45350. return rootItem->getItemOnRow (index);
  45351. return 0;
  45352. }
  45353. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45354. {
  45355. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45356. Rectangle<int> pos;
  45357. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45358. }
  45359. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45360. {
  45361. if (rootItem == 0)
  45362. return 0;
  45363. return rootItem->findItemFromIdentifierString (identifierString);
  45364. }
  45365. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45366. {
  45367. XmlElement* e = 0;
  45368. if (rootItem != 0)
  45369. {
  45370. e = rootItem->getOpennessState();
  45371. if (e != 0 && alsoIncludeScrollPosition)
  45372. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45373. }
  45374. return e;
  45375. }
  45376. void TreeView::restoreOpennessState (const XmlElement& newState)
  45377. {
  45378. if (rootItem != 0)
  45379. {
  45380. rootItem->restoreOpennessState (newState);
  45381. if (newState.hasAttribute ("scrollPos"))
  45382. viewport->setViewPosition (viewport->getViewPositionX(),
  45383. newState.getIntAttribute ("scrollPos"));
  45384. }
  45385. }
  45386. void TreeView::paint (Graphics& g)
  45387. {
  45388. g.fillAll (findColour (backgroundColourId));
  45389. }
  45390. void TreeView::resized()
  45391. {
  45392. viewport->setBounds (getLocalBounds());
  45393. itemsChanged();
  45394. handleAsyncUpdate();
  45395. }
  45396. void TreeView::enablementChanged()
  45397. {
  45398. repaint();
  45399. }
  45400. void TreeView::moveSelectedRow (int delta)
  45401. {
  45402. if (delta == 0)
  45403. return;
  45404. int rowSelected = 0;
  45405. TreeViewItem* const firstSelected = getSelectedItem (0);
  45406. if (firstSelected != 0)
  45407. rowSelected = firstSelected->getRowNumberInTree();
  45408. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45409. for (;;)
  45410. {
  45411. TreeViewItem* item = getItemOnRow (rowSelected);
  45412. if (item != 0)
  45413. {
  45414. if (! item->canBeSelected())
  45415. {
  45416. // if the row we want to highlight doesn't allow it, try skipping
  45417. // to the next item..
  45418. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45419. rowSelected + (delta < 0 ? -1 : 1));
  45420. if (rowSelected != nextRowToTry)
  45421. {
  45422. rowSelected = nextRowToTry;
  45423. continue;
  45424. }
  45425. else
  45426. {
  45427. break;
  45428. }
  45429. }
  45430. item->setSelected (true, true);
  45431. scrollToKeepItemVisible (item);
  45432. }
  45433. break;
  45434. }
  45435. }
  45436. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45437. {
  45438. if (item != 0 && item->ownerView == this)
  45439. {
  45440. handleAsyncUpdate();
  45441. item = item->getDeepestOpenParentItem();
  45442. int y = item->y;
  45443. int viewTop = viewport->getViewPositionY();
  45444. if (y < viewTop)
  45445. {
  45446. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45447. }
  45448. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45449. {
  45450. viewport->setViewPosition (viewport->getViewPositionX(),
  45451. (y + item->itemHeight) - viewport->getViewHeight());
  45452. }
  45453. }
  45454. }
  45455. bool TreeView::keyPressed (const KeyPress& key)
  45456. {
  45457. if (key.isKeyCode (KeyPress::upKey))
  45458. {
  45459. moveSelectedRow (-1);
  45460. }
  45461. else if (key.isKeyCode (KeyPress::downKey))
  45462. {
  45463. moveSelectedRow (1);
  45464. }
  45465. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45466. {
  45467. if (rootItem != 0)
  45468. {
  45469. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45470. if (key.isKeyCode (KeyPress::pageUpKey))
  45471. rowsOnScreen = -rowsOnScreen;
  45472. moveSelectedRow (rowsOnScreen);
  45473. }
  45474. }
  45475. else if (key.isKeyCode (KeyPress::homeKey))
  45476. {
  45477. moveSelectedRow (-0x3fffffff);
  45478. }
  45479. else if (key.isKeyCode (KeyPress::endKey))
  45480. {
  45481. moveSelectedRow (0x3fffffff);
  45482. }
  45483. else if (key.isKeyCode (KeyPress::returnKey))
  45484. {
  45485. TreeViewItem* const firstSelected = getSelectedItem (0);
  45486. if (firstSelected != 0)
  45487. firstSelected->setOpen (! firstSelected->isOpen());
  45488. }
  45489. else if (key.isKeyCode (KeyPress::leftKey))
  45490. {
  45491. TreeViewItem* const firstSelected = getSelectedItem (0);
  45492. if (firstSelected != 0)
  45493. {
  45494. if (firstSelected->isOpen())
  45495. {
  45496. firstSelected->setOpen (false);
  45497. }
  45498. else
  45499. {
  45500. TreeViewItem* parent = firstSelected->parentItem;
  45501. if ((! rootItemVisible) && parent == rootItem)
  45502. parent = 0;
  45503. if (parent != 0)
  45504. {
  45505. parent->setSelected (true, true);
  45506. scrollToKeepItemVisible (parent);
  45507. }
  45508. }
  45509. }
  45510. }
  45511. else if (key.isKeyCode (KeyPress::rightKey))
  45512. {
  45513. TreeViewItem* const firstSelected = getSelectedItem (0);
  45514. if (firstSelected != 0)
  45515. {
  45516. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45517. moveSelectedRow (1);
  45518. else
  45519. firstSelected->setOpen (true);
  45520. }
  45521. }
  45522. else
  45523. {
  45524. return false;
  45525. }
  45526. return true;
  45527. }
  45528. void TreeView::itemsChanged() throw()
  45529. {
  45530. needsRecalculating = true;
  45531. repaint();
  45532. triggerAsyncUpdate();
  45533. }
  45534. void TreeView::handleAsyncUpdate()
  45535. {
  45536. if (needsRecalculating)
  45537. {
  45538. needsRecalculating = false;
  45539. const ScopedLock sl (nodeAlterationLock);
  45540. if (rootItem != 0)
  45541. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45542. viewport->updateComponents();
  45543. if (rootItem != 0)
  45544. {
  45545. viewport->getViewedComponent()
  45546. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45547. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45548. }
  45549. else
  45550. {
  45551. viewport->getViewedComponent()->setSize (0, 0);
  45552. }
  45553. }
  45554. }
  45555. class TreeView::InsertPointHighlight : public Component
  45556. {
  45557. public:
  45558. InsertPointHighlight()
  45559. : lastItem (0)
  45560. {
  45561. setSize (100, 12);
  45562. setAlwaysOnTop (true);
  45563. setInterceptsMouseClicks (false, false);
  45564. }
  45565. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45566. {
  45567. lastItem = item;
  45568. lastIndex = insertIndex;
  45569. const int offset = getHeight() / 2;
  45570. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45571. }
  45572. void paint (Graphics& g)
  45573. {
  45574. Path p;
  45575. const float h = (float) getHeight();
  45576. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45577. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45578. p.lineTo ((float) getWidth(), h / 2.0f);
  45579. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45580. g.strokePath (p, PathStrokeType (2.0f));
  45581. }
  45582. TreeViewItem* lastItem;
  45583. int lastIndex;
  45584. private:
  45585. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45586. };
  45587. class TreeView::TargetGroupHighlight : public Component
  45588. {
  45589. public:
  45590. TargetGroupHighlight()
  45591. {
  45592. setAlwaysOnTop (true);
  45593. setInterceptsMouseClicks (false, false);
  45594. }
  45595. void setTargetPosition (TreeViewItem* const item) throw()
  45596. {
  45597. Rectangle<int> r (item->getItemPosition (true));
  45598. r.setHeight (item->getItemHeight());
  45599. setBounds (r);
  45600. }
  45601. void paint (Graphics& g)
  45602. {
  45603. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45604. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45605. }
  45606. private:
  45607. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45608. };
  45609. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45610. {
  45611. beginDragAutoRepeat (100);
  45612. if (dragInsertPointHighlight == 0)
  45613. {
  45614. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45615. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45616. }
  45617. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45618. dragTargetGroupHighlight->setTargetPosition (item);
  45619. }
  45620. void TreeView::hideDragHighlight() throw()
  45621. {
  45622. dragInsertPointHighlight = 0;
  45623. dragTargetGroupHighlight = 0;
  45624. }
  45625. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45626. const StringArray& files, const String& sourceDescription,
  45627. Component* sourceComponent) const throw()
  45628. {
  45629. insertIndex = 0;
  45630. TreeViewItem* item = getItemAt (y);
  45631. if (item == 0)
  45632. return 0;
  45633. Rectangle<int> itemPos (item->getItemPosition (true));
  45634. insertIndex = item->getIndexInParent();
  45635. const int oldY = y;
  45636. y = itemPos.getY();
  45637. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45638. {
  45639. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45640. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45641. {
  45642. // Check if we're trying to drag into an empty group item..
  45643. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45644. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45645. {
  45646. insertIndex = 0;
  45647. x = itemPos.getX() + getIndentSize();
  45648. y = itemPos.getBottom();
  45649. return item;
  45650. }
  45651. }
  45652. }
  45653. if (oldY > itemPos.getCentreY())
  45654. {
  45655. y += item->getItemHeight();
  45656. while (item->isLastOfSiblings() && item->parentItem != 0
  45657. && item->parentItem->parentItem != 0)
  45658. {
  45659. if (x > itemPos.getX())
  45660. break;
  45661. item = item->parentItem;
  45662. itemPos = item->getItemPosition (true);
  45663. insertIndex = item->getIndexInParent();
  45664. }
  45665. ++insertIndex;
  45666. }
  45667. x = itemPos.getX();
  45668. return item->parentItem;
  45669. }
  45670. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45671. {
  45672. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45673. int insertIndex;
  45674. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45675. if (item != 0)
  45676. {
  45677. if (scrolled || dragInsertPointHighlight == 0
  45678. || dragInsertPointHighlight->lastItem != item
  45679. || dragInsertPointHighlight->lastIndex != insertIndex)
  45680. {
  45681. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45682. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45683. showDragHighlight (item, insertIndex, x, y);
  45684. else
  45685. hideDragHighlight();
  45686. }
  45687. }
  45688. else
  45689. {
  45690. hideDragHighlight();
  45691. }
  45692. }
  45693. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45694. {
  45695. hideDragHighlight();
  45696. int insertIndex;
  45697. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45698. if (item != 0)
  45699. {
  45700. if (files.size() > 0)
  45701. {
  45702. if (item->isInterestedInFileDrag (files))
  45703. item->filesDropped (files, insertIndex);
  45704. }
  45705. else
  45706. {
  45707. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45708. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45709. }
  45710. }
  45711. }
  45712. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45713. {
  45714. return true;
  45715. }
  45716. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45717. {
  45718. fileDragMove (files, x, y);
  45719. }
  45720. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45721. {
  45722. handleDrag (files, String::empty, 0, x, y);
  45723. }
  45724. void TreeView::fileDragExit (const StringArray&)
  45725. {
  45726. hideDragHighlight();
  45727. }
  45728. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45729. {
  45730. handleDrop (files, String::empty, 0, x, y);
  45731. }
  45732. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45733. {
  45734. return true;
  45735. }
  45736. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45737. {
  45738. itemDragMove (sourceDescription, sourceComponent, x, y);
  45739. }
  45740. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45741. {
  45742. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45743. }
  45744. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45745. {
  45746. hideDragHighlight();
  45747. }
  45748. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45749. {
  45750. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45751. }
  45752. enum TreeViewOpenness
  45753. {
  45754. opennessDefault = 0,
  45755. opennessClosed = 1,
  45756. opennessOpen = 2
  45757. };
  45758. TreeViewItem::TreeViewItem()
  45759. : ownerView (0),
  45760. parentItem (0),
  45761. y (0),
  45762. itemHeight (0),
  45763. totalHeight (0),
  45764. selected (false),
  45765. redrawNeeded (true),
  45766. drawLinesInside (true),
  45767. drawsInLeftMargin (false),
  45768. openness (opennessDefault)
  45769. {
  45770. static int nextUID = 0;
  45771. uid = nextUID++;
  45772. }
  45773. TreeViewItem::~TreeViewItem()
  45774. {
  45775. }
  45776. const String TreeViewItem::getUniqueName() const
  45777. {
  45778. return String::empty;
  45779. }
  45780. void TreeViewItem::itemOpennessChanged (bool)
  45781. {
  45782. }
  45783. int TreeViewItem::getNumSubItems() const throw()
  45784. {
  45785. return subItems.size();
  45786. }
  45787. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45788. {
  45789. return subItems [index];
  45790. }
  45791. void TreeViewItem::clearSubItems()
  45792. {
  45793. if (subItems.size() > 0)
  45794. {
  45795. if (ownerView != 0)
  45796. {
  45797. const ScopedLock sl (ownerView->nodeAlterationLock);
  45798. subItems.clear();
  45799. treeHasChanged();
  45800. }
  45801. else
  45802. {
  45803. subItems.clear();
  45804. }
  45805. }
  45806. }
  45807. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45808. {
  45809. if (newItem != 0)
  45810. {
  45811. newItem->parentItem = this;
  45812. newItem->setOwnerView (ownerView);
  45813. newItem->y = 0;
  45814. newItem->itemHeight = newItem->getItemHeight();
  45815. newItem->totalHeight = 0;
  45816. newItem->itemWidth = newItem->getItemWidth();
  45817. newItem->totalWidth = 0;
  45818. if (ownerView != 0)
  45819. {
  45820. const ScopedLock sl (ownerView->nodeAlterationLock);
  45821. subItems.insert (insertPosition, newItem);
  45822. treeHasChanged();
  45823. if (newItem->isOpen())
  45824. newItem->itemOpennessChanged (true);
  45825. }
  45826. else
  45827. {
  45828. subItems.insert (insertPosition, newItem);
  45829. if (newItem->isOpen())
  45830. newItem->itemOpennessChanged (true);
  45831. }
  45832. }
  45833. }
  45834. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45835. {
  45836. if (ownerView != 0)
  45837. {
  45838. const ScopedLock sl (ownerView->nodeAlterationLock);
  45839. if (isPositiveAndBelow (index, subItems.size()))
  45840. {
  45841. subItems.remove (index, deleteItem);
  45842. treeHasChanged();
  45843. }
  45844. }
  45845. else
  45846. {
  45847. subItems.remove (index, deleteItem);
  45848. }
  45849. }
  45850. bool TreeViewItem::isOpen() const throw()
  45851. {
  45852. if (openness == opennessDefault)
  45853. return ownerView != 0 && ownerView->defaultOpenness;
  45854. else
  45855. return openness == opennessOpen;
  45856. }
  45857. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45858. {
  45859. if (isOpen() != shouldBeOpen)
  45860. {
  45861. openness = shouldBeOpen ? opennessOpen
  45862. : opennessClosed;
  45863. treeHasChanged();
  45864. itemOpennessChanged (isOpen());
  45865. }
  45866. }
  45867. bool TreeViewItem::isSelected() const throw()
  45868. {
  45869. return selected;
  45870. }
  45871. void TreeViewItem::deselectAllRecursively()
  45872. {
  45873. setSelected (false, false);
  45874. for (int i = 0; i < subItems.size(); ++i)
  45875. subItems.getUnchecked(i)->deselectAllRecursively();
  45876. }
  45877. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45878. const bool deselectOtherItemsFirst)
  45879. {
  45880. if (shouldBeSelected && ! canBeSelected())
  45881. return;
  45882. if (deselectOtherItemsFirst)
  45883. getTopLevelItem()->deselectAllRecursively();
  45884. if (shouldBeSelected != selected)
  45885. {
  45886. selected = shouldBeSelected;
  45887. if (ownerView != 0)
  45888. ownerView->repaint();
  45889. itemSelectionChanged (shouldBeSelected);
  45890. }
  45891. }
  45892. void TreeViewItem::paintItem (Graphics&, int, int)
  45893. {
  45894. }
  45895. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45896. {
  45897. ownerView->getLookAndFeel()
  45898. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45899. }
  45900. void TreeViewItem::itemClicked (const MouseEvent&)
  45901. {
  45902. }
  45903. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45904. {
  45905. if (mightContainSubItems())
  45906. setOpen (! isOpen());
  45907. }
  45908. void TreeViewItem::itemSelectionChanged (bool)
  45909. {
  45910. }
  45911. const String TreeViewItem::getTooltip()
  45912. {
  45913. return String::empty;
  45914. }
  45915. const String TreeViewItem::getDragSourceDescription()
  45916. {
  45917. return String::empty;
  45918. }
  45919. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45920. {
  45921. return false;
  45922. }
  45923. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45924. {
  45925. }
  45926. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45927. {
  45928. return false;
  45929. }
  45930. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45931. {
  45932. }
  45933. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45934. {
  45935. const int indentX = getIndentX();
  45936. int width = itemWidth;
  45937. if (ownerView != 0 && width < 0)
  45938. width = ownerView->viewport->getViewWidth() - indentX;
  45939. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45940. if (relativeToTreeViewTopLeft)
  45941. r -= ownerView->viewport->getViewPosition();
  45942. return r;
  45943. }
  45944. void TreeViewItem::treeHasChanged() const throw()
  45945. {
  45946. if (ownerView != 0)
  45947. ownerView->itemsChanged();
  45948. }
  45949. void TreeViewItem::repaintItem() const
  45950. {
  45951. if (ownerView != 0 && areAllParentsOpen())
  45952. {
  45953. Rectangle<int> r (getItemPosition (true));
  45954. r.setLeft (0);
  45955. ownerView->viewport->repaint (r);
  45956. }
  45957. }
  45958. bool TreeViewItem::areAllParentsOpen() const throw()
  45959. {
  45960. return parentItem == 0
  45961. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45962. }
  45963. void TreeViewItem::updatePositions (int newY)
  45964. {
  45965. y = newY;
  45966. itemHeight = getItemHeight();
  45967. totalHeight = itemHeight;
  45968. itemWidth = getItemWidth();
  45969. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45970. if (isOpen())
  45971. {
  45972. newY += totalHeight;
  45973. for (int i = 0; i < subItems.size(); ++i)
  45974. {
  45975. TreeViewItem* const ti = subItems.getUnchecked(i);
  45976. ti->updatePositions (newY);
  45977. newY += ti->totalHeight;
  45978. totalHeight += ti->totalHeight;
  45979. totalWidth = jmax (totalWidth, ti->totalWidth);
  45980. }
  45981. }
  45982. }
  45983. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45984. {
  45985. TreeViewItem* result = this;
  45986. TreeViewItem* item = this;
  45987. while (item->parentItem != 0)
  45988. {
  45989. item = item->parentItem;
  45990. if (! item->isOpen())
  45991. result = item;
  45992. }
  45993. return result;
  45994. }
  45995. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45996. {
  45997. ownerView = newOwner;
  45998. for (int i = subItems.size(); --i >= 0;)
  45999. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46000. }
  46001. int TreeViewItem::getIndentX() const throw()
  46002. {
  46003. const int indentWidth = ownerView->getIndentSize();
  46004. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46005. if (! ownerView->openCloseButtonsVisible)
  46006. x -= indentWidth;
  46007. TreeViewItem* p = parentItem;
  46008. while (p != 0)
  46009. {
  46010. x += indentWidth;
  46011. p = p->parentItem;
  46012. }
  46013. return x;
  46014. }
  46015. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46016. {
  46017. drawsInLeftMargin = canDrawInLeftMargin;
  46018. }
  46019. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46020. {
  46021. jassert (ownerView != 0);
  46022. if (ownerView == 0)
  46023. return;
  46024. const int indent = getIndentX();
  46025. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46026. {
  46027. Graphics::ScopedSaveState ss (g);
  46028. g.setOrigin (indent, 0);
  46029. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46030. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46031. paintItem (g, itemW, itemHeight);
  46032. }
  46033. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46034. const float halfH = itemHeight * 0.5f;
  46035. int depth = 0;
  46036. TreeViewItem* p = parentItem;
  46037. while (p != 0)
  46038. {
  46039. ++depth;
  46040. p = p->parentItem;
  46041. }
  46042. if (! ownerView->rootItemVisible)
  46043. --depth;
  46044. const int indentWidth = ownerView->getIndentSize();
  46045. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46046. {
  46047. float x = (depth + 0.5f) * indentWidth;
  46048. if (depth >= 0)
  46049. {
  46050. if (parentItem != 0 && parentItem->drawLinesInside)
  46051. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46052. if ((parentItem != 0 && parentItem->drawLinesInside)
  46053. || (parentItem == 0 && drawLinesInside))
  46054. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46055. }
  46056. p = parentItem;
  46057. int d = depth;
  46058. while (p != 0 && --d >= 0)
  46059. {
  46060. x -= (float) indentWidth;
  46061. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46062. && ! p->isLastOfSiblings())
  46063. {
  46064. g.drawLine (x, 0, x, (float) itemHeight);
  46065. }
  46066. p = p->parentItem;
  46067. }
  46068. if (mightContainSubItems())
  46069. {
  46070. Graphics::ScopedSaveState ss (g);
  46071. g.setOrigin (depth * indentWidth, 0);
  46072. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46073. paintOpenCloseButton (g, indentWidth, itemHeight,
  46074. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46075. ->isMouseOverButton (this));
  46076. }
  46077. }
  46078. if (isOpen())
  46079. {
  46080. const Rectangle<int> clip (g.getClipBounds());
  46081. for (int i = 0; i < subItems.size(); ++i)
  46082. {
  46083. TreeViewItem* const ti = subItems.getUnchecked(i);
  46084. const int relY = ti->y - y;
  46085. if (relY >= clip.getBottom())
  46086. break;
  46087. if (relY + ti->totalHeight >= clip.getY())
  46088. {
  46089. Graphics::ScopedSaveState ss (g);
  46090. g.setOrigin (0, relY);
  46091. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46092. ti->paintRecursively (g, width);
  46093. }
  46094. }
  46095. }
  46096. }
  46097. bool TreeViewItem::isLastOfSiblings() const throw()
  46098. {
  46099. return parentItem == 0
  46100. || parentItem->subItems.getLast() == this;
  46101. }
  46102. int TreeViewItem::getIndexInParent() const throw()
  46103. {
  46104. return parentItem == 0 ? 0
  46105. : parentItem->subItems.indexOf (this);
  46106. }
  46107. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46108. {
  46109. return parentItem == 0 ? this
  46110. : parentItem->getTopLevelItem();
  46111. }
  46112. int TreeViewItem::getNumRows() const throw()
  46113. {
  46114. int num = 1;
  46115. if (isOpen())
  46116. {
  46117. for (int i = subItems.size(); --i >= 0;)
  46118. num += subItems.getUnchecked(i)->getNumRows();
  46119. }
  46120. return num;
  46121. }
  46122. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46123. {
  46124. if (index == 0)
  46125. return this;
  46126. if (index > 0 && isOpen())
  46127. {
  46128. --index;
  46129. for (int i = 0; i < subItems.size(); ++i)
  46130. {
  46131. TreeViewItem* const item = subItems.getUnchecked(i);
  46132. if (index == 0)
  46133. return item;
  46134. const int numRows = item->getNumRows();
  46135. if (numRows > index)
  46136. return item->getItemOnRow (index);
  46137. index -= numRows;
  46138. }
  46139. }
  46140. return 0;
  46141. }
  46142. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46143. {
  46144. if (isPositiveAndBelow (targetY, totalHeight))
  46145. {
  46146. const int h = itemHeight;
  46147. if (targetY < h)
  46148. return this;
  46149. if (isOpen())
  46150. {
  46151. targetY -= h;
  46152. for (int i = 0; i < subItems.size(); ++i)
  46153. {
  46154. TreeViewItem* const ti = subItems.getUnchecked(i);
  46155. if (targetY < ti->totalHeight)
  46156. return ti->findItemRecursively (targetY);
  46157. targetY -= ti->totalHeight;
  46158. }
  46159. }
  46160. }
  46161. return 0;
  46162. }
  46163. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46164. {
  46165. int total = isSelected() ? 1 : 0;
  46166. if (depth != 0)
  46167. for (int i = subItems.size(); --i >= 0;)
  46168. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46169. return total;
  46170. }
  46171. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46172. {
  46173. if (isSelected())
  46174. {
  46175. if (index == 0)
  46176. return this;
  46177. --index;
  46178. }
  46179. if (index >= 0)
  46180. {
  46181. for (int i = 0; i < subItems.size(); ++i)
  46182. {
  46183. TreeViewItem* const item = subItems.getUnchecked(i);
  46184. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46185. if (found != 0)
  46186. return found;
  46187. index -= item->countSelectedItemsRecursively (-1);
  46188. }
  46189. }
  46190. return 0;
  46191. }
  46192. int TreeViewItem::getRowNumberInTree() const throw()
  46193. {
  46194. if (parentItem != 0 && ownerView != 0)
  46195. {
  46196. int n = 1 + parentItem->getRowNumberInTree();
  46197. int ourIndex = parentItem->subItems.indexOf (this);
  46198. jassert (ourIndex >= 0);
  46199. while (--ourIndex >= 0)
  46200. n += parentItem->subItems [ourIndex]->getNumRows();
  46201. if (parentItem->parentItem == 0
  46202. && ! ownerView->rootItemVisible)
  46203. --n;
  46204. return n;
  46205. }
  46206. else
  46207. {
  46208. return 0;
  46209. }
  46210. }
  46211. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46212. {
  46213. drawLinesInside = drawLines;
  46214. }
  46215. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46216. {
  46217. if (recurse && isOpen() && subItems.size() > 0)
  46218. return subItems [0];
  46219. if (parentItem != 0)
  46220. {
  46221. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46222. if (nextIndex >= parentItem->subItems.size())
  46223. return parentItem->getNextVisibleItem (false);
  46224. return parentItem->subItems [nextIndex];
  46225. }
  46226. return 0;
  46227. }
  46228. const String TreeViewItem::getItemIdentifierString() const
  46229. {
  46230. String s;
  46231. if (parentItem != 0)
  46232. s = parentItem->getItemIdentifierString();
  46233. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46234. }
  46235. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46236. {
  46237. const String thisId (getUniqueName());
  46238. if (thisId == identifierString)
  46239. return this;
  46240. if (identifierString.startsWith (thisId + "/"))
  46241. {
  46242. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46243. bool wasOpen = isOpen();
  46244. setOpen (true);
  46245. for (int i = subItems.size(); --i >= 0;)
  46246. {
  46247. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46248. if (item != 0)
  46249. return item;
  46250. }
  46251. setOpen (wasOpen);
  46252. }
  46253. return 0;
  46254. }
  46255. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46256. {
  46257. if (e.hasTagName ("CLOSED"))
  46258. {
  46259. setOpen (false);
  46260. }
  46261. else if (e.hasTagName ("OPEN"))
  46262. {
  46263. setOpen (true);
  46264. forEachXmlChildElement (e, n)
  46265. {
  46266. const String id (n->getStringAttribute ("id"));
  46267. for (int i = 0; i < subItems.size(); ++i)
  46268. {
  46269. TreeViewItem* const ti = subItems.getUnchecked(i);
  46270. if (ti->getUniqueName() == id)
  46271. {
  46272. ti->restoreOpennessState (*n);
  46273. break;
  46274. }
  46275. }
  46276. }
  46277. }
  46278. }
  46279. XmlElement* TreeViewItem::getOpennessState() const throw()
  46280. {
  46281. const String name (getUniqueName());
  46282. if (name.isNotEmpty())
  46283. {
  46284. XmlElement* e;
  46285. if (isOpen())
  46286. {
  46287. e = new XmlElement ("OPEN");
  46288. for (int i = 0; i < subItems.size(); ++i)
  46289. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46290. }
  46291. else
  46292. {
  46293. e = new XmlElement ("CLOSED");
  46294. }
  46295. e->setAttribute ("id", name);
  46296. return e;
  46297. }
  46298. else
  46299. {
  46300. // trying to save the openness for an element that has no name - this won't
  46301. // work because it needs the names to identify what to open.
  46302. jassertfalse;
  46303. }
  46304. return 0;
  46305. }
  46306. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46307. : treeViewItem (treeViewItem_),
  46308. oldOpenness (treeViewItem_.getOpennessState())
  46309. {
  46310. }
  46311. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46312. {
  46313. if (oldOpenness != 0)
  46314. treeViewItem.restoreOpennessState (*oldOpenness);
  46315. }
  46316. END_JUCE_NAMESPACE
  46317. /*** End of inlined file: juce_TreeView.cpp ***/
  46318. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46319. BEGIN_JUCE_NAMESPACE
  46320. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46321. : fileList (listToShow)
  46322. {
  46323. }
  46324. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46325. {
  46326. }
  46327. FileBrowserListener::~FileBrowserListener()
  46328. {
  46329. }
  46330. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46331. {
  46332. listeners.add (listener);
  46333. }
  46334. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46335. {
  46336. listeners.remove (listener);
  46337. }
  46338. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46339. {
  46340. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46341. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46342. }
  46343. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46344. {
  46345. if (fileList.getDirectory().exists())
  46346. {
  46347. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46348. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46349. }
  46350. }
  46351. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46352. {
  46353. if (fileList.getDirectory().exists())
  46354. {
  46355. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46356. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46357. }
  46358. }
  46359. END_JUCE_NAMESPACE
  46360. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46361. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46362. BEGIN_JUCE_NAMESPACE
  46363. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46364. TimeSliceThread& thread_)
  46365. : fileFilter (fileFilter_),
  46366. thread (thread_),
  46367. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46368. fileFindHandle (0),
  46369. shouldStop (true)
  46370. {
  46371. }
  46372. DirectoryContentsList::~DirectoryContentsList()
  46373. {
  46374. clear();
  46375. }
  46376. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46377. {
  46378. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46379. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46380. }
  46381. bool DirectoryContentsList::ignoresHiddenFiles() const
  46382. {
  46383. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46384. }
  46385. const File& DirectoryContentsList::getDirectory() const
  46386. {
  46387. return root;
  46388. }
  46389. void DirectoryContentsList::setDirectory (const File& directory,
  46390. const bool includeDirectories,
  46391. const bool includeFiles)
  46392. {
  46393. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46394. if (directory != root)
  46395. {
  46396. clear();
  46397. root = directory;
  46398. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46399. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46400. }
  46401. int newFlags = fileTypeFlags;
  46402. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46403. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46404. setTypeFlags (newFlags);
  46405. }
  46406. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46407. {
  46408. if (fileTypeFlags != newFlags)
  46409. {
  46410. fileTypeFlags = newFlags;
  46411. refresh();
  46412. }
  46413. }
  46414. void DirectoryContentsList::clear()
  46415. {
  46416. shouldStop = true;
  46417. thread.removeTimeSliceClient (this);
  46418. fileFindHandle = 0;
  46419. if (files.size() > 0)
  46420. {
  46421. files.clear();
  46422. changed();
  46423. }
  46424. }
  46425. void DirectoryContentsList::refresh()
  46426. {
  46427. clear();
  46428. if (root.isDirectory())
  46429. {
  46430. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46431. shouldStop = false;
  46432. thread.addTimeSliceClient (this);
  46433. }
  46434. }
  46435. int DirectoryContentsList::getNumFiles() const
  46436. {
  46437. return files.size();
  46438. }
  46439. bool DirectoryContentsList::getFileInfo (const int index,
  46440. FileInfo& result) const
  46441. {
  46442. const ScopedLock sl (fileListLock);
  46443. const FileInfo* const info = files [index];
  46444. if (info != 0)
  46445. {
  46446. result = *info;
  46447. return true;
  46448. }
  46449. return false;
  46450. }
  46451. const File DirectoryContentsList::getFile (const int index) const
  46452. {
  46453. const ScopedLock sl (fileListLock);
  46454. const FileInfo* const info = files [index];
  46455. if (info != 0)
  46456. return root.getChildFile (info->filename);
  46457. return File::nonexistent;
  46458. }
  46459. bool DirectoryContentsList::isStillLoading() const
  46460. {
  46461. return fileFindHandle != 0;
  46462. }
  46463. void DirectoryContentsList::changed()
  46464. {
  46465. sendChangeMessage();
  46466. }
  46467. int DirectoryContentsList::useTimeSlice()
  46468. {
  46469. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46470. bool hasChanged = false;
  46471. for (int i = 100; --i >= 0;)
  46472. {
  46473. if (! checkNextFile (hasChanged))
  46474. {
  46475. if (hasChanged)
  46476. changed();
  46477. return 500;
  46478. }
  46479. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46480. break;
  46481. }
  46482. if (hasChanged)
  46483. changed();
  46484. return 0;
  46485. }
  46486. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46487. {
  46488. if (fileFindHandle != 0)
  46489. {
  46490. bool fileFoundIsDir, isHidden, isReadOnly;
  46491. int64 fileSize;
  46492. Time modTime, creationTime;
  46493. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46494. &modTime, &creationTime, &isReadOnly))
  46495. {
  46496. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46497. fileSize, modTime, creationTime, isReadOnly))
  46498. {
  46499. hasChanged = true;
  46500. }
  46501. return true;
  46502. }
  46503. else
  46504. {
  46505. fileFindHandle = 0;
  46506. }
  46507. }
  46508. return false;
  46509. }
  46510. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46511. const DirectoryContentsList::FileInfo* const second)
  46512. {
  46513. #if JUCE_WINDOWS
  46514. if (first->isDirectory != second->isDirectory)
  46515. return first->isDirectory ? -1 : 1;
  46516. #endif
  46517. return first->filename.compareIgnoreCase (second->filename);
  46518. }
  46519. bool DirectoryContentsList::addFile (const File& file,
  46520. const bool isDir,
  46521. const int64 fileSize,
  46522. const Time& modTime,
  46523. const Time& creationTime,
  46524. const bool isReadOnly)
  46525. {
  46526. if (fileFilter == 0
  46527. || ((! isDir) && fileFilter->isFileSuitable (file))
  46528. || (isDir && fileFilter->isDirectorySuitable (file)))
  46529. {
  46530. ScopedPointer <FileInfo> info (new FileInfo());
  46531. info->filename = file.getFileName();
  46532. info->fileSize = fileSize;
  46533. info->modificationTime = modTime;
  46534. info->creationTime = creationTime;
  46535. info->isDirectory = isDir;
  46536. info->isReadOnly = isReadOnly;
  46537. const ScopedLock sl (fileListLock);
  46538. for (int i = files.size(); --i >= 0;)
  46539. if (files.getUnchecked(i)->filename == info->filename)
  46540. return false;
  46541. files.addSorted (*this, info.release());
  46542. return true;
  46543. }
  46544. return false;
  46545. }
  46546. END_JUCE_NAMESPACE
  46547. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46548. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46549. BEGIN_JUCE_NAMESPACE
  46550. FileBrowserComponent::FileBrowserComponent (int flags_,
  46551. const File& initialFileOrDirectory,
  46552. const FileFilter* fileFilter_,
  46553. FilePreviewComponent* previewComp_)
  46554. : FileFilter (String::empty),
  46555. fileFilter (fileFilter_),
  46556. flags (flags_),
  46557. previewComp (previewComp_),
  46558. currentPathBox ("path"),
  46559. fileLabel ("f", TRANS ("file:")),
  46560. thread ("Juce FileBrowser")
  46561. {
  46562. // You need to specify one or other of the open/save flags..
  46563. jassert ((flags & (saveMode | openMode)) != 0);
  46564. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46565. // You need to specify at least one of these flags..
  46566. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46567. String filename;
  46568. if (initialFileOrDirectory == File::nonexistent)
  46569. {
  46570. currentRoot = File::getCurrentWorkingDirectory();
  46571. }
  46572. else if (initialFileOrDirectory.isDirectory())
  46573. {
  46574. currentRoot = initialFileOrDirectory;
  46575. }
  46576. else
  46577. {
  46578. chosenFiles.add (initialFileOrDirectory);
  46579. currentRoot = initialFileOrDirectory.getParentDirectory();
  46580. filename = initialFileOrDirectory.getFileName();
  46581. }
  46582. fileList = new DirectoryContentsList (this, thread);
  46583. if ((flags & useTreeView) != 0)
  46584. {
  46585. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46586. fileListComponent = tree;
  46587. if ((flags & canSelectMultipleItems) != 0)
  46588. tree->setMultiSelectEnabled (true);
  46589. addAndMakeVisible (tree);
  46590. }
  46591. else
  46592. {
  46593. FileListComponent* const list = new FileListComponent (*fileList);
  46594. fileListComponent = list;
  46595. list->setOutlineThickness (1);
  46596. if ((flags & canSelectMultipleItems) != 0)
  46597. list->setMultipleSelectionEnabled (true);
  46598. addAndMakeVisible (list);
  46599. }
  46600. fileListComponent->addListener (this);
  46601. addAndMakeVisible (&currentPathBox);
  46602. currentPathBox.setEditableText (true);
  46603. StringArray rootNames, rootPaths;
  46604. getRoots (rootNames, rootPaths);
  46605. for (int i = 0; i < rootNames.size(); ++i)
  46606. {
  46607. if (rootNames[i].isEmpty())
  46608. currentPathBox.addSeparator();
  46609. else
  46610. currentPathBox.addItem (rootNames[i], i + 1);
  46611. }
  46612. currentPathBox.addSeparator();
  46613. currentPathBox.addListener (this);
  46614. addAndMakeVisible (&filenameBox);
  46615. filenameBox.setMultiLine (false);
  46616. filenameBox.setSelectAllWhenFocused (true);
  46617. filenameBox.setText (filename, false);
  46618. filenameBox.addListener (this);
  46619. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46620. addAndMakeVisible (&fileLabel);
  46621. fileLabel.attachToComponent (&filenameBox, true);
  46622. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46623. goUpButton->addListener (this);
  46624. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46625. if (previewComp != 0)
  46626. addAndMakeVisible (previewComp);
  46627. setRoot (currentRoot);
  46628. thread.startThread (4);
  46629. }
  46630. FileBrowserComponent::~FileBrowserComponent()
  46631. {
  46632. fileListComponent = 0;
  46633. fileList = 0;
  46634. thread.stopThread (10000);
  46635. }
  46636. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46637. {
  46638. listeners.add (newListener);
  46639. }
  46640. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46641. {
  46642. listeners.remove (listener);
  46643. }
  46644. bool FileBrowserComponent::isSaveMode() const throw()
  46645. {
  46646. return (flags & saveMode) != 0;
  46647. }
  46648. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46649. {
  46650. if (chosenFiles.size() == 0 && currentFileIsValid())
  46651. return 1;
  46652. return chosenFiles.size();
  46653. }
  46654. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46655. {
  46656. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46657. return currentRoot;
  46658. if (! filenameBox.isReadOnly())
  46659. return currentRoot.getChildFile (filenameBox.getText());
  46660. return chosenFiles[index];
  46661. }
  46662. bool FileBrowserComponent::currentFileIsValid() const
  46663. {
  46664. if (isSaveMode())
  46665. return ! getSelectedFile (0).isDirectory();
  46666. else
  46667. return getSelectedFile (0).exists();
  46668. }
  46669. const File FileBrowserComponent::getHighlightedFile() const throw()
  46670. {
  46671. return fileListComponent->getSelectedFile (0);
  46672. }
  46673. void FileBrowserComponent::deselectAllFiles()
  46674. {
  46675. fileListComponent->deselectAllFiles();
  46676. }
  46677. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46678. {
  46679. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46680. }
  46681. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46682. {
  46683. return true;
  46684. }
  46685. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46686. {
  46687. if (f.isDirectory())
  46688. return (flags & canSelectDirectories) != 0
  46689. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46690. return (flags & canSelectFiles) != 0 && f.exists()
  46691. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46692. }
  46693. const File FileBrowserComponent::getRoot() const
  46694. {
  46695. return currentRoot;
  46696. }
  46697. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46698. {
  46699. if (currentRoot != newRootDirectory)
  46700. {
  46701. fileListComponent->scrollToTop();
  46702. String path (newRootDirectory.getFullPathName());
  46703. if (path.isEmpty())
  46704. path = File::separatorString;
  46705. StringArray rootNames, rootPaths;
  46706. getRoots (rootNames, rootPaths);
  46707. if (! rootPaths.contains (path, true))
  46708. {
  46709. bool alreadyListed = false;
  46710. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46711. {
  46712. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46713. {
  46714. alreadyListed = true;
  46715. break;
  46716. }
  46717. }
  46718. if (! alreadyListed)
  46719. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46720. }
  46721. }
  46722. currentRoot = newRootDirectory;
  46723. fileList->setDirectory (currentRoot, true, true);
  46724. String currentRootName (currentRoot.getFullPathName());
  46725. if (currentRootName.isEmpty())
  46726. currentRootName = File::separatorString;
  46727. currentPathBox.setText (currentRootName, true);
  46728. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46729. && currentRoot.getParentDirectory() != currentRoot);
  46730. }
  46731. void FileBrowserComponent::goUp()
  46732. {
  46733. setRoot (getRoot().getParentDirectory());
  46734. }
  46735. void FileBrowserComponent::refresh()
  46736. {
  46737. fileList->refresh();
  46738. }
  46739. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46740. {
  46741. if (fileFilter != newFileFilter)
  46742. {
  46743. fileFilter = newFileFilter;
  46744. refresh();
  46745. }
  46746. }
  46747. const String FileBrowserComponent::getActionVerb() const
  46748. {
  46749. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46750. }
  46751. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46752. {
  46753. return previewComp;
  46754. }
  46755. void FileBrowserComponent::resized()
  46756. {
  46757. getLookAndFeel()
  46758. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46759. &currentPathBox, &filenameBox, goUpButton);
  46760. }
  46761. void FileBrowserComponent::sendListenerChangeMessage()
  46762. {
  46763. Component::BailOutChecker checker (this);
  46764. if (previewComp != 0)
  46765. previewComp->selectedFileChanged (getSelectedFile (0));
  46766. // You shouldn't delete the browser when the file gets changed!
  46767. jassert (! checker.shouldBailOut());
  46768. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46769. }
  46770. void FileBrowserComponent::selectionChanged()
  46771. {
  46772. StringArray newFilenames;
  46773. bool resetChosenFiles = true;
  46774. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46775. {
  46776. const File f (fileListComponent->getSelectedFile (i));
  46777. if (isFileOrDirSuitable (f))
  46778. {
  46779. if (resetChosenFiles)
  46780. {
  46781. chosenFiles.clear();
  46782. resetChosenFiles = false;
  46783. }
  46784. chosenFiles.add (f);
  46785. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46786. }
  46787. }
  46788. if (newFilenames.size() > 0)
  46789. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46790. sendListenerChangeMessage();
  46791. }
  46792. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46793. {
  46794. Component::BailOutChecker checker (this);
  46795. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46796. }
  46797. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46798. {
  46799. if (f.isDirectory())
  46800. {
  46801. setRoot (f);
  46802. if ((flags & canSelectDirectories) != 0)
  46803. filenameBox.setText (String::empty);
  46804. }
  46805. else
  46806. {
  46807. Component::BailOutChecker checker (this);
  46808. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46809. }
  46810. }
  46811. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46812. {
  46813. (void) key;
  46814. #if JUCE_LINUX || JUCE_WINDOWS
  46815. if (key.getModifiers().isCommandDown()
  46816. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46817. {
  46818. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46819. fileList->refresh();
  46820. return true;
  46821. }
  46822. #endif
  46823. return false;
  46824. }
  46825. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46826. {
  46827. sendListenerChangeMessage();
  46828. }
  46829. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46830. {
  46831. if (filenameBox.getText().containsChar (File::separator))
  46832. {
  46833. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46834. if (f.isDirectory())
  46835. {
  46836. setRoot (f);
  46837. chosenFiles.clear();
  46838. filenameBox.setText (String::empty);
  46839. }
  46840. else
  46841. {
  46842. setRoot (f.getParentDirectory());
  46843. chosenFiles.clear();
  46844. chosenFiles.add (f);
  46845. filenameBox.setText (f.getFileName());
  46846. }
  46847. }
  46848. else
  46849. {
  46850. fileDoubleClicked (getSelectedFile (0));
  46851. }
  46852. }
  46853. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46854. {
  46855. }
  46856. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46857. {
  46858. if (! isSaveMode())
  46859. selectionChanged();
  46860. }
  46861. void FileBrowserComponent::buttonClicked (Button*)
  46862. {
  46863. goUp();
  46864. }
  46865. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46866. {
  46867. const String newText (currentPathBox.getText().trim().unquoted());
  46868. if (newText.isNotEmpty())
  46869. {
  46870. const int index = currentPathBox.getSelectedId() - 1;
  46871. StringArray rootNames, rootPaths;
  46872. getRoots (rootNames, rootPaths);
  46873. if (rootPaths [index].isNotEmpty())
  46874. {
  46875. setRoot (File (rootPaths [index]));
  46876. }
  46877. else
  46878. {
  46879. File f (newText);
  46880. for (;;)
  46881. {
  46882. if (f.isDirectory())
  46883. {
  46884. setRoot (f);
  46885. break;
  46886. }
  46887. if (f.getParentDirectory() == f)
  46888. break;
  46889. f = f.getParentDirectory();
  46890. }
  46891. }
  46892. }
  46893. }
  46894. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46895. {
  46896. #if JUCE_WINDOWS
  46897. Array<File> roots;
  46898. File::findFileSystemRoots (roots);
  46899. rootPaths.clear();
  46900. for (int i = 0; i < roots.size(); ++i)
  46901. {
  46902. const File& drive = roots.getReference(i);
  46903. String name (drive.getFullPathName());
  46904. rootPaths.add (name);
  46905. if (drive.isOnHardDisk())
  46906. {
  46907. String volume (drive.getVolumeLabel());
  46908. if (volume.isEmpty())
  46909. volume = TRANS("Hard Drive");
  46910. name << " [" << volume << ']';
  46911. }
  46912. else if (drive.isOnCDRomDrive())
  46913. {
  46914. name << TRANS(" [CD/DVD drive]");
  46915. }
  46916. rootNames.add (name);
  46917. }
  46918. rootPaths.add (String::empty);
  46919. rootNames.add (String::empty);
  46920. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46921. rootNames.add ("Documents");
  46922. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46923. rootNames.add ("Desktop");
  46924. #endif
  46925. #if JUCE_MAC
  46926. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46927. rootNames.add ("Home folder");
  46928. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46929. rootNames.add ("Documents");
  46930. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46931. rootNames.add ("Desktop");
  46932. rootPaths.add (String::empty);
  46933. rootNames.add (String::empty);
  46934. Array <File> volumes;
  46935. File vol ("/Volumes");
  46936. vol.findChildFiles (volumes, File::findDirectories, false);
  46937. for (int i = 0; i < volumes.size(); ++i)
  46938. {
  46939. const File& volume = volumes.getReference(i);
  46940. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46941. {
  46942. rootPaths.add (volume.getFullPathName());
  46943. rootNames.add (volume.getFileName());
  46944. }
  46945. }
  46946. #endif
  46947. #if JUCE_LINUX
  46948. rootPaths.add ("/");
  46949. rootNames.add ("/");
  46950. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46951. rootNames.add ("Home folder");
  46952. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46953. rootNames.add ("Desktop");
  46954. #endif
  46955. }
  46956. END_JUCE_NAMESPACE
  46957. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46958. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46959. BEGIN_JUCE_NAMESPACE
  46960. FileChooser::FileChooser (const String& chooserBoxTitle,
  46961. const File& currentFileOrDirectory,
  46962. const String& fileFilters,
  46963. const bool useNativeDialogBox_)
  46964. : title (chooserBoxTitle),
  46965. filters (fileFilters),
  46966. startingFile (currentFileOrDirectory),
  46967. useNativeDialogBox (useNativeDialogBox_)
  46968. {
  46969. #if JUCE_LINUX
  46970. useNativeDialogBox = false;
  46971. #endif
  46972. if (! fileFilters.containsNonWhitespaceChars())
  46973. filters = "*";
  46974. }
  46975. FileChooser::~FileChooser()
  46976. {
  46977. }
  46978. #if JUCE_MODAL_LOOPS_PERMITTED
  46979. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46980. {
  46981. return showDialog (false, true, false, false, false, previewComponent);
  46982. }
  46983. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46984. {
  46985. return showDialog (false, true, false, false, true, previewComponent);
  46986. }
  46987. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46988. {
  46989. return showDialog (true, true, false, false, true, previewComponent);
  46990. }
  46991. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46992. {
  46993. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46994. }
  46995. bool FileChooser::browseForDirectory()
  46996. {
  46997. return showDialog (true, false, false, false, false, 0);
  46998. }
  46999. bool FileChooser::showDialog (const bool selectsDirectories,
  47000. const bool selectsFiles,
  47001. const bool isSave,
  47002. const bool warnAboutOverwritingExistingFiles,
  47003. const bool selectMultipleFiles,
  47004. FilePreviewComponent* const previewComponent)
  47005. {
  47006. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47007. results.clear();
  47008. // the preview component needs to be the right size before you pass it in here..
  47009. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47010. && previewComponent->getHeight() > 10));
  47011. #if JUCE_WINDOWS
  47012. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47013. #elif JUCE_MAC
  47014. if (useNativeDialogBox && (previewComponent == 0))
  47015. #else
  47016. if (false)
  47017. #endif
  47018. {
  47019. showPlatformDialog (results, title, startingFile, filters,
  47020. selectsDirectories, selectsFiles, isSave,
  47021. warnAboutOverwritingExistingFiles,
  47022. selectMultipleFiles,
  47023. previewComponent);
  47024. }
  47025. else
  47026. {
  47027. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47028. selectsDirectories ? "*" : String::empty,
  47029. String::empty);
  47030. int flags = isSave ? FileBrowserComponent::saveMode
  47031. : FileBrowserComponent::openMode;
  47032. if (selectsFiles)
  47033. flags |= FileBrowserComponent::canSelectFiles;
  47034. if (selectsDirectories)
  47035. {
  47036. flags |= FileBrowserComponent::canSelectDirectories;
  47037. if (! isSave)
  47038. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47039. }
  47040. if (selectMultipleFiles)
  47041. flags |= FileBrowserComponent::canSelectMultipleItems;
  47042. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47043. FileChooserDialogBox box (title, String::empty,
  47044. browserComponent,
  47045. warnAboutOverwritingExistingFiles,
  47046. browserComponent.findColour (AlertWindow::backgroundColourId));
  47047. if (box.show())
  47048. {
  47049. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47050. results.add (browserComponent.getSelectedFile (i));
  47051. }
  47052. }
  47053. if (previouslyFocused != 0)
  47054. previouslyFocused->grabKeyboardFocus();
  47055. return results.size() > 0;
  47056. }
  47057. #endif
  47058. const File FileChooser::getResult() const
  47059. {
  47060. // if you've used a multiple-file select, you should use the getResults() method
  47061. // to retrieve all the files that were chosen.
  47062. jassert (results.size() <= 1);
  47063. return results.getFirst();
  47064. }
  47065. const Array<File>& FileChooser::getResults() const
  47066. {
  47067. return results;
  47068. }
  47069. FilePreviewComponent::FilePreviewComponent()
  47070. {
  47071. }
  47072. FilePreviewComponent::~FilePreviewComponent()
  47073. {
  47074. }
  47075. END_JUCE_NAMESPACE
  47076. /*** End of inlined file: juce_FileChooser.cpp ***/
  47077. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47078. BEGIN_JUCE_NAMESPACE
  47079. class FileChooserDialogBox::ContentComponent : public Component
  47080. {
  47081. public:
  47082. ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47083. : Component (name),
  47084. chooserComponent (chooserComponent_),
  47085. okButton (chooserComponent_.getActionVerb()),
  47086. cancelButton (TRANS ("Cancel")),
  47087. newFolderButton (TRANS ("New Folder")),
  47088. instructions (instructions_)
  47089. {
  47090. addAndMakeVisible (&chooserComponent);
  47091. addAndMakeVisible (&okButton);
  47092. okButton.addShortcut (KeyPress::returnKey);
  47093. addAndMakeVisible (&cancelButton);
  47094. cancelButton.addShortcut (KeyPress::escapeKey);
  47095. addChildComponent (&newFolderButton);
  47096. setInterceptsMouseClicks (false, true);
  47097. }
  47098. void paint (Graphics& g)
  47099. {
  47100. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47101. text.draw (g);
  47102. }
  47103. void resized()
  47104. {
  47105. const int buttonHeight = 26;
  47106. Rectangle<int> area (getLocalBounds());
  47107. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47108. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47109. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47110. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47111. Rectangle<int> buttonArea (area.reduced (16, 10));
  47112. okButton.changeWidthToFitText (buttonHeight);
  47113. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47114. buttonArea.removeFromRight (16);
  47115. cancelButton.changeWidthToFitText (buttonHeight);
  47116. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47117. newFolderButton.changeWidthToFitText (buttonHeight);
  47118. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47119. }
  47120. FileBrowserComponent& chooserComponent;
  47121. TextButton okButton, cancelButton, newFolderButton;
  47122. private:
  47123. String instructions;
  47124. GlyphArrangement text;
  47125. };
  47126. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47127. const String& instructions,
  47128. FileBrowserComponent& chooserComponent,
  47129. const bool warnAboutOverwritingExistingFiles_,
  47130. const Colour& backgroundColour)
  47131. : ResizableWindow (name, backgroundColour, true),
  47132. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47133. {
  47134. content = new ContentComponent (name, instructions, chooserComponent);
  47135. setContentOwned (content, false);
  47136. setResizable (true, true);
  47137. setResizeLimits (300, 300, 1200, 1000);
  47138. content->okButton.addListener (this);
  47139. content->cancelButton.addListener (this);
  47140. content->newFolderButton.addListener (this);
  47141. content->chooserComponent.addListener (this);
  47142. selectionChanged();
  47143. }
  47144. FileChooserDialogBox::~FileChooserDialogBox()
  47145. {
  47146. content->chooserComponent.removeListener (this);
  47147. }
  47148. #if JUCE_MODAL_LOOPS_PERMITTED
  47149. bool FileChooserDialogBox::show (int w, int h)
  47150. {
  47151. return showAt (-1, -1, w, h);
  47152. }
  47153. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47154. {
  47155. if (w <= 0)
  47156. {
  47157. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47158. if (previewComp != 0)
  47159. w = 400 + previewComp->getWidth();
  47160. else
  47161. w = 600;
  47162. }
  47163. if (h <= 0)
  47164. h = 500;
  47165. if (x < 0 || y < 0)
  47166. centreWithSize (w, h);
  47167. else
  47168. setBounds (x, y, w, h);
  47169. const bool ok = (runModalLoop() != 0);
  47170. setVisible (false);
  47171. return ok;
  47172. }
  47173. #endif
  47174. void FileChooserDialogBox::centreWithDefaultSize (Component* componentToCentreAround)
  47175. {
  47176. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47177. centreAroundComponent (componentToCentreAround,
  47178. previewComp != 0 ? 400 + previewComp->getWidth() : 600,
  47179. 500);
  47180. }
  47181. void FileChooserDialogBox::buttonClicked (Button* button)
  47182. {
  47183. if (button == &(content->okButton))
  47184. {
  47185. okButtonPressed();
  47186. }
  47187. else if (button == &(content->cancelButton))
  47188. {
  47189. closeButtonPressed();
  47190. }
  47191. else if (button == &(content->newFolderButton))
  47192. {
  47193. createNewFolder();
  47194. }
  47195. }
  47196. void FileChooserDialogBox::closeButtonPressed()
  47197. {
  47198. setVisible (false);
  47199. }
  47200. void FileChooserDialogBox::selectionChanged()
  47201. {
  47202. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47203. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47204. && content->chooserComponent.getRoot().isDirectory());
  47205. }
  47206. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47207. {
  47208. }
  47209. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47210. {
  47211. selectionChanged();
  47212. content->okButton.triggerClick();
  47213. }
  47214. void FileChooserDialogBox::okToOverwriteFileCallback (int result, FileChooserDialogBox* box)
  47215. {
  47216. if (result != 0 && box != 0)
  47217. box->exitModalState (1);
  47218. }
  47219. void FileChooserDialogBox::okButtonPressed()
  47220. {
  47221. if (warnAboutOverwritingExistingFiles
  47222. && content->chooserComponent.isSaveMode()
  47223. && content->chooserComponent.getSelectedFile(0).exists())
  47224. {
  47225. AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47226. TRANS("File already exists"),
  47227. TRANS("There's already a file called:")
  47228. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47229. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47230. TRANS("overwrite"),
  47231. TRANS("cancel"),
  47232. this,
  47233. ModalCallbackFunction::forComponent (okToOverwriteFileCallback, this));
  47234. }
  47235. else
  47236. {
  47237. exitModalState (1);
  47238. }
  47239. }
  47240. void FileChooserDialogBox::createNewFolderCallback (int result, FileChooserDialogBox* box,
  47241. Component::SafePointer<AlertWindow> alert)
  47242. {
  47243. if (result != 0 && alert != 0 && box != 0)
  47244. {
  47245. alert->setVisible (false);
  47246. box->createNewFolderConfirmed (alert->getTextEditorContents ("name"));
  47247. }
  47248. }
  47249. void FileChooserDialogBox::createNewFolder()
  47250. {
  47251. File parent (content->chooserComponent.getRoot());
  47252. if (parent.isDirectory())
  47253. {
  47254. AlertWindow* aw = new AlertWindow (TRANS("New Folder"),
  47255. TRANS("Please enter the name for the folder"),
  47256. AlertWindow::NoIcon, this);
  47257. aw->addTextEditor ("name", String::empty, String::empty, false);
  47258. aw->addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47259. aw->addButton (TRANS("cancel"), KeyPress::escapeKey);
  47260. aw->enterModalState (true,
  47261. ModalCallbackFunction::forComponent (createNewFolderCallback, this,
  47262. Component::SafePointer<AlertWindow> (aw)),
  47263. true);
  47264. }
  47265. }
  47266. void FileChooserDialogBox::createNewFolderConfirmed (const String& nameFromDialog)
  47267. {
  47268. const String name (File::createLegalFileName (nameFromDialog));
  47269. if (! name.isEmpty())
  47270. {
  47271. const File parent (content->chooserComponent.getRoot());
  47272. if (! parent.getChildFile (name).createDirectory())
  47273. {
  47274. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  47275. TRANS ("New Folder"),
  47276. TRANS ("Couldn't create the folder!"));
  47277. }
  47278. content->chooserComponent.refresh();
  47279. }
  47280. }
  47281. END_JUCE_NAMESPACE
  47282. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47283. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47284. BEGIN_JUCE_NAMESPACE
  47285. FileFilter::FileFilter (const String& filterDescription)
  47286. : description (filterDescription)
  47287. {
  47288. }
  47289. FileFilter::~FileFilter()
  47290. {
  47291. }
  47292. const String& FileFilter::getDescription() const throw()
  47293. {
  47294. return description;
  47295. }
  47296. END_JUCE_NAMESPACE
  47297. /*** End of inlined file: juce_FileFilter.cpp ***/
  47298. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47299. BEGIN_JUCE_NAMESPACE
  47300. const Image juce_createIconForFile (const File& file);
  47301. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47302. : ListBox (String::empty, 0),
  47303. DirectoryContentsDisplayComponent (listToShow)
  47304. {
  47305. setModel (this);
  47306. fileList.addChangeListener (this);
  47307. }
  47308. FileListComponent::~FileListComponent()
  47309. {
  47310. fileList.removeChangeListener (this);
  47311. }
  47312. int FileListComponent::getNumSelectedFiles() const
  47313. {
  47314. return getNumSelectedRows();
  47315. }
  47316. const File FileListComponent::getSelectedFile (int index) const
  47317. {
  47318. return fileList.getFile (getSelectedRow (index));
  47319. }
  47320. void FileListComponent::deselectAllFiles()
  47321. {
  47322. deselectAllRows();
  47323. }
  47324. void FileListComponent::scrollToTop()
  47325. {
  47326. getVerticalScrollBar()->setCurrentRangeStart (0);
  47327. }
  47328. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47329. {
  47330. updateContent();
  47331. if (lastDirectory != fileList.getDirectory())
  47332. {
  47333. lastDirectory = fileList.getDirectory();
  47334. deselectAllRows();
  47335. }
  47336. }
  47337. class FileListItemComponent : public Component,
  47338. public TimeSliceClient,
  47339. public AsyncUpdater
  47340. {
  47341. public:
  47342. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47343. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47344. {
  47345. }
  47346. ~FileListItemComponent()
  47347. {
  47348. thread.removeTimeSliceClient (this);
  47349. }
  47350. void paint (Graphics& g)
  47351. {
  47352. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47353. file.getFileName(),
  47354. &icon, fileSize, modTime,
  47355. isDirectory, highlighted,
  47356. index, owner);
  47357. }
  47358. void mouseDown (const MouseEvent& e)
  47359. {
  47360. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47361. owner.sendMouseClickMessage (file, e);
  47362. }
  47363. void mouseDoubleClick (const MouseEvent&)
  47364. {
  47365. owner.sendDoubleClickMessage (file);
  47366. }
  47367. void update (const File& root,
  47368. const DirectoryContentsList::FileInfo* const fileInfo,
  47369. const int index_,
  47370. const bool highlighted_)
  47371. {
  47372. thread.removeTimeSliceClient (this);
  47373. if (highlighted_ != highlighted || index_ != index)
  47374. {
  47375. index = index_;
  47376. highlighted = highlighted_;
  47377. repaint();
  47378. }
  47379. File newFile;
  47380. String newFileSize, newModTime;
  47381. if (fileInfo != 0)
  47382. {
  47383. newFile = root.getChildFile (fileInfo->filename);
  47384. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47385. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47386. }
  47387. if (newFile != file
  47388. || fileSize != newFileSize
  47389. || modTime != newModTime)
  47390. {
  47391. file = newFile;
  47392. fileSize = newFileSize;
  47393. modTime = newModTime;
  47394. icon = Image::null;
  47395. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47396. repaint();
  47397. }
  47398. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47399. {
  47400. updateIcon (true);
  47401. if (! icon.isValid())
  47402. thread.addTimeSliceClient (this);
  47403. }
  47404. }
  47405. int useTimeSlice()
  47406. {
  47407. updateIcon (false);
  47408. return -1;
  47409. }
  47410. void handleAsyncUpdate()
  47411. {
  47412. repaint();
  47413. }
  47414. private:
  47415. FileListComponent& owner;
  47416. TimeSliceThread& thread;
  47417. File file;
  47418. String fileSize, modTime;
  47419. Image icon;
  47420. int index;
  47421. bool highlighted, isDirectory;
  47422. void updateIcon (const bool onlyUpdateIfCached)
  47423. {
  47424. if (icon.isNull())
  47425. {
  47426. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47427. Image im (ImageCache::getFromHashCode (hashCode));
  47428. if (im.isNull() && ! onlyUpdateIfCached)
  47429. {
  47430. im = juce_createIconForFile (file);
  47431. if (im.isValid())
  47432. ImageCache::addImageToCache (im, hashCode);
  47433. }
  47434. if (im.isValid())
  47435. {
  47436. icon = im;
  47437. triggerAsyncUpdate();
  47438. }
  47439. }
  47440. }
  47441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47442. };
  47443. int FileListComponent::getNumRows()
  47444. {
  47445. return fileList.getNumFiles();
  47446. }
  47447. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47448. {
  47449. }
  47450. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47451. {
  47452. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47453. if (comp == 0)
  47454. {
  47455. delete existingComponentToUpdate;
  47456. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47457. }
  47458. DirectoryContentsList::FileInfo fileInfo;
  47459. if (fileList.getFileInfo (row, fileInfo))
  47460. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47461. else
  47462. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47463. return comp;
  47464. }
  47465. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47466. {
  47467. sendSelectionChangeMessage();
  47468. }
  47469. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47470. {
  47471. }
  47472. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47473. {
  47474. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47475. }
  47476. END_JUCE_NAMESPACE
  47477. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47478. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47479. BEGIN_JUCE_NAMESPACE
  47480. FilenameComponent::FilenameComponent (const String& name,
  47481. const File& currentFile,
  47482. const bool canEditFilename,
  47483. const bool isDirectory,
  47484. const bool isForSaving,
  47485. const String& fileBrowserWildcard,
  47486. const String& enforcedSuffix_,
  47487. const String& textWhenNothingSelected)
  47488. : Component (name),
  47489. maxRecentFiles (30),
  47490. isDir (isDirectory),
  47491. isSaving (isForSaving),
  47492. isFileDragOver (false),
  47493. wildcard (fileBrowserWildcard),
  47494. enforcedSuffix (enforcedSuffix_)
  47495. {
  47496. addAndMakeVisible (&filenameBox);
  47497. filenameBox.setEditableText (canEditFilename);
  47498. filenameBox.addListener (this);
  47499. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47500. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47501. setBrowseButtonText ("...");
  47502. setCurrentFile (currentFile, true);
  47503. }
  47504. FilenameComponent::~FilenameComponent()
  47505. {
  47506. }
  47507. void FilenameComponent::paintOverChildren (Graphics& g)
  47508. {
  47509. if (isFileDragOver)
  47510. {
  47511. g.setColour (Colours::red.withAlpha (0.2f));
  47512. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47513. }
  47514. }
  47515. void FilenameComponent::resized()
  47516. {
  47517. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47518. }
  47519. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47520. {
  47521. browseButtonText = newBrowseButtonText;
  47522. lookAndFeelChanged();
  47523. }
  47524. void FilenameComponent::lookAndFeelChanged()
  47525. {
  47526. browseButton = 0;
  47527. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47528. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47529. resized();
  47530. browseButton->addListener (this);
  47531. }
  47532. void FilenameComponent::setTooltip (const String& newTooltip)
  47533. {
  47534. SettableTooltipClient::setTooltip (newTooltip);
  47535. filenameBox.setTooltip (newTooltip);
  47536. }
  47537. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47538. {
  47539. defaultBrowseFile = newDefaultDirectory;
  47540. }
  47541. void FilenameComponent::buttonClicked (Button*)
  47542. {
  47543. #if JUCE_MODAL_LOOPS_PERMITTED
  47544. FileChooser fc (TRANS("Choose a new file"),
  47545. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47546. : getCurrentFile(),
  47547. wildcard);
  47548. if (isDir ? fc.browseForDirectory()
  47549. : (isSaving ? fc.browseForFileToSave (false)
  47550. : fc.browseForFileToOpen()))
  47551. {
  47552. setCurrentFile (fc.getResult(), true);
  47553. }
  47554. #else
  47555. jassertfalse; // needs rewriting to deal with non-modal environments
  47556. #endif
  47557. }
  47558. void FilenameComponent::comboBoxChanged (ComboBox*)
  47559. {
  47560. setCurrentFile (getCurrentFile(), true);
  47561. }
  47562. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47563. {
  47564. return true;
  47565. }
  47566. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47567. {
  47568. isFileDragOver = false;
  47569. repaint();
  47570. const File f (filenames[0]);
  47571. if (f.exists() && (f.isDirectory() == isDir))
  47572. setCurrentFile (f, true);
  47573. }
  47574. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47575. {
  47576. isFileDragOver = true;
  47577. repaint();
  47578. }
  47579. void FilenameComponent::fileDragExit (const StringArray&)
  47580. {
  47581. isFileDragOver = false;
  47582. repaint();
  47583. }
  47584. const File FilenameComponent::getCurrentFile() const
  47585. {
  47586. File f (filenameBox.getText());
  47587. if (enforcedSuffix.isNotEmpty())
  47588. f = f.withFileExtension (enforcedSuffix);
  47589. return f;
  47590. }
  47591. void FilenameComponent::setCurrentFile (File newFile,
  47592. const bool addToRecentlyUsedList,
  47593. const bool sendChangeNotification)
  47594. {
  47595. if (enforcedSuffix.isNotEmpty())
  47596. newFile = newFile.withFileExtension (enforcedSuffix);
  47597. if (newFile.getFullPathName() != lastFilename)
  47598. {
  47599. lastFilename = newFile.getFullPathName();
  47600. if (addToRecentlyUsedList)
  47601. addRecentlyUsedFile (newFile);
  47602. filenameBox.setText (lastFilename, true);
  47603. if (sendChangeNotification)
  47604. triggerAsyncUpdate();
  47605. }
  47606. }
  47607. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47608. {
  47609. filenameBox.setEditableText (shouldBeEditable);
  47610. }
  47611. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47612. {
  47613. StringArray names;
  47614. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47615. names.add (filenameBox.getItemText (i));
  47616. return names;
  47617. }
  47618. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47619. {
  47620. if (filenames != getRecentlyUsedFilenames())
  47621. {
  47622. filenameBox.clear();
  47623. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47624. filenameBox.addItem (filenames[i], i + 1);
  47625. }
  47626. }
  47627. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47628. {
  47629. maxRecentFiles = jmax (1, newMaximum);
  47630. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47631. }
  47632. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47633. {
  47634. StringArray files (getRecentlyUsedFilenames());
  47635. if (file.getFullPathName().isNotEmpty())
  47636. {
  47637. files.removeString (file.getFullPathName(), true);
  47638. files.insert (0, file.getFullPathName());
  47639. setRecentlyUsedFilenames (files);
  47640. }
  47641. }
  47642. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47643. {
  47644. listeners.add (listener);
  47645. }
  47646. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47647. {
  47648. listeners.remove (listener);
  47649. }
  47650. void FilenameComponent::handleAsyncUpdate()
  47651. {
  47652. Component::BailOutChecker checker (this);
  47653. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47654. }
  47655. END_JUCE_NAMESPACE
  47656. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47657. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47658. BEGIN_JUCE_NAMESPACE
  47659. FileSearchPathListComponent::FileSearchPathListComponent()
  47660. : addButton ("+"),
  47661. removeButton ("-"),
  47662. changeButton (TRANS ("change...")),
  47663. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47664. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47665. {
  47666. listBox.setModel (this);
  47667. addAndMakeVisible (&listBox);
  47668. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47669. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47670. listBox.setOutlineThickness (1);
  47671. addAndMakeVisible (&addButton);
  47672. addButton.addListener (this);
  47673. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47674. addAndMakeVisible (&removeButton);
  47675. removeButton.addListener (this);
  47676. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47677. addAndMakeVisible (&changeButton);
  47678. changeButton.addListener (this);
  47679. addAndMakeVisible (&upButton);
  47680. upButton.addListener (this);
  47681. {
  47682. Path arrowPath;
  47683. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47684. DrawablePath arrowImage;
  47685. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47686. arrowImage.setPath (arrowPath);
  47687. upButton.setImages (&arrowImage);
  47688. }
  47689. addAndMakeVisible (&downButton);
  47690. downButton.addListener (this);
  47691. {
  47692. Path arrowPath;
  47693. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47694. DrawablePath arrowImage;
  47695. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47696. arrowImage.setPath (arrowPath);
  47697. downButton.setImages (&arrowImage);
  47698. }
  47699. updateButtons();
  47700. }
  47701. FileSearchPathListComponent::~FileSearchPathListComponent()
  47702. {
  47703. }
  47704. void FileSearchPathListComponent::updateButtons()
  47705. {
  47706. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47707. removeButton.setEnabled (anythingSelected);
  47708. changeButton.setEnabled (anythingSelected);
  47709. upButton.setEnabled (anythingSelected);
  47710. downButton.setEnabled (anythingSelected);
  47711. }
  47712. void FileSearchPathListComponent::changed()
  47713. {
  47714. listBox.updateContent();
  47715. listBox.repaint();
  47716. updateButtons();
  47717. }
  47718. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47719. {
  47720. if (newPath.toString() != path.toString())
  47721. {
  47722. path = newPath;
  47723. changed();
  47724. }
  47725. }
  47726. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47727. {
  47728. defaultBrowseTarget = newDefaultDirectory;
  47729. }
  47730. int FileSearchPathListComponent::getNumRows()
  47731. {
  47732. return path.getNumPaths();
  47733. }
  47734. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47735. {
  47736. if (rowIsSelected)
  47737. g.fillAll (findColour (TextEditor::highlightColourId));
  47738. g.setColour (findColour (ListBox::textColourId));
  47739. Font f (height * 0.7f);
  47740. f.setHorizontalScale (0.9f);
  47741. g.setFont (f);
  47742. g.drawText (path [rowNumber].getFullPathName(),
  47743. 4, 0, width - 6, height,
  47744. Justification::centredLeft, true);
  47745. }
  47746. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47747. {
  47748. if (isPositiveAndBelow (row, path.getNumPaths()))
  47749. {
  47750. path.remove (row);
  47751. changed();
  47752. }
  47753. }
  47754. void FileSearchPathListComponent::returnKeyPressed (int row)
  47755. {
  47756. #if JUCE_MODAL_LOOPS_PERMITTED
  47757. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47758. if (chooser.browseForDirectory())
  47759. {
  47760. path.remove (row);
  47761. path.add (chooser.getResult(), row);
  47762. changed();
  47763. }
  47764. #endif
  47765. }
  47766. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47767. {
  47768. returnKeyPressed (row);
  47769. }
  47770. void FileSearchPathListComponent::selectedRowsChanged (int)
  47771. {
  47772. updateButtons();
  47773. }
  47774. void FileSearchPathListComponent::paint (Graphics& g)
  47775. {
  47776. g.fillAll (findColour (backgroundColourId));
  47777. }
  47778. void FileSearchPathListComponent::resized()
  47779. {
  47780. const int buttonH = 22;
  47781. const int buttonY = getHeight() - buttonH - 4;
  47782. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47783. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47784. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47785. changeButton.changeWidthToFitText (buttonH);
  47786. downButton.setSize (buttonH * 2, buttonH);
  47787. upButton.setSize (buttonH * 2, buttonH);
  47788. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47789. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47790. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47791. }
  47792. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47793. {
  47794. return true;
  47795. }
  47796. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47797. {
  47798. for (int i = filenames.size(); --i >= 0;)
  47799. {
  47800. const File f (filenames[i]);
  47801. if (f.isDirectory())
  47802. {
  47803. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47804. path.add (f, row);
  47805. changed();
  47806. }
  47807. }
  47808. }
  47809. void FileSearchPathListComponent::buttonClicked (Button* button)
  47810. {
  47811. const int currentRow = listBox.getSelectedRow();
  47812. if (button == &removeButton)
  47813. {
  47814. deleteKeyPressed (currentRow);
  47815. }
  47816. else if (button == &addButton)
  47817. {
  47818. File start (defaultBrowseTarget);
  47819. if (start == File::nonexistent)
  47820. start = path [0];
  47821. if (start == File::nonexistent)
  47822. start = File::getCurrentWorkingDirectory();
  47823. #if JUCE_MODAL_LOOPS_PERMITTED
  47824. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47825. if (chooser.browseForDirectory())
  47826. path.add (chooser.getResult(), currentRow);
  47827. #else
  47828. jassertfalse; // needs rewriting to deal with non-modal environments
  47829. #endif
  47830. }
  47831. else if (button == &changeButton)
  47832. {
  47833. returnKeyPressed (currentRow);
  47834. }
  47835. else if (button == &upButton)
  47836. {
  47837. if (currentRow > 0 && currentRow < path.getNumPaths())
  47838. {
  47839. const File f (path[currentRow]);
  47840. path.remove (currentRow);
  47841. path.add (f, currentRow - 1);
  47842. listBox.selectRow (currentRow - 1);
  47843. }
  47844. }
  47845. else if (button == &downButton)
  47846. {
  47847. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47848. {
  47849. const File f (path[currentRow]);
  47850. path.remove (currentRow);
  47851. path.add (f, currentRow + 1);
  47852. listBox.selectRow (currentRow + 1);
  47853. }
  47854. }
  47855. changed();
  47856. }
  47857. END_JUCE_NAMESPACE
  47858. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47859. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47860. BEGIN_JUCE_NAMESPACE
  47861. const Image juce_createIconForFile (const File& file);
  47862. class FileListTreeItem : public TreeViewItem,
  47863. public TimeSliceClient,
  47864. public AsyncUpdater,
  47865. public ChangeListener
  47866. {
  47867. public:
  47868. FileListTreeItem (FileTreeComponent& owner_,
  47869. DirectoryContentsList* const parentContentsList_,
  47870. const int indexInContentsList_,
  47871. const File& file_,
  47872. TimeSliceThread& thread_)
  47873. : file (file_),
  47874. owner (owner_),
  47875. parentContentsList (parentContentsList_),
  47876. indexInContentsList (indexInContentsList_),
  47877. subContentsList (0),
  47878. canDeleteSubContentsList (false),
  47879. thread (thread_),
  47880. icon (0)
  47881. {
  47882. DirectoryContentsList::FileInfo fileInfo;
  47883. if (parentContentsList_ != 0
  47884. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47885. {
  47886. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47887. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47888. isDirectory = fileInfo.isDirectory;
  47889. }
  47890. else
  47891. {
  47892. isDirectory = true;
  47893. }
  47894. }
  47895. ~FileListTreeItem()
  47896. {
  47897. thread.removeTimeSliceClient (this);
  47898. clearSubItems();
  47899. if (canDeleteSubContentsList)
  47900. delete subContentsList;
  47901. }
  47902. bool mightContainSubItems() { return isDirectory; }
  47903. const String getUniqueName() const { return file.getFullPathName(); }
  47904. int getItemHeight() const { return 22; }
  47905. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47906. void itemOpennessChanged (bool isNowOpen)
  47907. {
  47908. if (isNowOpen)
  47909. {
  47910. clearSubItems();
  47911. isDirectory = file.isDirectory();
  47912. if (isDirectory)
  47913. {
  47914. if (subContentsList == 0)
  47915. {
  47916. jassert (parentContentsList != 0);
  47917. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47918. l->setDirectory (file, true, true);
  47919. setSubContentsList (l);
  47920. canDeleteSubContentsList = true;
  47921. }
  47922. changeListenerCallback (0);
  47923. }
  47924. }
  47925. }
  47926. void setSubContentsList (DirectoryContentsList* newList)
  47927. {
  47928. jassert (subContentsList == 0);
  47929. subContentsList = newList;
  47930. newList->addChangeListener (this);
  47931. }
  47932. void changeListenerCallback (ChangeBroadcaster*)
  47933. {
  47934. clearSubItems();
  47935. if (isOpen() && subContentsList != 0)
  47936. {
  47937. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47938. {
  47939. FileListTreeItem* const item
  47940. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47941. addSubItem (item);
  47942. }
  47943. }
  47944. }
  47945. void paintItem (Graphics& g, int width, int height)
  47946. {
  47947. if (file != File::nonexistent)
  47948. {
  47949. updateIcon (true);
  47950. if (icon.isNull())
  47951. thread.addTimeSliceClient (this);
  47952. }
  47953. owner.getLookAndFeel()
  47954. .drawFileBrowserRow (g, width, height,
  47955. file.getFileName(),
  47956. &icon, fileSize, modTime,
  47957. isDirectory, isSelected(),
  47958. indexInContentsList, owner);
  47959. }
  47960. void itemClicked (const MouseEvent& e)
  47961. {
  47962. owner.sendMouseClickMessage (file, e);
  47963. }
  47964. void itemDoubleClicked (const MouseEvent& e)
  47965. {
  47966. TreeViewItem::itemDoubleClicked (e);
  47967. owner.sendDoubleClickMessage (file);
  47968. }
  47969. void itemSelectionChanged (bool)
  47970. {
  47971. owner.sendSelectionChangeMessage();
  47972. }
  47973. int useTimeSlice()
  47974. {
  47975. updateIcon (false);
  47976. return -1;
  47977. }
  47978. void handleAsyncUpdate()
  47979. {
  47980. owner.repaint();
  47981. }
  47982. const File file;
  47983. private:
  47984. FileTreeComponent& owner;
  47985. DirectoryContentsList* parentContentsList;
  47986. int indexInContentsList;
  47987. DirectoryContentsList* subContentsList;
  47988. bool isDirectory, canDeleteSubContentsList;
  47989. TimeSliceThread& thread;
  47990. Image icon;
  47991. String fileSize;
  47992. String modTime;
  47993. void updateIcon (const bool onlyUpdateIfCached)
  47994. {
  47995. if (icon.isNull())
  47996. {
  47997. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47998. Image im (ImageCache::getFromHashCode (hashCode));
  47999. if (im.isNull() && ! onlyUpdateIfCached)
  48000. {
  48001. im = juce_createIconForFile (file);
  48002. if (im.isValid())
  48003. ImageCache::addImageToCache (im, hashCode);
  48004. }
  48005. if (im.isValid())
  48006. {
  48007. icon = im;
  48008. triggerAsyncUpdate();
  48009. }
  48010. }
  48011. }
  48012. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  48013. };
  48014. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48015. : DirectoryContentsDisplayComponent (listToShow)
  48016. {
  48017. FileListTreeItem* const root
  48018. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48019. listToShow.getTimeSliceThread());
  48020. root->setSubContentsList (&listToShow);
  48021. setRootItemVisible (false);
  48022. setRootItem (root);
  48023. }
  48024. FileTreeComponent::~FileTreeComponent()
  48025. {
  48026. deleteRootItem();
  48027. }
  48028. const File FileTreeComponent::getSelectedFile (const int index) const
  48029. {
  48030. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48031. return item != 0 ? item->file
  48032. : File::nonexistent;
  48033. }
  48034. void FileTreeComponent::deselectAllFiles()
  48035. {
  48036. clearSelectedItems();
  48037. }
  48038. void FileTreeComponent::scrollToTop()
  48039. {
  48040. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48041. }
  48042. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48043. {
  48044. dragAndDropDescription = description;
  48045. }
  48046. END_JUCE_NAMESPACE
  48047. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48048. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48049. BEGIN_JUCE_NAMESPACE
  48050. ImagePreviewComponent::ImagePreviewComponent()
  48051. {
  48052. }
  48053. ImagePreviewComponent::~ImagePreviewComponent()
  48054. {
  48055. }
  48056. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48057. {
  48058. const int availableW = proportionOfWidth (0.97f);
  48059. const int availableH = getHeight() - 13 * 4;
  48060. const double scale = jmin (1.0,
  48061. availableW / (double) w,
  48062. availableH / (double) h);
  48063. w = roundToInt (scale * w);
  48064. h = roundToInt (scale * h);
  48065. }
  48066. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48067. {
  48068. if (fileToLoad != file)
  48069. {
  48070. fileToLoad = file;
  48071. startTimer (100);
  48072. }
  48073. }
  48074. void ImagePreviewComponent::timerCallback()
  48075. {
  48076. stopTimer();
  48077. currentThumbnail = Image::null;
  48078. currentDetails = String::empty;
  48079. repaint();
  48080. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48081. if (in != 0)
  48082. {
  48083. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48084. if (format != 0)
  48085. {
  48086. currentThumbnail = format->decodeImage (*in);
  48087. if (currentThumbnail.isValid())
  48088. {
  48089. int w = currentThumbnail.getWidth();
  48090. int h = currentThumbnail.getHeight();
  48091. currentDetails
  48092. << fileToLoad.getFileName() << "\n"
  48093. << format->getFormatName() << "\n"
  48094. << w << " x " << h << " pixels\n"
  48095. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48096. getThumbSize (w, h);
  48097. currentThumbnail = currentThumbnail.rescaled (w, h);
  48098. }
  48099. }
  48100. }
  48101. }
  48102. void ImagePreviewComponent::paint (Graphics& g)
  48103. {
  48104. if (currentThumbnail.isValid())
  48105. {
  48106. g.setFont (13.0f);
  48107. int w = currentThumbnail.getWidth();
  48108. int h = currentThumbnail.getHeight();
  48109. getThumbSize (w, h);
  48110. const int numLines = 4;
  48111. const int totalH = 13 * numLines + h + 4;
  48112. const int y = (getHeight() - totalH) / 2;
  48113. g.drawImageWithin (currentThumbnail,
  48114. (getWidth() - w) / 2, y, w, h,
  48115. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48116. false);
  48117. g.drawFittedText (currentDetails,
  48118. 0, y + h + 4, getWidth(), 100,
  48119. Justification::centredTop, numLines);
  48120. }
  48121. }
  48122. END_JUCE_NAMESPACE
  48123. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48124. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48125. BEGIN_JUCE_NAMESPACE
  48126. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48127. const String& directoryWildcardPatterns,
  48128. const String& description_)
  48129. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48130. : (description_ + " (" + fileWildcardPatterns + ")"))
  48131. {
  48132. parse (fileWildcardPatterns, fileWildcards);
  48133. parse (directoryWildcardPatterns, directoryWildcards);
  48134. }
  48135. WildcardFileFilter::~WildcardFileFilter()
  48136. {
  48137. }
  48138. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48139. {
  48140. return match (file, fileWildcards);
  48141. }
  48142. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48143. {
  48144. return match (file, directoryWildcards);
  48145. }
  48146. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48147. {
  48148. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48149. result.trim();
  48150. result.removeEmptyStrings();
  48151. // special case for *.*, because people use it to mean "any file", but it
  48152. // would actually ignore files with no extension.
  48153. for (int i = result.size(); --i >= 0;)
  48154. if (result[i] == "*.*")
  48155. result.set (i, "*");
  48156. }
  48157. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48158. {
  48159. const String filename (file.getFileName());
  48160. for (int i = wildcards.size(); --i >= 0;)
  48161. if (filename.matchesWildcard (wildcards[i], true))
  48162. return true;
  48163. return false;
  48164. }
  48165. END_JUCE_NAMESPACE
  48166. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48167. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48168. BEGIN_JUCE_NAMESPACE
  48169. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48170. {
  48171. }
  48172. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48173. {
  48174. }
  48175. namespace KeyboardFocusHelpers
  48176. {
  48177. // This will sort a set of components, so that they are ordered in terms of
  48178. // left-to-right and then top-to-bottom.
  48179. class ScreenPositionComparator
  48180. {
  48181. public:
  48182. ScreenPositionComparator() {}
  48183. static int compareElements (const Component* const first, const Component* const second)
  48184. {
  48185. int explicitOrder1 = first->getExplicitFocusOrder();
  48186. if (explicitOrder1 <= 0)
  48187. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48188. int explicitOrder2 = second->getExplicitFocusOrder();
  48189. if (explicitOrder2 <= 0)
  48190. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48191. if (explicitOrder1 != explicitOrder2)
  48192. return explicitOrder1 - explicitOrder2;
  48193. const int diff = first->getY() - second->getY();
  48194. return (diff == 0) ? first->getX() - second->getX()
  48195. : diff;
  48196. }
  48197. };
  48198. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48199. {
  48200. if (parent->getNumChildComponents() > 0)
  48201. {
  48202. Array <Component*> localComps;
  48203. ScreenPositionComparator comparator;
  48204. int i;
  48205. for (i = parent->getNumChildComponents(); --i >= 0;)
  48206. {
  48207. Component* const c = parent->getChildComponent (i);
  48208. if (c->isVisible() && c->isEnabled())
  48209. localComps.addSorted (comparator, c);
  48210. }
  48211. for (i = 0; i < localComps.size(); ++i)
  48212. {
  48213. Component* const c = localComps.getUnchecked (i);
  48214. if (c->getWantsKeyboardFocus())
  48215. comps.add (c);
  48216. if (! c->isFocusContainer())
  48217. findAllFocusableComponents (c, comps);
  48218. }
  48219. }
  48220. }
  48221. }
  48222. namespace KeyboardFocusHelpers
  48223. {
  48224. Component* getIncrementedComponent (Component* const current, const int delta)
  48225. {
  48226. Component* focusContainer = current->getParentComponent();
  48227. if (focusContainer != 0)
  48228. {
  48229. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48230. focusContainer = focusContainer->getParentComponent();
  48231. if (focusContainer != 0)
  48232. {
  48233. Array <Component*> comps;
  48234. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48235. if (comps.size() > 0)
  48236. {
  48237. const int index = comps.indexOf (current);
  48238. return comps [(index + comps.size() + delta) % comps.size()];
  48239. }
  48240. }
  48241. }
  48242. return 0;
  48243. }
  48244. }
  48245. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48246. {
  48247. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48248. }
  48249. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48250. {
  48251. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48252. }
  48253. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48254. {
  48255. Array <Component*> comps;
  48256. if (parentComponent != 0)
  48257. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48258. return comps.getFirst();
  48259. }
  48260. END_JUCE_NAMESPACE
  48261. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48262. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48263. BEGIN_JUCE_NAMESPACE
  48264. bool KeyListener::keyStateChanged (const bool, Component*)
  48265. {
  48266. return false;
  48267. }
  48268. END_JUCE_NAMESPACE
  48269. /*** End of inlined file: juce_KeyListener.cpp ***/
  48270. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48271. BEGIN_JUCE_NAMESPACE
  48272. // N.B. these two includes are put here deliberately to avoid problems with
  48273. // old GCCs failing on long include paths
  48274. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48275. {
  48276. public:
  48277. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48278. const CommandID commandID_,
  48279. const String& keyName,
  48280. const int keyNum_)
  48281. : Button (keyName),
  48282. owner (owner_),
  48283. commandID (commandID_),
  48284. keyNum (keyNum_)
  48285. {
  48286. setWantsKeyboardFocus (false);
  48287. setTriggeredOnMouseDown (keyNum >= 0);
  48288. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48289. : TRANS("click to change this key-mapping"));
  48290. }
  48291. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48292. {
  48293. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48294. keyNum >= 0 ? getName() : String::empty);
  48295. }
  48296. static void menuCallback (int result, ChangeKeyButton* button)
  48297. {
  48298. if (button != 0)
  48299. {
  48300. switch (result)
  48301. {
  48302. case 1: button->assignNewKey(); break;
  48303. case 2: button->owner.getMappings().removeKeyPress (button->commandID, button->keyNum); break;
  48304. default: break;
  48305. }
  48306. }
  48307. }
  48308. void clicked()
  48309. {
  48310. if (keyNum >= 0)
  48311. {
  48312. // existing key clicked..
  48313. PopupMenu m;
  48314. m.addItem (1, TRANS("change this key-mapping"));
  48315. m.addSeparator();
  48316. m.addItem (2, TRANS("remove this key-mapping"));
  48317. m.showMenuAsync (PopupMenu::Options(),
  48318. ModalCallbackFunction::forComponent (menuCallback, this));
  48319. }
  48320. else
  48321. {
  48322. assignNewKey(); // + button pressed..
  48323. }
  48324. }
  48325. void fitToContent (const int h) throw()
  48326. {
  48327. if (keyNum < 0)
  48328. {
  48329. setSize (h, h);
  48330. }
  48331. else
  48332. {
  48333. Font f (h * 0.6f);
  48334. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48335. }
  48336. }
  48337. class KeyEntryWindow : public AlertWindow
  48338. {
  48339. public:
  48340. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48341. : AlertWindow (TRANS("New key-mapping"),
  48342. TRANS("Please press a key combination now..."),
  48343. AlertWindow::NoIcon),
  48344. owner (owner_)
  48345. {
  48346. addButton (TRANS("Ok"), 1);
  48347. addButton (TRANS("Cancel"), 0);
  48348. // (avoid return + escape keys getting processed by the buttons..)
  48349. for (int i = getNumChildComponents(); --i >= 0;)
  48350. getChildComponent (i)->setWantsKeyboardFocus (false);
  48351. setWantsKeyboardFocus (true);
  48352. grabKeyboardFocus();
  48353. }
  48354. bool keyPressed (const KeyPress& key)
  48355. {
  48356. lastPress = key;
  48357. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48358. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48359. if (previousCommand != 0)
  48360. message << "\n\n" << TRANS("(Currently assigned to \"")
  48361. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48362. setMessage (message);
  48363. return true;
  48364. }
  48365. bool keyStateChanged (bool)
  48366. {
  48367. return true;
  48368. }
  48369. KeyPress lastPress;
  48370. private:
  48371. KeyMappingEditorComponent& owner;
  48372. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48373. };
  48374. static void assignNewKeyCallback (int result, ChangeKeyButton* button, KeyPress newKey)
  48375. {
  48376. if (result != 0 && button != 0)
  48377. button->setNewKey (newKey, true);
  48378. }
  48379. void setNewKey (const KeyPress& newKey, bool dontAskUser)
  48380. {
  48381. if (newKey.isValid())
  48382. {
  48383. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (newKey);
  48384. if (previousCommand == 0 || dontAskUser)
  48385. {
  48386. owner.getMappings().removeKeyPress (newKey);
  48387. if (keyNum >= 0)
  48388. owner.getMappings().removeKeyPress (commandID, keyNum);
  48389. owner.getMappings().addKeyPress (commandID, newKey, keyNum);
  48390. }
  48391. else
  48392. {
  48393. AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48394. TRANS("Change key-mapping"),
  48395. TRANS("This key is already assigned to the command \"")
  48396. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48397. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48398. TRANS("Re-assign"),
  48399. TRANS("Cancel"),
  48400. this,
  48401. ModalCallbackFunction::forComponent (assignNewKeyCallback,
  48402. this, KeyPress (newKey)));
  48403. }
  48404. }
  48405. }
  48406. static void keyChosen (int result, ChangeKeyButton* button)
  48407. {
  48408. if (result != 0 && button != 0 && button->currentKeyEntryWindow != 0)
  48409. {
  48410. button->currentKeyEntryWindow->setVisible (false);
  48411. button->setNewKey (button->currentKeyEntryWindow->lastPress, false);
  48412. }
  48413. button->currentKeyEntryWindow = 0;
  48414. }
  48415. void assignNewKey()
  48416. {
  48417. currentKeyEntryWindow = new KeyEntryWindow (owner);
  48418. currentKeyEntryWindow->enterModalState (true, ModalCallbackFunction::forComponent (keyChosen, this));
  48419. }
  48420. private:
  48421. KeyMappingEditorComponent& owner;
  48422. const CommandID commandID;
  48423. const int keyNum;
  48424. ScopedPointer<KeyEntryWindow> currentKeyEntryWindow;
  48425. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48426. };
  48427. class KeyMappingEditorComponent::ItemComponent : public Component
  48428. {
  48429. public:
  48430. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48431. : owner (owner_), commandID (commandID_)
  48432. {
  48433. setInterceptsMouseClicks (false, true);
  48434. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48435. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48436. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48437. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48438. addKeyPressButton (String::empty, -1, isReadOnly);
  48439. }
  48440. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48441. {
  48442. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48443. keyChangeButtons.add (b);
  48444. b->setEnabled (! isReadOnly);
  48445. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48446. addChildComponent (b);
  48447. }
  48448. void paint (Graphics& g)
  48449. {
  48450. g.setFont (getHeight() * 0.7f);
  48451. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48452. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48453. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48454. Justification::centredLeft, true);
  48455. }
  48456. void resized()
  48457. {
  48458. int x = getWidth() - 4;
  48459. for (int i = keyChangeButtons.size(); --i >= 0;)
  48460. {
  48461. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48462. b->fitToContent (getHeight() - 2);
  48463. b->setTopRightPosition (x, 1);
  48464. x = b->getX() - 5;
  48465. }
  48466. }
  48467. private:
  48468. KeyMappingEditorComponent& owner;
  48469. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48470. const CommandID commandID;
  48471. enum { maxNumAssignments = 3 };
  48472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48473. };
  48474. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48475. {
  48476. public:
  48477. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48478. : owner (owner_), commandID (commandID_)
  48479. {
  48480. }
  48481. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48482. bool mightContainSubItems() { return false; }
  48483. int getItemHeight() const { return 20; }
  48484. Component* createItemComponent()
  48485. {
  48486. return new ItemComponent (owner, commandID);
  48487. }
  48488. private:
  48489. KeyMappingEditorComponent& owner;
  48490. const CommandID commandID;
  48491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48492. };
  48493. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48494. {
  48495. public:
  48496. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48497. : owner (owner_), categoryName (name)
  48498. {
  48499. }
  48500. const String getUniqueName() const { return categoryName + "_cat"; }
  48501. bool mightContainSubItems() { return true; }
  48502. int getItemHeight() const { return 28; }
  48503. void paintItem (Graphics& g, int width, int height)
  48504. {
  48505. g.setFont (height * 0.6f, Font::bold);
  48506. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48507. g.drawText (categoryName,
  48508. 2, 0, width - 2, height,
  48509. Justification::centredLeft, true);
  48510. }
  48511. void itemOpennessChanged (bool isNowOpen)
  48512. {
  48513. if (isNowOpen)
  48514. {
  48515. if (getNumSubItems() == 0)
  48516. {
  48517. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48518. for (int i = 0; i < commands.size(); ++i)
  48519. {
  48520. if (owner.shouldCommandBeIncluded (commands[i]))
  48521. addSubItem (new MappingItem (owner, commands[i]));
  48522. }
  48523. }
  48524. }
  48525. else
  48526. {
  48527. clearSubItems();
  48528. }
  48529. }
  48530. private:
  48531. KeyMappingEditorComponent& owner;
  48532. String categoryName;
  48533. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48534. };
  48535. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48536. public ChangeListener,
  48537. public ButtonListener
  48538. {
  48539. public:
  48540. TopLevelItem (KeyMappingEditorComponent& owner_)
  48541. : owner (owner_)
  48542. {
  48543. setLinesDrawnForSubItems (false);
  48544. owner.getMappings().addChangeListener (this);
  48545. }
  48546. ~TopLevelItem()
  48547. {
  48548. owner.getMappings().removeChangeListener (this);
  48549. }
  48550. bool mightContainSubItems() { return true; }
  48551. const String getUniqueName() const { return "keys"; }
  48552. void changeListenerCallback (ChangeBroadcaster*)
  48553. {
  48554. const OpennessRestorer openness (*this);
  48555. clearSubItems();
  48556. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48557. for (int i = 0; i < categories.size(); ++i)
  48558. {
  48559. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48560. int count = 0;
  48561. for (int j = 0; j < commands.size(); ++j)
  48562. if (owner.shouldCommandBeIncluded (commands[j]))
  48563. ++count;
  48564. if (count > 0)
  48565. addSubItem (new CategoryItem (owner, categories[i]));
  48566. }
  48567. }
  48568. static void resetToDefaultsCallback (int result, KeyMappingEditorComponent* owner)
  48569. {
  48570. if (result != 0 && owner != 0)
  48571. owner->getMappings().resetToDefaultMappings();
  48572. }
  48573. void buttonClicked (Button*)
  48574. {
  48575. AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48576. TRANS("Reset to defaults"),
  48577. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48578. TRANS("Reset"),
  48579. String::empty,
  48580. &owner,
  48581. ModalCallbackFunction::forComponent (resetToDefaultsCallback, &owner));
  48582. }
  48583. private:
  48584. KeyMappingEditorComponent& owner;
  48585. };
  48586. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48587. const bool showResetToDefaultButton)
  48588. : mappings (mappingManager),
  48589. resetButton (TRANS ("reset to defaults"))
  48590. {
  48591. treeItem = new TopLevelItem (*this);
  48592. if (showResetToDefaultButton)
  48593. {
  48594. addAndMakeVisible (&resetButton);
  48595. resetButton.addListener (treeItem);
  48596. }
  48597. addAndMakeVisible (&tree);
  48598. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48599. tree.setRootItemVisible (false);
  48600. tree.setDefaultOpenness (true);
  48601. tree.setRootItem (treeItem);
  48602. }
  48603. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48604. {
  48605. tree.setRootItem (0);
  48606. }
  48607. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48608. const Colour& textColour)
  48609. {
  48610. setColour (backgroundColourId, mainBackground);
  48611. setColour (textColourId, textColour);
  48612. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48613. }
  48614. void KeyMappingEditorComponent::parentHierarchyChanged()
  48615. {
  48616. treeItem->changeListenerCallback (0);
  48617. }
  48618. void KeyMappingEditorComponent::resized()
  48619. {
  48620. int h = getHeight();
  48621. if (resetButton.isVisible())
  48622. {
  48623. const int buttonHeight = 20;
  48624. h -= buttonHeight + 8;
  48625. int x = getWidth() - 8;
  48626. resetButton.changeWidthToFitText (buttonHeight);
  48627. resetButton.setTopRightPosition (x, h + 6);
  48628. }
  48629. tree.setBounds (0, 0, getWidth(), h);
  48630. }
  48631. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48632. {
  48633. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48634. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48635. }
  48636. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48637. {
  48638. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48639. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48640. }
  48641. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48642. {
  48643. return key.getTextDescription();
  48644. }
  48645. END_JUCE_NAMESPACE
  48646. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48647. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48648. BEGIN_JUCE_NAMESPACE
  48649. KeyPress::KeyPress() throw()
  48650. : keyCode (0),
  48651. mods (0),
  48652. textCharacter (0)
  48653. {
  48654. }
  48655. KeyPress::KeyPress (const int keyCode_,
  48656. const ModifierKeys& mods_,
  48657. const juce_wchar textCharacter_) throw()
  48658. : keyCode (keyCode_),
  48659. mods (mods_),
  48660. textCharacter (textCharacter_)
  48661. {
  48662. }
  48663. KeyPress::KeyPress (const int keyCode_) throw()
  48664. : keyCode (keyCode_),
  48665. textCharacter (0)
  48666. {
  48667. }
  48668. KeyPress::KeyPress (const KeyPress& other) throw()
  48669. : keyCode (other.keyCode),
  48670. mods (other.mods),
  48671. textCharacter (other.textCharacter)
  48672. {
  48673. }
  48674. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48675. {
  48676. keyCode = other.keyCode;
  48677. mods = other.mods;
  48678. textCharacter = other.textCharacter;
  48679. return *this;
  48680. }
  48681. bool KeyPress::operator== (const KeyPress& other) const throw()
  48682. {
  48683. return mods.getRawFlags() == other.mods.getRawFlags()
  48684. && (textCharacter == other.textCharacter
  48685. || textCharacter == 0
  48686. || other.textCharacter == 0)
  48687. && (keyCode == other.keyCode
  48688. || (keyCode < 256
  48689. && other.keyCode < 256
  48690. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48691. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48692. }
  48693. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48694. {
  48695. return ! operator== (other);
  48696. }
  48697. bool KeyPress::isCurrentlyDown() const
  48698. {
  48699. return isKeyCurrentlyDown (keyCode)
  48700. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48701. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48702. }
  48703. namespace KeyPressHelpers
  48704. {
  48705. struct KeyNameAndCode
  48706. {
  48707. const char* name;
  48708. int code;
  48709. };
  48710. const KeyNameAndCode translations[] =
  48711. {
  48712. { "spacebar", KeyPress::spaceKey },
  48713. { "return", KeyPress::returnKey },
  48714. { "escape", KeyPress::escapeKey },
  48715. { "backspace", KeyPress::backspaceKey },
  48716. { "cursor left", KeyPress::leftKey },
  48717. { "cursor right", KeyPress::rightKey },
  48718. { "cursor up", KeyPress::upKey },
  48719. { "cursor down", KeyPress::downKey },
  48720. { "page up", KeyPress::pageUpKey },
  48721. { "page down", KeyPress::pageDownKey },
  48722. { "home", KeyPress::homeKey },
  48723. { "end", KeyPress::endKey },
  48724. { "delete", KeyPress::deleteKey },
  48725. { "insert", KeyPress::insertKey },
  48726. { "tab", KeyPress::tabKey },
  48727. { "play", KeyPress::playKey },
  48728. { "stop", KeyPress::stopKey },
  48729. { "fast forward", KeyPress::fastForwardKey },
  48730. { "rewind", KeyPress::rewindKey }
  48731. };
  48732. const String numberPadPrefix() { return "numpad "; }
  48733. }
  48734. const KeyPress KeyPress::createFromDescription (const String& desc)
  48735. {
  48736. int modifiers = 0;
  48737. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48738. || desc.containsWholeWordIgnoreCase ("control")
  48739. || desc.containsWholeWordIgnoreCase ("ctl"))
  48740. modifiers |= ModifierKeys::ctrlModifier;
  48741. if (desc.containsWholeWordIgnoreCase ("shift")
  48742. || desc.containsWholeWordIgnoreCase ("shft"))
  48743. modifiers |= ModifierKeys::shiftModifier;
  48744. if (desc.containsWholeWordIgnoreCase ("alt")
  48745. || desc.containsWholeWordIgnoreCase ("option"))
  48746. modifiers |= ModifierKeys::altModifier;
  48747. if (desc.containsWholeWordIgnoreCase ("command")
  48748. || desc.containsWholeWordIgnoreCase ("cmd"))
  48749. modifiers |= ModifierKeys::commandModifier;
  48750. int key = 0;
  48751. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48752. {
  48753. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48754. {
  48755. key = KeyPressHelpers::translations[i].code;
  48756. break;
  48757. }
  48758. }
  48759. if (key == 0)
  48760. {
  48761. // see if it's a numpad key..
  48762. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48763. {
  48764. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48765. if (lastChar >= '0' && lastChar <= '9')
  48766. key = numberPad0 + lastChar - '0';
  48767. else if (lastChar == '+')
  48768. key = numberPadAdd;
  48769. else if (lastChar == '-')
  48770. key = numberPadSubtract;
  48771. else if (lastChar == '*')
  48772. key = numberPadMultiply;
  48773. else if (lastChar == '/')
  48774. key = numberPadDivide;
  48775. else if (lastChar == '.')
  48776. key = numberPadDecimalPoint;
  48777. else if (lastChar == '=')
  48778. key = numberPadEquals;
  48779. else if (desc.endsWith ("separator"))
  48780. key = numberPadSeparator;
  48781. else if (desc.endsWith ("delete"))
  48782. key = numberPadDelete;
  48783. }
  48784. if (key == 0)
  48785. {
  48786. // see if it's a function key..
  48787. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48788. for (int i = 1; i <= 12; ++i)
  48789. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48790. key = F1Key + i - 1;
  48791. if (key == 0)
  48792. {
  48793. // give up and use the hex code..
  48794. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48795. .toLowerCase()
  48796. .retainCharacters ("0123456789abcdef")
  48797. .getHexValue32();
  48798. if (hexCode > 0)
  48799. key = hexCode;
  48800. else
  48801. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48802. }
  48803. }
  48804. }
  48805. return KeyPress (key, ModifierKeys (modifiers), 0);
  48806. }
  48807. const String KeyPress::getTextDescription() const
  48808. {
  48809. String desc;
  48810. if (keyCode > 0)
  48811. {
  48812. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48813. // want to store it as being a slash, not shift+whatever.
  48814. if (textCharacter == '/')
  48815. return "/";
  48816. if (mods.isCtrlDown())
  48817. desc << "ctrl + ";
  48818. if (mods.isShiftDown())
  48819. desc << "shift + ";
  48820. #if JUCE_MAC
  48821. // only do this on the mac, because on Windows ctrl and command are the same,
  48822. // and this would get confusing
  48823. if (mods.isCommandDown())
  48824. desc << "command + ";
  48825. if (mods.isAltDown())
  48826. desc << "option + ";
  48827. #else
  48828. if (mods.isAltDown())
  48829. desc << "alt + ";
  48830. #endif
  48831. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48832. if (keyCode == KeyPressHelpers::translations[i].code)
  48833. return desc + KeyPressHelpers::translations[i].name;
  48834. if (keyCode >= F1Key && keyCode <= F16Key)
  48835. desc << 'F' << (1 + keyCode - F1Key);
  48836. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48837. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48838. else if (keyCode >= 33 && keyCode < 176)
  48839. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48840. else if (keyCode == numberPadAdd)
  48841. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48842. else if (keyCode == numberPadSubtract)
  48843. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48844. else if (keyCode == numberPadMultiply)
  48845. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48846. else if (keyCode == numberPadDivide)
  48847. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48848. else if (keyCode == numberPadSeparator)
  48849. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48850. else if (keyCode == numberPadDecimalPoint)
  48851. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48852. else if (keyCode == numberPadDelete)
  48853. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48854. else
  48855. desc << '#' << String::toHexString (keyCode);
  48856. }
  48857. return desc;
  48858. }
  48859. END_JUCE_NAMESPACE
  48860. /*** End of inlined file: juce_KeyPress.cpp ***/
  48861. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48862. BEGIN_JUCE_NAMESPACE
  48863. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48864. : commandManager (commandManager_)
  48865. {
  48866. // A manager is needed to get the descriptions of commands, and will be called when
  48867. // a command is invoked. So you can't leave this null..
  48868. jassert (commandManager_ != 0);
  48869. Desktop::getInstance().addFocusChangeListener (this);
  48870. }
  48871. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48872. : commandManager (other.commandManager)
  48873. {
  48874. Desktop::getInstance().addFocusChangeListener (this);
  48875. }
  48876. KeyPressMappingSet::~KeyPressMappingSet()
  48877. {
  48878. Desktop::getInstance().removeFocusChangeListener (this);
  48879. }
  48880. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48881. {
  48882. for (int i = 0; i < mappings.size(); ++i)
  48883. if (mappings.getUnchecked(i)->commandID == commandID)
  48884. return mappings.getUnchecked (i)->keypresses;
  48885. return Array <KeyPress> ();
  48886. }
  48887. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48888. const KeyPress& newKeyPress,
  48889. int insertIndex)
  48890. {
  48891. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48892. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48893. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48894. && ! newKeyPress.getModifiers().isShiftDown()));
  48895. if (findCommandForKeyPress (newKeyPress) != commandID)
  48896. {
  48897. removeKeyPress (newKeyPress);
  48898. if (newKeyPress.isValid())
  48899. {
  48900. for (int i = mappings.size(); --i >= 0;)
  48901. {
  48902. if (mappings.getUnchecked(i)->commandID == commandID)
  48903. {
  48904. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48905. sendChangeMessage();
  48906. return;
  48907. }
  48908. }
  48909. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48910. if (ci != 0)
  48911. {
  48912. CommandMapping* const cm = new CommandMapping();
  48913. cm->commandID = commandID;
  48914. cm->keypresses.add (newKeyPress);
  48915. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48916. mappings.add (cm);
  48917. sendChangeMessage();
  48918. }
  48919. }
  48920. }
  48921. }
  48922. void KeyPressMappingSet::resetToDefaultMappings()
  48923. {
  48924. mappings.clear();
  48925. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48926. {
  48927. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48928. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48929. {
  48930. addKeyPress (ci->commandID,
  48931. ci->defaultKeypresses.getReference (j));
  48932. }
  48933. }
  48934. sendChangeMessage();
  48935. }
  48936. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48937. {
  48938. clearAllKeyPresses (commandID);
  48939. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48940. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48941. {
  48942. addKeyPress (ci->commandID,
  48943. ci->defaultKeypresses.getReference (j));
  48944. }
  48945. }
  48946. void KeyPressMappingSet::clearAllKeyPresses()
  48947. {
  48948. if (mappings.size() > 0)
  48949. {
  48950. sendChangeMessage();
  48951. mappings.clear();
  48952. }
  48953. }
  48954. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48955. {
  48956. for (int i = mappings.size(); --i >= 0;)
  48957. {
  48958. if (mappings.getUnchecked(i)->commandID == commandID)
  48959. {
  48960. mappings.remove (i);
  48961. sendChangeMessage();
  48962. }
  48963. }
  48964. }
  48965. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48966. {
  48967. if (keypress.isValid())
  48968. {
  48969. for (int i = mappings.size(); --i >= 0;)
  48970. {
  48971. CommandMapping* const cm = mappings.getUnchecked(i);
  48972. for (int j = cm->keypresses.size(); --j >= 0;)
  48973. {
  48974. if (keypress == cm->keypresses [j])
  48975. {
  48976. cm->keypresses.remove (j);
  48977. sendChangeMessage();
  48978. }
  48979. }
  48980. }
  48981. }
  48982. }
  48983. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48984. {
  48985. for (int i = mappings.size(); --i >= 0;)
  48986. {
  48987. if (mappings.getUnchecked(i)->commandID == commandID)
  48988. {
  48989. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48990. sendChangeMessage();
  48991. break;
  48992. }
  48993. }
  48994. }
  48995. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48996. {
  48997. for (int i = 0; i < mappings.size(); ++i)
  48998. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48999. return mappings.getUnchecked(i)->commandID;
  49000. return 0;
  49001. }
  49002. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49003. {
  49004. for (int i = mappings.size(); --i >= 0;)
  49005. if (mappings.getUnchecked(i)->commandID == commandID)
  49006. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49007. return false;
  49008. }
  49009. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49010. const KeyPress& key,
  49011. const bool isKeyDown,
  49012. const int millisecsSinceKeyPressed,
  49013. Component* const originatingComponent) const
  49014. {
  49015. ApplicationCommandTarget::InvocationInfo info (commandID);
  49016. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49017. info.isKeyDown = isKeyDown;
  49018. info.keyPress = key;
  49019. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49020. info.originatingComponent = originatingComponent;
  49021. commandManager->invoke (info, false);
  49022. }
  49023. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49024. {
  49025. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49026. {
  49027. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49028. {
  49029. // if the XML was created as a set of differences from the default mappings,
  49030. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49031. resetToDefaultMappings();
  49032. }
  49033. else
  49034. {
  49035. // if the XML was created calling createXml (false), then we need to clear all
  49036. // the keys and treat the xml as describing the entire set of mappings.
  49037. clearAllKeyPresses();
  49038. }
  49039. forEachXmlChildElement (xmlVersion, map)
  49040. {
  49041. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49042. if (commandId != 0)
  49043. {
  49044. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49045. if (map->hasTagName ("MAPPING"))
  49046. {
  49047. addKeyPress (commandId, key);
  49048. }
  49049. else if (map->hasTagName ("UNMAPPING"))
  49050. {
  49051. if (containsMapping (commandId, key))
  49052. removeKeyPress (key);
  49053. }
  49054. }
  49055. }
  49056. return true;
  49057. }
  49058. return false;
  49059. }
  49060. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49061. {
  49062. ScopedPointer <KeyPressMappingSet> defaultSet;
  49063. if (saveDifferencesFromDefaultSet)
  49064. {
  49065. defaultSet = new KeyPressMappingSet (commandManager);
  49066. defaultSet->resetToDefaultMappings();
  49067. }
  49068. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49069. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49070. int i;
  49071. for (i = 0; i < mappings.size(); ++i)
  49072. {
  49073. const CommandMapping* const cm = mappings.getUnchecked(i);
  49074. for (int j = 0; j < cm->keypresses.size(); ++j)
  49075. {
  49076. if (defaultSet == 0
  49077. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49078. {
  49079. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49080. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49081. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49082. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49083. }
  49084. }
  49085. }
  49086. if (defaultSet != 0)
  49087. {
  49088. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49089. {
  49090. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49091. for (int j = 0; j < cm->keypresses.size(); ++j)
  49092. {
  49093. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49094. {
  49095. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49096. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49097. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49098. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49099. }
  49100. }
  49101. }
  49102. }
  49103. return doc;
  49104. }
  49105. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49106. Component* originatingComponent)
  49107. {
  49108. bool used = false;
  49109. const CommandID commandID = findCommandForKeyPress (key);
  49110. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49111. if (ci != 0
  49112. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49113. {
  49114. ApplicationCommandInfo info (0);
  49115. if (commandManager->getTargetForCommand (commandID, info) != 0
  49116. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49117. {
  49118. invokeCommand (commandID, key, true, 0, originatingComponent);
  49119. used = true;
  49120. }
  49121. else
  49122. {
  49123. if (originatingComponent != 0)
  49124. originatingComponent->getLookAndFeel().playAlertSound();
  49125. }
  49126. }
  49127. return used;
  49128. }
  49129. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49130. {
  49131. bool used = false;
  49132. const uint32 now = Time::getMillisecondCounter();
  49133. for (int i = mappings.size(); --i >= 0;)
  49134. {
  49135. CommandMapping* const cm = mappings.getUnchecked(i);
  49136. if (cm->wantsKeyUpDownCallbacks)
  49137. {
  49138. for (int j = cm->keypresses.size(); --j >= 0;)
  49139. {
  49140. const KeyPress key (cm->keypresses.getReference (j));
  49141. const bool isDown = key.isCurrentlyDown();
  49142. int keyPressEntryIndex = 0;
  49143. bool wasDown = false;
  49144. for (int k = keysDown.size(); --k >= 0;)
  49145. {
  49146. if (key == keysDown.getUnchecked(k)->key)
  49147. {
  49148. keyPressEntryIndex = k;
  49149. wasDown = true;
  49150. used = true;
  49151. break;
  49152. }
  49153. }
  49154. if (isDown != wasDown)
  49155. {
  49156. int millisecs = 0;
  49157. if (isDown)
  49158. {
  49159. KeyPressTime* const k = new KeyPressTime();
  49160. k->key = key;
  49161. k->timeWhenPressed = now;
  49162. keysDown.add (k);
  49163. }
  49164. else
  49165. {
  49166. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49167. if (now > pressTime)
  49168. millisecs = now - pressTime;
  49169. keysDown.remove (keyPressEntryIndex);
  49170. }
  49171. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49172. used = true;
  49173. }
  49174. }
  49175. }
  49176. }
  49177. return used;
  49178. }
  49179. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49180. {
  49181. if (focusedComponent != 0)
  49182. focusedComponent->keyStateChanged (false);
  49183. }
  49184. END_JUCE_NAMESPACE
  49185. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49186. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49187. BEGIN_JUCE_NAMESPACE
  49188. ModifierKeys::ModifierKeys (const int flags_) throw()
  49189. : flags (flags_)
  49190. {
  49191. }
  49192. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49193. : flags (other.flags)
  49194. {
  49195. }
  49196. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49197. {
  49198. flags = other.flags;
  49199. return *this;
  49200. }
  49201. ModifierKeys ModifierKeys::currentModifiers;
  49202. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49203. {
  49204. return currentModifiers;
  49205. }
  49206. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49207. {
  49208. int num = 0;
  49209. if (isLeftButtonDown()) ++num;
  49210. if (isRightButtonDown()) ++num;
  49211. if (isMiddleButtonDown()) ++num;
  49212. return num;
  49213. }
  49214. END_JUCE_NAMESPACE
  49215. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49216. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49217. BEGIN_JUCE_NAMESPACE
  49218. class ComponentAnimator::AnimationTask
  49219. {
  49220. public:
  49221. AnimationTask (Component* const comp)
  49222. : component (comp)
  49223. {
  49224. }
  49225. void reset (const Rectangle<int>& finalBounds,
  49226. float finalAlpha,
  49227. int millisecondsToSpendMoving,
  49228. bool useProxyComponent,
  49229. double startSpeed_, double endSpeed_)
  49230. {
  49231. msElapsed = 0;
  49232. msTotal = jmax (1, millisecondsToSpendMoving);
  49233. lastProgress = 0;
  49234. destination = finalBounds;
  49235. destAlpha = finalAlpha;
  49236. isMoving = (finalBounds != component->getBounds());
  49237. isChangingAlpha = (finalAlpha != component->getAlpha());
  49238. left = component->getX();
  49239. top = component->getY();
  49240. right = component->getRight();
  49241. bottom = component->getBottom();
  49242. alpha = component->getAlpha();
  49243. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49244. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49245. midSpeed = invTotalDistance;
  49246. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49247. if (useProxyComponent)
  49248. proxy = new ProxyComponent (*component);
  49249. else
  49250. proxy = 0;
  49251. component->setVisible (! useProxyComponent);
  49252. }
  49253. bool useTimeslice (const int elapsed)
  49254. {
  49255. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49256. : static_cast <Component*> (component);
  49257. if (c != 0)
  49258. {
  49259. msElapsed += elapsed;
  49260. double newProgress = msElapsed / (double) msTotal;
  49261. if (newProgress >= 0 && newProgress < 1.0)
  49262. {
  49263. newProgress = timeToDistance (newProgress);
  49264. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49265. jassert (newProgress >= lastProgress);
  49266. lastProgress = newProgress;
  49267. if (delta < 1.0)
  49268. {
  49269. bool stillBusy = false;
  49270. if (isMoving)
  49271. {
  49272. left += (destination.getX() - left) * delta;
  49273. top += (destination.getY() - top) * delta;
  49274. right += (destination.getRight() - right) * delta;
  49275. bottom += (destination.getBottom() - bottom) * delta;
  49276. const Rectangle<int> newBounds (roundToInt (left),
  49277. roundToInt (top),
  49278. roundToInt (right - left),
  49279. roundToInt (bottom - top));
  49280. if (newBounds != destination)
  49281. {
  49282. c->setBounds (newBounds);
  49283. stillBusy = true;
  49284. }
  49285. }
  49286. if (isChangingAlpha)
  49287. {
  49288. alpha += (destAlpha - alpha) * delta;
  49289. c->setAlpha ((float) alpha);
  49290. stillBusy = true;
  49291. }
  49292. if (stillBusy)
  49293. return true;
  49294. }
  49295. }
  49296. }
  49297. moveToFinalDestination();
  49298. return false;
  49299. }
  49300. void moveToFinalDestination()
  49301. {
  49302. if (component != 0)
  49303. {
  49304. component->setAlpha ((float) destAlpha);
  49305. component->setBounds (destination);
  49306. }
  49307. }
  49308. class ProxyComponent : public Component
  49309. {
  49310. public:
  49311. ProxyComponent (Component& component)
  49312. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49313. {
  49314. setBounds (component.getBounds());
  49315. setAlpha (component.getAlpha());
  49316. setInterceptsMouseClicks (false, false);
  49317. Component* const parent = component.getParentComponent();
  49318. if (parent != 0)
  49319. parent->addAndMakeVisible (this);
  49320. else if (component.isOnDesktop() && component.getPeer() != 0)
  49321. addToDesktop (component.getPeer()->getStyleFlags());
  49322. else
  49323. jassertfalse; // seem to be trying to animate a component that's not visible..
  49324. setVisible (true);
  49325. toBehind (&component);
  49326. }
  49327. void paint (Graphics& g)
  49328. {
  49329. g.setOpacity (1.0f);
  49330. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49331. 0, 0, image.getWidth(), image.getHeight());
  49332. }
  49333. private:
  49334. Image image;
  49335. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49336. };
  49337. WeakReference<Component> component;
  49338. ScopedPointer<Component> proxy;
  49339. Rectangle<int> destination;
  49340. double destAlpha;
  49341. int msElapsed, msTotal;
  49342. double startSpeed, midSpeed, endSpeed, lastProgress;
  49343. double left, top, right, bottom, alpha;
  49344. bool isMoving, isChangingAlpha;
  49345. private:
  49346. double timeToDistance (const double time) const throw()
  49347. {
  49348. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49349. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49350. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49351. }
  49352. };
  49353. ComponentAnimator::ComponentAnimator()
  49354. : lastTime (0)
  49355. {
  49356. }
  49357. ComponentAnimator::~ComponentAnimator()
  49358. {
  49359. }
  49360. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49361. {
  49362. for (int i = tasks.size(); --i >= 0;)
  49363. if (component == tasks.getUnchecked(i)->component.get())
  49364. return tasks.getUnchecked(i);
  49365. return 0;
  49366. }
  49367. void ComponentAnimator::animateComponent (Component* const component,
  49368. const Rectangle<int>& finalBounds,
  49369. const float finalAlpha,
  49370. const int millisecondsToSpendMoving,
  49371. const bool useProxyComponent,
  49372. const double startSpeed,
  49373. const double endSpeed)
  49374. {
  49375. // the speeds must be 0 or greater!
  49376. jassert (startSpeed >= 0 && endSpeed >= 0)
  49377. if (component != 0)
  49378. {
  49379. AnimationTask* at = findTaskFor (component);
  49380. if (at == 0)
  49381. {
  49382. at = new AnimationTask (component);
  49383. tasks.add (at);
  49384. sendChangeMessage();
  49385. }
  49386. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49387. useProxyComponent, startSpeed, endSpeed);
  49388. if (! isTimerRunning())
  49389. {
  49390. lastTime = Time::getMillisecondCounter();
  49391. startTimer (1000 / 50);
  49392. }
  49393. }
  49394. }
  49395. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49396. {
  49397. if (component != 0)
  49398. {
  49399. if (component->isShowing() && millisecondsToTake > 0)
  49400. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49401. component->setVisible (false);
  49402. }
  49403. }
  49404. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49405. {
  49406. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49407. {
  49408. component->setAlpha (0.0f);
  49409. component->setVisible (true);
  49410. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49411. }
  49412. }
  49413. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49414. {
  49415. if (tasks.size() > 0)
  49416. {
  49417. if (moveComponentsToTheirFinalPositions)
  49418. for (int i = tasks.size(); --i >= 0;)
  49419. tasks.getUnchecked(i)->moveToFinalDestination();
  49420. tasks.clear();
  49421. sendChangeMessage();
  49422. }
  49423. }
  49424. void ComponentAnimator::cancelAnimation (Component* const component,
  49425. const bool moveComponentToItsFinalPosition)
  49426. {
  49427. AnimationTask* const at = findTaskFor (component);
  49428. if (at != 0)
  49429. {
  49430. if (moveComponentToItsFinalPosition)
  49431. at->moveToFinalDestination();
  49432. tasks.removeObject (at);
  49433. sendChangeMessage();
  49434. }
  49435. }
  49436. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49437. {
  49438. jassert (component != 0);
  49439. AnimationTask* const at = findTaskFor (component);
  49440. if (at != 0)
  49441. return at->destination;
  49442. return component->getBounds();
  49443. }
  49444. bool ComponentAnimator::isAnimating (Component* component) const
  49445. {
  49446. return findTaskFor (component) != 0;
  49447. }
  49448. void ComponentAnimator::timerCallback()
  49449. {
  49450. const uint32 timeNow = Time::getMillisecondCounter();
  49451. if (lastTime == 0 || lastTime == timeNow)
  49452. lastTime = timeNow;
  49453. const int elapsed = timeNow - lastTime;
  49454. for (int i = tasks.size(); --i >= 0;)
  49455. {
  49456. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49457. {
  49458. tasks.remove (i);
  49459. sendChangeMessage();
  49460. }
  49461. }
  49462. lastTime = timeNow;
  49463. if (tasks.size() == 0)
  49464. stopTimer();
  49465. }
  49466. END_JUCE_NAMESPACE
  49467. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49468. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49469. BEGIN_JUCE_NAMESPACE
  49470. namespace ComponentBuilderHelpers
  49471. {
  49472. const String getStateId (const ValueTree& state)
  49473. {
  49474. return state [ComponentBuilder::idProperty].toString();
  49475. }
  49476. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49477. {
  49478. jassert (compId.isNotEmpty());
  49479. for (int i = components.size(); --i >= 0;)
  49480. {
  49481. Component* const c = components.getUnchecked (i);
  49482. if (c->getComponentID() == compId)
  49483. return components.removeAndReturn (i);
  49484. }
  49485. return 0;
  49486. }
  49487. Component* findComponentWithID (Component* const c, const String& compId)
  49488. {
  49489. jassert (compId.isNotEmpty());
  49490. if (c->getComponentID() == compId)
  49491. return c;
  49492. for (int i = c->getNumChildComponents(); --i >= 0;)
  49493. {
  49494. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49495. if (child != 0)
  49496. return child;
  49497. }
  49498. return 0;
  49499. }
  49500. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49501. const ValueTree& state, Component* parent)
  49502. {
  49503. Component* const c = type.addNewComponentFromState (state, parent);
  49504. jassert (c != 0 && c->getParentComponent() == parent);
  49505. c->setComponentID (getStateId (state));
  49506. return c;
  49507. }
  49508. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49509. {
  49510. Component* topLevelComp = builder.getManagedComponent();
  49511. if (topLevelComp != 0)
  49512. {
  49513. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49514. const String uid (getStateId (state));
  49515. if (type == 0 || uid.isEmpty())
  49516. {
  49517. // ..handle the case where a child of the actual state node has changed.
  49518. if (state.getParent().isValid())
  49519. updateComponent (builder, state.getParent());
  49520. }
  49521. else
  49522. {
  49523. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49524. if (changedComp != 0)
  49525. type->updateComponentFromState (changedComp, state);
  49526. }
  49527. }
  49528. }
  49529. }
  49530. const Identifier ComponentBuilder::idProperty ("id");
  49531. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49532. : state (state_), imageProvider (0)
  49533. {
  49534. state.addListener (this);
  49535. }
  49536. ComponentBuilder::~ComponentBuilder()
  49537. {
  49538. state.removeListener (this);
  49539. #if JUCE_DEBUG
  49540. // Don't delete the managed component!! The builder owns that component, and will delete
  49541. // it automatically when it gets deleted.
  49542. jassert (componentRef.get() == static_cast <Component*> (component));
  49543. #endif
  49544. }
  49545. Component* ComponentBuilder::getManagedComponent()
  49546. {
  49547. if (component == 0)
  49548. {
  49549. component = createComponent();
  49550. #if JUCE_DEBUG
  49551. componentRef = component;
  49552. #endif
  49553. }
  49554. return component;
  49555. }
  49556. Component* ComponentBuilder::createComponent()
  49557. {
  49558. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49559. TypeHandler* const type = getHandlerForState (state);
  49560. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49561. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49562. }
  49563. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49564. {
  49565. jassert (type != 0);
  49566. // Don't try to move your types around! Once a type has been added to a builder, the
  49567. // builder owns it, and you should leave it alone!
  49568. jassert (type->builder == 0);
  49569. types.add (type);
  49570. type->builder = this;
  49571. }
  49572. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49573. {
  49574. const Identifier targetType (s.getType());
  49575. for (int i = 0; i < types.size(); ++i)
  49576. {
  49577. TypeHandler* const t = types.getUnchecked(i);
  49578. if (t->getType() == targetType)
  49579. return t;
  49580. }
  49581. return 0;
  49582. }
  49583. int ComponentBuilder::getNumHandlers() const throw()
  49584. {
  49585. return types.size();
  49586. }
  49587. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49588. {
  49589. return types [index];
  49590. }
  49591. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49592. {
  49593. imageProvider = newImageProvider;
  49594. }
  49595. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49596. {
  49597. return imageProvider;
  49598. }
  49599. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49600. {
  49601. ComponentBuilderHelpers::updateComponent (*this, tree);
  49602. }
  49603. void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
  49604. {
  49605. ComponentBuilderHelpers::updateComponent (*this, tree);
  49606. }
  49607. void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&)
  49608. {
  49609. ComponentBuilderHelpers::updateComponent (*this, tree);
  49610. }
  49611. void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree)
  49612. {
  49613. ComponentBuilderHelpers::updateComponent (*this, tree);
  49614. }
  49615. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49616. {
  49617. ComponentBuilderHelpers::updateComponent (*this, tree);
  49618. }
  49619. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49620. : builder (0), valueTreeType (valueTreeType_)
  49621. {
  49622. }
  49623. ComponentBuilder::TypeHandler::~TypeHandler()
  49624. {
  49625. }
  49626. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49627. {
  49628. // A type handler needs to be registered with a ComponentBuilder before using it!
  49629. jassert (builder != 0);
  49630. return builder;
  49631. }
  49632. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49633. {
  49634. using namespace ComponentBuilderHelpers;
  49635. const int numExistingChildComps = parent.getNumChildComponents();
  49636. Array <Component*> componentsInOrder;
  49637. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49638. {
  49639. OwnedArray<Component> existingComponents;
  49640. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49641. int i;
  49642. for (i = 0; i < numExistingChildComps; ++i)
  49643. existingComponents.add (parent.getChildComponent (i));
  49644. const int newNumChildren = children.getNumChildren();
  49645. for (i = 0; i < newNumChildren; ++i)
  49646. {
  49647. const ValueTree childState (children.getChild (i));
  49648. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49649. jassert (type != 0);
  49650. if (type != 0)
  49651. {
  49652. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49653. if (c == 0)
  49654. c = createNewComponent (*type, childState, &parent);
  49655. componentsInOrder.add (c);
  49656. }
  49657. }
  49658. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49659. }
  49660. // Make sure the z-order is correct..
  49661. if (componentsInOrder.size() > 0)
  49662. {
  49663. componentsInOrder.getLast()->toFront (false);
  49664. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49665. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49666. }
  49667. }
  49668. END_JUCE_NAMESPACE
  49669. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49670. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49671. BEGIN_JUCE_NAMESPACE
  49672. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49673. : minW (0),
  49674. maxW (0x3fffffff),
  49675. minH (0),
  49676. maxH (0x3fffffff),
  49677. minOffTop (0),
  49678. minOffLeft (0),
  49679. minOffBottom (0),
  49680. minOffRight (0),
  49681. aspectRatio (0.0)
  49682. {
  49683. }
  49684. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49685. {
  49686. }
  49687. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49688. {
  49689. minW = minimumWidth;
  49690. }
  49691. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49692. {
  49693. maxW = maximumWidth;
  49694. }
  49695. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49696. {
  49697. minH = minimumHeight;
  49698. }
  49699. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49700. {
  49701. maxH = maximumHeight;
  49702. }
  49703. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49704. {
  49705. jassert (maxW >= minimumWidth);
  49706. jassert (maxH >= minimumHeight);
  49707. jassert (minimumWidth > 0 && minimumHeight > 0);
  49708. minW = minimumWidth;
  49709. minH = minimumHeight;
  49710. if (minW > maxW)
  49711. maxW = minW;
  49712. if (minH > maxH)
  49713. maxH = minH;
  49714. }
  49715. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49716. {
  49717. jassert (maximumWidth >= minW);
  49718. jassert (maximumHeight >= minH);
  49719. jassert (maximumWidth > 0 && maximumHeight > 0);
  49720. maxW = jmax (minW, maximumWidth);
  49721. maxH = jmax (minH, maximumHeight);
  49722. }
  49723. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49724. const int minimumHeight,
  49725. const int maximumWidth,
  49726. const int maximumHeight) throw()
  49727. {
  49728. jassert (maximumWidth >= minimumWidth);
  49729. jassert (maximumHeight >= minimumHeight);
  49730. jassert (maximumWidth > 0 && maximumHeight > 0);
  49731. jassert (minimumWidth > 0 && minimumHeight > 0);
  49732. minW = jmax (0, minimumWidth);
  49733. minH = jmax (0, minimumHeight);
  49734. maxW = jmax (minW, maximumWidth);
  49735. maxH = jmax (minH, maximumHeight);
  49736. }
  49737. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49738. const int minimumWhenOffTheLeft,
  49739. const int minimumWhenOffTheBottom,
  49740. const int minimumWhenOffTheRight) throw()
  49741. {
  49742. minOffTop = minimumWhenOffTheTop;
  49743. minOffLeft = minimumWhenOffTheLeft;
  49744. minOffBottom = minimumWhenOffTheBottom;
  49745. minOffRight = minimumWhenOffTheRight;
  49746. }
  49747. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49748. {
  49749. aspectRatio = jmax (0.0, widthOverHeight);
  49750. }
  49751. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49752. {
  49753. return aspectRatio;
  49754. }
  49755. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49756. const Rectangle<int>& targetBounds,
  49757. const bool isStretchingTop,
  49758. const bool isStretchingLeft,
  49759. const bool isStretchingBottom,
  49760. const bool isStretchingRight)
  49761. {
  49762. jassert (component != 0);
  49763. Rectangle<int> limits, bounds (targetBounds);
  49764. BorderSize<int> border;
  49765. Component* const parent = component->getParentComponent();
  49766. if (parent == 0)
  49767. {
  49768. ComponentPeer* peer = component->getPeer();
  49769. if (peer != 0)
  49770. border = peer->getFrameSize();
  49771. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49772. }
  49773. else
  49774. {
  49775. limits.setSize (parent->getWidth(), parent->getHeight());
  49776. }
  49777. border.addTo (bounds);
  49778. checkBounds (bounds,
  49779. border.addedTo (component->getBounds()), limits,
  49780. isStretchingTop, isStretchingLeft,
  49781. isStretchingBottom, isStretchingRight);
  49782. border.subtractFrom (bounds);
  49783. applyBoundsToComponent (component, bounds);
  49784. }
  49785. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49786. {
  49787. setBoundsForComponent (component, component->getBounds(),
  49788. false, false, false, false);
  49789. }
  49790. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49791. const Rectangle<int>& bounds)
  49792. {
  49793. Component::Positioner* const positioner = component->getPositioner();
  49794. if (positioner != 0)
  49795. positioner->applyNewBounds (bounds);
  49796. else
  49797. component->setBounds (bounds);
  49798. }
  49799. void ComponentBoundsConstrainer::resizeStart()
  49800. {
  49801. }
  49802. void ComponentBoundsConstrainer::resizeEnd()
  49803. {
  49804. }
  49805. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49806. const Rectangle<int>& old,
  49807. const Rectangle<int>& limits,
  49808. const bool isStretchingTop,
  49809. const bool isStretchingLeft,
  49810. const bool isStretchingBottom,
  49811. const bool isStretchingRight)
  49812. {
  49813. // constrain the size if it's being stretched..
  49814. if (isStretchingLeft)
  49815. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49816. if (isStretchingRight)
  49817. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49818. if (isStretchingTop)
  49819. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49820. if (isStretchingBottom)
  49821. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49822. if (bounds.isEmpty())
  49823. return;
  49824. if (minOffTop > 0)
  49825. {
  49826. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49827. if (bounds.getY() < limit)
  49828. {
  49829. if (isStretchingTop)
  49830. bounds.setTop (limits.getY());
  49831. else
  49832. bounds.setY (limit);
  49833. }
  49834. }
  49835. if (minOffLeft > 0)
  49836. {
  49837. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49838. if (bounds.getX() < limit)
  49839. {
  49840. if (isStretchingLeft)
  49841. bounds.setLeft (limits.getX());
  49842. else
  49843. bounds.setX (limit);
  49844. }
  49845. }
  49846. if (minOffBottom > 0)
  49847. {
  49848. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49849. if (bounds.getY() > limit)
  49850. {
  49851. if (isStretchingBottom)
  49852. bounds.setBottom (limits.getBottom());
  49853. else
  49854. bounds.setY (limit);
  49855. }
  49856. }
  49857. if (minOffRight > 0)
  49858. {
  49859. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49860. if (bounds.getX() > limit)
  49861. {
  49862. if (isStretchingRight)
  49863. bounds.setRight (limits.getRight());
  49864. else
  49865. bounds.setX (limit);
  49866. }
  49867. }
  49868. // constrain the aspect ratio if one has been specified..
  49869. if (aspectRatio > 0.0)
  49870. {
  49871. bool adjustWidth;
  49872. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49873. {
  49874. adjustWidth = true;
  49875. }
  49876. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49877. {
  49878. adjustWidth = false;
  49879. }
  49880. else
  49881. {
  49882. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49883. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49884. adjustWidth = (oldRatio > newRatio);
  49885. }
  49886. if (adjustWidth)
  49887. {
  49888. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49889. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49890. {
  49891. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49892. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49893. }
  49894. }
  49895. else
  49896. {
  49897. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49898. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49899. {
  49900. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49901. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49902. }
  49903. }
  49904. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49905. {
  49906. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49907. }
  49908. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49909. {
  49910. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49911. }
  49912. else
  49913. {
  49914. if (isStretchingLeft)
  49915. bounds.setX (old.getRight() - bounds.getWidth());
  49916. if (isStretchingTop)
  49917. bounds.setY (old.getBottom() - bounds.getHeight());
  49918. }
  49919. }
  49920. jassert (! bounds.isEmpty());
  49921. }
  49922. END_JUCE_NAMESPACE
  49923. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49924. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49925. BEGIN_JUCE_NAMESPACE
  49926. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49927. : component (component_),
  49928. lastPeer (0),
  49929. reentrant (false),
  49930. wasShowing (component_->isShowing())
  49931. {
  49932. jassert (component != 0); // can't use this with a null pointer..
  49933. component->addComponentListener (this);
  49934. registerWithParentComps();
  49935. }
  49936. ComponentMovementWatcher::~ComponentMovementWatcher()
  49937. {
  49938. if (component != 0)
  49939. component->removeComponentListener (this);
  49940. unregister();
  49941. }
  49942. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49943. {
  49944. if (component != 0 && ! reentrant)
  49945. {
  49946. const ScopedValueSetter<bool> setter (reentrant, true);
  49947. ComponentPeer* const peer = component->getPeer();
  49948. if (peer != lastPeer)
  49949. {
  49950. componentPeerChanged();
  49951. if (component == 0)
  49952. return;
  49953. lastPeer = peer;
  49954. }
  49955. unregister();
  49956. registerWithParentComps();
  49957. componentMovedOrResized (*component, true, true);
  49958. if (component != 0)
  49959. componentVisibilityChanged (*component);
  49960. }
  49961. }
  49962. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49963. {
  49964. if (component != 0)
  49965. {
  49966. if (wasMoved)
  49967. {
  49968. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49969. wasMoved = lastBounds.getPosition() != pos;
  49970. lastBounds.setPosition (pos);
  49971. }
  49972. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49973. lastBounds.setSize (component->getWidth(), component->getHeight());
  49974. if (wasMoved || wasResized)
  49975. componentMovedOrResized (wasMoved, wasResized);
  49976. }
  49977. }
  49978. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49979. {
  49980. registeredParentComps.removeValue (&comp);
  49981. if (component == &comp)
  49982. unregister();
  49983. }
  49984. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49985. {
  49986. if (component != 0)
  49987. {
  49988. const bool isShowingNow = component->isShowing();
  49989. if (wasShowing != isShowingNow)
  49990. {
  49991. wasShowing = isShowingNow;
  49992. componentVisibilityChanged();
  49993. }
  49994. }
  49995. }
  49996. void ComponentMovementWatcher::registerWithParentComps()
  49997. {
  49998. Component* p = component->getParentComponent();
  49999. while (p != 0)
  50000. {
  50001. p->addComponentListener (this);
  50002. registeredParentComps.add (p);
  50003. p = p->getParentComponent();
  50004. }
  50005. }
  50006. void ComponentMovementWatcher::unregister()
  50007. {
  50008. for (int i = registeredParentComps.size(); --i >= 0;)
  50009. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50010. registeredParentComps.clear();
  50011. }
  50012. END_JUCE_NAMESPACE
  50013. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50014. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50015. BEGIN_JUCE_NAMESPACE
  50016. GroupComponent::GroupComponent (const String& componentName,
  50017. const String& labelText)
  50018. : Component (componentName),
  50019. text (labelText),
  50020. justification (Justification::left)
  50021. {
  50022. setInterceptsMouseClicks (false, true);
  50023. }
  50024. GroupComponent::~GroupComponent()
  50025. {
  50026. }
  50027. void GroupComponent::setText (const String& newText)
  50028. {
  50029. if (text != newText)
  50030. {
  50031. text = newText;
  50032. repaint();
  50033. }
  50034. }
  50035. const String GroupComponent::getText() const
  50036. {
  50037. return text;
  50038. }
  50039. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50040. {
  50041. if (justification != newJustification)
  50042. {
  50043. justification = newJustification;
  50044. repaint();
  50045. }
  50046. }
  50047. void GroupComponent::paint (Graphics& g)
  50048. {
  50049. getLookAndFeel()
  50050. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50051. text, justification,
  50052. *this);
  50053. }
  50054. void GroupComponent::enablementChanged()
  50055. {
  50056. repaint();
  50057. }
  50058. void GroupComponent::colourChanged()
  50059. {
  50060. repaint();
  50061. }
  50062. END_JUCE_NAMESPACE
  50063. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50064. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50065. BEGIN_JUCE_NAMESPACE
  50066. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50067. : DocumentWindow (String::empty, backgroundColour,
  50068. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50069. {
  50070. }
  50071. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50072. {
  50073. }
  50074. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50075. {
  50076. MultiDocumentPanel* const owner = getOwner();
  50077. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50078. if (owner != 0)
  50079. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50080. }
  50081. void MultiDocumentPanelWindow::closeButtonPressed()
  50082. {
  50083. MultiDocumentPanel* const owner = getOwner();
  50084. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50085. if (owner != 0)
  50086. owner->closeDocument (getContentComponent(), true);
  50087. }
  50088. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50089. {
  50090. DocumentWindow::activeWindowStatusChanged();
  50091. updateOrder();
  50092. }
  50093. void MultiDocumentPanelWindow::broughtToFront()
  50094. {
  50095. DocumentWindow::broughtToFront();
  50096. updateOrder();
  50097. }
  50098. void MultiDocumentPanelWindow::updateOrder()
  50099. {
  50100. MultiDocumentPanel* const owner = getOwner();
  50101. if (owner != 0)
  50102. owner->updateOrder();
  50103. }
  50104. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50105. {
  50106. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50107. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50108. }
  50109. class MDITabbedComponentInternal : public TabbedComponent
  50110. {
  50111. public:
  50112. MDITabbedComponentInternal()
  50113. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50114. {
  50115. }
  50116. ~MDITabbedComponentInternal()
  50117. {
  50118. }
  50119. void currentTabChanged (int, const String&)
  50120. {
  50121. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50122. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50123. if (owner != 0)
  50124. owner->updateOrder();
  50125. }
  50126. };
  50127. MultiDocumentPanel::MultiDocumentPanel()
  50128. : mode (MaximisedWindowsWithTabs),
  50129. backgroundColour (Colours::lightblue),
  50130. maximumNumDocuments (0),
  50131. numDocsBeforeTabsUsed (0)
  50132. {
  50133. setOpaque (true);
  50134. }
  50135. MultiDocumentPanel::~MultiDocumentPanel()
  50136. {
  50137. closeAllDocuments (false);
  50138. }
  50139. namespace MultiDocHelpers
  50140. {
  50141. bool shouldDeleteComp (Component* const c)
  50142. {
  50143. return c->getProperties() ["mdiDocumentDelete_"];
  50144. }
  50145. }
  50146. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50147. {
  50148. while (components.size() > 0)
  50149. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50150. return false;
  50151. return true;
  50152. }
  50153. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50154. {
  50155. return new MultiDocumentPanelWindow (backgroundColour);
  50156. }
  50157. void MultiDocumentPanel::addWindow (Component* component)
  50158. {
  50159. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50160. dw->setResizable (true, false);
  50161. dw->setContentNonOwned (component, true);
  50162. dw->setName (component->getName());
  50163. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50164. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50165. int x = 4;
  50166. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50167. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50168. x += 16;
  50169. dw->setTopLeftPosition (x, x);
  50170. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50171. if (pos.toString().isNotEmpty())
  50172. dw->restoreWindowStateFromString (pos.toString());
  50173. addAndMakeVisible (dw);
  50174. dw->toFront (true);
  50175. }
  50176. bool MultiDocumentPanel::addDocument (Component* const component,
  50177. const Colour& docColour,
  50178. const bool deleteWhenRemoved)
  50179. {
  50180. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50181. // with a frame-within-a-frame! Just pass in the bare content component.
  50182. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50183. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50184. return false;
  50185. components.add (component);
  50186. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50187. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50188. component->addComponentListener (this);
  50189. if (mode == FloatingWindows)
  50190. {
  50191. if (isFullscreenWhenOneDocument())
  50192. {
  50193. if (components.size() == 1)
  50194. {
  50195. addAndMakeVisible (component);
  50196. }
  50197. else
  50198. {
  50199. if (components.size() == 2)
  50200. addWindow (components.getFirst());
  50201. addWindow (component);
  50202. }
  50203. }
  50204. else
  50205. {
  50206. addWindow (component);
  50207. }
  50208. }
  50209. else
  50210. {
  50211. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50212. {
  50213. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50214. Array <Component*> temp (components);
  50215. for (int i = 0; i < temp.size(); ++i)
  50216. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50217. resized();
  50218. }
  50219. else
  50220. {
  50221. if (tabComponent != 0)
  50222. tabComponent->addTab (component->getName(), docColour, component, false);
  50223. else
  50224. addAndMakeVisible (component);
  50225. }
  50226. setActiveDocument (component);
  50227. }
  50228. resized();
  50229. activeDocumentChanged();
  50230. return true;
  50231. }
  50232. bool MultiDocumentPanel::closeDocument (Component* component,
  50233. const bool checkItsOkToCloseFirst)
  50234. {
  50235. if (components.contains (component))
  50236. {
  50237. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50238. return false;
  50239. component->removeComponentListener (this);
  50240. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50241. component->getProperties().remove ("mdiDocumentDelete_");
  50242. component->getProperties().remove ("mdiDocumentBkg_");
  50243. if (mode == FloatingWindows)
  50244. {
  50245. for (int i = getNumChildComponents(); --i >= 0;)
  50246. {
  50247. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50248. if (dw != 0 && dw->getContentComponent() == component)
  50249. {
  50250. ScopedPointer<MultiDocumentPanelWindow> (dw)->clearContentComponent();
  50251. break;
  50252. }
  50253. }
  50254. if (shouldDelete)
  50255. delete component;
  50256. components.removeValue (component);
  50257. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50258. {
  50259. for (int i = getNumChildComponents(); --i >= 0;)
  50260. {
  50261. ScopedPointer<MultiDocumentPanelWindow> dw (dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i)));
  50262. if (dw != 0)
  50263. dw->clearContentComponent();
  50264. }
  50265. addAndMakeVisible (components.getFirst());
  50266. }
  50267. }
  50268. else
  50269. {
  50270. jassert (components.indexOf (component) >= 0);
  50271. if (tabComponent != 0)
  50272. {
  50273. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50274. if (tabComponent->getTabContentComponent (i) == component)
  50275. tabComponent->removeTab (i);
  50276. }
  50277. else
  50278. {
  50279. removeChildComponent (component);
  50280. }
  50281. if (shouldDelete)
  50282. delete component;
  50283. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50284. tabComponent = 0;
  50285. components.removeValue (component);
  50286. if (components.size() > 0 && tabComponent == 0)
  50287. addAndMakeVisible (components.getFirst());
  50288. }
  50289. resized();
  50290. activeDocumentChanged();
  50291. }
  50292. else
  50293. {
  50294. jassertfalse;
  50295. }
  50296. return true;
  50297. }
  50298. int MultiDocumentPanel::getNumDocuments() const throw()
  50299. {
  50300. return components.size();
  50301. }
  50302. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50303. {
  50304. return components [index];
  50305. }
  50306. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50307. {
  50308. if (mode == FloatingWindows)
  50309. {
  50310. for (int i = getNumChildComponents(); --i >= 0;)
  50311. {
  50312. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50313. if (dw != 0 && dw->isActiveWindow())
  50314. return dw->getContentComponent();
  50315. }
  50316. }
  50317. return components.getLast();
  50318. }
  50319. void MultiDocumentPanel::setActiveDocument (Component* component)
  50320. {
  50321. if (mode == FloatingWindows)
  50322. {
  50323. component = getContainerComp (component);
  50324. if (component != 0)
  50325. component->toFront (true);
  50326. }
  50327. else if (tabComponent != 0)
  50328. {
  50329. jassert (components.indexOf (component) >= 0);
  50330. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50331. {
  50332. if (tabComponent->getTabContentComponent (i) == component)
  50333. {
  50334. tabComponent->setCurrentTabIndex (i);
  50335. break;
  50336. }
  50337. }
  50338. }
  50339. else
  50340. {
  50341. component->grabKeyboardFocus();
  50342. }
  50343. }
  50344. void MultiDocumentPanel::activeDocumentChanged()
  50345. {
  50346. }
  50347. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50348. {
  50349. maximumNumDocuments = newNumber;
  50350. }
  50351. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50352. {
  50353. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50354. }
  50355. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50356. {
  50357. return numDocsBeforeTabsUsed != 0;
  50358. }
  50359. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50360. {
  50361. if (mode != newLayoutMode)
  50362. {
  50363. mode = newLayoutMode;
  50364. if (mode == FloatingWindows)
  50365. {
  50366. tabComponent = 0;
  50367. }
  50368. else
  50369. {
  50370. for (int i = getNumChildComponents(); --i >= 0;)
  50371. {
  50372. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50373. if (dw != 0)
  50374. {
  50375. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50376. dw->clearContentComponent();
  50377. delete dw;
  50378. }
  50379. }
  50380. }
  50381. resized();
  50382. const Array <Component*> tempComps (components);
  50383. components.clear();
  50384. for (int i = 0; i < tempComps.size(); ++i)
  50385. {
  50386. Component* const c = tempComps.getUnchecked(i);
  50387. addDocument (c,
  50388. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50389. MultiDocHelpers::shouldDeleteComp (c));
  50390. }
  50391. }
  50392. }
  50393. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50394. {
  50395. if (backgroundColour != newBackgroundColour)
  50396. {
  50397. backgroundColour = newBackgroundColour;
  50398. setOpaque (newBackgroundColour.isOpaque());
  50399. repaint();
  50400. }
  50401. }
  50402. void MultiDocumentPanel::paint (Graphics& g)
  50403. {
  50404. g.fillAll (backgroundColour);
  50405. }
  50406. void MultiDocumentPanel::resized()
  50407. {
  50408. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50409. {
  50410. for (int i = getNumChildComponents(); --i >= 0;)
  50411. getChildComponent (i)->setBounds (getLocalBounds());
  50412. }
  50413. setWantsKeyboardFocus (components.size() == 0);
  50414. }
  50415. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50416. {
  50417. if (mode == FloatingWindows)
  50418. {
  50419. for (int i = 0; i < getNumChildComponents(); ++i)
  50420. {
  50421. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50422. if (dw != 0 && dw->getContentComponent() == c)
  50423. {
  50424. c = dw;
  50425. break;
  50426. }
  50427. }
  50428. }
  50429. return c;
  50430. }
  50431. void MultiDocumentPanel::componentNameChanged (Component&)
  50432. {
  50433. if (mode == FloatingWindows)
  50434. {
  50435. for (int i = 0; i < getNumChildComponents(); ++i)
  50436. {
  50437. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50438. if (dw != 0)
  50439. dw->setName (dw->getContentComponent()->getName());
  50440. }
  50441. }
  50442. else if (tabComponent != 0)
  50443. {
  50444. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50445. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50446. }
  50447. }
  50448. void MultiDocumentPanel::updateOrder()
  50449. {
  50450. const Array <Component*> oldList (components);
  50451. if (mode == FloatingWindows)
  50452. {
  50453. components.clear();
  50454. for (int i = 0; i < getNumChildComponents(); ++i)
  50455. {
  50456. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50457. if (dw != 0)
  50458. components.add (dw->getContentComponent());
  50459. }
  50460. }
  50461. else
  50462. {
  50463. if (tabComponent != 0)
  50464. {
  50465. Component* const current = tabComponent->getCurrentContentComponent();
  50466. if (current != 0)
  50467. {
  50468. components.removeValue (current);
  50469. components.add (current);
  50470. }
  50471. }
  50472. }
  50473. if (components != oldList)
  50474. activeDocumentChanged();
  50475. }
  50476. END_JUCE_NAMESPACE
  50477. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50478. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50479. BEGIN_JUCE_NAMESPACE
  50480. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50481. : zone (zoneFlags)
  50482. {}
  50483. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50484. : zone (other.zone)
  50485. {}
  50486. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50487. {
  50488. zone = other.zone;
  50489. return *this;
  50490. }
  50491. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50492. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50493. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50494. const BorderSize<int>& border,
  50495. const Point<int>& position)
  50496. {
  50497. int z = 0;
  50498. if (totalSize.contains (position)
  50499. && ! border.subtractedFrom (totalSize).contains (position))
  50500. {
  50501. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50502. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50503. z |= left;
  50504. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50505. z |= right;
  50506. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50507. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50508. z |= top;
  50509. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50510. z |= bottom;
  50511. }
  50512. return Zone (z);
  50513. }
  50514. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50515. {
  50516. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50517. switch (zone)
  50518. {
  50519. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50520. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50521. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50522. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50523. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50524. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50525. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50526. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50527. default: break;
  50528. }
  50529. return mc;
  50530. }
  50531. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50532. ComponentBoundsConstrainer* const constrainer_)
  50533. : component (componentToResize),
  50534. constrainer (constrainer_),
  50535. borderSize (5),
  50536. mouseZone (0)
  50537. {
  50538. }
  50539. ResizableBorderComponent::~ResizableBorderComponent()
  50540. {
  50541. }
  50542. void ResizableBorderComponent::paint (Graphics& g)
  50543. {
  50544. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50545. }
  50546. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50547. {
  50548. updateMouseZone (e);
  50549. }
  50550. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50551. {
  50552. updateMouseZone (e);
  50553. }
  50554. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50555. {
  50556. if (component == 0)
  50557. {
  50558. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50559. return;
  50560. }
  50561. updateMouseZone (e);
  50562. originalBounds = component->getBounds();
  50563. if (constrainer != 0)
  50564. constrainer->resizeStart();
  50565. }
  50566. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50567. {
  50568. if (component == 0)
  50569. {
  50570. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50571. return;
  50572. }
  50573. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50574. if (constrainer != 0)
  50575. {
  50576. constrainer->setBoundsForComponent (component, bounds,
  50577. mouseZone.isDraggingTopEdge(),
  50578. mouseZone.isDraggingLeftEdge(),
  50579. mouseZone.isDraggingBottomEdge(),
  50580. mouseZone.isDraggingRightEdge());
  50581. }
  50582. else
  50583. {
  50584. Component::Positioner* const positioner = component->getPositioner();
  50585. if (positioner != 0)
  50586. positioner->applyNewBounds (bounds);
  50587. else
  50588. component->setBounds (bounds);
  50589. }
  50590. }
  50591. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50592. {
  50593. if (constrainer != 0)
  50594. constrainer->resizeEnd();
  50595. }
  50596. bool ResizableBorderComponent::hitTest (int x, int y)
  50597. {
  50598. return x < borderSize.getLeft()
  50599. || x >= getWidth() - borderSize.getRight()
  50600. || y < borderSize.getTop()
  50601. || y >= getHeight() - borderSize.getBottom();
  50602. }
  50603. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50604. {
  50605. if (borderSize != newBorderSize)
  50606. {
  50607. borderSize = newBorderSize;
  50608. repaint();
  50609. }
  50610. }
  50611. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50612. {
  50613. return borderSize;
  50614. }
  50615. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50616. {
  50617. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50618. if (mouseZone != newZone)
  50619. {
  50620. mouseZone = newZone;
  50621. setMouseCursor (newZone.getMouseCursor());
  50622. }
  50623. }
  50624. END_JUCE_NAMESPACE
  50625. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50626. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50627. BEGIN_JUCE_NAMESPACE
  50628. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50629. ComponentBoundsConstrainer* const constrainer_)
  50630. : component (componentToResize),
  50631. constrainer (constrainer_)
  50632. {
  50633. setRepaintsOnMouseActivity (true);
  50634. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50635. }
  50636. ResizableCornerComponent::~ResizableCornerComponent()
  50637. {
  50638. }
  50639. void ResizableCornerComponent::paint (Graphics& g)
  50640. {
  50641. getLookAndFeel()
  50642. .drawCornerResizer (g, getWidth(), getHeight(),
  50643. isMouseOverOrDragging(),
  50644. isMouseButtonDown());
  50645. }
  50646. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50647. {
  50648. if (component == 0)
  50649. {
  50650. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50651. return;
  50652. }
  50653. originalBounds = component->getBounds();
  50654. if (constrainer != 0)
  50655. constrainer->resizeStart();
  50656. }
  50657. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50658. {
  50659. if (component == 0)
  50660. {
  50661. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50662. return;
  50663. }
  50664. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50665. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50666. if (constrainer != 0)
  50667. {
  50668. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50669. }
  50670. else
  50671. {
  50672. Component::Positioner* const positioner = component->getPositioner();
  50673. if (positioner != 0)
  50674. positioner->applyNewBounds (r);
  50675. else
  50676. component->setBounds (r);
  50677. }
  50678. }
  50679. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50680. {
  50681. if (constrainer != 0)
  50682. constrainer->resizeStart();
  50683. }
  50684. bool ResizableCornerComponent::hitTest (int x, int y)
  50685. {
  50686. if (getWidth() <= 0)
  50687. return false;
  50688. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50689. return y >= yAtX - getHeight() / 4;
  50690. }
  50691. END_JUCE_NAMESPACE
  50692. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50693. /*** Start of inlined file: juce_ResizableEdgeComponent.cpp ***/
  50694. BEGIN_JUCE_NAMESPACE
  50695. ResizableEdgeComponent::ResizableEdgeComponent (Component* const componentToResize,
  50696. ComponentBoundsConstrainer* const constrainer_,
  50697. Edge edge_)
  50698. : component (componentToResize),
  50699. constrainer (constrainer_),
  50700. edge (edge_)
  50701. {
  50702. setRepaintsOnMouseActivity (true);
  50703. setMouseCursor (MouseCursor (isVertical() ? MouseCursor::LeftRightResizeCursor
  50704. : MouseCursor::UpDownResizeCursor));
  50705. }
  50706. ResizableEdgeComponent::~ResizableEdgeComponent()
  50707. {
  50708. }
  50709. bool ResizableEdgeComponent::isVertical() const throw()
  50710. {
  50711. return edge == leftEdge || edge == rightEdge;
  50712. }
  50713. void ResizableEdgeComponent::paint (Graphics& g)
  50714. {
  50715. getLookAndFeel().drawStretchableLayoutResizerBar (g, getWidth(), getHeight(), isVertical(),
  50716. isMouseOver(), isMouseButtonDown());
  50717. }
  50718. void ResizableEdgeComponent::mouseDown (const MouseEvent&)
  50719. {
  50720. if (component == 0)
  50721. {
  50722. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50723. return;
  50724. }
  50725. originalBounds = component->getBounds();
  50726. if (constrainer != 0)
  50727. constrainer->resizeStart();
  50728. }
  50729. void ResizableEdgeComponent::mouseDrag (const MouseEvent& e)
  50730. {
  50731. if (component == 0)
  50732. {
  50733. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50734. return;
  50735. }
  50736. Rectangle<int> bounds (originalBounds);
  50737. switch (edge)
  50738. {
  50739. case leftEdge: bounds.setLeft (bounds.getX() + e.getDistanceFromDragStartX()); break;
  50740. case rightEdge: bounds.setWidth (bounds.getWidth() + e.getDistanceFromDragStartX()); break;
  50741. case topEdge: bounds.setTop (bounds.getY() + e.getDistanceFromDragStartY()); break;
  50742. case bottomEdge: bounds.setHeight (bounds.getHeight() + e.getDistanceFromDragStartY()); break;
  50743. default: jassertfalse; break;
  50744. }
  50745. if (constrainer != 0)
  50746. {
  50747. constrainer->setBoundsForComponent (component, bounds,
  50748. edge == topEdge,
  50749. edge == leftEdge,
  50750. edge == bottomEdge,
  50751. edge == rightEdge);
  50752. }
  50753. else
  50754. {
  50755. Component::Positioner* const positioner = component->getPositioner();
  50756. if (positioner != 0)
  50757. positioner->applyNewBounds (bounds);
  50758. else
  50759. component->setBounds (bounds);
  50760. }
  50761. }
  50762. void ResizableEdgeComponent::mouseUp (const MouseEvent&)
  50763. {
  50764. if (constrainer != 0)
  50765. constrainer->resizeEnd();
  50766. }
  50767. END_JUCE_NAMESPACE
  50768. /*** End of inlined file: juce_ResizableEdgeComponent.cpp ***/
  50769. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50770. BEGIN_JUCE_NAMESPACE
  50771. class ScrollBar::ScrollbarButton : public Button
  50772. {
  50773. public:
  50774. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50775. : Button (String::empty),
  50776. direction (direction_),
  50777. owner (owner_)
  50778. {
  50779. setWantsKeyboardFocus (false);
  50780. }
  50781. void paintButton (Graphics& g, bool over, bool down)
  50782. {
  50783. getLookAndFeel()
  50784. .drawScrollbarButton (g, owner,
  50785. getWidth(), getHeight(),
  50786. direction,
  50787. owner.isVertical(),
  50788. over, down);
  50789. }
  50790. void clicked()
  50791. {
  50792. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50793. }
  50794. int direction;
  50795. private:
  50796. ScrollBar& owner;
  50797. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50798. };
  50799. ScrollBar::ScrollBar (const bool vertical_,
  50800. const bool buttonsAreVisible)
  50801. : totalRange (0.0, 1.0),
  50802. visibleRange (0.0, 0.1),
  50803. singleStepSize (0.1),
  50804. thumbAreaStart (0),
  50805. thumbAreaSize (0),
  50806. thumbStart (0),
  50807. thumbSize (0),
  50808. initialDelayInMillisecs (100),
  50809. repeatDelayInMillisecs (50),
  50810. minimumDelayInMillisecs (10),
  50811. vertical (vertical_),
  50812. isDraggingThumb (false),
  50813. autohides (true)
  50814. {
  50815. setButtonVisibility (buttonsAreVisible);
  50816. setRepaintsOnMouseActivity (true);
  50817. setFocusContainer (true);
  50818. }
  50819. ScrollBar::~ScrollBar()
  50820. {
  50821. upButton = 0;
  50822. downButton = 0;
  50823. }
  50824. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50825. {
  50826. if (totalRange != newRangeLimit)
  50827. {
  50828. totalRange = newRangeLimit;
  50829. setCurrentRange (visibleRange);
  50830. updateThumbPosition();
  50831. }
  50832. }
  50833. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50834. {
  50835. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50836. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50837. }
  50838. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50839. {
  50840. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50841. if (visibleRange != constrainedRange)
  50842. {
  50843. visibleRange = constrainedRange;
  50844. updateThumbPosition();
  50845. triggerAsyncUpdate();
  50846. }
  50847. }
  50848. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50849. {
  50850. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50851. }
  50852. void ScrollBar::setCurrentRangeStart (const double newStart)
  50853. {
  50854. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50855. }
  50856. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50857. {
  50858. singleStepSize = newSingleStepSize;
  50859. }
  50860. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50861. {
  50862. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50863. }
  50864. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50865. {
  50866. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50867. }
  50868. void ScrollBar::scrollToTop()
  50869. {
  50870. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50871. }
  50872. void ScrollBar::scrollToBottom()
  50873. {
  50874. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50875. }
  50876. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50877. const int repeatDelayInMillisecs_,
  50878. const int minimumDelayInMillisecs_)
  50879. {
  50880. initialDelayInMillisecs = initialDelayInMillisecs_;
  50881. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50882. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50883. if (upButton != 0)
  50884. {
  50885. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50886. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50887. }
  50888. }
  50889. void ScrollBar::addListener (Listener* const listener)
  50890. {
  50891. listeners.add (listener);
  50892. }
  50893. void ScrollBar::removeListener (Listener* const listener)
  50894. {
  50895. listeners.remove (listener);
  50896. }
  50897. void ScrollBar::handleAsyncUpdate()
  50898. {
  50899. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50900. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50901. }
  50902. void ScrollBar::updateThumbPosition()
  50903. {
  50904. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50905. : thumbAreaSize);
  50906. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50907. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50908. if (newThumbSize > thumbAreaSize)
  50909. newThumbSize = thumbAreaSize;
  50910. int newThumbStart = thumbAreaStart;
  50911. if (totalRange.getLength() > visibleRange.getLength())
  50912. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50913. / (totalRange.getLength() - visibleRange.getLength()));
  50914. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50915. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50916. {
  50917. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50918. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50919. if (vertical)
  50920. repaint (0, repaintStart, getWidth(), repaintSize);
  50921. else
  50922. repaint (repaintStart, 0, repaintSize, getHeight());
  50923. thumbStart = newThumbStart;
  50924. thumbSize = newThumbSize;
  50925. }
  50926. }
  50927. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50928. {
  50929. if (vertical != shouldBeVertical)
  50930. {
  50931. vertical = shouldBeVertical;
  50932. if (upButton != 0)
  50933. {
  50934. upButton->direction = vertical ? 0 : 3;
  50935. downButton->direction = vertical ? 2 : 1;
  50936. }
  50937. updateThumbPosition();
  50938. }
  50939. }
  50940. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50941. {
  50942. upButton = 0;
  50943. downButton = 0;
  50944. if (buttonsAreVisible)
  50945. {
  50946. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50947. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50948. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50949. }
  50950. updateThumbPosition();
  50951. }
  50952. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50953. {
  50954. autohides = shouldHideWhenFullRange;
  50955. updateThumbPosition();
  50956. }
  50957. bool ScrollBar::autoHides() const throw()
  50958. {
  50959. return autohides;
  50960. }
  50961. void ScrollBar::paint (Graphics& g)
  50962. {
  50963. if (thumbAreaSize > 0)
  50964. {
  50965. LookAndFeel& lf = getLookAndFeel();
  50966. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50967. ? thumbSize : 0;
  50968. if (vertical)
  50969. {
  50970. lf.drawScrollbar (g, *this,
  50971. 0, thumbAreaStart,
  50972. getWidth(), thumbAreaSize,
  50973. vertical,
  50974. thumbStart, thumb,
  50975. isMouseOver(), isMouseButtonDown());
  50976. }
  50977. else
  50978. {
  50979. lf.drawScrollbar (g, *this,
  50980. thumbAreaStart, 0,
  50981. thumbAreaSize, getHeight(),
  50982. vertical,
  50983. thumbStart, thumb,
  50984. isMouseOver(), isMouseButtonDown());
  50985. }
  50986. }
  50987. }
  50988. void ScrollBar::lookAndFeelChanged()
  50989. {
  50990. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50991. }
  50992. void ScrollBar::resized()
  50993. {
  50994. const int length = ((vertical) ? getHeight() : getWidth());
  50995. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50996. : 0;
  50997. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50998. {
  50999. thumbAreaStart = length >> 1;
  51000. thumbAreaSize = 0;
  51001. }
  51002. else
  51003. {
  51004. thumbAreaStart = buttonSize;
  51005. thumbAreaSize = length - (buttonSize << 1);
  51006. }
  51007. if (upButton != 0)
  51008. {
  51009. if (vertical)
  51010. {
  51011. upButton->setBounds (0, 0, getWidth(), buttonSize);
  51012. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  51013. }
  51014. else
  51015. {
  51016. upButton->setBounds (0, 0, buttonSize, getHeight());
  51017. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  51018. }
  51019. }
  51020. updateThumbPosition();
  51021. }
  51022. void ScrollBar::mouseDown (const MouseEvent& e)
  51023. {
  51024. isDraggingThumb = false;
  51025. lastMousePos = vertical ? e.y : e.x;
  51026. dragStartMousePos = lastMousePos;
  51027. dragStartRange = visibleRange.getStart();
  51028. if (dragStartMousePos < thumbStart)
  51029. {
  51030. moveScrollbarInPages (-1);
  51031. startTimer (400);
  51032. }
  51033. else if (dragStartMousePos >= thumbStart + thumbSize)
  51034. {
  51035. moveScrollbarInPages (1);
  51036. startTimer (400);
  51037. }
  51038. else
  51039. {
  51040. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51041. && (thumbAreaSize > thumbSize);
  51042. }
  51043. }
  51044. void ScrollBar::mouseDrag (const MouseEvent& e)
  51045. {
  51046. const int mousePos = vertical ? e.y : e.x;
  51047. if (isDraggingThumb && lastMousePos != mousePos)
  51048. {
  51049. const int deltaPixels = mousePos - dragStartMousePos;
  51050. setCurrentRangeStart (dragStartRange
  51051. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  51052. / (thumbAreaSize - thumbSize));
  51053. }
  51054. lastMousePos = mousePos;
  51055. }
  51056. void ScrollBar::mouseUp (const MouseEvent&)
  51057. {
  51058. isDraggingThumb = false;
  51059. stopTimer();
  51060. repaint();
  51061. }
  51062. void ScrollBar::mouseWheelMove (const MouseEvent&,
  51063. float wheelIncrementX,
  51064. float wheelIncrementY)
  51065. {
  51066. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  51067. if (increment < 0)
  51068. increment = jmin (increment * 10.0f, -1.0f);
  51069. else if (increment > 0)
  51070. increment = jmax (increment * 10.0f, 1.0f);
  51071. setCurrentRange (visibleRange - singleStepSize * increment);
  51072. }
  51073. void ScrollBar::timerCallback()
  51074. {
  51075. if (isMouseButtonDown())
  51076. {
  51077. startTimer (40);
  51078. if (lastMousePos < thumbStart)
  51079. setCurrentRange (visibleRange - visibleRange.getLength());
  51080. else if (lastMousePos > thumbStart + thumbSize)
  51081. setCurrentRangeStart (visibleRange.getEnd());
  51082. }
  51083. else
  51084. {
  51085. stopTimer();
  51086. }
  51087. }
  51088. bool ScrollBar::keyPressed (const KeyPress& key)
  51089. {
  51090. if (! isVisible())
  51091. return false;
  51092. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51093. moveScrollbarInSteps (-1);
  51094. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51095. moveScrollbarInSteps (1);
  51096. else if (key.isKeyCode (KeyPress::pageUpKey))
  51097. moveScrollbarInPages (-1);
  51098. else if (key.isKeyCode (KeyPress::pageDownKey))
  51099. moveScrollbarInPages (1);
  51100. else if (key.isKeyCode (KeyPress::homeKey))
  51101. scrollToTop();
  51102. else if (key.isKeyCode (KeyPress::endKey))
  51103. scrollToBottom();
  51104. else
  51105. return false;
  51106. return true;
  51107. }
  51108. END_JUCE_NAMESPACE
  51109. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51110. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51111. BEGIN_JUCE_NAMESPACE
  51112. StretchableLayoutManager::StretchableLayoutManager()
  51113. : totalSize (0)
  51114. {
  51115. }
  51116. StretchableLayoutManager::~StretchableLayoutManager()
  51117. {
  51118. }
  51119. void StretchableLayoutManager::clearAllItems()
  51120. {
  51121. items.clear();
  51122. totalSize = 0;
  51123. }
  51124. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51125. const double minimumSize,
  51126. const double maximumSize,
  51127. const double preferredSize)
  51128. {
  51129. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51130. if (layout == 0)
  51131. {
  51132. layout = new ItemLayoutProperties();
  51133. layout->itemIndex = itemIndex;
  51134. int i;
  51135. for (i = 0; i < items.size(); ++i)
  51136. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51137. break;
  51138. items.insert (i, layout);
  51139. }
  51140. layout->minSize = minimumSize;
  51141. layout->maxSize = maximumSize;
  51142. layout->preferredSize = preferredSize;
  51143. layout->currentSize = 0;
  51144. }
  51145. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51146. double& minimumSize,
  51147. double& maximumSize,
  51148. double& preferredSize) const
  51149. {
  51150. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51151. if (layout != 0)
  51152. {
  51153. minimumSize = layout->minSize;
  51154. maximumSize = layout->maxSize;
  51155. preferredSize = layout->preferredSize;
  51156. return true;
  51157. }
  51158. return false;
  51159. }
  51160. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51161. {
  51162. totalSize = newTotalSize;
  51163. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51164. }
  51165. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51166. {
  51167. int pos = 0;
  51168. for (int i = 0; i < itemIndex; ++i)
  51169. {
  51170. const ItemLayoutProperties* const layout = getInfoFor (i);
  51171. if (layout != 0)
  51172. pos += layout->currentSize;
  51173. }
  51174. return pos;
  51175. }
  51176. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51177. {
  51178. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51179. if (layout != 0)
  51180. return layout->currentSize;
  51181. return 0;
  51182. }
  51183. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51184. {
  51185. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51186. if (layout != 0)
  51187. return -layout->currentSize / (double) totalSize;
  51188. return 0;
  51189. }
  51190. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51191. int newPosition)
  51192. {
  51193. for (int i = items.size(); --i >= 0;)
  51194. {
  51195. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51196. if (layout->itemIndex == itemIndex)
  51197. {
  51198. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51199. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51200. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51201. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51202. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51203. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51204. endPos += layout->currentSize;
  51205. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51206. updatePrefSizesToMatchCurrentPositions();
  51207. break;
  51208. }
  51209. }
  51210. }
  51211. void StretchableLayoutManager::layOutComponents (Component** const components,
  51212. int numComponents,
  51213. int x, int y, int w, int h,
  51214. const bool vertically,
  51215. const bool resizeOtherDimension)
  51216. {
  51217. setTotalSize (vertically ? h : w);
  51218. int pos = vertically ? y : x;
  51219. for (int i = 0; i < numComponents; ++i)
  51220. {
  51221. const ItemLayoutProperties* const layout = getInfoFor (i);
  51222. if (layout != 0)
  51223. {
  51224. Component* const c = components[i];
  51225. if (c != 0)
  51226. {
  51227. if (i == numComponents - 1)
  51228. {
  51229. // if it's the last item, crop it to exactly fit the available space..
  51230. if (resizeOtherDimension)
  51231. {
  51232. if (vertically)
  51233. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51234. else
  51235. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51236. }
  51237. else
  51238. {
  51239. if (vertically)
  51240. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51241. else
  51242. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51243. }
  51244. }
  51245. else
  51246. {
  51247. if (resizeOtherDimension)
  51248. {
  51249. if (vertically)
  51250. c->setBounds (x, pos, w, layout->currentSize);
  51251. else
  51252. c->setBounds (pos, y, layout->currentSize, h);
  51253. }
  51254. else
  51255. {
  51256. if (vertically)
  51257. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51258. else
  51259. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51260. }
  51261. }
  51262. }
  51263. pos += layout->currentSize;
  51264. }
  51265. }
  51266. }
  51267. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51268. {
  51269. for (int i = items.size(); --i >= 0;)
  51270. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51271. return items.getUnchecked(i);
  51272. return 0;
  51273. }
  51274. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51275. const int endIndex,
  51276. const int availableSpace,
  51277. int startPos)
  51278. {
  51279. // calculate the total sizes
  51280. int i;
  51281. double totalIdealSize = 0.0;
  51282. int totalMinimums = 0;
  51283. for (i = startIndex; i < endIndex; ++i)
  51284. {
  51285. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51286. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51287. totalMinimums += layout->currentSize;
  51288. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51289. }
  51290. if (totalIdealSize <= 0)
  51291. totalIdealSize = 1.0;
  51292. // now calc the best sizes..
  51293. int extraSpace = availableSpace - totalMinimums;
  51294. while (extraSpace > 0)
  51295. {
  51296. int numWantingMoreSpace = 0;
  51297. int numHavingTakenExtraSpace = 0;
  51298. // first figure out how many comps want a slice of the extra space..
  51299. for (i = startIndex; i < endIndex; ++i)
  51300. {
  51301. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51302. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51303. const int bestSize = jlimit (layout->currentSize,
  51304. jmax (layout->currentSize,
  51305. sizeToRealSize (layout->maxSize, totalSize)),
  51306. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51307. if (bestSize > layout->currentSize)
  51308. ++numWantingMoreSpace;
  51309. }
  51310. // ..share out the extra space..
  51311. for (i = startIndex; i < endIndex; ++i)
  51312. {
  51313. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51314. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51315. int bestSize = jlimit (layout->currentSize,
  51316. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51317. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51318. const int extraWanted = bestSize - layout->currentSize;
  51319. if (extraWanted > 0)
  51320. {
  51321. const int extraAllowed = jmin (extraWanted,
  51322. extraSpace / jmax (1, numWantingMoreSpace));
  51323. if (extraAllowed > 0)
  51324. {
  51325. ++numHavingTakenExtraSpace;
  51326. --numWantingMoreSpace;
  51327. layout->currentSize += extraAllowed;
  51328. extraSpace -= extraAllowed;
  51329. }
  51330. }
  51331. }
  51332. if (numHavingTakenExtraSpace <= 0)
  51333. break;
  51334. }
  51335. // ..and calculate the end position
  51336. for (i = startIndex; i < endIndex; ++i)
  51337. {
  51338. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51339. startPos += layout->currentSize;
  51340. }
  51341. return startPos;
  51342. }
  51343. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51344. const int endIndex) const
  51345. {
  51346. int totalMinimums = 0;
  51347. for (int i = startIndex; i < endIndex; ++i)
  51348. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51349. return totalMinimums;
  51350. }
  51351. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51352. {
  51353. int totalMaximums = 0;
  51354. for (int i = startIndex; i < endIndex; ++i)
  51355. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51356. return totalMaximums;
  51357. }
  51358. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51359. {
  51360. for (int i = 0; i < items.size(); ++i)
  51361. {
  51362. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51363. layout->preferredSize
  51364. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51365. : getItemCurrentAbsoluteSize (i);
  51366. }
  51367. }
  51368. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51369. {
  51370. if (size < 0)
  51371. size *= -totalSpace;
  51372. return roundToInt (size);
  51373. }
  51374. END_JUCE_NAMESPACE
  51375. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51376. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51377. BEGIN_JUCE_NAMESPACE
  51378. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51379. const int itemIndex_,
  51380. const bool isVertical_)
  51381. : layout (layout_),
  51382. itemIndex (itemIndex_),
  51383. isVertical (isVertical_)
  51384. {
  51385. setRepaintsOnMouseActivity (true);
  51386. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51387. : MouseCursor::UpDownResizeCursor));
  51388. }
  51389. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51390. {
  51391. }
  51392. void StretchableLayoutResizerBar::paint (Graphics& g)
  51393. {
  51394. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51395. getWidth(), getHeight(),
  51396. isVertical,
  51397. isMouseOver(),
  51398. isMouseButtonDown());
  51399. }
  51400. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51401. {
  51402. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51403. }
  51404. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51405. {
  51406. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51407. : e.getDistanceFromDragStartY());
  51408. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51409. {
  51410. layout->setItemPosition (itemIndex, desiredPos);
  51411. hasBeenMoved();
  51412. }
  51413. }
  51414. void StretchableLayoutResizerBar::hasBeenMoved()
  51415. {
  51416. if (getParentComponent() != 0)
  51417. getParentComponent()->resized();
  51418. }
  51419. END_JUCE_NAMESPACE
  51420. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51421. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51422. BEGIN_JUCE_NAMESPACE
  51423. StretchableObjectResizer::StretchableObjectResizer()
  51424. {
  51425. }
  51426. StretchableObjectResizer::~StretchableObjectResizer()
  51427. {
  51428. }
  51429. void StretchableObjectResizer::addItem (const double size,
  51430. const double minSize, const double maxSize,
  51431. const int order)
  51432. {
  51433. // the order must be >= 0 but less than the maximum integer value.
  51434. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51435. Item* const item = new Item();
  51436. item->size = size;
  51437. item->minSize = minSize;
  51438. item->maxSize = maxSize;
  51439. item->order = order;
  51440. items.add (item);
  51441. }
  51442. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51443. {
  51444. const Item* const it = items [index];
  51445. return it != 0 ? it->size : 0;
  51446. }
  51447. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51448. {
  51449. int order = 0;
  51450. for (;;)
  51451. {
  51452. double currentSize = 0;
  51453. double minSize = 0;
  51454. double maxSize = 0;
  51455. int nextHighestOrder = std::numeric_limits<int>::max();
  51456. for (int i = 0; i < items.size(); ++i)
  51457. {
  51458. const Item* const it = items.getUnchecked(i);
  51459. currentSize += it->size;
  51460. if (it->order <= order)
  51461. {
  51462. minSize += it->minSize;
  51463. maxSize += it->maxSize;
  51464. }
  51465. else
  51466. {
  51467. minSize += it->size;
  51468. maxSize += it->size;
  51469. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51470. }
  51471. }
  51472. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51473. if (thisIterationTarget >= currentSize)
  51474. {
  51475. const double availableExtraSpace = maxSize - currentSize;
  51476. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51477. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51478. for (int i = 0; i < items.size(); ++i)
  51479. {
  51480. Item* const it = items.getUnchecked(i);
  51481. if (it->order <= order)
  51482. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51483. }
  51484. }
  51485. else
  51486. {
  51487. const double amountOfSlack = currentSize - minSize;
  51488. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51489. const double scale = targetAmountOfSlack / amountOfSlack;
  51490. for (int i = 0; i < items.size(); ++i)
  51491. {
  51492. Item* const it = items.getUnchecked(i);
  51493. if (it->order <= order)
  51494. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51495. }
  51496. }
  51497. if (nextHighestOrder < std::numeric_limits<int>::max())
  51498. order = nextHighestOrder;
  51499. else
  51500. break;
  51501. }
  51502. }
  51503. END_JUCE_NAMESPACE
  51504. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51505. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51506. BEGIN_JUCE_NAMESPACE
  51507. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51508. : Button (name),
  51509. owner (owner_),
  51510. overlapPixels (0)
  51511. {
  51512. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51513. setComponentEffect (&shadow);
  51514. setWantsKeyboardFocus (false);
  51515. }
  51516. TabBarButton::~TabBarButton()
  51517. {
  51518. }
  51519. int TabBarButton::getIndex() const
  51520. {
  51521. return owner.indexOfTabButton (this);
  51522. }
  51523. void TabBarButton::paintButton (Graphics& g,
  51524. bool isMouseOverButton,
  51525. bool isButtonDown)
  51526. {
  51527. const Rectangle<int> area (getActiveArea());
  51528. g.setOrigin (area.getX(), area.getY());
  51529. getLookAndFeel()
  51530. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51531. owner.getTabBackgroundColour (getIndex()),
  51532. getIndex(), getButtonText(), *this,
  51533. owner.getOrientation(),
  51534. isMouseOverButton, isButtonDown,
  51535. getToggleState());
  51536. }
  51537. void TabBarButton::clicked (const ModifierKeys& mods)
  51538. {
  51539. if (mods.isPopupMenu())
  51540. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51541. else
  51542. owner.setCurrentTabIndex (getIndex());
  51543. }
  51544. bool TabBarButton::hitTest (int mx, int my)
  51545. {
  51546. const Rectangle<int> area (getActiveArea());
  51547. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51548. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51549. {
  51550. if (isPositiveAndBelow (mx, getWidth())
  51551. && my >= area.getY() + overlapPixels
  51552. && my < area.getBottom() - overlapPixels)
  51553. return true;
  51554. }
  51555. else
  51556. {
  51557. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51558. && isPositiveAndBelow (my, getHeight()))
  51559. return true;
  51560. }
  51561. Path p;
  51562. getLookAndFeel()
  51563. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51564. owner.getOrientation(), false, false, getToggleState());
  51565. return p.contains ((float) (mx - area.getX()),
  51566. (float) (my - area.getY()));
  51567. }
  51568. int TabBarButton::getBestTabLength (const int depth)
  51569. {
  51570. return jlimit (depth * 2,
  51571. depth * 7,
  51572. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51573. }
  51574. const Rectangle<int> TabBarButton::getActiveArea()
  51575. {
  51576. Rectangle<int> r (getLocalBounds());
  51577. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51578. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51579. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51580. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51581. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51582. return r;
  51583. }
  51584. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51585. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51586. {
  51587. public:
  51588. BehindFrontTabComp (TabbedButtonBar& owner_)
  51589. : owner (owner_)
  51590. {
  51591. setInterceptsMouseClicks (false, false);
  51592. }
  51593. void paint (Graphics& g)
  51594. {
  51595. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51596. owner, owner.getOrientation());
  51597. }
  51598. void enablementChanged()
  51599. {
  51600. repaint();
  51601. }
  51602. void buttonClicked (Button*)
  51603. {
  51604. owner.showExtraItemsMenu();
  51605. }
  51606. private:
  51607. TabbedButtonBar& owner;
  51608. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51609. };
  51610. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51611. : orientation (orientation_),
  51612. minimumScale (0.7),
  51613. currentTabIndex (-1)
  51614. {
  51615. setInterceptsMouseClicks (false, true);
  51616. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51617. setFocusContainer (true);
  51618. }
  51619. TabbedButtonBar::~TabbedButtonBar()
  51620. {
  51621. tabs.clear();
  51622. extraTabsButton = 0;
  51623. }
  51624. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51625. {
  51626. orientation = newOrientation;
  51627. for (int i = getNumChildComponents(); --i >= 0;)
  51628. getChildComponent (i)->resized();
  51629. resized();
  51630. }
  51631. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51632. {
  51633. return new TabBarButton (name, *this);
  51634. }
  51635. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51636. {
  51637. minimumScale = newMinimumScale;
  51638. resized();
  51639. }
  51640. void TabbedButtonBar::clearTabs()
  51641. {
  51642. tabs.clear();
  51643. extraTabsButton = 0;
  51644. setCurrentTabIndex (-1);
  51645. }
  51646. void TabbedButtonBar::addTab (const String& tabName,
  51647. const Colour& tabBackgroundColour,
  51648. int insertIndex)
  51649. {
  51650. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51651. if (tabName.isNotEmpty())
  51652. {
  51653. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51654. insertIndex = tabs.size();
  51655. TabInfo* newTab = new TabInfo();
  51656. newTab->name = tabName;
  51657. newTab->colour = tabBackgroundColour;
  51658. newTab->component = createTabButton (tabName, insertIndex);
  51659. jassert (newTab->component != 0);
  51660. tabs.insert (insertIndex, newTab);
  51661. addAndMakeVisible (newTab->component, insertIndex);
  51662. resized();
  51663. if (currentTabIndex < 0)
  51664. setCurrentTabIndex (0);
  51665. }
  51666. }
  51667. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51668. {
  51669. TabInfo* const tab = tabs [tabIndex];
  51670. if (tab != 0 && tab->name != newName)
  51671. {
  51672. tab->name = newName;
  51673. tab->component->setButtonText (newName);
  51674. resized();
  51675. }
  51676. }
  51677. void TabbedButtonBar::removeTab (const int tabIndex)
  51678. {
  51679. if (tabs [tabIndex] != 0)
  51680. {
  51681. const int oldTabIndex = currentTabIndex;
  51682. if (currentTabIndex == tabIndex)
  51683. currentTabIndex = -1;
  51684. tabs.remove (tabIndex);
  51685. resized();
  51686. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51687. }
  51688. }
  51689. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51690. {
  51691. tabs.move (currentIndex, newIndex);
  51692. resized();
  51693. }
  51694. int TabbedButtonBar::getNumTabs() const
  51695. {
  51696. return tabs.size();
  51697. }
  51698. const String TabbedButtonBar::getCurrentTabName() const
  51699. {
  51700. TabInfo* tab = tabs [currentTabIndex];
  51701. return tab == 0 ? String::empty : tab->name;
  51702. }
  51703. const StringArray TabbedButtonBar::getTabNames() const
  51704. {
  51705. StringArray names;
  51706. for (int i = 0; i < tabs.size(); ++i)
  51707. names.add (tabs.getUnchecked(i)->name);
  51708. return names;
  51709. }
  51710. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51711. {
  51712. if (currentTabIndex != newIndex)
  51713. {
  51714. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51715. newIndex = -1;
  51716. currentTabIndex = newIndex;
  51717. for (int i = 0; i < tabs.size(); ++i)
  51718. {
  51719. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51720. tb->setToggleState (i == newIndex, false);
  51721. }
  51722. resized();
  51723. if (sendChangeMessage_)
  51724. sendChangeMessage();
  51725. currentTabChanged (newIndex, getCurrentTabName());
  51726. }
  51727. }
  51728. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51729. {
  51730. TabInfo* const tab = tabs[index];
  51731. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51732. }
  51733. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51734. {
  51735. for (int i = tabs.size(); --i >= 0;)
  51736. if (tabs.getUnchecked(i)->component == button)
  51737. return i;
  51738. return -1;
  51739. }
  51740. void TabbedButtonBar::lookAndFeelChanged()
  51741. {
  51742. extraTabsButton = 0;
  51743. resized();
  51744. }
  51745. void TabbedButtonBar::resized()
  51746. {
  51747. int depth = getWidth();
  51748. int length = getHeight();
  51749. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51750. swapVariables (depth, length);
  51751. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51752. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51753. int i, totalLength = overlap;
  51754. int numVisibleButtons = tabs.size();
  51755. for (i = 0; i < tabs.size(); ++i)
  51756. {
  51757. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51758. totalLength += tb->getBestTabLength (depth) - overlap;
  51759. tb->overlapPixels = overlap / 2;
  51760. }
  51761. double scale = 1.0;
  51762. if (totalLength > length)
  51763. scale = jmax (minimumScale, length / (double) totalLength);
  51764. const bool isTooBig = totalLength * scale > length;
  51765. int tabsButtonPos = 0;
  51766. if (isTooBig)
  51767. {
  51768. if (extraTabsButton == 0)
  51769. {
  51770. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51771. extraTabsButton->addListener (behindFrontTab);
  51772. extraTabsButton->setAlwaysOnTop (true);
  51773. extraTabsButton->setTriggeredOnMouseDown (true);
  51774. }
  51775. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51776. extraTabsButton->setSize (buttonSize, buttonSize);
  51777. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51778. {
  51779. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51780. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51781. }
  51782. else
  51783. {
  51784. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51785. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51786. }
  51787. totalLength = 0;
  51788. for (i = 0; i < tabs.size(); ++i)
  51789. {
  51790. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51791. const int newLength = totalLength + tb->getBestTabLength (depth);
  51792. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51793. {
  51794. totalLength += overlap;
  51795. break;
  51796. }
  51797. numVisibleButtons = i + 1;
  51798. totalLength = newLength - overlap;
  51799. }
  51800. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51801. }
  51802. else
  51803. {
  51804. extraTabsButton = 0;
  51805. }
  51806. int pos = 0;
  51807. TabBarButton* frontTab = 0;
  51808. for (i = 0; i < tabs.size(); ++i)
  51809. {
  51810. TabBarButton* const tb = getTabButton (i);
  51811. if (tb != 0)
  51812. {
  51813. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51814. if (i < numVisibleButtons)
  51815. {
  51816. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51817. tb->setBounds (pos, 0, bestLength, getHeight());
  51818. else
  51819. tb->setBounds (0, pos, getWidth(), bestLength);
  51820. tb->toBack();
  51821. if (i == currentTabIndex)
  51822. frontTab = tb;
  51823. tb->setVisible (true);
  51824. }
  51825. else
  51826. {
  51827. tb->setVisible (false);
  51828. }
  51829. pos += bestLength - overlap;
  51830. }
  51831. }
  51832. behindFrontTab->setBounds (getLocalBounds());
  51833. if (frontTab != 0)
  51834. {
  51835. frontTab->toFront (false);
  51836. behindFrontTab->toBehind (frontTab);
  51837. }
  51838. }
  51839. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51840. {
  51841. TabInfo* const tab = tabs [tabIndex];
  51842. return tab == 0 ? Colours::white : tab->colour;
  51843. }
  51844. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51845. {
  51846. TabInfo* const tab = tabs [tabIndex];
  51847. if (tab != 0 && tab->colour != newColour)
  51848. {
  51849. tab->colour = newColour;
  51850. repaint();
  51851. }
  51852. }
  51853. void TabbedButtonBar::extraItemsMenuCallback (int result, TabbedButtonBar* bar)
  51854. {
  51855. if (bar != 0 && result > 0)
  51856. bar->setCurrentTabIndex (result - 1);
  51857. }
  51858. void TabbedButtonBar::showExtraItemsMenu()
  51859. {
  51860. PopupMenu m;
  51861. for (int i = 0; i < tabs.size(); ++i)
  51862. {
  51863. const TabInfo* const tab = tabs.getUnchecked(i);
  51864. if (! tab->component->isVisible())
  51865. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51866. }
  51867. m.showMenuAsync (PopupMenu::Options().withTargetComponent (extraTabsButton),
  51868. ModalCallbackFunction::forComponent (extraItemsMenuCallback, this));
  51869. }
  51870. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51871. {
  51872. }
  51873. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51874. {
  51875. }
  51876. END_JUCE_NAMESPACE
  51877. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51878. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51879. BEGIN_JUCE_NAMESPACE
  51880. namespace TabbedComponentHelpers
  51881. {
  51882. const Identifier deleteComponentId ("deleteByTabComp_");
  51883. void deleteIfNecessary (Component* const comp)
  51884. {
  51885. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51886. delete comp;
  51887. }
  51888. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51889. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51890. {
  51891. switch (orientation)
  51892. {
  51893. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51894. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51895. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51896. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51897. default: jassertfalse; break;
  51898. }
  51899. return Rectangle<int>();
  51900. }
  51901. }
  51902. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51903. {
  51904. public:
  51905. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51906. : TabbedButtonBar (orientation_),
  51907. owner (owner_)
  51908. {
  51909. }
  51910. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51911. {
  51912. owner.changeCallback (newCurrentTabIndex, newTabName);
  51913. }
  51914. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51915. {
  51916. owner.popupMenuClickOnTab (tabIndex, tabName);
  51917. }
  51918. const Colour getTabBackgroundColour (const int tabIndex)
  51919. {
  51920. return owner.tabs->getTabBackgroundColour (tabIndex);
  51921. }
  51922. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51923. {
  51924. return owner.createTabButton (tabName, tabIndex);
  51925. }
  51926. private:
  51927. TabbedComponent& owner;
  51928. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51929. };
  51930. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51931. : tabDepth (30),
  51932. outlineThickness (1),
  51933. edgeIndent (0)
  51934. {
  51935. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51936. }
  51937. TabbedComponent::~TabbedComponent()
  51938. {
  51939. clearTabs();
  51940. tabs = 0;
  51941. }
  51942. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51943. {
  51944. tabs->setOrientation (orientation);
  51945. resized();
  51946. }
  51947. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51948. {
  51949. return tabs->getOrientation();
  51950. }
  51951. void TabbedComponent::setTabBarDepth (const int newDepth)
  51952. {
  51953. if (tabDepth != newDepth)
  51954. {
  51955. tabDepth = newDepth;
  51956. resized();
  51957. }
  51958. }
  51959. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51960. {
  51961. return new TabBarButton (tabName, *tabs);
  51962. }
  51963. void TabbedComponent::clearTabs()
  51964. {
  51965. if (panelComponent != 0)
  51966. {
  51967. panelComponent->setVisible (false);
  51968. removeChildComponent (panelComponent);
  51969. panelComponent = 0;
  51970. }
  51971. tabs->clearTabs();
  51972. for (int i = contentComponents.size(); --i >= 0;)
  51973. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51974. contentComponents.clear();
  51975. }
  51976. void TabbedComponent::addTab (const String& tabName,
  51977. const Colour& tabBackgroundColour,
  51978. Component* const contentComponent,
  51979. const bool deleteComponentWhenNotNeeded,
  51980. const int insertIndex)
  51981. {
  51982. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51983. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51984. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51985. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51986. }
  51987. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51988. {
  51989. tabs->setTabName (tabIndex, newName);
  51990. }
  51991. void TabbedComponent::removeTab (const int tabIndex)
  51992. {
  51993. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51994. {
  51995. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51996. contentComponents.remove (tabIndex);
  51997. tabs->removeTab (tabIndex);
  51998. }
  51999. }
  52000. int TabbedComponent::getNumTabs() const
  52001. {
  52002. return tabs->getNumTabs();
  52003. }
  52004. const StringArray TabbedComponent::getTabNames() const
  52005. {
  52006. return tabs->getTabNames();
  52007. }
  52008. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  52009. {
  52010. return contentComponents [tabIndex];
  52011. }
  52012. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  52013. {
  52014. return tabs->getTabBackgroundColour (tabIndex);
  52015. }
  52016. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52017. {
  52018. tabs->setTabBackgroundColour (tabIndex, newColour);
  52019. if (getCurrentTabIndex() == tabIndex)
  52020. repaint();
  52021. }
  52022. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  52023. {
  52024. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  52025. }
  52026. int TabbedComponent::getCurrentTabIndex() const
  52027. {
  52028. return tabs->getCurrentTabIndex();
  52029. }
  52030. const String TabbedComponent::getCurrentTabName() const
  52031. {
  52032. return tabs->getCurrentTabName();
  52033. }
  52034. void TabbedComponent::setOutline (const int thickness)
  52035. {
  52036. outlineThickness = thickness;
  52037. resized();
  52038. repaint();
  52039. }
  52040. void TabbedComponent::setIndent (const int indentThickness)
  52041. {
  52042. edgeIndent = indentThickness;
  52043. resized();
  52044. repaint();
  52045. }
  52046. void TabbedComponent::paint (Graphics& g)
  52047. {
  52048. g.fillAll (findColour (backgroundColourId));
  52049. Rectangle<int> content (getLocalBounds());
  52050. BorderSize<int> outline (outlineThickness);
  52051. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  52052. g.reduceClipRegion (content);
  52053. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52054. if (outlineThickness > 0)
  52055. {
  52056. RectangleList rl (content);
  52057. rl.subtract (outline.subtractedFrom (content));
  52058. g.reduceClipRegion (rl);
  52059. g.fillAll (findColour (outlineColourId));
  52060. }
  52061. }
  52062. void TabbedComponent::resized()
  52063. {
  52064. Rectangle<int> content (getLocalBounds());
  52065. BorderSize<int> outline (outlineThickness);
  52066. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  52067. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  52068. for (int i = contentComponents.size(); --i >= 0;)
  52069. if (contentComponents.getReference (i) != 0)
  52070. contentComponents.getReference (i)->setBounds (content);
  52071. }
  52072. void TabbedComponent::lookAndFeelChanged()
  52073. {
  52074. for (int i = contentComponents.size(); --i >= 0;)
  52075. if (contentComponents.getReference (i) != 0)
  52076. contentComponents.getReference (i)->lookAndFeelChanged();
  52077. }
  52078. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  52079. {
  52080. if (panelComponent != 0)
  52081. {
  52082. panelComponent->setVisible (false);
  52083. removeChildComponent (panelComponent);
  52084. panelComponent = 0;
  52085. }
  52086. if (getCurrentTabIndex() >= 0)
  52087. {
  52088. panelComponent = getTabContentComponent (getCurrentTabIndex());
  52089. if (panelComponent != 0)
  52090. {
  52091. // do these ops as two stages instead of addAndMakeVisible() so that the
  52092. // component has always got a parent when it gets the visibilityChanged() callback
  52093. addChildComponent (panelComponent);
  52094. panelComponent->setVisible (true);
  52095. panelComponent->toFront (true);
  52096. }
  52097. repaint();
  52098. }
  52099. resized();
  52100. currentTabChanged (newCurrentTabIndex, newTabName);
  52101. }
  52102. void TabbedComponent::currentTabChanged (const int, const String&) {}
  52103. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  52104. END_JUCE_NAMESPACE
  52105. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52106. /*** Start of inlined file: juce_Viewport.cpp ***/
  52107. BEGIN_JUCE_NAMESPACE
  52108. Viewport::Viewport (const String& componentName)
  52109. : Component (componentName),
  52110. scrollBarThickness (0),
  52111. singleStepX (16),
  52112. singleStepY (16),
  52113. showHScrollbar (true),
  52114. showVScrollbar (true),
  52115. verticalScrollBar (true),
  52116. horizontalScrollBar (false)
  52117. {
  52118. // content holder is used to clip the contents so they don't overlap the scrollbars
  52119. addAndMakeVisible (&contentHolder);
  52120. contentHolder.setInterceptsMouseClicks (false, true);
  52121. addChildComponent (&verticalScrollBar);
  52122. addChildComponent (&horizontalScrollBar);
  52123. verticalScrollBar.addListener (this);
  52124. horizontalScrollBar.addListener (this);
  52125. setInterceptsMouseClicks (false, true);
  52126. setWantsKeyboardFocus (true);
  52127. }
  52128. Viewport::~Viewport()
  52129. {
  52130. deleteContentComp();
  52131. }
  52132. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  52133. {
  52134. }
  52135. void Viewport::deleteContentComp()
  52136. {
  52137. // This sets the content comp to a null pointer before deleting the old one, in case
  52138. // anything tries to use the old one while it's in mid-deletion..
  52139. ScopedPointer<Component> oldCompDeleter (contentComp);
  52140. contentComp = 0;
  52141. }
  52142. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52143. {
  52144. if (contentComp.get() != newViewedComponent)
  52145. {
  52146. deleteContentComp();
  52147. contentComp = newViewedComponent;
  52148. if (contentComp != 0)
  52149. {
  52150. contentHolder.addAndMakeVisible (contentComp);
  52151. setViewPosition (0, 0);
  52152. contentComp->addComponentListener (this);
  52153. }
  52154. updateVisibleArea();
  52155. }
  52156. }
  52157. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  52158. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  52159. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52160. {
  52161. if (contentComp != 0)
  52162. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52163. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52164. }
  52165. void Viewport::setViewPosition (const Point<int>& newPosition)
  52166. {
  52167. setViewPosition (newPosition.getX(), newPosition.getY());
  52168. }
  52169. void Viewport::setViewPositionProportionately (const double x, const double y)
  52170. {
  52171. if (contentComp != 0)
  52172. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52173. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52174. }
  52175. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52176. {
  52177. if (contentComp != 0)
  52178. {
  52179. int dx = 0, dy = 0;
  52180. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52181. {
  52182. if (mouseX < activeBorderThickness)
  52183. dx = activeBorderThickness - mouseX;
  52184. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52185. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52186. if (dx < 0)
  52187. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52188. else
  52189. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52190. }
  52191. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52192. {
  52193. if (mouseY < activeBorderThickness)
  52194. dy = activeBorderThickness - mouseY;
  52195. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52196. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52197. if (dy < 0)
  52198. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52199. else
  52200. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52201. }
  52202. if (dx != 0 || dy != 0)
  52203. {
  52204. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52205. contentComp->getY() + dy);
  52206. return true;
  52207. }
  52208. }
  52209. return false;
  52210. }
  52211. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52212. {
  52213. updateVisibleArea();
  52214. }
  52215. void Viewport::resized()
  52216. {
  52217. updateVisibleArea();
  52218. }
  52219. void Viewport::updateVisibleArea()
  52220. {
  52221. const int scrollbarWidth = getScrollBarThickness();
  52222. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52223. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52224. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52225. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52226. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52227. Rectangle<int> contentArea (getLocalBounds());
  52228. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52229. {
  52230. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52231. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52232. if (vBarVisible)
  52233. contentArea.setWidth (getWidth() - scrollbarWidth);
  52234. if (hBarVisible)
  52235. contentArea.setHeight (getHeight() - scrollbarWidth);
  52236. if (! contentArea.contains (contentComp->getBounds()))
  52237. {
  52238. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52239. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52240. }
  52241. }
  52242. if (vBarVisible)
  52243. contentArea.setWidth (getWidth() - scrollbarWidth);
  52244. if (hBarVisible)
  52245. contentArea.setHeight (getHeight() - scrollbarWidth);
  52246. contentHolder.setBounds (contentArea);
  52247. Rectangle<int> contentBounds;
  52248. if (contentComp != 0)
  52249. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  52250. Point<int> visibleOrigin (-contentBounds.getPosition());
  52251. if (hBarVisible)
  52252. {
  52253. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52254. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52255. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52256. horizontalScrollBar.setSingleStepSize (singleStepX);
  52257. horizontalScrollBar.cancelPendingUpdate();
  52258. }
  52259. else if (canShowHBar)
  52260. {
  52261. visibleOrigin.setX (0);
  52262. }
  52263. if (vBarVisible)
  52264. {
  52265. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52266. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52267. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52268. verticalScrollBar.setSingleStepSize (singleStepY);
  52269. verticalScrollBar.cancelPendingUpdate();
  52270. }
  52271. else if (canShowVBar)
  52272. {
  52273. visibleOrigin.setY (0);
  52274. }
  52275. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52276. horizontalScrollBar.setVisible (hBarVisible);
  52277. verticalScrollBar.setVisible (vBarVisible);
  52278. setViewPosition (visibleOrigin);
  52279. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52280. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52281. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52282. if (lastVisibleArea != visibleArea)
  52283. {
  52284. lastVisibleArea = visibleArea;
  52285. visibleAreaChanged (visibleArea);
  52286. }
  52287. horizontalScrollBar.handleUpdateNowIfNeeded();
  52288. verticalScrollBar.handleUpdateNowIfNeeded();
  52289. }
  52290. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52291. {
  52292. if (singleStepX != stepX || singleStepY != stepY)
  52293. {
  52294. singleStepX = stepX;
  52295. singleStepY = stepY;
  52296. updateVisibleArea();
  52297. }
  52298. }
  52299. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52300. const bool showHorizontalScrollbarIfNeeded)
  52301. {
  52302. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52303. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52304. {
  52305. showVScrollbar = showVerticalScrollbarIfNeeded;
  52306. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52307. updateVisibleArea();
  52308. }
  52309. }
  52310. void Viewport::setScrollBarThickness (const int thickness)
  52311. {
  52312. if (scrollBarThickness != thickness)
  52313. {
  52314. scrollBarThickness = thickness;
  52315. updateVisibleArea();
  52316. }
  52317. }
  52318. int Viewport::getScrollBarThickness() const
  52319. {
  52320. return scrollBarThickness > 0 ? scrollBarThickness
  52321. : getLookAndFeel().getDefaultScrollbarWidth();
  52322. }
  52323. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52324. {
  52325. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52326. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52327. }
  52328. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52329. {
  52330. const int newRangeStartInt = roundToInt (newRangeStart);
  52331. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52332. {
  52333. setViewPosition (newRangeStartInt, getViewPositionY());
  52334. }
  52335. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52336. {
  52337. setViewPosition (getViewPositionX(), newRangeStartInt);
  52338. }
  52339. }
  52340. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52341. {
  52342. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52343. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52344. }
  52345. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52346. {
  52347. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52348. {
  52349. const bool hasVertBar = verticalScrollBar.isVisible();
  52350. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52351. if (hasHorzBar || hasVertBar)
  52352. {
  52353. if (wheelIncrementX != 0)
  52354. {
  52355. wheelIncrementX *= 14.0f * singleStepX;
  52356. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52357. : jmax (wheelIncrementX, 1.0f);
  52358. }
  52359. if (wheelIncrementY != 0)
  52360. {
  52361. wheelIncrementY *= 14.0f * singleStepY;
  52362. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52363. : jmax (wheelIncrementY, 1.0f);
  52364. }
  52365. Point<int> pos (getViewPosition());
  52366. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52367. {
  52368. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52369. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52370. }
  52371. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52372. {
  52373. if (wheelIncrementX == 0 && ! hasVertBar)
  52374. wheelIncrementX = wheelIncrementY;
  52375. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52376. }
  52377. else if (hasVertBar && wheelIncrementY != 0)
  52378. {
  52379. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52380. }
  52381. if (pos != getViewPosition())
  52382. {
  52383. setViewPosition (pos);
  52384. return true;
  52385. }
  52386. }
  52387. }
  52388. return false;
  52389. }
  52390. bool Viewport::keyPressed (const KeyPress& key)
  52391. {
  52392. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52393. || key.isKeyCode (KeyPress::downKey)
  52394. || key.isKeyCode (KeyPress::pageUpKey)
  52395. || key.isKeyCode (KeyPress::pageDownKey)
  52396. || key.isKeyCode (KeyPress::homeKey)
  52397. || key.isKeyCode (KeyPress::endKey);
  52398. if (verticalScrollBar.isVisible() && isUpDownKey)
  52399. return verticalScrollBar.keyPressed (key);
  52400. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52401. || key.isKeyCode (KeyPress::rightKey);
  52402. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52403. return horizontalScrollBar.keyPressed (key);
  52404. return false;
  52405. }
  52406. END_JUCE_NAMESPACE
  52407. /*** End of inlined file: juce_Viewport.cpp ***/
  52408. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52409. BEGIN_JUCE_NAMESPACE
  52410. namespace LookAndFeelHelpers
  52411. {
  52412. void createRoundedPath (Path& p,
  52413. const float x, const float y,
  52414. const float w, const float h,
  52415. const float cs,
  52416. const bool curveTopLeft, const bool curveTopRight,
  52417. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52418. {
  52419. const float cs2 = 2.0f * cs;
  52420. if (curveTopLeft)
  52421. {
  52422. p.startNewSubPath (x, y + cs);
  52423. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52424. }
  52425. else
  52426. {
  52427. p.startNewSubPath (x, y);
  52428. }
  52429. if (curveTopRight)
  52430. {
  52431. p.lineTo (x + w - cs, y);
  52432. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52433. }
  52434. else
  52435. {
  52436. p.lineTo (x + w, y);
  52437. }
  52438. if (curveBottomRight)
  52439. {
  52440. p.lineTo (x + w, y + h - cs);
  52441. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52442. }
  52443. else
  52444. {
  52445. p.lineTo (x + w, y + h);
  52446. }
  52447. if (curveBottomLeft)
  52448. {
  52449. p.lineTo (x + cs, y + h);
  52450. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52451. }
  52452. else
  52453. {
  52454. p.lineTo (x, y + h);
  52455. }
  52456. p.closeSubPath();
  52457. }
  52458. const Colour createBaseColour (const Colour& buttonColour,
  52459. const bool hasKeyboardFocus,
  52460. const bool isMouseOverButton,
  52461. const bool isButtonDown) throw()
  52462. {
  52463. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52464. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52465. if (isButtonDown)
  52466. return baseColour.contrasting (0.2f);
  52467. else if (isMouseOverButton)
  52468. return baseColour.contrasting (0.1f);
  52469. return baseColour;
  52470. }
  52471. const TextLayout layoutTooltipText (const String& text) throw()
  52472. {
  52473. const float tooltipFontSize = 12.0f;
  52474. const int maxToolTipWidth = 400;
  52475. const Font f (tooltipFontSize, Font::bold);
  52476. TextLayout tl (text, f);
  52477. tl.layout (maxToolTipWidth, Justification::left, true);
  52478. return tl;
  52479. }
  52480. LookAndFeel* defaultLF = 0;
  52481. LookAndFeel* currentDefaultLF = 0;
  52482. }
  52483. LookAndFeel::LookAndFeel()
  52484. {
  52485. /* if this fails it means you're trying to create a LookAndFeel object before
  52486. the static Colours have been initialised. That ain't gonna work. It probably
  52487. means that you're using a static LookAndFeel object and that your compiler has
  52488. decided to intialise it before the Colours class.
  52489. */
  52490. jassert (Colours::white == Colour (0xffffffff));
  52491. // set up the standard set of colours..
  52492. const int textButtonColour = 0xffbbbbff;
  52493. const int textHighlightColour = 0x401111ee;
  52494. const int standardOutlineColour = 0xb2808080;
  52495. static const int standardColours[] =
  52496. {
  52497. TextButton::buttonColourId, textButtonColour,
  52498. TextButton::buttonOnColourId, 0xff4444ff,
  52499. TextButton::textColourOnId, 0xff000000,
  52500. TextButton::textColourOffId, 0xff000000,
  52501. ComboBox::buttonColourId, 0xffbbbbff,
  52502. ComboBox::outlineColourId, standardOutlineColour,
  52503. ToggleButton::textColourId, 0xff000000,
  52504. TextEditor::backgroundColourId, 0xffffffff,
  52505. TextEditor::textColourId, 0xff000000,
  52506. TextEditor::highlightColourId, textHighlightColour,
  52507. TextEditor::highlightedTextColourId, 0xff000000,
  52508. TextEditor::caretColourId, 0xff000000,
  52509. TextEditor::outlineColourId, 0x00000000,
  52510. TextEditor::focusedOutlineColourId, textButtonColour,
  52511. TextEditor::shadowColourId, 0x38000000,
  52512. Label::backgroundColourId, 0x00000000,
  52513. Label::textColourId, 0xff000000,
  52514. Label::outlineColourId, 0x00000000,
  52515. ScrollBar::backgroundColourId, 0x00000000,
  52516. ScrollBar::thumbColourId, 0xffffffff,
  52517. TreeView::linesColourId, 0x4c000000,
  52518. TreeView::backgroundColourId, 0x00000000,
  52519. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52520. PopupMenu::backgroundColourId, 0xffffffff,
  52521. PopupMenu::textColourId, 0xff000000,
  52522. PopupMenu::headerTextColourId, 0xff000000,
  52523. PopupMenu::highlightedTextColourId, 0xffffffff,
  52524. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52525. ComboBox::textColourId, 0xff000000,
  52526. ComboBox::backgroundColourId, 0xffffffff,
  52527. ComboBox::arrowColourId, 0x99000000,
  52528. ListBox::backgroundColourId, 0xffffffff,
  52529. ListBox::outlineColourId, standardOutlineColour,
  52530. ListBox::textColourId, 0xff000000,
  52531. Slider::backgroundColourId, 0x00000000,
  52532. Slider::thumbColourId, textButtonColour,
  52533. Slider::trackColourId, 0x7fffffff,
  52534. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52535. Slider::rotarySliderOutlineColourId, 0x66000000,
  52536. Slider::textBoxTextColourId, 0xff000000,
  52537. Slider::textBoxBackgroundColourId, 0xffffffff,
  52538. Slider::textBoxHighlightColourId, textHighlightColour,
  52539. Slider::textBoxOutlineColourId, standardOutlineColour,
  52540. ResizableWindow::backgroundColourId, 0xff777777,
  52541. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52542. AlertWindow::backgroundColourId, 0xffededed,
  52543. AlertWindow::textColourId, 0xff000000,
  52544. AlertWindow::outlineColourId, 0xff666666,
  52545. ProgressBar::backgroundColourId, 0xffeeeeee,
  52546. ProgressBar::foregroundColourId, 0xffaaaaee,
  52547. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52548. TooltipWindow::textColourId, 0xff000000,
  52549. TooltipWindow::outlineColourId, 0x4c000000,
  52550. TabbedComponent::backgroundColourId, 0x00000000,
  52551. TabbedComponent::outlineColourId, 0xff777777,
  52552. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52553. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52554. Toolbar::backgroundColourId, 0xfff6f8f9,
  52555. Toolbar::separatorColourId, 0x4c000000,
  52556. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52557. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52558. Toolbar::labelTextColourId, 0xff000000,
  52559. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52560. HyperlinkButton::textColourId, 0xcc1111ee,
  52561. GroupComponent::outlineColourId, 0x66000000,
  52562. GroupComponent::textColourId, 0xff000000,
  52563. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52564. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52565. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52566. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52567. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52568. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52569. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52570. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52571. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52572. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52573. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52574. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52575. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52576. CodeEditorComponent::caretColourId, 0xff000000,
  52577. CodeEditorComponent::highlightColourId, textHighlightColour,
  52578. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52579. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52580. ColourSelector::labelTextColourId, 0xff000000,
  52581. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52582. KeyMappingEditorComponent::textColourId, 0xff000000,
  52583. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52584. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52585. DrawableButton::textColourId, 0xff000000,
  52586. };
  52587. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52588. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52589. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52590. if (defaultSansName.isEmpty())
  52591. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52592. defaultSans = defaultSansName;
  52593. defaultSerif = defaultSerifName;
  52594. defaultFixed = defaultFixedName;
  52595. Font::setFallbackFontName (defaultFallback);
  52596. }
  52597. LookAndFeel::~LookAndFeel()
  52598. {
  52599. if (this == LookAndFeelHelpers::currentDefaultLF)
  52600. setDefaultLookAndFeel (0);
  52601. }
  52602. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52603. {
  52604. const int index = colourIds.indexOf (colourId);
  52605. if (index >= 0)
  52606. return colours [index];
  52607. jassertfalse;
  52608. return Colours::black;
  52609. }
  52610. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52611. {
  52612. const int index = colourIds.indexOf (colourId);
  52613. if (index >= 0)
  52614. {
  52615. colours.set (index, colour);
  52616. }
  52617. else
  52618. {
  52619. colourIds.add (colourId);
  52620. colours.add (colour);
  52621. }
  52622. }
  52623. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52624. {
  52625. return colourIds.contains (colourId);
  52626. }
  52627. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52628. {
  52629. // if this happens, your app hasn't initialised itself properly.. if you're
  52630. // trying to hack your own main() function, have a look at
  52631. // JUCEApplication::initialiseForGUI()
  52632. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52633. return *LookAndFeelHelpers::currentDefaultLF;
  52634. }
  52635. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52636. {
  52637. using namespace LookAndFeelHelpers;
  52638. if (newDefaultLookAndFeel == 0)
  52639. {
  52640. if (defaultLF == 0)
  52641. defaultLF = new LookAndFeel();
  52642. newDefaultLookAndFeel = defaultLF;
  52643. }
  52644. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52645. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52646. {
  52647. Component* const c = Desktop::getInstance().getComponent (i);
  52648. if (c != 0)
  52649. c->sendLookAndFeelChange();
  52650. }
  52651. }
  52652. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52653. {
  52654. using namespace LookAndFeelHelpers;
  52655. if (currentDefaultLF == defaultLF)
  52656. currentDefaultLF = 0;
  52657. deleteAndZero (defaultLF);
  52658. }
  52659. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52660. {
  52661. String faceName (font.getTypefaceName());
  52662. if (faceName == Font::getDefaultSansSerifFontName())
  52663. faceName = defaultSans;
  52664. else if (faceName == Font::getDefaultSerifFontName())
  52665. faceName = defaultSerif;
  52666. else if (faceName == Font::getDefaultMonospacedFontName())
  52667. faceName = defaultFixed;
  52668. Font f (font);
  52669. f.setTypefaceName (faceName);
  52670. return Typeface::createSystemTypefaceFor (f);
  52671. }
  52672. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52673. {
  52674. defaultSans = newName;
  52675. }
  52676. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52677. {
  52678. return component.getMouseCursor();
  52679. }
  52680. void LookAndFeel::drawButtonBackground (Graphics& g,
  52681. Button& button,
  52682. const Colour& backgroundColour,
  52683. bool isMouseOverButton,
  52684. bool isButtonDown)
  52685. {
  52686. const int width = button.getWidth();
  52687. const int height = button.getHeight();
  52688. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52689. const float halfThickness = outlineThickness * 0.5f;
  52690. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52691. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52692. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52693. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52694. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52695. button.hasKeyboardFocus (true),
  52696. isMouseOverButton, isButtonDown)
  52697. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52698. drawGlassLozenge (g,
  52699. indentL,
  52700. indentT,
  52701. width - indentL - indentR,
  52702. height - indentT - indentB,
  52703. baseColour, outlineThickness, -1.0f,
  52704. button.isConnectedOnLeft(),
  52705. button.isConnectedOnRight(),
  52706. button.isConnectedOnTop(),
  52707. button.isConnectedOnBottom());
  52708. }
  52709. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52710. {
  52711. return button.getFont();
  52712. }
  52713. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52714. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52715. {
  52716. Font font (getFontForTextButton (button));
  52717. g.setFont (font);
  52718. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52719. : TextButton::textColourOffId)
  52720. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52721. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52722. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52723. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52724. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52725. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52726. g.drawFittedText (button.getButtonText(),
  52727. leftIndent,
  52728. yIndent,
  52729. button.getWidth() - leftIndent - rightIndent,
  52730. button.getHeight() - yIndent * 2,
  52731. Justification::centred, 2);
  52732. }
  52733. void LookAndFeel::drawTickBox (Graphics& g,
  52734. Component& component,
  52735. float x, float y, float w, float h,
  52736. const bool ticked,
  52737. const bool isEnabled,
  52738. const bool isMouseOverButton,
  52739. const bool isButtonDown)
  52740. {
  52741. const float boxSize = w * 0.7f;
  52742. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52743. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52744. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52745. true, isMouseOverButton, isButtonDown),
  52746. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52747. if (ticked)
  52748. {
  52749. Path tick;
  52750. tick.startNewSubPath (1.5f, 3.0f);
  52751. tick.lineTo (3.0f, 6.0f);
  52752. tick.lineTo (6.0f, 0.0f);
  52753. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52754. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52755. .translated (x, y));
  52756. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52757. }
  52758. }
  52759. void LookAndFeel::drawToggleButton (Graphics& g,
  52760. ToggleButton& button,
  52761. bool isMouseOverButton,
  52762. bool isButtonDown)
  52763. {
  52764. if (button.hasKeyboardFocus (true))
  52765. {
  52766. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52767. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52768. }
  52769. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52770. const float tickWidth = fontSize * 1.1f;
  52771. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52772. tickWidth, tickWidth,
  52773. button.getToggleState(),
  52774. button.isEnabled(),
  52775. isMouseOverButton,
  52776. isButtonDown);
  52777. g.setColour (button.findColour (ToggleButton::textColourId));
  52778. g.setFont (fontSize);
  52779. if (! button.isEnabled())
  52780. g.setOpacity (0.5f);
  52781. const int textX = (int) tickWidth + 5;
  52782. g.drawFittedText (button.getButtonText(),
  52783. textX, 0,
  52784. button.getWidth() - textX - 2, button.getHeight(),
  52785. Justification::centredLeft, 10);
  52786. }
  52787. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52788. {
  52789. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52790. const int tickWidth = jmin (24, button.getHeight());
  52791. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52792. button.getHeight());
  52793. }
  52794. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52795. const String& message,
  52796. const String& button1,
  52797. const String& button2,
  52798. const String& button3,
  52799. AlertWindow::AlertIconType iconType,
  52800. int numButtons,
  52801. Component* associatedComponent)
  52802. {
  52803. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52804. if (numButtons == 1)
  52805. {
  52806. aw->addButton (button1, 0,
  52807. KeyPress (KeyPress::escapeKey, 0, 0),
  52808. KeyPress (KeyPress::returnKey, 0, 0));
  52809. }
  52810. else
  52811. {
  52812. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52813. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52814. if (button1ShortCut == button2ShortCut)
  52815. button2ShortCut = KeyPress();
  52816. if (numButtons == 2)
  52817. {
  52818. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52819. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52820. }
  52821. else if (numButtons == 3)
  52822. {
  52823. aw->addButton (button1, 1, button1ShortCut);
  52824. aw->addButton (button2, 2, button2ShortCut);
  52825. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52826. }
  52827. }
  52828. return aw;
  52829. }
  52830. void LookAndFeel::drawAlertBox (Graphics& g,
  52831. AlertWindow& alert,
  52832. const Rectangle<int>& textArea,
  52833. TextLayout& textLayout)
  52834. {
  52835. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52836. int iconSpaceUsed = 0;
  52837. Justification alignment (Justification::horizontallyCentred);
  52838. const int iconWidth = 80;
  52839. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52840. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52841. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52842. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52843. iconSize, iconSize);
  52844. if (alert.getAlertType() != AlertWindow::NoIcon)
  52845. {
  52846. Path icon;
  52847. uint32 colour;
  52848. char character;
  52849. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52850. {
  52851. colour = 0x55ff5555;
  52852. character = '!';
  52853. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52854. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52855. (float) iconRect.getX(), (float) iconRect.getBottom());
  52856. icon = icon.createPathWithRoundedCorners (5.0f);
  52857. }
  52858. else
  52859. {
  52860. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52861. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52862. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52863. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52864. }
  52865. GlyphArrangement ga;
  52866. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52867. String::charToString (character),
  52868. (float) iconRect.getX(), (float) iconRect.getY(),
  52869. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52870. Justification::centred, false);
  52871. ga.createPath (icon);
  52872. icon.setUsingNonZeroWinding (false);
  52873. g.setColour (Colour (colour));
  52874. g.fillPath (icon);
  52875. iconSpaceUsed = iconWidth;
  52876. alignment = Justification::left;
  52877. }
  52878. g.setColour (alert.findColour (AlertWindow::textColourId));
  52879. textLayout.drawWithin (g,
  52880. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52881. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52882. alignment.getFlags() | Justification::top);
  52883. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52884. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52885. }
  52886. int LookAndFeel::getAlertBoxWindowFlags()
  52887. {
  52888. return ComponentPeer::windowAppearsOnTaskbar
  52889. | ComponentPeer::windowHasDropShadow;
  52890. }
  52891. int LookAndFeel::getAlertWindowButtonHeight()
  52892. {
  52893. return 28;
  52894. }
  52895. const Font LookAndFeel::getAlertWindowMessageFont()
  52896. {
  52897. return Font (15.0f);
  52898. }
  52899. const Font LookAndFeel::getAlertWindowFont()
  52900. {
  52901. return Font (12.0f);
  52902. }
  52903. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52904. int width, int height,
  52905. double progress, const String& textToShow)
  52906. {
  52907. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52908. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52909. g.fillAll (background);
  52910. if (progress >= 0.0f && progress < 1.0f)
  52911. {
  52912. drawGlassLozenge (g, 1.0f, 1.0f,
  52913. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52914. (float) (height - 2),
  52915. foreground,
  52916. 0.5f, 0.0f,
  52917. true, true, true, true);
  52918. }
  52919. else
  52920. {
  52921. // spinning bar..
  52922. g.setColour (foreground);
  52923. const int stripeWidth = height * 2;
  52924. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52925. Path p;
  52926. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52927. p.addQuadrilateral (x, 0.0f,
  52928. x + stripeWidth * 0.5f, 0.0f,
  52929. x, (float) height,
  52930. x - stripeWidth * 0.5f, (float) height);
  52931. Image im (Image::ARGB, width, height, true);
  52932. {
  52933. Graphics g2 (im);
  52934. drawGlassLozenge (g2, 1.0f, 1.0f,
  52935. (float) (width - 2),
  52936. (float) (height - 2),
  52937. foreground,
  52938. 0.5f, 0.0f,
  52939. true, true, true, true);
  52940. }
  52941. g.setTiledImageFill (im, 0, 0, 0.85f);
  52942. g.fillPath (p);
  52943. }
  52944. if (textToShow.isNotEmpty())
  52945. {
  52946. g.setColour (Colour::contrasting (background, foreground));
  52947. g.setFont (height * 0.6f);
  52948. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52949. }
  52950. }
  52951. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52952. {
  52953. const float radius = jmin (w, h) * 0.4f;
  52954. const float thickness = radius * 0.15f;
  52955. Path p;
  52956. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52957. radius * 0.6f, thickness,
  52958. thickness * 0.5f);
  52959. const float cx = x + w * 0.5f;
  52960. const float cy = y + h * 0.5f;
  52961. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52962. for (int i = 0; i < 12; ++i)
  52963. {
  52964. const int n = (i + 12 - animationIndex) % 12;
  52965. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52966. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52967. .translated (cx, cy));
  52968. }
  52969. }
  52970. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52971. ScrollBar& scrollbar,
  52972. int width, int height,
  52973. int buttonDirection,
  52974. bool /*isScrollbarVertical*/,
  52975. bool /*isMouseOverButton*/,
  52976. bool isButtonDown)
  52977. {
  52978. Path p;
  52979. if (buttonDirection == 0)
  52980. p.addTriangle (width * 0.5f, height * 0.2f,
  52981. width * 0.1f, height * 0.7f,
  52982. width * 0.9f, height * 0.7f);
  52983. else if (buttonDirection == 1)
  52984. p.addTriangle (width * 0.8f, height * 0.5f,
  52985. width * 0.3f, height * 0.1f,
  52986. width * 0.3f, height * 0.9f);
  52987. else if (buttonDirection == 2)
  52988. p.addTriangle (width * 0.5f, height * 0.8f,
  52989. width * 0.1f, height * 0.3f,
  52990. width * 0.9f, height * 0.3f);
  52991. else if (buttonDirection == 3)
  52992. p.addTriangle (width * 0.2f, height * 0.5f,
  52993. width * 0.7f, height * 0.1f,
  52994. width * 0.7f, height * 0.9f);
  52995. if (isButtonDown)
  52996. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52997. else
  52998. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52999. g.fillPath (p);
  53000. g.setColour (Colour (0x80000000));
  53001. g.strokePath (p, PathStrokeType (0.5f));
  53002. }
  53003. void LookAndFeel::drawScrollbar (Graphics& g,
  53004. ScrollBar& scrollbar,
  53005. int x, int y,
  53006. int width, int height,
  53007. bool isScrollbarVertical,
  53008. int thumbStartPosition,
  53009. int thumbSize,
  53010. bool /*isMouseOver*/,
  53011. bool /*isMouseDown*/)
  53012. {
  53013. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  53014. Path slotPath, thumbPath;
  53015. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  53016. const float slotIndentx2 = slotIndent * 2.0f;
  53017. const float thumbIndent = slotIndent + 1.0f;
  53018. const float thumbIndentx2 = thumbIndent * 2.0f;
  53019. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  53020. if (isScrollbarVertical)
  53021. {
  53022. slotPath.addRoundedRectangle (x + slotIndent,
  53023. y + slotIndent,
  53024. width - slotIndentx2,
  53025. height - slotIndentx2,
  53026. (width - slotIndentx2) * 0.5f);
  53027. if (thumbSize > 0)
  53028. thumbPath.addRoundedRectangle (x + thumbIndent,
  53029. thumbStartPosition + thumbIndent,
  53030. width - thumbIndentx2,
  53031. thumbSize - thumbIndentx2,
  53032. (width - thumbIndentx2) * 0.5f);
  53033. gx1 = (float) x;
  53034. gx2 = x + width * 0.7f;
  53035. }
  53036. else
  53037. {
  53038. slotPath.addRoundedRectangle (x + slotIndent,
  53039. y + slotIndent,
  53040. width - slotIndentx2,
  53041. height - slotIndentx2,
  53042. (height - slotIndentx2) * 0.5f);
  53043. if (thumbSize > 0)
  53044. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  53045. y + thumbIndent,
  53046. thumbSize - thumbIndentx2,
  53047. height - thumbIndentx2,
  53048. (height - thumbIndentx2) * 0.5f);
  53049. gy1 = (float) y;
  53050. gy2 = y + height * 0.7f;
  53051. }
  53052. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53053. Colour trackColour1, trackColour2;
  53054. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  53055. {
  53056. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  53057. }
  53058. else
  53059. {
  53060. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  53061. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  53062. }
  53063. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  53064. trackColour2, gx2, gy2, false));
  53065. g.fillPath (slotPath);
  53066. if (isScrollbarVertical)
  53067. {
  53068. gx1 = x + width * 0.6f;
  53069. gx2 = (float) x + width;
  53070. }
  53071. else
  53072. {
  53073. gy1 = y + height * 0.6f;
  53074. gy2 = (float) y + height;
  53075. }
  53076. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  53077. Colour (0x19000000), gx2, gy2, false));
  53078. g.fillPath (slotPath);
  53079. g.setColour (thumbColour);
  53080. g.fillPath (thumbPath);
  53081. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  53082. Colours::transparentBlack, gx2, gy2, false));
  53083. g.saveState();
  53084. if (isScrollbarVertical)
  53085. g.reduceClipRegion (x + width / 2, y, width, height);
  53086. else
  53087. g.reduceClipRegion (x, y + height / 2, width, height);
  53088. g.fillPath (thumbPath);
  53089. g.restoreState();
  53090. g.setColour (Colour (0x4c000000));
  53091. g.strokePath (thumbPath, PathStrokeType (0.4f));
  53092. }
  53093. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  53094. {
  53095. return 0;
  53096. }
  53097. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53098. {
  53099. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53100. }
  53101. int LookAndFeel::getDefaultScrollbarWidth()
  53102. {
  53103. return 18;
  53104. }
  53105. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53106. {
  53107. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53108. : scrollbar.getHeight());
  53109. }
  53110. const Path LookAndFeel::getTickShape (const float height)
  53111. {
  53112. static const unsigned char tickShapeData[] =
  53113. {
  53114. 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,
  53115. 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,
  53116. 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,
  53117. 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,
  53118. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53119. };
  53120. Path p;
  53121. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53122. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53123. return p;
  53124. }
  53125. const Path LookAndFeel::getCrossShape (const float height)
  53126. {
  53127. static const unsigned char crossShapeData[] =
  53128. {
  53129. 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,
  53130. 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,
  53131. 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,
  53132. 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,
  53133. 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,
  53134. 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,
  53135. 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
  53136. };
  53137. Path p;
  53138. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53139. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53140. return p;
  53141. }
  53142. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53143. {
  53144. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53145. x += (w - boxSize) >> 1;
  53146. y += (h - boxSize) >> 1;
  53147. w = boxSize;
  53148. h = boxSize;
  53149. g.setColour (Colour (0xe5ffffff));
  53150. g.fillRect (x, y, w, h);
  53151. g.setColour (Colour (0x80000000));
  53152. g.drawRect (x, y, w, h);
  53153. const float size = boxSize / 2 + 1.0f;
  53154. const float centre = (float) (boxSize / 2);
  53155. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53156. if (isPlus)
  53157. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53158. }
  53159. void LookAndFeel::drawBubble (Graphics& g,
  53160. float tipX, float tipY,
  53161. float boxX, float boxY,
  53162. float boxW, float boxH)
  53163. {
  53164. int side = 0;
  53165. if (tipX < boxX)
  53166. side = 1;
  53167. else if (tipX > boxX + boxW)
  53168. side = 3;
  53169. else if (tipY > boxY + boxH)
  53170. side = 2;
  53171. const float indent = 2.0f;
  53172. Path p;
  53173. p.addBubble (boxX + indent,
  53174. boxY + indent,
  53175. boxW - indent * 2.0f,
  53176. boxH - indent * 2.0f,
  53177. 5.0f,
  53178. tipX, tipY,
  53179. side,
  53180. 0.5f,
  53181. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53182. //xxx need to take comp as param for colour
  53183. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53184. g.fillPath (p);
  53185. //xxx as above
  53186. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53187. g.strokePath (p, PathStrokeType (1.33f));
  53188. }
  53189. const Font LookAndFeel::getPopupMenuFont()
  53190. {
  53191. return Font (17.0f);
  53192. }
  53193. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53194. const bool isSeparator,
  53195. int standardMenuItemHeight,
  53196. int& idealWidth,
  53197. int& idealHeight)
  53198. {
  53199. if (isSeparator)
  53200. {
  53201. idealWidth = 50;
  53202. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53203. }
  53204. else
  53205. {
  53206. Font font (getPopupMenuFont());
  53207. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53208. font.setHeight (standardMenuItemHeight / 1.3f);
  53209. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53210. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53211. }
  53212. }
  53213. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53214. {
  53215. const Colour background (findColour (PopupMenu::backgroundColourId));
  53216. g.fillAll (background);
  53217. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53218. for (int i = 0; i < height; i += 3)
  53219. g.fillRect (0, i, width, 1);
  53220. #if ! JUCE_MAC
  53221. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53222. g.drawRect (0, 0, width, height);
  53223. #endif
  53224. }
  53225. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53226. int width, int height,
  53227. bool isScrollUpArrow)
  53228. {
  53229. const Colour background (findColour (PopupMenu::backgroundColourId));
  53230. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53231. background.withAlpha (0.0f),
  53232. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53233. false));
  53234. g.fillRect (1, 1, width - 2, height - 2);
  53235. const float hw = width * 0.5f;
  53236. const float arrowW = height * 0.3f;
  53237. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53238. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53239. Path p;
  53240. p.addTriangle (hw - arrowW, y1,
  53241. hw + arrowW, y1,
  53242. hw, y2);
  53243. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53244. g.fillPath (p);
  53245. }
  53246. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53247. int width, int height,
  53248. const bool isSeparator,
  53249. const bool isActive,
  53250. const bool isHighlighted,
  53251. const bool isTicked,
  53252. const bool hasSubMenu,
  53253. const String& text,
  53254. const String& shortcutKeyText,
  53255. Image* image,
  53256. const Colour* const textColourToUse)
  53257. {
  53258. const float halfH = height * 0.5f;
  53259. if (isSeparator)
  53260. {
  53261. const float separatorIndent = 5.5f;
  53262. g.setColour (Colour (0x33000000));
  53263. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53264. g.setColour (Colour (0x66ffffff));
  53265. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53266. }
  53267. else
  53268. {
  53269. Colour textColour (findColour (PopupMenu::textColourId));
  53270. if (textColourToUse != 0)
  53271. textColour = *textColourToUse;
  53272. if (isHighlighted)
  53273. {
  53274. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53275. g.fillRect (1, 1, width - 2, height - 2);
  53276. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53277. }
  53278. else
  53279. {
  53280. g.setColour (textColour);
  53281. }
  53282. if (! isActive)
  53283. g.setOpacity (0.3f);
  53284. Font font (getPopupMenuFont());
  53285. if (font.getHeight() > height / 1.3f)
  53286. font.setHeight (height / 1.3f);
  53287. g.setFont (font);
  53288. const int leftBorder = (height * 5) / 4;
  53289. const int rightBorder = 4;
  53290. if (image != 0)
  53291. {
  53292. g.drawImageWithin (*image,
  53293. 2, 1, leftBorder - 4, height - 2,
  53294. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53295. }
  53296. else if (isTicked)
  53297. {
  53298. const Path tick (getTickShape (1.0f));
  53299. const float th = font.getAscent();
  53300. const float ty = halfH - th * 0.5f;
  53301. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53302. th, true));
  53303. }
  53304. g.drawFittedText (text,
  53305. leftBorder, 0,
  53306. width - (leftBorder + rightBorder), height,
  53307. Justification::centredLeft, 1);
  53308. if (shortcutKeyText.isNotEmpty())
  53309. {
  53310. Font f2 (font);
  53311. f2.setHeight (f2.getHeight() * 0.75f);
  53312. f2.setHorizontalScale (0.95f);
  53313. g.setFont (f2);
  53314. g.drawText (shortcutKeyText,
  53315. leftBorder,
  53316. 0,
  53317. width - (leftBorder + rightBorder + 4),
  53318. height,
  53319. Justification::centredRight,
  53320. true);
  53321. }
  53322. if (hasSubMenu)
  53323. {
  53324. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53325. const float x = width - height * 0.6f;
  53326. Path p;
  53327. p.addTriangle (x, halfH - arrowH * 0.5f,
  53328. x, halfH + arrowH * 0.5f,
  53329. x + arrowH * 0.6f, halfH);
  53330. g.fillPath (p);
  53331. }
  53332. }
  53333. }
  53334. int LookAndFeel::getMenuWindowFlags()
  53335. {
  53336. return ComponentPeer::windowHasDropShadow;
  53337. }
  53338. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53339. bool, MenuBarComponent& menuBar)
  53340. {
  53341. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53342. if (menuBar.isEnabled())
  53343. {
  53344. drawShinyButtonShape (g,
  53345. -4.0f, 0.0f,
  53346. width + 8.0f, (float) height,
  53347. 0.0f,
  53348. baseColour,
  53349. 0.4f,
  53350. true, true, true, true);
  53351. }
  53352. else
  53353. {
  53354. g.fillAll (baseColour);
  53355. }
  53356. }
  53357. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53358. {
  53359. return Font (menuBar.getHeight() * 0.7f);
  53360. }
  53361. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53362. {
  53363. return getMenuBarFont (menuBar, itemIndex, itemText)
  53364. .getStringWidth (itemText) + menuBar.getHeight();
  53365. }
  53366. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53367. int width, int height,
  53368. int itemIndex,
  53369. const String& itemText,
  53370. bool isMouseOverItem,
  53371. bool isMenuOpen,
  53372. bool /*isMouseOverBar*/,
  53373. MenuBarComponent& menuBar)
  53374. {
  53375. if (! menuBar.isEnabled())
  53376. {
  53377. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53378. .withMultipliedAlpha (0.5f));
  53379. }
  53380. else if (isMenuOpen || isMouseOverItem)
  53381. {
  53382. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53383. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53384. }
  53385. else
  53386. {
  53387. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53388. }
  53389. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53390. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53391. }
  53392. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53393. TextEditor& textEditor)
  53394. {
  53395. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53396. }
  53397. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53398. {
  53399. if (textEditor.isEnabled())
  53400. {
  53401. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53402. {
  53403. const int border = 2;
  53404. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53405. g.drawRect (0, 0, width, height, border);
  53406. g.setOpacity (1.0f);
  53407. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53408. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53409. }
  53410. else
  53411. {
  53412. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53413. g.drawRect (0, 0, width, height);
  53414. g.setOpacity (1.0f);
  53415. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53416. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53417. }
  53418. }
  53419. }
  53420. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53421. const bool isButtonDown,
  53422. int buttonX, int buttonY,
  53423. int buttonW, int buttonH,
  53424. ComboBox& box)
  53425. {
  53426. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53427. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53428. {
  53429. g.setColour (box.findColour (TextButton::buttonColourId));
  53430. g.drawRect (0, 0, width, height, 2);
  53431. }
  53432. else
  53433. {
  53434. g.setColour (box.findColour (ComboBox::outlineColourId));
  53435. g.drawRect (0, 0, width, height);
  53436. }
  53437. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53438. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53439. box.hasKeyboardFocus (true),
  53440. false, isButtonDown)
  53441. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53442. drawGlassLozenge (g,
  53443. buttonX + outlineThickness, buttonY + outlineThickness,
  53444. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53445. baseColour, outlineThickness, -1.0f,
  53446. true, true, true, true);
  53447. if (box.isEnabled())
  53448. {
  53449. const float arrowX = 0.3f;
  53450. const float arrowH = 0.2f;
  53451. Path p;
  53452. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53453. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53454. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53455. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53456. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53457. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53458. g.setColour (box.findColour (ComboBox::arrowColourId));
  53459. g.fillPath (p);
  53460. }
  53461. }
  53462. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53463. {
  53464. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53465. }
  53466. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53467. {
  53468. return new Label (String::empty, String::empty);
  53469. }
  53470. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53471. {
  53472. label.setBounds (1, 1,
  53473. box.getWidth() + 3 - box.getHeight(),
  53474. box.getHeight() - 2);
  53475. label.setFont (getComboBoxFont (box));
  53476. }
  53477. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53478. {
  53479. g.fillAll (label.findColour (Label::backgroundColourId));
  53480. if (! label.isBeingEdited())
  53481. {
  53482. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53483. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53484. g.setFont (label.getFont());
  53485. g.drawFittedText (label.getText(),
  53486. label.getHorizontalBorderSize(),
  53487. label.getVerticalBorderSize(),
  53488. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53489. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53490. label.getJustificationType(),
  53491. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53492. label.getMinimumHorizontalScale());
  53493. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53494. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53495. }
  53496. else if (label.isEnabled())
  53497. {
  53498. g.setColour (label.findColour (Label::outlineColourId));
  53499. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53500. }
  53501. }
  53502. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53503. int x, int y,
  53504. int width, int height,
  53505. float /*sliderPos*/,
  53506. float /*minSliderPos*/,
  53507. float /*maxSliderPos*/,
  53508. const Slider::SliderStyle /*style*/,
  53509. Slider& slider)
  53510. {
  53511. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53512. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53513. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53514. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53515. Path indent;
  53516. if (slider.isHorizontal())
  53517. {
  53518. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53519. const float ih = sliderRadius;
  53520. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53521. gradCol2, 0.0f, iy + ih, false));
  53522. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53523. width + sliderRadius, ih,
  53524. 5.0f);
  53525. g.fillPath (indent);
  53526. }
  53527. else
  53528. {
  53529. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53530. const float iw = sliderRadius;
  53531. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53532. gradCol2, ix + iw, 0.0f, false));
  53533. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53534. iw, height + sliderRadius,
  53535. 5.0f);
  53536. g.fillPath (indent);
  53537. }
  53538. g.setColour (Colour (0x4c000000));
  53539. g.strokePath (indent, PathStrokeType (0.5f));
  53540. }
  53541. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53542. int x, int y,
  53543. int width, int height,
  53544. float sliderPos,
  53545. float minSliderPos,
  53546. float maxSliderPos,
  53547. const Slider::SliderStyle style,
  53548. Slider& slider)
  53549. {
  53550. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53551. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53552. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53553. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53554. slider.isMouseButtonDown() && slider.isEnabled()));
  53555. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53556. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53557. {
  53558. float kx, ky;
  53559. if (style == Slider::LinearVertical)
  53560. {
  53561. kx = x + width * 0.5f;
  53562. ky = sliderPos;
  53563. }
  53564. else
  53565. {
  53566. kx = sliderPos;
  53567. ky = y + height * 0.5f;
  53568. }
  53569. drawGlassSphere (g,
  53570. kx - sliderRadius,
  53571. ky - sliderRadius,
  53572. sliderRadius * 2.0f,
  53573. knobColour, outlineThickness);
  53574. }
  53575. else
  53576. {
  53577. if (style == Slider::ThreeValueVertical)
  53578. {
  53579. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53580. sliderPos - sliderRadius,
  53581. sliderRadius * 2.0f,
  53582. knobColour, outlineThickness);
  53583. }
  53584. else if (style == Slider::ThreeValueHorizontal)
  53585. {
  53586. drawGlassSphere (g,sliderPos - sliderRadius,
  53587. y + height * 0.5f - sliderRadius,
  53588. sliderRadius * 2.0f,
  53589. knobColour, outlineThickness);
  53590. }
  53591. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53592. {
  53593. const float sr = jmin (sliderRadius, width * 0.4f);
  53594. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53595. minSliderPos - sliderRadius,
  53596. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53597. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53598. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53599. }
  53600. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53601. {
  53602. const float sr = jmin (sliderRadius, height * 0.4f);
  53603. drawGlassPointer (g, minSliderPos - sr,
  53604. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53605. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53606. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53607. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53608. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53609. }
  53610. }
  53611. }
  53612. void LookAndFeel::drawLinearSlider (Graphics& g,
  53613. int x, int y,
  53614. int width, int height,
  53615. float sliderPos,
  53616. float minSliderPos,
  53617. float maxSliderPos,
  53618. const Slider::SliderStyle style,
  53619. Slider& slider)
  53620. {
  53621. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53622. if (style == Slider::LinearBar)
  53623. {
  53624. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53625. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53626. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53627. false, isMouseOver,
  53628. isMouseOver || slider.isMouseButtonDown()));
  53629. drawShinyButtonShape (g,
  53630. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53631. baseColour,
  53632. slider.isEnabled() ? 0.9f : 0.3f,
  53633. true, true, true, true);
  53634. }
  53635. else
  53636. {
  53637. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53638. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53639. }
  53640. }
  53641. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53642. {
  53643. return jmin (7,
  53644. slider.getHeight() / 2,
  53645. slider.getWidth() / 2) + 2;
  53646. }
  53647. void LookAndFeel::drawRotarySlider (Graphics& g,
  53648. int x, int y,
  53649. int width, int height,
  53650. float sliderPos,
  53651. const float rotaryStartAngle,
  53652. const float rotaryEndAngle,
  53653. Slider& slider)
  53654. {
  53655. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53656. const float centreX = x + width * 0.5f;
  53657. const float centreY = y + height * 0.5f;
  53658. const float rx = centreX - radius;
  53659. const float ry = centreY - radius;
  53660. const float rw = radius * 2.0f;
  53661. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53662. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53663. if (radius > 12.0f)
  53664. {
  53665. if (slider.isEnabled())
  53666. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53667. else
  53668. g.setColour (Colour (0x80808080));
  53669. const float thickness = 0.7f;
  53670. {
  53671. Path filledArc;
  53672. filledArc.addPieSegment (rx, ry, rw, rw,
  53673. rotaryStartAngle,
  53674. angle,
  53675. thickness);
  53676. g.fillPath (filledArc);
  53677. }
  53678. if (thickness > 0)
  53679. {
  53680. const float innerRadius = radius * 0.2f;
  53681. Path p;
  53682. p.addTriangle (-innerRadius, 0.0f,
  53683. 0.0f, -radius * thickness * 1.1f,
  53684. innerRadius, 0.0f);
  53685. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53686. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53687. }
  53688. if (slider.isEnabled())
  53689. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53690. else
  53691. g.setColour (Colour (0x80808080));
  53692. Path outlineArc;
  53693. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53694. outlineArc.closeSubPath();
  53695. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53696. }
  53697. else
  53698. {
  53699. if (slider.isEnabled())
  53700. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53701. else
  53702. g.setColour (Colour (0x80808080));
  53703. Path p;
  53704. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53705. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53706. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53707. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53708. }
  53709. }
  53710. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53711. {
  53712. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53713. }
  53714. class SliderLabelComp : public Label
  53715. {
  53716. public:
  53717. SliderLabelComp() : Label (String::empty, String::empty) {}
  53718. ~SliderLabelComp() {}
  53719. void mouseWheelMove (const MouseEvent&, float, float) {}
  53720. };
  53721. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53722. {
  53723. Label* const l = new SliderLabelComp();
  53724. l->setJustificationType (Justification::centred);
  53725. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53726. l->setColour (Label::backgroundColourId,
  53727. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53728. : slider.findColour (Slider::textBoxBackgroundColourId));
  53729. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53730. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53731. l->setColour (TextEditor::backgroundColourId,
  53732. slider.findColour (Slider::textBoxBackgroundColourId)
  53733. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53734. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53735. return l;
  53736. }
  53737. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53738. {
  53739. return 0;
  53740. }
  53741. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53742. {
  53743. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53744. width = tl.getWidth() + 14;
  53745. height = tl.getHeight() + 6;
  53746. }
  53747. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53748. {
  53749. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53750. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53751. g.setColour (findColour (TooltipWindow::outlineColourId));
  53752. g.drawRect (0, 0, width, height, 1);
  53753. #endif
  53754. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53755. g.setColour (findColour (TooltipWindow::textColourId));
  53756. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53757. }
  53758. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53759. {
  53760. return new TextButton (text, TRANS("click to browse for a different file"));
  53761. }
  53762. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53763. ComboBox* filenameBox,
  53764. Button* browseButton)
  53765. {
  53766. browseButton->setSize (80, filenameComp.getHeight());
  53767. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53768. if (tb != 0)
  53769. tb->changeWidthToFitText();
  53770. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53771. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53772. }
  53773. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53774. int imageX, int imageY, int imageW, int imageH,
  53775. const Colour& overlayColour,
  53776. float imageOpacity,
  53777. ImageButton& button)
  53778. {
  53779. if (! button.isEnabled())
  53780. imageOpacity *= 0.3f;
  53781. if (! overlayColour.isOpaque())
  53782. {
  53783. g.setOpacity (imageOpacity);
  53784. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53785. 0, 0, image->getWidth(), image->getHeight(), false);
  53786. }
  53787. if (! overlayColour.isTransparent())
  53788. {
  53789. g.setColour (overlayColour);
  53790. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53791. 0, 0, image->getWidth(), image->getHeight(), true);
  53792. }
  53793. }
  53794. void LookAndFeel::drawCornerResizer (Graphics& g,
  53795. int w, int h,
  53796. bool /*isMouseOver*/,
  53797. bool /*isMouseDragging*/)
  53798. {
  53799. const float lineThickness = jmin (w, h) * 0.075f;
  53800. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53801. {
  53802. g.setColour (Colours::lightgrey);
  53803. g.drawLine (w * i,
  53804. h + 1.0f,
  53805. w + 1.0f,
  53806. h * i,
  53807. lineThickness);
  53808. g.setColour (Colours::darkgrey);
  53809. g.drawLine (w * i + lineThickness,
  53810. h + 1.0f,
  53811. w + 1.0f,
  53812. h * i + lineThickness,
  53813. lineThickness);
  53814. }
  53815. }
  53816. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53817. {
  53818. if (! border.isEmpty())
  53819. {
  53820. const Rectangle<int> fullSize (0, 0, w, h);
  53821. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53822. g.saveState();
  53823. g.excludeClipRegion (centreArea);
  53824. g.setColour (Colour (0x50000000));
  53825. g.drawRect (fullSize);
  53826. g.setColour (Colour (0x19000000));
  53827. g.drawRect (centreArea.expanded (1, 1));
  53828. g.restoreState();
  53829. }
  53830. }
  53831. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53832. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53833. {
  53834. g.fillAll (window.getBackgroundColour());
  53835. }
  53836. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53837. const BorderSize<int>& /*border*/, ResizableWindow&)
  53838. {
  53839. }
  53840. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53841. Graphics& g, int w, int h,
  53842. int titleSpaceX, int titleSpaceW,
  53843. const Image* icon,
  53844. bool drawTitleTextOnLeft)
  53845. {
  53846. const bool isActive = window.isActiveWindow();
  53847. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53848. 0.0f, 0.0f,
  53849. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53850. 0.0f, (float) h, false));
  53851. g.fillAll();
  53852. Font font (h * 0.65f, Font::bold);
  53853. g.setFont (font);
  53854. int textW = font.getStringWidth (window.getName());
  53855. int iconW = 0;
  53856. int iconH = 0;
  53857. if (icon != 0)
  53858. {
  53859. iconH = (int) font.getHeight();
  53860. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53861. }
  53862. textW = jmin (titleSpaceW, textW + iconW);
  53863. int textX = drawTitleTextOnLeft ? titleSpaceX
  53864. : jmax (titleSpaceX, (w - textW) / 2);
  53865. if (textX + textW > titleSpaceX + titleSpaceW)
  53866. textX = titleSpaceX + titleSpaceW - textW;
  53867. if (icon != 0)
  53868. {
  53869. g.setOpacity (isActive ? 1.0f : 0.6f);
  53870. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53871. RectanglePlacement::centred, false);
  53872. textX += iconW;
  53873. textW -= iconW;
  53874. }
  53875. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53876. g.setColour (findColour (DocumentWindow::textColourId));
  53877. else
  53878. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53879. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53880. }
  53881. class GlassWindowButton : public Button
  53882. {
  53883. public:
  53884. GlassWindowButton (const String& name, const Colour& col,
  53885. const Path& normalShape_,
  53886. const Path& toggledShape_) throw()
  53887. : Button (name),
  53888. colour (col),
  53889. normalShape (normalShape_),
  53890. toggledShape (toggledShape_)
  53891. {
  53892. }
  53893. ~GlassWindowButton()
  53894. {
  53895. }
  53896. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53897. {
  53898. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53899. if (! isEnabled())
  53900. alpha *= 0.5f;
  53901. float x = 0, y = 0, diam;
  53902. if (getWidth() < getHeight())
  53903. {
  53904. diam = (float) getWidth();
  53905. y = (getHeight() - getWidth()) * 0.5f;
  53906. }
  53907. else
  53908. {
  53909. diam = (float) getHeight();
  53910. y = (getWidth() - getHeight()) * 0.5f;
  53911. }
  53912. x += diam * 0.05f;
  53913. y += diam * 0.05f;
  53914. diam *= 0.9f;
  53915. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53916. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53917. g.fillEllipse (x, y, diam, diam);
  53918. x += 2.0f;
  53919. y += 2.0f;
  53920. diam -= 4.0f;
  53921. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53922. Path& p = getToggleState() ? toggledShape : normalShape;
  53923. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53924. diam * 0.4f, diam * 0.4f, true));
  53925. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53926. g.fillPath (p, t);
  53927. }
  53928. private:
  53929. Colour colour;
  53930. Path normalShape, toggledShape;
  53931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53932. };
  53933. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53934. {
  53935. Path shape;
  53936. const float crossThickness = 0.25f;
  53937. if (buttonType == DocumentWindow::closeButton)
  53938. {
  53939. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53940. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53941. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53942. }
  53943. else if (buttonType == DocumentWindow::minimiseButton)
  53944. {
  53945. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53946. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53947. }
  53948. else if (buttonType == DocumentWindow::maximiseButton)
  53949. {
  53950. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53951. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53952. Path fullscreenShape;
  53953. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53954. fullscreenShape.lineTo (0.0f, 100.0f);
  53955. fullscreenShape.lineTo (0.0f, 0.0f);
  53956. fullscreenShape.lineTo (100.0f, 0.0f);
  53957. fullscreenShape.lineTo (100.0f, 45.0f);
  53958. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53959. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53960. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53961. }
  53962. jassertfalse;
  53963. return 0;
  53964. }
  53965. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53966. int titleBarX,
  53967. int titleBarY,
  53968. int titleBarW,
  53969. int titleBarH,
  53970. Button* minimiseButton,
  53971. Button* maximiseButton,
  53972. Button* closeButton,
  53973. bool positionTitleBarButtonsOnLeft)
  53974. {
  53975. const int buttonW = titleBarH - titleBarH / 8;
  53976. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53977. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53978. if (closeButton != 0)
  53979. {
  53980. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53981. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53982. }
  53983. if (positionTitleBarButtonsOnLeft)
  53984. swapVariables (minimiseButton, maximiseButton);
  53985. if (maximiseButton != 0)
  53986. {
  53987. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53988. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53989. }
  53990. if (minimiseButton != 0)
  53991. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53992. }
  53993. int LookAndFeel::getDefaultMenuBarHeight()
  53994. {
  53995. return 24;
  53996. }
  53997. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53998. {
  53999. return new DropShadower (0.4f, 1, 5, 10);
  54000. }
  54001. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  54002. int w, int h,
  54003. bool /*isVerticalBar*/,
  54004. bool isMouseOver,
  54005. bool isMouseDragging)
  54006. {
  54007. float alpha = 0.5f;
  54008. if (isMouseOver || isMouseDragging)
  54009. {
  54010. g.fillAll (Colour (0x190000ff));
  54011. alpha = 1.0f;
  54012. }
  54013. const float cx = w * 0.5f;
  54014. const float cy = h * 0.5f;
  54015. const float cr = jmin (w, h) * 0.4f;
  54016. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  54017. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  54018. true));
  54019. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  54020. }
  54021. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  54022. const String& text,
  54023. const Justification& position,
  54024. GroupComponent& group)
  54025. {
  54026. const float textH = 15.0f;
  54027. const float indent = 3.0f;
  54028. const float textEdgeGap = 4.0f;
  54029. float cs = 5.0f;
  54030. Font f (textH);
  54031. Path p;
  54032. float x = indent;
  54033. float y = f.getAscent() - 3.0f;
  54034. float w = jmax (0.0f, width - x * 2.0f);
  54035. float h = jmax (0.0f, height - y - indent);
  54036. cs = jmin (cs, w * 0.5f, h * 0.5f);
  54037. const float cs2 = 2.0f * cs;
  54038. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  54039. float textX = cs + textEdgeGap;
  54040. if (position.testFlags (Justification::horizontallyCentred))
  54041. textX = cs + (w - cs2 - textW) * 0.5f;
  54042. else if (position.testFlags (Justification::right))
  54043. textX = w - cs - textW - textEdgeGap;
  54044. p.startNewSubPath (x + textX + textW, y);
  54045. p.lineTo (x + w - cs, y);
  54046. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  54047. p.lineTo (x + w, y + h - cs);
  54048. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54049. p.lineTo (x + cs, y + h);
  54050. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54051. p.lineTo (x, y + cs);
  54052. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54053. p.lineTo (x + textX, y);
  54054. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  54055. g.setColour (group.findColour (GroupComponent::outlineColourId)
  54056. .withMultipliedAlpha (alpha));
  54057. g.strokePath (p, PathStrokeType (2.0f));
  54058. g.setColour (group.findColour (GroupComponent::textColourId)
  54059. .withMultipliedAlpha (alpha));
  54060. g.setFont (f);
  54061. g.drawText (text,
  54062. roundToInt (x + textX), 0,
  54063. roundToInt (textW),
  54064. roundToInt (textH),
  54065. Justification::centred, true);
  54066. }
  54067. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  54068. {
  54069. return 1 + tabDepth / 3;
  54070. }
  54071. int LookAndFeel::getTabButtonSpaceAroundImage()
  54072. {
  54073. return 4;
  54074. }
  54075. void LookAndFeel::createTabButtonShape (Path& p,
  54076. int width, int height,
  54077. int /*tabIndex*/,
  54078. const String& /*text*/,
  54079. Button& /*button*/,
  54080. TabbedButtonBar::Orientation orientation,
  54081. const bool /*isMouseOver*/,
  54082. const bool /*isMouseDown*/,
  54083. const bool /*isFrontTab*/)
  54084. {
  54085. const float w = (float) width;
  54086. const float h = (float) height;
  54087. float length = w;
  54088. float depth = h;
  54089. if (orientation == TabbedButtonBar::TabsAtLeft
  54090. || orientation == TabbedButtonBar::TabsAtRight)
  54091. {
  54092. swapVariables (length, depth);
  54093. }
  54094. const float indent = (float) getTabButtonOverlap ((int) depth);
  54095. const float overhang = 4.0f;
  54096. if (orientation == TabbedButtonBar::TabsAtLeft)
  54097. {
  54098. p.startNewSubPath (w, 0.0f);
  54099. p.lineTo (0.0f, indent);
  54100. p.lineTo (0.0f, h - indent);
  54101. p.lineTo (w, h);
  54102. p.lineTo (w + overhang, h + overhang);
  54103. p.lineTo (w + overhang, -overhang);
  54104. }
  54105. else if (orientation == TabbedButtonBar::TabsAtRight)
  54106. {
  54107. p.startNewSubPath (0.0f, 0.0f);
  54108. p.lineTo (w, indent);
  54109. p.lineTo (w, h - indent);
  54110. p.lineTo (0.0f, h);
  54111. p.lineTo (-overhang, h + overhang);
  54112. p.lineTo (-overhang, -overhang);
  54113. }
  54114. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54115. {
  54116. p.startNewSubPath (0.0f, 0.0f);
  54117. p.lineTo (indent, h);
  54118. p.lineTo (w - indent, h);
  54119. p.lineTo (w, 0.0f);
  54120. p.lineTo (w + overhang, -overhang);
  54121. p.lineTo (-overhang, -overhang);
  54122. }
  54123. else
  54124. {
  54125. p.startNewSubPath (0.0f, h);
  54126. p.lineTo (indent, 0.0f);
  54127. p.lineTo (w - indent, 0.0f);
  54128. p.lineTo (w, h);
  54129. p.lineTo (w + overhang, h + overhang);
  54130. p.lineTo (-overhang, h + overhang);
  54131. }
  54132. p.closeSubPath();
  54133. p = p.createPathWithRoundedCorners (3.0f);
  54134. }
  54135. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54136. const Path& path,
  54137. const Colour& preferredColour,
  54138. int /*tabIndex*/,
  54139. const String& /*text*/,
  54140. Button& button,
  54141. TabbedButtonBar::Orientation /*orientation*/,
  54142. const bool /*isMouseOver*/,
  54143. const bool /*isMouseDown*/,
  54144. const bool isFrontTab)
  54145. {
  54146. g.setColour (isFrontTab ? preferredColour
  54147. : preferredColour.withMultipliedAlpha (0.9f));
  54148. g.fillPath (path);
  54149. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54150. : TabbedButtonBar::tabOutlineColourId, false)
  54151. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54152. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54153. }
  54154. void LookAndFeel::drawTabButtonText (Graphics& g,
  54155. int x, int y, int w, int h,
  54156. const Colour& preferredBackgroundColour,
  54157. int /*tabIndex*/,
  54158. const String& text,
  54159. Button& button,
  54160. TabbedButtonBar::Orientation orientation,
  54161. const bool isMouseOver,
  54162. const bool isMouseDown,
  54163. const bool isFrontTab)
  54164. {
  54165. int length = w;
  54166. int depth = h;
  54167. if (orientation == TabbedButtonBar::TabsAtLeft
  54168. || orientation == TabbedButtonBar::TabsAtRight)
  54169. {
  54170. swapVariables (length, depth);
  54171. }
  54172. Font font (depth * 0.6f);
  54173. font.setUnderline (button.hasKeyboardFocus (false));
  54174. GlyphArrangement textLayout;
  54175. textLayout.addFittedText (font, text.trim(),
  54176. 0.0f, 0.0f, (float) length, (float) depth,
  54177. Justification::centred,
  54178. jmax (1, depth / 12));
  54179. AffineTransform transform;
  54180. if (orientation == TabbedButtonBar::TabsAtLeft)
  54181. {
  54182. transform = transform.rotated (float_Pi * -0.5f)
  54183. .translated ((float) x, (float) (y + h));
  54184. }
  54185. else if (orientation == TabbedButtonBar::TabsAtRight)
  54186. {
  54187. transform = transform.rotated (float_Pi * 0.5f)
  54188. .translated ((float) (x + w), (float) y);
  54189. }
  54190. else
  54191. {
  54192. transform = transform.translated ((float) x, (float) y);
  54193. }
  54194. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54195. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54196. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54197. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54198. else
  54199. g.setColour (preferredBackgroundColour.contrasting());
  54200. if (! (isMouseOver || isMouseDown))
  54201. g.setOpacity (0.8f);
  54202. if (! button.isEnabled())
  54203. g.setOpacity (0.3f);
  54204. textLayout.draw (g, transform);
  54205. }
  54206. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54207. const String& text,
  54208. int tabDepth,
  54209. Button&)
  54210. {
  54211. Font f (tabDepth * 0.6f);
  54212. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54213. }
  54214. void LookAndFeel::drawTabButton (Graphics& g,
  54215. int w, int h,
  54216. const Colour& preferredColour,
  54217. int tabIndex,
  54218. const String& text,
  54219. Button& button,
  54220. TabbedButtonBar::Orientation orientation,
  54221. const bool isMouseOver,
  54222. const bool isMouseDown,
  54223. const bool isFrontTab)
  54224. {
  54225. int length = w;
  54226. int depth = h;
  54227. if (orientation == TabbedButtonBar::TabsAtLeft
  54228. || orientation == TabbedButtonBar::TabsAtRight)
  54229. {
  54230. swapVariables (length, depth);
  54231. }
  54232. Path tabShape;
  54233. createTabButtonShape (tabShape, w, h,
  54234. tabIndex, text, button, orientation,
  54235. isMouseOver, isMouseDown, isFrontTab);
  54236. fillTabButtonShape (g, tabShape, preferredColour,
  54237. tabIndex, text, button, orientation,
  54238. isMouseOver, isMouseDown, isFrontTab);
  54239. const int indent = getTabButtonOverlap (depth);
  54240. int x = 0, y = 0;
  54241. if (orientation == TabbedButtonBar::TabsAtLeft
  54242. || orientation == TabbedButtonBar::TabsAtRight)
  54243. {
  54244. y += indent;
  54245. h -= indent * 2;
  54246. }
  54247. else
  54248. {
  54249. x += indent;
  54250. w -= indent * 2;
  54251. }
  54252. drawTabButtonText (g, x, y, w, h, preferredColour,
  54253. tabIndex, text, button, orientation,
  54254. isMouseOver, isMouseDown, isFrontTab);
  54255. }
  54256. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54257. int w, int h,
  54258. TabbedButtonBar& tabBar,
  54259. TabbedButtonBar::Orientation orientation)
  54260. {
  54261. const float shadowSize = 0.2f;
  54262. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54263. Rectangle<int> shadowRect;
  54264. if (orientation == TabbedButtonBar::TabsAtLeft)
  54265. {
  54266. x1 = (float) w;
  54267. x2 = w * (1.0f - shadowSize);
  54268. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54269. }
  54270. else if (orientation == TabbedButtonBar::TabsAtRight)
  54271. {
  54272. x2 = w * shadowSize;
  54273. shadowRect.setBounds (0, 0, (int) x2, h);
  54274. }
  54275. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54276. {
  54277. y2 = h * shadowSize;
  54278. shadowRect.setBounds (0, 0, w, (int) y2);
  54279. }
  54280. else
  54281. {
  54282. y1 = (float) h;
  54283. y2 = h * (1.0f - shadowSize);
  54284. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54285. }
  54286. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54287. Colours::transparentBlack, x2, y2, false));
  54288. shadowRect.expand (2, 2);
  54289. g.fillRect (shadowRect);
  54290. g.setColour (Colour (0x80000000));
  54291. if (orientation == TabbedButtonBar::TabsAtLeft)
  54292. {
  54293. g.fillRect (w - 1, 0, 1, h);
  54294. }
  54295. else if (orientation == TabbedButtonBar::TabsAtRight)
  54296. {
  54297. g.fillRect (0, 0, 1, h);
  54298. }
  54299. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54300. {
  54301. g.fillRect (0, 0, w, 1);
  54302. }
  54303. else
  54304. {
  54305. g.fillRect (0, h - 1, w, 1);
  54306. }
  54307. }
  54308. Button* LookAndFeel::createTabBarExtrasButton()
  54309. {
  54310. const float thickness = 7.0f;
  54311. const float indent = 22.0f;
  54312. Path p;
  54313. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54314. DrawablePath ellipse;
  54315. ellipse.setPath (p);
  54316. ellipse.setFill (Colour (0x99ffffff));
  54317. p.clear();
  54318. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54319. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54320. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54321. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54322. p.setUsingNonZeroWinding (false);
  54323. DrawablePath dp;
  54324. dp.setPath (p);
  54325. dp.setFill (Colour (0x59000000));
  54326. DrawableComposite normalImage;
  54327. normalImage.addAndMakeVisible (ellipse.createCopy());
  54328. normalImage.addAndMakeVisible (dp.createCopy());
  54329. dp.setFill (Colour (0xcc000000));
  54330. DrawableComposite overImage;
  54331. overImage.addAndMakeVisible (ellipse.createCopy());
  54332. overImage.addAndMakeVisible (dp.createCopy());
  54333. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54334. db->setImages (&normalImage, &overImage, 0);
  54335. return db;
  54336. }
  54337. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54338. {
  54339. g.fillAll (Colours::white);
  54340. const int w = header.getWidth();
  54341. const int h = header.getHeight();
  54342. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54343. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54344. false));
  54345. g.fillRect (0, h / 2, w, h);
  54346. g.setColour (Colour (0x33000000));
  54347. g.fillRect (0, h - 1, w, 1);
  54348. for (int i = header.getNumColumns (true); --i >= 0;)
  54349. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54350. }
  54351. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54352. int width, int height,
  54353. bool isMouseOver, bool isMouseDown,
  54354. int columnFlags)
  54355. {
  54356. if (isMouseDown)
  54357. g.fillAll (Colour (0x8899aadd));
  54358. else if (isMouseOver)
  54359. g.fillAll (Colour (0x5599aadd));
  54360. int rightOfText = width - 4;
  54361. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54362. {
  54363. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54364. const float bottom = height - top;
  54365. const float w = height * 0.5f;
  54366. const float x = rightOfText - (w * 1.25f);
  54367. rightOfText = (int) x;
  54368. Path sortArrow;
  54369. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54370. g.setColour (Colour (0x99000000));
  54371. g.fillPath (sortArrow);
  54372. }
  54373. g.setColour (Colours::black);
  54374. g.setFont (height * 0.5f, Font::bold);
  54375. const int textX = 4;
  54376. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54377. }
  54378. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54379. {
  54380. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54381. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54382. background.darker (0.1f),
  54383. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54384. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54385. false));
  54386. g.fillAll();
  54387. }
  54388. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54389. {
  54390. return createTabBarExtrasButton();
  54391. }
  54392. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54393. bool isMouseOver, bool isMouseDown,
  54394. ToolbarItemComponent& component)
  54395. {
  54396. if (isMouseDown)
  54397. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54398. else if (isMouseOver)
  54399. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54400. }
  54401. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54402. const String& text, ToolbarItemComponent& component)
  54403. {
  54404. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54405. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54406. const float fontHeight = jmin (14.0f, height * 0.85f);
  54407. g.setFont (fontHeight);
  54408. g.drawFittedText (text,
  54409. x, y, width, height,
  54410. Justification::centred,
  54411. jmax (1, height / (int) fontHeight));
  54412. }
  54413. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54414. bool isOpen, int width, int height)
  54415. {
  54416. const int buttonSize = (height * 3) / 4;
  54417. const int buttonIndent = (height - buttonSize) / 2;
  54418. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54419. const int textX = buttonIndent * 2 + buttonSize + 2;
  54420. g.setColour (Colours::black);
  54421. g.setFont (height * 0.7f, Font::bold);
  54422. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54423. }
  54424. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54425. PropertyComponent&)
  54426. {
  54427. g.setColour (Colour (0x66ffffff));
  54428. g.fillRect (0, 0, width, height - 1);
  54429. }
  54430. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54431. PropertyComponent& component)
  54432. {
  54433. g.setColour (Colours::black);
  54434. if (! component.isEnabled())
  54435. g.setOpacity (0.6f);
  54436. g.setFont (jmin (height, 24) * 0.65f);
  54437. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54438. g.drawFittedText (component.getName(),
  54439. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54440. Justification::centredLeft, 2);
  54441. }
  54442. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54443. {
  54444. return Rectangle<int> (component.getWidth() / 3, 1,
  54445. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54446. }
  54447. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54448. {
  54449. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54450. {
  54451. Graphics g2 (content);
  54452. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54453. g2.fillPath (path);
  54454. g2.setColour (Colours::white.withAlpha (0.8f));
  54455. g2.strokePath (path, PathStrokeType (2.0f));
  54456. }
  54457. DropShadowEffect shadow;
  54458. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54459. shadow.applyEffect (content, g, 1.0f);
  54460. }
  54461. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54462. const String& instructions,
  54463. GlyphArrangement& text,
  54464. int width)
  54465. {
  54466. text.clear();
  54467. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54468. 8.0f, 22.0f, width - 16.0f,
  54469. Justification::centred);
  54470. text.addJustifiedText (Font (14.0f), instructions,
  54471. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54472. Justification::centred);
  54473. }
  54474. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54475. const String& filename, Image* icon,
  54476. const String& fileSizeDescription,
  54477. const String& fileTimeDescription,
  54478. const bool isDirectory,
  54479. const bool isItemSelected,
  54480. const int /*itemIndex*/,
  54481. DirectoryContentsDisplayComponent&)
  54482. {
  54483. if (isItemSelected)
  54484. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54485. const int x = 32;
  54486. g.setColour (Colours::black);
  54487. if (icon != 0 && icon->isValid())
  54488. {
  54489. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54490. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54491. false);
  54492. }
  54493. else
  54494. {
  54495. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54496. : getDefaultDocumentFileImage();
  54497. if (d != 0)
  54498. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54499. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54500. }
  54501. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54502. g.setFont (height * 0.7f);
  54503. if (width > 450 && ! isDirectory)
  54504. {
  54505. const int sizeX = roundToInt (width * 0.7f);
  54506. const int dateX = roundToInt (width * 0.8f);
  54507. g.drawFittedText (filename,
  54508. x, 0, sizeX - x, height,
  54509. Justification::centredLeft, 1);
  54510. g.setFont (height * 0.5f);
  54511. g.setColour (Colours::darkgrey);
  54512. if (! isDirectory)
  54513. {
  54514. g.drawFittedText (fileSizeDescription,
  54515. sizeX, 0, dateX - sizeX - 8, height,
  54516. Justification::centredRight, 1);
  54517. g.drawFittedText (fileTimeDescription,
  54518. dateX, 0, width - 8 - dateX, height,
  54519. Justification::centredRight, 1);
  54520. }
  54521. }
  54522. else
  54523. {
  54524. g.drawFittedText (filename,
  54525. x, 0, width - x, height,
  54526. Justification::centredLeft, 1);
  54527. }
  54528. }
  54529. Button* LookAndFeel::createFileBrowserGoUpButton()
  54530. {
  54531. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54532. Path arrowPath;
  54533. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54534. DrawablePath arrowImage;
  54535. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54536. arrowImage.setPath (arrowPath);
  54537. goUpButton->setImages (&arrowImage);
  54538. return goUpButton;
  54539. }
  54540. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54541. DirectoryContentsDisplayComponent* fileListComponent,
  54542. FilePreviewComponent* previewComp,
  54543. ComboBox* currentPathBox,
  54544. TextEditor* filenameBox,
  54545. Button* goUpButton)
  54546. {
  54547. const int x = 8;
  54548. int w = browserComp.getWidth() - x - x;
  54549. if (previewComp != 0)
  54550. {
  54551. const int previewWidth = w / 3;
  54552. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54553. w -= previewWidth + 4;
  54554. }
  54555. int y = 4;
  54556. const int controlsHeight = 22;
  54557. const int bottomSectionHeight = controlsHeight + 8;
  54558. const int upButtonWidth = 50;
  54559. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54560. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54561. y += controlsHeight + 4;
  54562. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54563. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54564. y = listAsComp->getBottom() + 4;
  54565. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54566. }
  54567. // Pulls a drawable out of compressed valuetree data..
  54568. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54569. {
  54570. MemoryInputStream m (data, numBytes, false);
  54571. GZIPDecompressorInputStream gz (m);
  54572. ValueTree drawable (ValueTree::readFromStream (gz));
  54573. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54574. }
  54575. const Drawable* LookAndFeel::getDefaultFolderImage()
  54576. {
  54577. if (folderImage == 0)
  54578. {
  54579. static const unsigned char drawableData[] =
  54580. { 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,
  54581. 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,
  54582. 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,
  54583. 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,
  54584. 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,
  54585. 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,
  54586. 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,
  54587. 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,
  54588. 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,
  54589. 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,
  54590. 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,
  54591. 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,
  54592. 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,
  54593. 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,
  54594. 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 };
  54595. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54596. }
  54597. return folderImage;
  54598. }
  54599. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54600. {
  54601. if (documentImage == 0)
  54602. {
  54603. static const unsigned char drawableData[] =
  54604. { 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,
  54605. 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,
  54606. 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,
  54607. 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,
  54608. 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,
  54609. 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,
  54610. 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,
  54611. 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,
  54612. 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,
  54613. 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,
  54614. 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,
  54615. 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,
  54616. 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,
  54617. 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,
  54618. 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,
  54619. 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,
  54620. 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,
  54621. 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,
  54622. 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,
  54623. 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,
  54624. 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,
  54625. 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,
  54626. 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 };
  54627. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54628. }
  54629. return documentImage;
  54630. }
  54631. void LookAndFeel::playAlertSound()
  54632. {
  54633. PlatformUtilities::beep();
  54634. }
  54635. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54636. {
  54637. g.setColour (Colours::white.withAlpha (0.7f));
  54638. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54639. g.setColour (Colours::black.withAlpha (0.2f));
  54640. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54641. const int totalBlocks = 7;
  54642. const int numBlocks = roundToInt (totalBlocks * level);
  54643. const float w = (width - 6.0f) / (float) totalBlocks;
  54644. for (int i = 0; i < totalBlocks; ++i)
  54645. {
  54646. if (i >= numBlocks)
  54647. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54648. else
  54649. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54650. : Colours::red);
  54651. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54652. }
  54653. }
  54654. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54655. {
  54656. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54657. if (keyDescription.isNotEmpty())
  54658. {
  54659. if (button.isEnabled())
  54660. {
  54661. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54662. g.fillAll (textColour.withAlpha (alpha));
  54663. g.setOpacity (0.3f);
  54664. g.drawBevel (0, 0, width, height, 2);
  54665. }
  54666. g.setColour (textColour);
  54667. g.setFont (height * 0.6f);
  54668. g.drawFittedText (keyDescription,
  54669. 3, 0, width - 6, height,
  54670. Justification::centred, 1);
  54671. }
  54672. else
  54673. {
  54674. const float thickness = 7.0f;
  54675. const float indent = 22.0f;
  54676. Path p;
  54677. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54678. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54679. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54680. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54681. p.setUsingNonZeroWinding (false);
  54682. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54683. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54684. }
  54685. if (button.hasKeyboardFocus (false))
  54686. {
  54687. g.setColour (textColour.withAlpha (0.4f));
  54688. g.drawRect (0, 0, width, height);
  54689. }
  54690. }
  54691. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54692. float x, float y, float w, float h,
  54693. float maxCornerSize,
  54694. const Colour& baseColour,
  54695. const float strokeWidth,
  54696. const bool flatOnLeft,
  54697. const bool flatOnRight,
  54698. const bool flatOnTop,
  54699. const bool flatOnBottom) throw()
  54700. {
  54701. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54702. return;
  54703. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54704. Path outline;
  54705. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54706. ! (flatOnLeft || flatOnTop),
  54707. ! (flatOnRight || flatOnTop),
  54708. ! (flatOnLeft || flatOnBottom),
  54709. ! (flatOnRight || flatOnBottom));
  54710. ColourGradient cg (baseColour, 0.0f, y,
  54711. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54712. false);
  54713. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54714. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54715. g.setGradientFill (cg);
  54716. g.fillPath (outline);
  54717. g.setColour (Colour (0x80000000));
  54718. g.strokePath (outline, PathStrokeType (strokeWidth));
  54719. }
  54720. void LookAndFeel::drawGlassSphere (Graphics& g,
  54721. const float x, const float y,
  54722. const float diameter,
  54723. const Colour& colour,
  54724. const float outlineThickness) throw()
  54725. {
  54726. if (diameter <= outlineThickness)
  54727. return;
  54728. Path p;
  54729. p.addEllipse (x, y, diameter, diameter);
  54730. {
  54731. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54732. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54733. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54734. g.setGradientFill (cg);
  54735. g.fillPath (p);
  54736. }
  54737. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54738. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54739. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54740. ColourGradient cg (Colours::transparentBlack,
  54741. x + diameter * 0.5f, y + diameter * 0.5f,
  54742. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54743. x, y + diameter * 0.5f, true);
  54744. cg.addColour (0.7, Colours::transparentBlack);
  54745. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54746. g.setGradientFill (cg);
  54747. g.fillPath (p);
  54748. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54749. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54750. }
  54751. void LookAndFeel::drawGlassPointer (Graphics& g,
  54752. const float x, const float y,
  54753. const float diameter,
  54754. const Colour& colour, const float outlineThickness,
  54755. const int direction) throw()
  54756. {
  54757. if (diameter <= outlineThickness)
  54758. return;
  54759. Path p;
  54760. p.startNewSubPath (x + diameter * 0.5f, y);
  54761. p.lineTo (x + diameter, y + diameter * 0.6f);
  54762. p.lineTo (x + diameter, y + diameter);
  54763. p.lineTo (x, y + diameter);
  54764. p.lineTo (x, y + diameter * 0.6f);
  54765. p.closeSubPath();
  54766. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54767. {
  54768. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54769. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54770. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54771. g.setGradientFill (cg);
  54772. g.fillPath (p);
  54773. }
  54774. ColourGradient cg (Colours::transparentBlack,
  54775. x + diameter * 0.5f, y + diameter * 0.5f,
  54776. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54777. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54778. cg.addColour (0.5, Colours::transparentBlack);
  54779. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54780. g.setGradientFill (cg);
  54781. g.fillPath (p);
  54782. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54783. g.strokePath (p, PathStrokeType (outlineThickness));
  54784. }
  54785. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54786. const float x, const float y,
  54787. const float width, const float height,
  54788. const Colour& colour,
  54789. const float outlineThickness,
  54790. const float cornerSize,
  54791. const bool flatOnLeft,
  54792. const bool flatOnRight,
  54793. const bool flatOnTop,
  54794. const bool flatOnBottom) throw()
  54795. {
  54796. if (width <= outlineThickness || height <= outlineThickness)
  54797. return;
  54798. const int intX = (int) x;
  54799. const int intY = (int) y;
  54800. const int intW = (int) width;
  54801. const int intH = (int) height;
  54802. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54803. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54804. const int intEdge = (int) edgeBlurRadius;
  54805. Path outline;
  54806. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54807. ! (flatOnLeft || flatOnTop),
  54808. ! (flatOnRight || flatOnTop),
  54809. ! (flatOnLeft || flatOnBottom),
  54810. ! (flatOnRight || flatOnBottom));
  54811. {
  54812. ColourGradient cg (colour.darker (0.2f), 0, y,
  54813. colour.darker (0.2f), 0, y + height, false);
  54814. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54815. cg.addColour (0.4, colour);
  54816. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54817. g.setGradientFill (cg);
  54818. g.fillPath (outline);
  54819. }
  54820. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54821. colour.darker (0.2f), x, y + height * 0.5f, true);
  54822. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54823. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54824. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54825. {
  54826. g.saveState();
  54827. g.setGradientFill (cg);
  54828. g.reduceClipRegion (intX, intY, intEdge, intH);
  54829. g.fillPath (outline);
  54830. g.restoreState();
  54831. }
  54832. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54833. {
  54834. cg.point1.setX (x + width - edgeBlurRadius);
  54835. cg.point2.setX (x + width);
  54836. g.saveState();
  54837. g.setGradientFill (cg);
  54838. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54839. g.fillPath (outline);
  54840. g.restoreState();
  54841. }
  54842. {
  54843. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54844. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54845. Path highlight;
  54846. LookAndFeelHelpers::createRoundedPath (highlight,
  54847. x + leftIndent,
  54848. y + cs * 0.1f,
  54849. width - (leftIndent + rightIndent),
  54850. height * 0.4f, cs * 0.4f,
  54851. ! (flatOnLeft || flatOnTop),
  54852. ! (flatOnRight || flatOnTop),
  54853. ! (flatOnLeft || flatOnBottom),
  54854. ! (flatOnRight || flatOnBottom));
  54855. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54856. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54857. g.fillPath (highlight);
  54858. }
  54859. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54860. g.strokePath (outline, PathStrokeType (outlineThickness));
  54861. }
  54862. END_JUCE_NAMESPACE
  54863. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54864. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54865. BEGIN_JUCE_NAMESPACE
  54866. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54867. {
  54868. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54869. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54870. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54871. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54872. setColour (Slider::thumbColourId, Colours::white);
  54873. setColour (Slider::trackColourId, Colour (0x7f000000));
  54874. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54875. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54876. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54877. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54878. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54879. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54880. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54881. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54882. }
  54883. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54884. {
  54885. }
  54886. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54887. Button& button,
  54888. const Colour& backgroundColour,
  54889. bool isMouseOverButton,
  54890. bool isButtonDown)
  54891. {
  54892. const int width = button.getWidth();
  54893. const int height = button.getHeight();
  54894. const float indent = 2.0f;
  54895. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54896. roundToInt (height * 0.4f));
  54897. Path p;
  54898. p.addRoundedRectangle (indent, indent,
  54899. width - indent * 2.0f,
  54900. height - indent * 2.0f,
  54901. (float) cornerSize);
  54902. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54903. if (isMouseOverButton)
  54904. {
  54905. if (isButtonDown)
  54906. bc = bc.brighter();
  54907. else if (bc.getBrightness() > 0.5f)
  54908. bc = bc.darker (0.1f);
  54909. else
  54910. bc = bc.brighter (0.1f);
  54911. }
  54912. g.setColour (bc);
  54913. g.fillPath (p);
  54914. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54915. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54916. }
  54917. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54918. Component& /*component*/,
  54919. float x, float y, float w, float h,
  54920. const bool ticked,
  54921. const bool isEnabled,
  54922. const bool /*isMouseOverButton*/,
  54923. const bool isButtonDown)
  54924. {
  54925. Path box;
  54926. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54927. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54928. : Colours::lightgrey.withAlpha (0.1f));
  54929. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54930. g.fillPath (box, trans);
  54931. g.setColour (Colours::black.withAlpha (0.6f));
  54932. g.strokePath (box, PathStrokeType (0.9f), trans);
  54933. if (ticked)
  54934. {
  54935. Path tick;
  54936. tick.startNewSubPath (1.5f, 3.0f);
  54937. tick.lineTo (3.0f, 6.0f);
  54938. tick.lineTo (6.0f, 0.0f);
  54939. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54940. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54941. }
  54942. }
  54943. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54944. ToggleButton& button,
  54945. bool isMouseOverButton,
  54946. bool isButtonDown)
  54947. {
  54948. if (button.hasKeyboardFocus (true))
  54949. {
  54950. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54951. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54952. }
  54953. const int tickWidth = jmin (20, button.getHeight() - 4);
  54954. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54955. (float) tickWidth, (float) tickWidth,
  54956. button.getToggleState(),
  54957. button.isEnabled(),
  54958. isMouseOverButton,
  54959. isButtonDown);
  54960. g.setColour (button.findColour (ToggleButton::textColourId));
  54961. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54962. if (! button.isEnabled())
  54963. g.setOpacity (0.5f);
  54964. const int textX = tickWidth + 5;
  54965. g.drawFittedText (button.getButtonText(),
  54966. textX, 4,
  54967. button.getWidth() - textX - 2, button.getHeight() - 8,
  54968. Justification::centredLeft, 10);
  54969. }
  54970. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54971. int width, int height,
  54972. double progress, const String& textToShow)
  54973. {
  54974. if (progress < 0 || progress >= 1.0)
  54975. {
  54976. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54977. }
  54978. else
  54979. {
  54980. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54981. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54982. g.fillAll (background);
  54983. g.setColour (foreground);
  54984. g.fillRect (1, 1,
  54985. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54986. height - 2);
  54987. if (textToShow.isNotEmpty())
  54988. {
  54989. g.setColour (Colour::contrasting (background, foreground));
  54990. g.setFont (height * 0.6f);
  54991. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54992. }
  54993. }
  54994. }
  54995. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54996. ScrollBar& bar,
  54997. int width, int height,
  54998. int buttonDirection,
  54999. bool isScrollbarVertical,
  55000. bool isMouseOverButton,
  55001. bool isButtonDown)
  55002. {
  55003. if (isScrollbarVertical)
  55004. width -= 2;
  55005. else
  55006. height -= 2;
  55007. Path p;
  55008. if (buttonDirection == 0)
  55009. p.addTriangle (width * 0.5f, height * 0.2f,
  55010. width * 0.1f, height * 0.7f,
  55011. width * 0.9f, height * 0.7f);
  55012. else if (buttonDirection == 1)
  55013. p.addTriangle (width * 0.8f, height * 0.5f,
  55014. width * 0.3f, height * 0.1f,
  55015. width * 0.3f, height * 0.9f);
  55016. else if (buttonDirection == 2)
  55017. p.addTriangle (width * 0.5f, height * 0.8f,
  55018. width * 0.1f, height * 0.3f,
  55019. width * 0.9f, height * 0.3f);
  55020. else if (buttonDirection == 3)
  55021. p.addTriangle (width * 0.2f, height * 0.5f,
  55022. width * 0.7f, height * 0.1f,
  55023. width * 0.7f, height * 0.9f);
  55024. if (isButtonDown)
  55025. g.setColour (Colours::white);
  55026. else if (isMouseOverButton)
  55027. g.setColour (Colours::white.withAlpha (0.7f));
  55028. else
  55029. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  55030. g.fillPath (p);
  55031. g.setColour (Colours::black.withAlpha (0.5f));
  55032. g.strokePath (p, PathStrokeType (0.5f));
  55033. }
  55034. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55035. ScrollBar& bar,
  55036. int x, int y,
  55037. int width, int height,
  55038. bool isScrollbarVertical,
  55039. int thumbStartPosition,
  55040. int thumbSize,
  55041. bool isMouseOver,
  55042. bool isMouseDown)
  55043. {
  55044. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55045. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55046. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55047. if (thumbSize > 0.0f)
  55048. {
  55049. Rectangle<int> thumb;
  55050. if (isScrollbarVertical)
  55051. {
  55052. width -= 2;
  55053. g.fillRect (x + roundToInt (width * 0.35f), y,
  55054. roundToInt (width * 0.3f), height);
  55055. thumb.setBounds (x + 1, thumbStartPosition,
  55056. width - 2, thumbSize);
  55057. }
  55058. else
  55059. {
  55060. height -= 2;
  55061. g.fillRect (x, y + roundToInt (height * 0.35f),
  55062. width, roundToInt (height * 0.3f));
  55063. thumb.setBounds (thumbStartPosition, y + 1,
  55064. thumbSize, height - 2);
  55065. }
  55066. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55067. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55068. g.fillRect (thumb);
  55069. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55070. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55071. if (thumbSize > 16)
  55072. {
  55073. for (int i = 3; --i >= 0;)
  55074. {
  55075. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55076. g.setColour (Colours::black.withAlpha (0.15f));
  55077. if (isScrollbarVertical)
  55078. {
  55079. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55080. g.setColour (Colours::white.withAlpha (0.15f));
  55081. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55082. }
  55083. else
  55084. {
  55085. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55086. g.setColour (Colours::white.withAlpha (0.15f));
  55087. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55088. }
  55089. }
  55090. }
  55091. }
  55092. }
  55093. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55094. {
  55095. return &scrollbarShadow;
  55096. }
  55097. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55098. {
  55099. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55100. g.setColour (Colours::black.withAlpha (0.6f));
  55101. g.drawRect (0, 0, width, height);
  55102. }
  55103. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55104. bool, MenuBarComponent& menuBar)
  55105. {
  55106. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55107. }
  55108. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55109. {
  55110. if (textEditor.isEnabled())
  55111. {
  55112. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55113. g.drawRect (0, 0, width, height);
  55114. }
  55115. }
  55116. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55117. const bool isButtonDown,
  55118. int buttonX, int buttonY,
  55119. int buttonW, int buttonH,
  55120. ComboBox& box)
  55121. {
  55122. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55123. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55124. : ComboBox::backgroundColourId));
  55125. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55126. g.setColour (box.findColour (ComboBox::outlineColourId));
  55127. g.drawRect (0, 0, width, height);
  55128. const float arrowX = 0.2f;
  55129. const float arrowH = 0.3f;
  55130. if (box.isEnabled())
  55131. {
  55132. Path p;
  55133. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55134. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55135. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55136. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55137. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55138. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55139. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55140. : ComboBox::buttonColourId));
  55141. g.fillPath (p);
  55142. }
  55143. }
  55144. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55145. {
  55146. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55147. f.setHorizontalScale (0.9f);
  55148. return f;
  55149. }
  55150. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55151. {
  55152. Path p;
  55153. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55154. g.setColour (fill);
  55155. g.fillPath (p);
  55156. g.setColour (outline);
  55157. g.strokePath (p, PathStrokeType (0.3f));
  55158. }
  55159. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55160. int x, int y,
  55161. int w, int h,
  55162. float sliderPos,
  55163. float minSliderPos,
  55164. float maxSliderPos,
  55165. const Slider::SliderStyle style,
  55166. Slider& slider)
  55167. {
  55168. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55169. if (style == Slider::LinearBar)
  55170. {
  55171. g.setColour (slider.findColour (Slider::thumbColourId));
  55172. g.fillRect (x, y, (int) sliderPos - x, h);
  55173. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55174. g.drawRect (x, y, (int) sliderPos - x, h);
  55175. }
  55176. else
  55177. {
  55178. g.setColour (slider.findColour (Slider::trackColourId)
  55179. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55180. if (slider.isHorizontal())
  55181. {
  55182. g.fillRect (x, y + roundToInt (h * 0.6f),
  55183. w, roundToInt (h * 0.2f));
  55184. }
  55185. else
  55186. {
  55187. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55188. jmin (4, roundToInt (w * 0.2f)), h);
  55189. }
  55190. float alpha = 0.35f;
  55191. if (slider.isEnabled())
  55192. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55193. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55194. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55195. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55196. {
  55197. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55198. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55199. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55200. fill, outline);
  55201. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55202. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55203. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55204. fill, outline);
  55205. }
  55206. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55207. {
  55208. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55209. minSliderPos - 7.0f, y + h * 0.9f ,
  55210. minSliderPos, y + h * 0.9f,
  55211. fill, outline);
  55212. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55213. maxSliderPos, y + h * 0.9f,
  55214. maxSliderPos + 7.0f, y + h * 0.9f,
  55215. fill, outline);
  55216. }
  55217. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55218. {
  55219. drawTriangle (g, sliderPos, y + h * 0.9f,
  55220. sliderPos - 7.0f, y + h * 0.2f,
  55221. sliderPos + 7.0f, y + h * 0.2f,
  55222. fill, outline);
  55223. }
  55224. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55225. {
  55226. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55227. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55228. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55229. fill, outline);
  55230. }
  55231. }
  55232. }
  55233. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55234. {
  55235. if (isIncrement)
  55236. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55237. else
  55238. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55239. }
  55240. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55241. {
  55242. return &scrollbarShadow;
  55243. }
  55244. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55245. {
  55246. return 8;
  55247. }
  55248. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55249. int w, int h,
  55250. bool isMouseOver,
  55251. bool isMouseDragging)
  55252. {
  55253. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55254. : Colours::darkgrey);
  55255. const float lineThickness = jmin (w, h) * 0.1f;
  55256. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55257. {
  55258. g.drawLine (w * i,
  55259. h + 1.0f,
  55260. w + 1.0f,
  55261. h * i,
  55262. lineThickness);
  55263. }
  55264. }
  55265. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55266. {
  55267. Path shape;
  55268. if (buttonType == DocumentWindow::closeButton)
  55269. {
  55270. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55271. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55272. ShapeButton* const b = new ShapeButton ("close",
  55273. Colour (0x7fff3333),
  55274. Colour (0xd7ff3333),
  55275. Colour (0xf7ff3333));
  55276. b->setShape (shape, true, true, true);
  55277. return b;
  55278. }
  55279. else if (buttonType == DocumentWindow::minimiseButton)
  55280. {
  55281. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55282. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55283. DrawablePath dp;
  55284. dp.setPath (shape);
  55285. dp.setFill (Colours::black.withAlpha (0.3f));
  55286. b->setImages (&dp);
  55287. return b;
  55288. }
  55289. else if (buttonType == DocumentWindow::maximiseButton)
  55290. {
  55291. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55292. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55293. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55294. DrawablePath dp;
  55295. dp.setPath (shape);
  55296. dp.setFill (Colours::black.withAlpha (0.3f));
  55297. b->setImages (&dp);
  55298. return b;
  55299. }
  55300. jassertfalse;
  55301. return 0;
  55302. }
  55303. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55304. int titleBarX,
  55305. int titleBarY,
  55306. int titleBarW,
  55307. int titleBarH,
  55308. Button* minimiseButton,
  55309. Button* maximiseButton,
  55310. Button* closeButton,
  55311. bool positionTitleBarButtonsOnLeft)
  55312. {
  55313. titleBarY += titleBarH / 8;
  55314. titleBarH -= titleBarH / 4;
  55315. const int buttonW = titleBarH;
  55316. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55317. : titleBarX + titleBarW - buttonW - 4;
  55318. if (closeButton != 0)
  55319. {
  55320. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55321. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55322. : -(buttonW + buttonW / 5);
  55323. }
  55324. if (positionTitleBarButtonsOnLeft)
  55325. swapVariables (minimiseButton, maximiseButton);
  55326. if (maximiseButton != 0)
  55327. {
  55328. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55329. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55330. }
  55331. if (minimiseButton != 0)
  55332. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55333. }
  55334. END_JUCE_NAMESPACE
  55335. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55336. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55337. BEGIN_JUCE_NAMESPACE
  55338. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55339. : model (0),
  55340. itemUnderMouse (-1),
  55341. currentPopupIndex (-1),
  55342. topLevelIndexClicked (0),
  55343. lastMouseX (0),
  55344. lastMouseY (0)
  55345. {
  55346. setRepaintsOnMouseActivity (true);
  55347. setWantsKeyboardFocus (false);
  55348. setMouseClickGrabsKeyboardFocus (false);
  55349. setModel (model_);
  55350. }
  55351. MenuBarComponent::~MenuBarComponent()
  55352. {
  55353. setModel (0);
  55354. Desktop::getInstance().removeGlobalMouseListener (this);
  55355. }
  55356. MenuBarModel* MenuBarComponent::getModel() const throw()
  55357. {
  55358. return model;
  55359. }
  55360. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55361. {
  55362. if (model != newModel)
  55363. {
  55364. if (model != 0)
  55365. model->removeListener (this);
  55366. model = newModel;
  55367. if (model != 0)
  55368. model->addListener (this);
  55369. repaint();
  55370. menuBarItemsChanged (0);
  55371. }
  55372. }
  55373. void MenuBarComponent::paint (Graphics& g)
  55374. {
  55375. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55376. getLookAndFeel().drawMenuBarBackground (g,
  55377. getWidth(),
  55378. getHeight(),
  55379. isMouseOverBar,
  55380. *this);
  55381. if (model != 0)
  55382. {
  55383. for (int i = 0; i < menuNames.size(); ++i)
  55384. {
  55385. Graphics::ScopedSaveState ss (g);
  55386. g.setOrigin (xPositions [i], 0);
  55387. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55388. getLookAndFeel().drawMenuBarItem (g,
  55389. xPositions[i + 1] - xPositions[i],
  55390. getHeight(),
  55391. i,
  55392. menuNames[i],
  55393. i == itemUnderMouse,
  55394. i == currentPopupIndex,
  55395. isMouseOverBar,
  55396. *this);
  55397. }
  55398. }
  55399. }
  55400. void MenuBarComponent::resized()
  55401. {
  55402. xPositions.clear();
  55403. int x = 0;
  55404. xPositions.add (x);
  55405. for (int i = 0; i < menuNames.size(); ++i)
  55406. {
  55407. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55408. xPositions.add (x);
  55409. }
  55410. }
  55411. int MenuBarComponent::getItemAt (const int x, const int y)
  55412. {
  55413. for (int i = 0; i < xPositions.size(); ++i)
  55414. if (x >= xPositions[i] && x < xPositions[i + 1])
  55415. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55416. return -1;
  55417. }
  55418. void MenuBarComponent::repaintMenuItem (int index)
  55419. {
  55420. if (isPositiveAndBelow (index, xPositions.size()))
  55421. {
  55422. const int x1 = xPositions [index];
  55423. const int x2 = xPositions [index + 1];
  55424. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55425. }
  55426. }
  55427. void MenuBarComponent::setItemUnderMouse (const int index)
  55428. {
  55429. if (itemUnderMouse != index)
  55430. {
  55431. repaintMenuItem (itemUnderMouse);
  55432. itemUnderMouse = index;
  55433. repaintMenuItem (itemUnderMouse);
  55434. }
  55435. }
  55436. void MenuBarComponent::setOpenItem (int index)
  55437. {
  55438. if (currentPopupIndex != index)
  55439. {
  55440. repaintMenuItem (currentPopupIndex);
  55441. currentPopupIndex = index;
  55442. repaintMenuItem (currentPopupIndex);
  55443. if (index >= 0)
  55444. Desktop::getInstance().addGlobalMouseListener (this);
  55445. else
  55446. Desktop::getInstance().removeGlobalMouseListener (this);
  55447. }
  55448. }
  55449. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55450. {
  55451. setItemUnderMouse (getItemAt (x, y));
  55452. }
  55453. void MenuBarComponent::showMenu (int index)
  55454. {
  55455. if (index != currentPopupIndex)
  55456. {
  55457. PopupMenu::dismissAllActiveMenus();
  55458. menuBarItemsChanged (0);
  55459. setOpenItem (index);
  55460. setItemUnderMouse (index);
  55461. if (index >= 0)
  55462. {
  55463. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55464. menuNames [itemUnderMouse]));
  55465. if (m.lookAndFeel == 0)
  55466. m.setLookAndFeel (&getLookAndFeel());
  55467. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55468. m.showMenuAsync (PopupMenu::Options().withTargetComponent (this)
  55469. .withTargetScreenArea (localAreaToGlobal (itemPos))
  55470. .withMinimumWidth (itemPos.getWidth()),
  55471. ModalCallbackFunction::forComponent (menuBarMenuDismissedCallback, this, index));
  55472. }
  55473. }
  55474. }
  55475. void MenuBarComponent::menuBarMenuDismissedCallback (int result, MenuBarComponent* bar, int topLevelIndex)
  55476. {
  55477. if (bar != 0)
  55478. bar->menuDismissed (topLevelIndex, result);
  55479. }
  55480. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55481. {
  55482. topLevelIndexClicked = topLevelIndex;
  55483. postCommandMessage (itemId);
  55484. }
  55485. void MenuBarComponent::handleCommandMessage (int commandId)
  55486. {
  55487. const Point<int> mousePos (getMouseXYRelative());
  55488. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55489. if (currentPopupIndex == topLevelIndexClicked)
  55490. setOpenItem (-1);
  55491. if (commandId != 0 && model != 0)
  55492. model->menuItemSelected (commandId, topLevelIndexClicked);
  55493. }
  55494. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55495. {
  55496. if (e.eventComponent == this)
  55497. updateItemUnderMouse (e.x, e.y);
  55498. }
  55499. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55500. {
  55501. if (e.eventComponent == this)
  55502. updateItemUnderMouse (e.x, e.y);
  55503. }
  55504. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55505. {
  55506. if (currentPopupIndex < 0)
  55507. {
  55508. const MouseEvent e2 (e.getEventRelativeTo (this));
  55509. updateItemUnderMouse (e2.x, e2.y);
  55510. currentPopupIndex = -2;
  55511. showMenu (itemUnderMouse);
  55512. }
  55513. }
  55514. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55515. {
  55516. const MouseEvent e2 (e.getEventRelativeTo (this));
  55517. const int item = getItemAt (e2.x, e2.y);
  55518. if (item >= 0)
  55519. showMenu (item);
  55520. }
  55521. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55522. {
  55523. const MouseEvent e2 (e.getEventRelativeTo (this));
  55524. updateItemUnderMouse (e2.x, e2.y);
  55525. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55526. {
  55527. setOpenItem (-1);
  55528. PopupMenu::dismissAllActiveMenus();
  55529. }
  55530. }
  55531. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55532. {
  55533. const MouseEvent e2 (e.getEventRelativeTo (this));
  55534. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55535. {
  55536. if (currentPopupIndex >= 0)
  55537. {
  55538. const int item = getItemAt (e2.x, e2.y);
  55539. if (item >= 0)
  55540. showMenu (item);
  55541. }
  55542. else
  55543. {
  55544. updateItemUnderMouse (e2.x, e2.y);
  55545. }
  55546. lastMouseX = e2.x;
  55547. lastMouseY = e2.y;
  55548. }
  55549. }
  55550. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55551. {
  55552. bool used = false;
  55553. const int numMenus = menuNames.size();
  55554. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55555. if (key.isKeyCode (KeyPress::leftKey))
  55556. {
  55557. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55558. used = true;
  55559. }
  55560. else if (key.isKeyCode (KeyPress::rightKey))
  55561. {
  55562. showMenu ((currentIndex + 1) % numMenus);
  55563. used = true;
  55564. }
  55565. return used;
  55566. }
  55567. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55568. {
  55569. StringArray newNames;
  55570. if (model != 0)
  55571. newNames = model->getMenuBarNames();
  55572. if (newNames != menuNames)
  55573. {
  55574. menuNames = newNames;
  55575. repaint();
  55576. resized();
  55577. }
  55578. }
  55579. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55580. const ApplicationCommandTarget::InvocationInfo& info)
  55581. {
  55582. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55583. return;
  55584. for (int i = 0; i < menuNames.size(); ++i)
  55585. {
  55586. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55587. if (menu.containsCommandItem (info.commandID))
  55588. {
  55589. setItemUnderMouse (i);
  55590. startTimer (200);
  55591. break;
  55592. }
  55593. }
  55594. }
  55595. void MenuBarComponent::timerCallback()
  55596. {
  55597. stopTimer();
  55598. const Point<int> mousePos (getMouseXYRelative());
  55599. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55600. }
  55601. END_JUCE_NAMESPACE
  55602. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55603. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55604. BEGIN_JUCE_NAMESPACE
  55605. MenuBarModel::MenuBarModel() throw()
  55606. : manager (0)
  55607. {
  55608. }
  55609. MenuBarModel::~MenuBarModel()
  55610. {
  55611. setApplicationCommandManagerToWatch (0);
  55612. }
  55613. void MenuBarModel::menuItemsChanged()
  55614. {
  55615. triggerAsyncUpdate();
  55616. }
  55617. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55618. {
  55619. if (manager != newManager)
  55620. {
  55621. if (manager != 0)
  55622. manager->removeListener (this);
  55623. manager = newManager;
  55624. if (manager != 0)
  55625. manager->addListener (this);
  55626. }
  55627. }
  55628. void MenuBarModel::addListener (Listener* const newListener) throw()
  55629. {
  55630. listeners.add (newListener);
  55631. }
  55632. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55633. {
  55634. // Trying to remove a listener that isn't on the list!
  55635. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55636. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55637. jassert (listeners.contains (listenerToRemove));
  55638. listeners.remove (listenerToRemove);
  55639. }
  55640. void MenuBarModel::handleAsyncUpdate()
  55641. {
  55642. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55643. }
  55644. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55645. {
  55646. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55647. }
  55648. void MenuBarModel::applicationCommandListChanged()
  55649. {
  55650. menuItemsChanged();
  55651. }
  55652. END_JUCE_NAMESPACE
  55653. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55654. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55655. BEGIN_JUCE_NAMESPACE
  55656. class PopupMenu::Item
  55657. {
  55658. public:
  55659. Item()
  55660. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55661. usesColour (false), customComp (0), commandManager (0)
  55662. {
  55663. }
  55664. Item (const int itemId_,
  55665. const String& text_,
  55666. const bool active_,
  55667. const bool isTicked_,
  55668. const Image& im,
  55669. const Colour& textColour_,
  55670. const bool usesColour_,
  55671. CustomComponent* const customComp_,
  55672. const PopupMenu* const subMenu_,
  55673. ApplicationCommandManager* const commandManager_)
  55674. : itemId (itemId_), text (text_), textColour (textColour_),
  55675. active (active_), isSeparator (false), isTicked (isTicked_),
  55676. usesColour (usesColour_), image (im), customComp (customComp_),
  55677. commandManager (commandManager_)
  55678. {
  55679. if (subMenu_ != 0)
  55680. subMenu = new PopupMenu (*subMenu_);
  55681. if (commandManager_ != 0 && itemId_ != 0)
  55682. {
  55683. String shortcutKey;
  55684. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55685. ->getKeyPressesAssignedToCommand (itemId_));
  55686. for (int i = 0; i < keyPresses.size(); ++i)
  55687. {
  55688. const String key (keyPresses.getReference(i).getTextDescription());
  55689. if (shortcutKey.isNotEmpty())
  55690. shortcutKey << ", ";
  55691. if (key.length() == 1)
  55692. shortcutKey << "shortcut: '" << key << '\'';
  55693. else
  55694. shortcutKey << key;
  55695. }
  55696. shortcutKey = shortcutKey.trim();
  55697. if (shortcutKey.isNotEmpty())
  55698. text << "<end>" << shortcutKey;
  55699. }
  55700. }
  55701. Item (const Item& other)
  55702. : itemId (other.itemId),
  55703. text (other.text),
  55704. textColour (other.textColour),
  55705. active (other.active),
  55706. isSeparator (other.isSeparator),
  55707. isTicked (other.isTicked),
  55708. usesColour (other.usesColour),
  55709. image (other.image),
  55710. customComp (other.customComp),
  55711. commandManager (other.commandManager)
  55712. {
  55713. if (other.subMenu != 0)
  55714. subMenu = new PopupMenu (*(other.subMenu));
  55715. }
  55716. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55717. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55718. const int itemId;
  55719. String text;
  55720. const Colour textColour;
  55721. const bool active, isSeparator, isTicked, usesColour;
  55722. Image image;
  55723. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55724. ScopedPointer <PopupMenu> subMenu;
  55725. ApplicationCommandManager* const commandManager;
  55726. private:
  55727. Item& operator= (const Item&);
  55728. JUCE_LEAK_DETECTOR (Item);
  55729. };
  55730. class PopupMenu::ItemComponent : public Component
  55731. {
  55732. public:
  55733. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight, Component* const parent)
  55734. : itemInfo (itemInfo_),
  55735. isHighlighted (false)
  55736. {
  55737. if (itemInfo.customComp != 0)
  55738. addAndMakeVisible (itemInfo.customComp);
  55739. parent->addAndMakeVisible (this);
  55740. int itemW = 80;
  55741. int itemH = 16;
  55742. getIdealSize (itemW, itemH, standardItemHeight);
  55743. setSize (itemW, jlimit (2, 600, itemH));
  55744. addMouseListener (parent, false);
  55745. }
  55746. ~ItemComponent()
  55747. {
  55748. if (itemInfo.customComp != 0)
  55749. removeChildComponent (itemInfo.customComp);
  55750. }
  55751. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55752. {
  55753. if (itemInfo.customComp != 0)
  55754. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55755. else
  55756. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55757. itemInfo.isSeparator,
  55758. standardItemHeight,
  55759. idealWidth, idealHeight);
  55760. }
  55761. void paint (Graphics& g)
  55762. {
  55763. if (itemInfo.customComp == 0)
  55764. {
  55765. String mainText (itemInfo.text);
  55766. String endText;
  55767. const int endIndex = mainText.indexOf ("<end>");
  55768. if (endIndex >= 0)
  55769. {
  55770. endText = mainText.substring (endIndex + 5).trim();
  55771. mainText = mainText.substring (0, endIndex);
  55772. }
  55773. getLookAndFeel()
  55774. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55775. itemInfo.isSeparator,
  55776. itemInfo.active,
  55777. isHighlighted,
  55778. itemInfo.isTicked,
  55779. itemInfo.subMenu != 0,
  55780. mainText, endText,
  55781. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55782. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55783. }
  55784. }
  55785. void resized()
  55786. {
  55787. if (getNumChildComponents() > 0)
  55788. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55789. }
  55790. void setHighlighted (bool shouldBeHighlighted)
  55791. {
  55792. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55793. if (isHighlighted != shouldBeHighlighted)
  55794. {
  55795. isHighlighted = shouldBeHighlighted;
  55796. if (itemInfo.customComp != 0)
  55797. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55798. repaint();
  55799. }
  55800. }
  55801. PopupMenu::Item itemInfo;
  55802. private:
  55803. bool isHighlighted;
  55804. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55805. };
  55806. namespace PopupMenuSettings
  55807. {
  55808. const int scrollZone = 24;
  55809. const int borderSize = 2;
  55810. const int timerInterval = 50;
  55811. const int dismissCommandId = 0x6287345f;
  55812. static bool menuWasHiddenBecauseOfAppChange = false;
  55813. }
  55814. class PopupMenu::Window : public Component,
  55815. private Timer
  55816. {
  55817. public:
  55818. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55819. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55820. const int minimumWidth_, const int maximumNumColumns_,
  55821. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55822. ApplicationCommandManager** const managerOfChosenCommand_,
  55823. Component* const componentAttachedTo_)
  55824. : Component ("menu"),
  55825. owner (owner_),
  55826. activeSubMenu (0),
  55827. managerOfChosenCommand (managerOfChosenCommand_),
  55828. componentAttachedTo (componentAttachedTo_),
  55829. componentAttachedToOriginal (componentAttachedTo_),
  55830. minimumWidth (minimumWidth_),
  55831. maximumNumColumns (maximumNumColumns_),
  55832. standardItemHeight (standardItemHeight_),
  55833. isOver (false),
  55834. hasBeenOver (false),
  55835. isDown (false),
  55836. needsToScroll (false),
  55837. dismissOnMouseUp (dismissOnMouseUp_),
  55838. hideOnExit (false),
  55839. disableMouseMoves (false),
  55840. hasAnyJuceCompHadFocus (false),
  55841. numColumns (0),
  55842. contentHeight (0),
  55843. childYOffset (0),
  55844. menuCreationTime (Time::getMillisecondCounter()),
  55845. lastMouseMoveTime (0),
  55846. timeEnteredCurrentChildComp (0),
  55847. scrollAcceleration (1.0)
  55848. {
  55849. lastFocused = lastScroll = menuCreationTime;
  55850. setWantsKeyboardFocus (false);
  55851. setMouseClickGrabsKeyboardFocus (false);
  55852. setAlwaysOnTop (true);
  55853. setLookAndFeel (menu.lookAndFeel);
  55854. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55855. for (int i = 0; i < menu.items.size(); ++i)
  55856. items.add (new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight, this));
  55857. calculateWindowPos (target, alignToRectangle);
  55858. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55859. updateYPositions();
  55860. if (itemIdThatMustBeVisible != 0)
  55861. {
  55862. const int y = target.getY() - windowPos.getY();
  55863. ensureItemIsVisible (itemIdThatMustBeVisible,
  55864. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55865. }
  55866. resizeToBestWindowPos();
  55867. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55868. getActiveWindows().add (this);
  55869. Desktop::getInstance().addGlobalMouseListener (this);
  55870. }
  55871. ~Window()
  55872. {
  55873. getActiveWindows().removeValue (this);
  55874. Desktop::getInstance().removeGlobalMouseListener (this);
  55875. activeSubMenu = 0;
  55876. items.clear();
  55877. }
  55878. static Window* create (const PopupMenu& menu,
  55879. bool dismissOnMouseUp,
  55880. Window* const owner_,
  55881. const Rectangle<int>& target,
  55882. int minimumWidth,
  55883. int maximumNumColumns,
  55884. int standardItemHeight,
  55885. bool alignToRectangle,
  55886. int itemIdThatMustBeVisible,
  55887. ApplicationCommandManager** managerOfChosenCommand,
  55888. Component* componentAttachedTo)
  55889. {
  55890. if (menu.items.size() > 0)
  55891. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55892. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55893. managerOfChosenCommand, componentAttachedTo);
  55894. return 0;
  55895. }
  55896. void paint (Graphics& g)
  55897. {
  55898. if (isOpaque())
  55899. g.fillAll (Colours::white);
  55900. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55901. }
  55902. void paintOverChildren (Graphics& g)
  55903. {
  55904. if (isScrolling())
  55905. {
  55906. LookAndFeel& lf = getLookAndFeel();
  55907. if (isScrollZoneActive (false))
  55908. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55909. if (isScrollZoneActive (true))
  55910. {
  55911. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55912. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55913. }
  55914. }
  55915. }
  55916. bool isScrollZoneActive (bool bottomOne) const
  55917. {
  55918. return isScrolling()
  55919. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55920. : childYOffset > 0);
  55921. }
  55922. // hide this and all sub-comps
  55923. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55924. {
  55925. if (isVisible())
  55926. {
  55927. activeSubMenu = 0;
  55928. currentChild = 0;
  55929. exitModalState (item != 0 ? item->itemId : 0);
  55930. if (makeInvisible)
  55931. setVisible (false);
  55932. if (item != 0
  55933. && item->commandManager != 0
  55934. && item->itemId != 0)
  55935. {
  55936. *managerOfChosenCommand = item->commandManager;
  55937. }
  55938. }
  55939. }
  55940. void dismissMenu (const PopupMenu::Item* const item)
  55941. {
  55942. if (owner != 0)
  55943. {
  55944. owner->dismissMenu (item);
  55945. }
  55946. else
  55947. {
  55948. if (item != 0)
  55949. {
  55950. // need a copy of this on the stack as the one passed in will get deleted during this call
  55951. const PopupMenu::Item mi (*item);
  55952. hide (&mi, false);
  55953. }
  55954. else
  55955. {
  55956. hide (0, false);
  55957. }
  55958. }
  55959. }
  55960. void mouseMove (const MouseEvent&) { timerCallback(); }
  55961. void mouseDown (const MouseEvent&) { timerCallback(); }
  55962. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55963. void mouseUp (const MouseEvent&) { timerCallback(); }
  55964. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55965. {
  55966. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55967. lastMouse = Point<int> (-1, -1);
  55968. }
  55969. bool keyPressed (const KeyPress& key)
  55970. {
  55971. if (key.isKeyCode (KeyPress::downKey))
  55972. {
  55973. selectNextItem (1);
  55974. }
  55975. else if (key.isKeyCode (KeyPress::upKey))
  55976. {
  55977. selectNextItem (-1);
  55978. }
  55979. else if (key.isKeyCode (KeyPress::leftKey))
  55980. {
  55981. if (owner != 0)
  55982. {
  55983. Component::SafePointer<Window> parentWindow (owner);
  55984. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55985. hide (0, true);
  55986. if (parentWindow != 0)
  55987. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55988. disableTimerUntilMouseMoves();
  55989. }
  55990. else if (componentAttachedTo != 0)
  55991. {
  55992. componentAttachedTo->keyPressed (key);
  55993. }
  55994. }
  55995. else if (key.isKeyCode (KeyPress::rightKey))
  55996. {
  55997. disableTimerUntilMouseMoves();
  55998. if (showSubMenuFor (currentChild))
  55999. {
  56000. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56001. activeSubMenu->selectNextItem (1);
  56002. }
  56003. else if (componentAttachedTo != 0)
  56004. {
  56005. componentAttachedTo->keyPressed (key);
  56006. }
  56007. }
  56008. else if (key.isKeyCode (KeyPress::returnKey))
  56009. {
  56010. triggerCurrentlyHighlightedItem();
  56011. }
  56012. else if (key.isKeyCode (KeyPress::escapeKey))
  56013. {
  56014. dismissMenu (0);
  56015. }
  56016. else
  56017. {
  56018. return false;
  56019. }
  56020. return true;
  56021. }
  56022. void inputAttemptWhenModal()
  56023. {
  56024. WeakReference<Component> deletionChecker (this);
  56025. timerCallback();
  56026. if (deletionChecker != 0 && ! isOverAnyMenu())
  56027. {
  56028. if (componentAttachedTo != 0)
  56029. {
  56030. // we want to dismiss the menu, but if we do it synchronously, then
  56031. // the mouse-click will be allowed to pass through. That's good, except
  56032. // when the user clicks on the button that orginally popped the menu up,
  56033. // as they'll expect the menu to go away, and in fact it'll just
  56034. // come back. So only dismiss synchronously if they're not on the original
  56035. // comp that we're attached to.
  56036. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56037. if (componentAttachedTo->reallyContains (mousePos, true))
  56038. {
  56039. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56040. return;
  56041. }
  56042. }
  56043. dismissMenu (0);
  56044. }
  56045. }
  56046. void handleCommandMessage (int commandId)
  56047. {
  56048. Component::handleCommandMessage (commandId);
  56049. if (commandId == PopupMenuSettings::dismissCommandId)
  56050. dismissMenu (0);
  56051. }
  56052. void timerCallback()
  56053. {
  56054. if (! isVisible())
  56055. return;
  56056. if (componentAttachedTo != componentAttachedToOriginal)
  56057. {
  56058. dismissMenu (0);
  56059. return;
  56060. }
  56061. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56062. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56063. return;
  56064. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56065. // move rather than a real timer callback
  56066. const Point<int> globalMousePos (Desktop::getMousePosition());
  56067. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  56068. const uint32 now = Time::getMillisecondCounter();
  56069. if (now > timeEnteredCurrentChildComp + 100
  56070. && reallyContains (localMousePos, true)
  56071. && currentChild != 0
  56072. && (! disableMouseMoves)
  56073. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56074. {
  56075. showSubMenuFor (currentChild);
  56076. }
  56077. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56078. {
  56079. highlightItemUnderMouse (globalMousePos, localMousePos);
  56080. }
  56081. bool overScrollArea = false;
  56082. if (isScrolling()
  56083. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  56084. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56085. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56086. {
  56087. if (now > lastScroll + 20)
  56088. {
  56089. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56090. int amount = 0;
  56091. for (int i = 0; i < items.size() && amount == 0; ++i)
  56092. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  56093. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56094. lastScroll = now;
  56095. }
  56096. overScrollArea = true;
  56097. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56098. }
  56099. else
  56100. {
  56101. scrollAcceleration = 1.0;
  56102. }
  56103. const bool wasDown = isDown;
  56104. bool isOverAny = isOverAnyMenu();
  56105. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56106. {
  56107. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56108. isOverAny = isOverAnyMenu();
  56109. }
  56110. if (hideOnExit && hasBeenOver && ! isOverAny)
  56111. {
  56112. hide (0, true);
  56113. }
  56114. else
  56115. {
  56116. isDown = hasBeenOver
  56117. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56118. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56119. bool anyFocused = Process::isForegroundProcess();
  56120. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56121. {
  56122. // because no component at all may have focus, our test here will
  56123. // only be triggered when something has focus and then loses it.
  56124. anyFocused = ! hasAnyJuceCompHadFocus;
  56125. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56126. {
  56127. if (ComponentPeer::getPeer (i)->isFocused())
  56128. {
  56129. anyFocused = true;
  56130. hasAnyJuceCompHadFocus = true;
  56131. break;
  56132. }
  56133. }
  56134. }
  56135. if (! anyFocused)
  56136. {
  56137. if (now > lastFocused + 10)
  56138. {
  56139. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  56140. dismissMenu (0);
  56141. return; // may have been deleted by the previous call..
  56142. }
  56143. }
  56144. else if (wasDown && now > menuCreationTime + 250
  56145. && ! (isDown || overScrollArea))
  56146. {
  56147. isOver = reallyContains (localMousePos, true);
  56148. if (isOver)
  56149. {
  56150. triggerCurrentlyHighlightedItem();
  56151. }
  56152. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56153. {
  56154. dismissMenu (0);
  56155. }
  56156. return; // may have been deleted by the previous calls..
  56157. }
  56158. else
  56159. {
  56160. lastFocused = now;
  56161. }
  56162. }
  56163. }
  56164. static Array<Window*>& getActiveWindows()
  56165. {
  56166. static Array<Window*> activeMenuWindows;
  56167. return activeMenuWindows;
  56168. }
  56169. private:
  56170. Window* owner;
  56171. OwnedArray <PopupMenu::ItemComponent> items;
  56172. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  56173. ScopedPointer <Window> activeSubMenu;
  56174. ApplicationCommandManager** managerOfChosenCommand;
  56175. WeakReference<Component> componentAttachedTo;
  56176. Component* componentAttachedToOriginal;
  56177. Rectangle<int> windowPos;
  56178. Point<int> lastMouse;
  56179. int minimumWidth, maximumNumColumns, standardItemHeight;
  56180. bool isOver, hasBeenOver, isDown, needsToScroll;
  56181. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56182. int numColumns, contentHeight, childYOffset;
  56183. Array <int> columnWidths;
  56184. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56185. double scrollAcceleration;
  56186. bool overlaps (const Rectangle<int>& r) const
  56187. {
  56188. return r.intersects (getBounds())
  56189. || (owner != 0 && owner->overlaps (r));
  56190. }
  56191. bool isOverAnyMenu() const
  56192. {
  56193. return (owner != 0) ? owner->isOverAnyMenu()
  56194. : isOverChildren();
  56195. }
  56196. bool isOverChildren() const
  56197. {
  56198. return isVisible()
  56199. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56200. }
  56201. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56202. {
  56203. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56204. isOver = reallyContains (relPos, true);
  56205. if (activeSubMenu != 0)
  56206. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56207. }
  56208. bool treeContains (const Window* const window) const throw()
  56209. {
  56210. const Window* mw = this;
  56211. while (mw->owner != 0)
  56212. mw = mw->owner;
  56213. while (mw != 0)
  56214. {
  56215. if (mw == window)
  56216. return true;
  56217. mw = mw->activeSubMenu;
  56218. }
  56219. return false;
  56220. }
  56221. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56222. {
  56223. const Rectangle<int> mon (Desktop::getInstance()
  56224. .getMonitorAreaContaining (target.getCentre(),
  56225. #if JUCE_MAC
  56226. true));
  56227. #else
  56228. false)); // on windows, don't stop the menu overlapping the taskbar
  56229. #endif
  56230. int x, y, widthToUse, heightToUse;
  56231. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56232. if (alignToRectangle)
  56233. {
  56234. x = target.getX();
  56235. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56236. const int spaceOver = target.getY() - mon.getY();
  56237. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56238. y = target.getBottom();
  56239. else
  56240. y = target.getY() - heightToUse;
  56241. }
  56242. else
  56243. {
  56244. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56245. if (owner != 0)
  56246. {
  56247. if (owner->owner != 0)
  56248. {
  56249. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56250. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56251. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56252. tendTowardsRight = true;
  56253. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56254. tendTowardsRight = false;
  56255. }
  56256. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56257. {
  56258. tendTowardsRight = true;
  56259. }
  56260. }
  56261. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56262. target.getX() - mon.getX()) - 32;
  56263. if (biggestSpace < widthToUse)
  56264. {
  56265. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56266. if (numColumns > 1)
  56267. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56268. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56269. }
  56270. if (tendTowardsRight)
  56271. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56272. else
  56273. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56274. y = target.getY();
  56275. if (target.getCentreY() > mon.getCentreY())
  56276. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56277. }
  56278. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56279. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56280. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56281. // sets this flag if it's big enough to obscure any of its parent menus
  56282. hideOnExit = (owner != 0)
  56283. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56284. }
  56285. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56286. {
  56287. numColumns = 0;
  56288. contentHeight = 0;
  56289. const int maxMenuH = getParentHeight() - 24;
  56290. int totalW;
  56291. do
  56292. {
  56293. ++numColumns;
  56294. totalW = workOutBestSize (maxMenuW);
  56295. if (totalW > maxMenuW)
  56296. {
  56297. numColumns = jmax (1, numColumns - 1);
  56298. totalW = workOutBestSize (maxMenuW); // to update col widths
  56299. break;
  56300. }
  56301. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56302. {
  56303. break;
  56304. }
  56305. } while (numColumns < maximumNumColumns);
  56306. const int actualH = jmin (contentHeight, maxMenuH);
  56307. needsToScroll = contentHeight > actualH;
  56308. width = updateYPositions();
  56309. height = actualH + PopupMenuSettings::borderSize * 2;
  56310. }
  56311. int workOutBestSize (const int maxMenuW)
  56312. {
  56313. int totalW = 0;
  56314. contentHeight = 0;
  56315. int childNum = 0;
  56316. for (int col = 0; col < numColumns; ++col)
  56317. {
  56318. int i, colW = 50, colH = 0;
  56319. const int numChildren = jmin (items.size() - childNum,
  56320. (items.size() + numColumns - 1) / numColumns);
  56321. for (i = numChildren; --i >= 0;)
  56322. {
  56323. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56324. colH += items.getUnchecked (childNum + i)->getHeight();
  56325. }
  56326. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56327. columnWidths.set (col, colW);
  56328. totalW += colW;
  56329. contentHeight = jmax (contentHeight, colH);
  56330. childNum += numChildren;
  56331. }
  56332. if (totalW < minimumWidth)
  56333. {
  56334. totalW = minimumWidth;
  56335. for (int col = 0; col < numColumns; ++col)
  56336. columnWidths.set (0, totalW / numColumns);
  56337. }
  56338. return totalW;
  56339. }
  56340. void ensureItemIsVisible (const int itemId, int wantedY)
  56341. {
  56342. jassert (itemId != 0)
  56343. for (int i = items.size(); --i >= 0;)
  56344. {
  56345. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56346. if (m != 0
  56347. && m->itemInfo.itemId == itemId
  56348. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56349. {
  56350. const int currentY = m->getY();
  56351. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56352. {
  56353. if (wantedY < 0)
  56354. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56355. jmax (PopupMenuSettings::scrollZone,
  56356. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56357. currentY);
  56358. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56359. int deltaY = wantedY - currentY;
  56360. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56361. jmin (windowPos.getHeight(), mon.getHeight()));
  56362. const int newY = jlimit (mon.getY(),
  56363. mon.getBottom() - windowPos.getHeight(),
  56364. windowPos.getY() + deltaY);
  56365. deltaY -= newY - windowPos.getY();
  56366. childYOffset -= deltaY;
  56367. windowPos.setPosition (windowPos.getX(), newY);
  56368. updateYPositions();
  56369. }
  56370. break;
  56371. }
  56372. }
  56373. }
  56374. void resizeToBestWindowPos()
  56375. {
  56376. Rectangle<int> r (windowPos);
  56377. if (childYOffset < 0)
  56378. {
  56379. r.setBounds (r.getX(), r.getY() - childYOffset,
  56380. r.getWidth(), r.getHeight() + childYOffset);
  56381. }
  56382. else if (childYOffset > 0)
  56383. {
  56384. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56385. if (spaceAtBottom > 0)
  56386. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56387. }
  56388. setBounds (r);
  56389. updateYPositions();
  56390. }
  56391. void alterChildYPos (const int delta)
  56392. {
  56393. if (isScrolling())
  56394. {
  56395. childYOffset += delta;
  56396. if (delta < 0)
  56397. {
  56398. childYOffset = jmax (childYOffset, 0);
  56399. }
  56400. else if (delta > 0)
  56401. {
  56402. childYOffset = jmin (childYOffset,
  56403. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56404. }
  56405. updateYPositions();
  56406. }
  56407. else
  56408. {
  56409. childYOffset = 0;
  56410. }
  56411. resizeToBestWindowPos();
  56412. repaint();
  56413. }
  56414. int updateYPositions()
  56415. {
  56416. int x = 0;
  56417. int childNum = 0;
  56418. for (int col = 0; col < numColumns; ++col)
  56419. {
  56420. const int numChildren = jmin (items.size() - childNum,
  56421. (items.size() + numColumns - 1) / numColumns);
  56422. const int colW = columnWidths [col];
  56423. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56424. for (int i = 0; i < numChildren; ++i)
  56425. {
  56426. Component* const c = items.getUnchecked (childNum + i);
  56427. c->setBounds (x, y, colW, c->getHeight());
  56428. y += c->getHeight();
  56429. }
  56430. x += colW;
  56431. childNum += numChildren;
  56432. }
  56433. return x;
  56434. }
  56435. bool isScrolling() const throw()
  56436. {
  56437. return childYOffset != 0 || needsToScroll;
  56438. }
  56439. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56440. {
  56441. if (currentChild != 0)
  56442. currentChild->setHighlighted (false);
  56443. currentChild = child;
  56444. if (currentChild != 0)
  56445. {
  56446. currentChild->setHighlighted (true);
  56447. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56448. }
  56449. }
  56450. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56451. {
  56452. activeSubMenu = 0;
  56453. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56454. {
  56455. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56456. dismissOnMouseUp,
  56457. this,
  56458. childComp->getScreenBounds(),
  56459. 0, maximumNumColumns,
  56460. standardItemHeight,
  56461. false, 0, managerOfChosenCommand,
  56462. componentAttachedTo);
  56463. if (activeSubMenu != 0)
  56464. {
  56465. activeSubMenu->setVisible (true);
  56466. activeSubMenu->enterModalState (false);
  56467. activeSubMenu->toFront (false);
  56468. return true;
  56469. }
  56470. }
  56471. return false;
  56472. }
  56473. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56474. {
  56475. isOver = reallyContains (localMousePos, true);
  56476. if (isOver)
  56477. hasBeenOver = true;
  56478. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56479. {
  56480. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56481. if (disableMouseMoves && isOver)
  56482. disableMouseMoves = false;
  56483. }
  56484. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56485. return;
  56486. bool isMovingTowardsMenu = false;
  56487. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56488. {
  56489. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56490. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56491. // extends from the last mouse pos to the submenu's rectangle..
  56492. float subX = (float) activeSubMenu->getScreenX();
  56493. if (activeSubMenu->getX() > getX())
  56494. {
  56495. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56496. }
  56497. else
  56498. {
  56499. lastMouse += Point<int> (2, 0);
  56500. subX += activeSubMenu->getWidth();
  56501. }
  56502. Path areaTowardsSubMenu;
  56503. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56504. subX, (float) activeSubMenu->getScreenY(),
  56505. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56506. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56507. }
  56508. lastMouse = globalMousePos;
  56509. if (! isMovingTowardsMenu)
  56510. {
  56511. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56512. if (c == this)
  56513. c = 0;
  56514. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56515. if (mic == 0 && c != 0)
  56516. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56517. if (mic != currentChild
  56518. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56519. {
  56520. if (isOver && (c != 0) && (activeSubMenu != 0))
  56521. activeSubMenu->hide (0, true);
  56522. if (! isOver)
  56523. mic = 0;
  56524. setCurrentlyHighlightedChild (mic);
  56525. }
  56526. }
  56527. }
  56528. void triggerCurrentlyHighlightedItem()
  56529. {
  56530. if (currentChild != 0
  56531. && currentChild->itemInfo.canBeTriggered()
  56532. && (currentChild->itemInfo.customComp == 0
  56533. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56534. {
  56535. dismissMenu (&currentChild->itemInfo);
  56536. }
  56537. }
  56538. void selectNextItem (const int delta)
  56539. {
  56540. disableTimerUntilMouseMoves();
  56541. PopupMenu::ItemComponent* mic = 0;
  56542. bool wasLastOne = (currentChild == 0);
  56543. const int numItems = items.size();
  56544. for (int i = 0; i < numItems + 1; ++i)
  56545. {
  56546. int index = (delta > 0) ? i : (numItems - 1 - i);
  56547. index = (index + numItems) % numItems;
  56548. mic = items.getUnchecked (index);
  56549. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56550. && wasLastOne)
  56551. break;
  56552. if (mic == currentChild)
  56553. wasLastOne = true;
  56554. }
  56555. setCurrentlyHighlightedChild (mic);
  56556. }
  56557. void disableTimerUntilMouseMoves()
  56558. {
  56559. disableMouseMoves = true;
  56560. if (owner != 0)
  56561. owner->disableTimerUntilMouseMoves();
  56562. }
  56563. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56564. };
  56565. PopupMenu::PopupMenu()
  56566. : lookAndFeel (0),
  56567. separatorPending (false)
  56568. {
  56569. }
  56570. PopupMenu::PopupMenu (const PopupMenu& other)
  56571. : lookAndFeel (other.lookAndFeel),
  56572. separatorPending (false)
  56573. {
  56574. items.addCopiesOf (other.items);
  56575. }
  56576. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56577. {
  56578. if (this != &other)
  56579. {
  56580. lookAndFeel = other.lookAndFeel;
  56581. clear();
  56582. items.addCopiesOf (other.items);
  56583. }
  56584. return *this;
  56585. }
  56586. PopupMenu::~PopupMenu()
  56587. {
  56588. clear();
  56589. }
  56590. void PopupMenu::clear()
  56591. {
  56592. items.clear();
  56593. separatorPending = false;
  56594. }
  56595. void PopupMenu::addSeparatorIfPending()
  56596. {
  56597. if (separatorPending)
  56598. {
  56599. separatorPending = false;
  56600. if (items.size() > 0)
  56601. items.add (new Item());
  56602. }
  56603. }
  56604. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56605. const bool isActive, const bool isTicked, const Image& iconToUse)
  56606. {
  56607. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56608. // didn't pick anything, so you shouldn't use it as the id
  56609. // for an item..
  56610. addSeparatorIfPending();
  56611. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56612. Colours::black, false, 0, 0, 0));
  56613. }
  56614. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56615. const int commandID,
  56616. const String& displayName)
  56617. {
  56618. jassert (commandManager != 0 && commandID != 0);
  56619. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56620. if (registeredInfo != 0)
  56621. {
  56622. ApplicationCommandInfo info (*registeredInfo);
  56623. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56624. addSeparatorIfPending();
  56625. items.add (new Item (commandID,
  56626. displayName.isNotEmpty() ? displayName
  56627. : info.shortName,
  56628. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56629. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56630. Image::null,
  56631. Colours::black,
  56632. false,
  56633. 0, 0,
  56634. commandManager));
  56635. }
  56636. }
  56637. void PopupMenu::addColouredItem (const int itemResultId,
  56638. const String& itemText,
  56639. const Colour& itemTextColour,
  56640. const bool isActive,
  56641. const bool isTicked,
  56642. const Image& iconToUse)
  56643. {
  56644. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56645. // didn't pick anything, so you shouldn't use it as the id
  56646. // for an item..
  56647. addSeparatorIfPending();
  56648. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56649. itemTextColour, true, 0, 0, 0));
  56650. }
  56651. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56652. {
  56653. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56654. // didn't pick anything, so you shouldn't use it as the id
  56655. // for an item..
  56656. addSeparatorIfPending();
  56657. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56658. Colours::black, false, customComponent, 0, 0));
  56659. }
  56660. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56661. {
  56662. public:
  56663. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56664. const bool triggerMenuItemAutomaticallyWhenClicked)
  56665. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56666. width (w), height (h)
  56667. {
  56668. addAndMakeVisible (comp);
  56669. }
  56670. void getIdealSize (int& idealWidth, int& idealHeight)
  56671. {
  56672. idealWidth = width;
  56673. idealHeight = height;
  56674. }
  56675. void resized()
  56676. {
  56677. if (getChildComponent(0) != 0)
  56678. getChildComponent(0)->setBounds (getLocalBounds());
  56679. }
  56680. private:
  56681. const int width, height;
  56682. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56683. };
  56684. void PopupMenu::addCustomItem (const int itemResultId,
  56685. Component* customComponent,
  56686. int idealWidth, int idealHeight,
  56687. const bool triggerMenuItemAutomaticallyWhenClicked)
  56688. {
  56689. addCustomItem (itemResultId,
  56690. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56691. triggerMenuItemAutomaticallyWhenClicked));
  56692. }
  56693. void PopupMenu::addSubMenu (const String& subMenuName,
  56694. const PopupMenu& subMenu,
  56695. const bool isActive,
  56696. const Image& iconToUse,
  56697. const bool isTicked)
  56698. {
  56699. addSeparatorIfPending();
  56700. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56701. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56702. }
  56703. void PopupMenu::addSeparator()
  56704. {
  56705. separatorPending = true;
  56706. }
  56707. class HeaderItemComponent : public PopupMenu::CustomComponent
  56708. {
  56709. public:
  56710. HeaderItemComponent (const String& name)
  56711. : PopupMenu::CustomComponent (false)
  56712. {
  56713. setName (name);
  56714. }
  56715. void paint (Graphics& g)
  56716. {
  56717. Font f (getLookAndFeel().getPopupMenuFont());
  56718. f.setBold (true);
  56719. g.setFont (f);
  56720. g.setColour (findColour (PopupMenu::headerTextColourId));
  56721. g.drawFittedText (getName(),
  56722. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56723. Justification::bottomLeft, 1);
  56724. }
  56725. void getIdealSize (int& idealWidth, int& idealHeight)
  56726. {
  56727. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56728. idealHeight += idealHeight / 2;
  56729. idealWidth += idealWidth / 4;
  56730. }
  56731. private:
  56732. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56733. };
  56734. void PopupMenu::addSectionHeader (const String& title)
  56735. {
  56736. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56737. }
  56738. PopupMenu::Options::Options()
  56739. : targetComponent (0),
  56740. visibleItemID (0),
  56741. minWidth (0),
  56742. maxColumns (0),
  56743. standardHeight (0)
  56744. {
  56745. targetArea.setPosition (Desktop::getMousePosition());
  56746. }
  56747. const PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  56748. {
  56749. Options o (*this);
  56750. o.targetComponent = comp;
  56751. if (comp != 0)
  56752. o.targetArea = comp->getScreenBounds();
  56753. return o;
  56754. }
  56755. const PopupMenu::Options PopupMenu::Options::withTargetScreenArea (const Rectangle<int>& area) const
  56756. {
  56757. Options o (*this);
  56758. o.targetArea = area;
  56759. return o;
  56760. }
  56761. const PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  56762. {
  56763. Options o (*this);
  56764. o.minWidth = w;
  56765. return o;
  56766. }
  56767. const PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  56768. {
  56769. Options o (*this);
  56770. o.maxColumns = cols;
  56771. return o;
  56772. }
  56773. const PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  56774. {
  56775. Options o (*this);
  56776. o.standardHeight = height;
  56777. return o;
  56778. }
  56779. const PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  56780. {
  56781. Options o (*this);
  56782. o.visibleItemID = idOfItemToBeVisible;
  56783. return o;
  56784. }
  56785. Component* PopupMenu::createWindow (const Options& options,
  56786. ApplicationCommandManager** managerOfChosenCommand) const
  56787. {
  56788. return Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56789. 0, options.targetArea, options.minWidth, options.maxColumns > 0 ? options.maxColumns : 7,
  56790. options.standardHeight, ! options.targetArea.isEmpty(), options.visibleItemID,
  56791. managerOfChosenCommand, options.targetComponent);
  56792. }
  56793. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56794. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56795. {
  56796. public:
  56797. PopupMenuCompletionCallback()
  56798. : managerOfChosenCommand (0),
  56799. prevFocused (Component::getCurrentlyFocusedComponent()),
  56800. prevTopLevel (prevFocused != 0 ? prevFocused->getTopLevelComponent() : 0)
  56801. {
  56802. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  56803. }
  56804. void modalStateFinished (int result)
  56805. {
  56806. if (managerOfChosenCommand != 0 && result != 0)
  56807. {
  56808. ApplicationCommandTarget::InvocationInfo info (result);
  56809. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56810. managerOfChosenCommand->invoke (info, true);
  56811. }
  56812. // (this would be the place to fade out the component, if that's what's required)
  56813. component = 0;
  56814. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  56815. {
  56816. if (prevTopLevel != 0)
  56817. prevTopLevel->toFront (true);
  56818. if (prevFocused != 0)
  56819. prevFocused->grabKeyboardFocus();
  56820. }
  56821. }
  56822. ApplicationCommandManager* managerOfChosenCommand;
  56823. ScopedPointer<Component> component;
  56824. WeakReference<Component> prevFocused, prevTopLevel;
  56825. private:
  56826. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56827. };
  56828. int PopupMenu::showWithOptionalCallback (const Options& options, ModalComponentManager::Callback* const userCallback,
  56829. const bool canBeModal)
  56830. {
  56831. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56832. ScopedPointer<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  56833. Component* window = createWindow (options, &(callback->managerOfChosenCommand));
  56834. if (window == 0)
  56835. return 0;
  56836. callback->component = window;
  56837. window->enterModalState (false, userCallbackDeleter.release());
  56838. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  56839. window->toFront (false); // need to do this after making it modal, or it could
  56840. // be stuck behind other comps that are already modal..
  56841. #if JUCE_MODAL_LOOPS_PERMITTED
  56842. return (userCallback == 0 && canBeModal) ? window->runModalLoop() : 0;
  56843. #else
  56844. jassert (userCallback != 0 && canBeModal);
  56845. return 0;
  56846. #endif
  56847. }
  56848. #if JUCE_MODAL_LOOPS_PERMITTED
  56849. int PopupMenu::showMenu (const Options& options)
  56850. {
  56851. return showWithOptionalCallback (options, 0, true);
  56852. }
  56853. #endif
  56854. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  56855. {
  56856. #if ! JUCE_MODAL_LOOPS_PERMITTED
  56857. jassert (userCallback != 0);
  56858. #endif
  56859. showWithOptionalCallback (options, userCallback, false);
  56860. }
  56861. #if JUCE_MODAL_LOOPS_PERMITTED
  56862. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56863. const int minimumWidth, const int maximumNumColumns,
  56864. const int standardItemHeight,
  56865. ModalComponentManager::Callback* callback)
  56866. {
  56867. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56868. .withMinimumWidth (minimumWidth)
  56869. .withMaximumNumColumns (maximumNumColumns)
  56870. .withStandardItemHeight (standardItemHeight),
  56871. callback, true);
  56872. }
  56873. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56874. const int itemIdThatMustBeVisible,
  56875. const int minimumWidth, const int maximumNumColumns,
  56876. const int standardItemHeight,
  56877. ModalComponentManager::Callback* callback)
  56878. {
  56879. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  56880. .withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56881. .withMinimumWidth (minimumWidth)
  56882. .withMaximumNumColumns (maximumNumColumns)
  56883. .withStandardItemHeight (standardItemHeight),
  56884. callback, true);
  56885. }
  56886. int PopupMenu::showAt (Component* componentToAttachTo,
  56887. const int itemIdThatMustBeVisible,
  56888. const int minimumWidth, const int maximumNumColumns,
  56889. const int standardItemHeight,
  56890. ModalComponentManager::Callback* callback)
  56891. {
  56892. Options options (Options().withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56893. .withMinimumWidth (minimumWidth)
  56894. .withMaximumNumColumns (maximumNumColumns)
  56895. .withStandardItemHeight (standardItemHeight));
  56896. if (componentToAttachTo != 0)
  56897. options = options.withTargetComponent (componentToAttachTo);
  56898. return showWithOptionalCallback (options, callback, true);
  56899. }
  56900. #endif
  56901. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56902. {
  56903. const int numWindows = Window::getActiveWindows().size();
  56904. for (int i = numWindows; --i >= 0;)
  56905. {
  56906. Window* const pmw = Window::getActiveWindows()[i];
  56907. if (pmw != 0)
  56908. pmw->dismissMenu (0);
  56909. }
  56910. return numWindows > 0;
  56911. }
  56912. int PopupMenu::getNumItems() const throw()
  56913. {
  56914. int num = 0;
  56915. for (int i = items.size(); --i >= 0;)
  56916. if (! (items.getUnchecked(i))->isSeparator)
  56917. ++num;
  56918. return num;
  56919. }
  56920. bool PopupMenu::containsCommandItem (const int commandID) const
  56921. {
  56922. for (int i = items.size(); --i >= 0;)
  56923. {
  56924. const Item* mi = items.getUnchecked (i);
  56925. if ((mi->itemId == commandID && mi->commandManager != 0)
  56926. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56927. {
  56928. return true;
  56929. }
  56930. }
  56931. return false;
  56932. }
  56933. bool PopupMenu::containsAnyActiveItems() const throw()
  56934. {
  56935. for (int i = items.size(); --i >= 0;)
  56936. {
  56937. const Item* const mi = items.getUnchecked (i);
  56938. if (mi->subMenu != 0)
  56939. {
  56940. if (mi->subMenu->containsAnyActiveItems())
  56941. return true;
  56942. }
  56943. else if (mi->active)
  56944. {
  56945. return true;
  56946. }
  56947. }
  56948. return false;
  56949. }
  56950. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56951. {
  56952. lookAndFeel = newLookAndFeel;
  56953. }
  56954. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56955. : isHighlighted (false),
  56956. triggeredAutomatically (isTriggeredAutomatically_)
  56957. {
  56958. }
  56959. PopupMenu::CustomComponent::~CustomComponent()
  56960. {
  56961. }
  56962. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56963. {
  56964. isHighlighted = shouldBeHighlighted;
  56965. repaint();
  56966. }
  56967. void PopupMenu::CustomComponent::triggerMenuItem()
  56968. {
  56969. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56970. if (mic != 0)
  56971. {
  56972. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56973. if (pmw != 0)
  56974. {
  56975. pmw->dismissMenu (&mic->itemInfo);
  56976. }
  56977. else
  56978. {
  56979. // something must have gone wrong with the component hierarchy if this happens..
  56980. jassertfalse;
  56981. }
  56982. }
  56983. else
  56984. {
  56985. // why isn't this component inside a menu? Not much point triggering the item if
  56986. // there's no menu.
  56987. jassertfalse;
  56988. }
  56989. }
  56990. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56991. : subMenu (0),
  56992. itemId (0),
  56993. isSeparator (false),
  56994. isTicked (false),
  56995. isEnabled (false),
  56996. isCustomComponent (false),
  56997. isSectionHeader (false),
  56998. customColour (0),
  56999. customImage (0),
  57000. menu (menu_),
  57001. index (0)
  57002. {
  57003. }
  57004. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57005. {
  57006. }
  57007. bool PopupMenu::MenuItemIterator::next()
  57008. {
  57009. if (index >= menu.items.size())
  57010. return false;
  57011. const Item* const item = menu.items.getUnchecked (index);
  57012. ++index;
  57013. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57014. subMenu = item->subMenu;
  57015. itemId = item->itemId;
  57016. isSeparator = item->isSeparator;
  57017. isTicked = item->isTicked;
  57018. isEnabled = item->active;
  57019. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  57020. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57021. customColour = item->usesColour ? &(item->textColour) : 0;
  57022. customImage = item->image;
  57023. commandManager = item->commandManager;
  57024. return true;
  57025. }
  57026. END_JUCE_NAMESPACE
  57027. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57028. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57029. BEGIN_JUCE_NAMESPACE
  57030. ComponentDragger::ComponentDragger()
  57031. {
  57032. }
  57033. ComponentDragger::~ComponentDragger()
  57034. {
  57035. }
  57036. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  57037. {
  57038. jassert (componentToDrag != 0);
  57039. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  57040. if (componentToDrag != 0)
  57041. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  57042. }
  57043. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  57044. ComponentBoundsConstrainer* const constrainer)
  57045. {
  57046. jassert (componentToDrag != 0);
  57047. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  57048. if (componentToDrag != 0)
  57049. {
  57050. Rectangle<int> bounds (componentToDrag->getBounds());
  57051. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  57052. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  57053. // the current mouse position instead of the one that the event contains...
  57054. if (componentToDrag->isOnDesktop())
  57055. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  57056. else
  57057. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  57058. if (constrainer != 0)
  57059. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57060. else
  57061. componentToDrag->setBounds (bounds);
  57062. }
  57063. }
  57064. END_JUCE_NAMESPACE
  57065. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57066. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57067. BEGIN_JUCE_NAMESPACE
  57068. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57069. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57070. class DragImageComponent : public Component,
  57071. public Timer
  57072. {
  57073. public:
  57074. DragImageComponent (const Image& im,
  57075. const String& desc,
  57076. Component* const sourceComponent,
  57077. Component* const mouseDragSource_,
  57078. DragAndDropContainer* const o,
  57079. const Point<int>& imageOffset_)
  57080. : image (im),
  57081. source (sourceComponent),
  57082. mouseDragSource (mouseDragSource_),
  57083. owner (o),
  57084. dragDesc (desc),
  57085. imageOffset (imageOffset_),
  57086. hasCheckedForExternalDrag (false),
  57087. drawImage (true)
  57088. {
  57089. setSize (im.getWidth(), im.getHeight());
  57090. if (mouseDragSource == 0)
  57091. mouseDragSource = source;
  57092. mouseDragSource->addMouseListener (this, false);
  57093. startTimer (200);
  57094. setInterceptsMouseClicks (false, false);
  57095. setAlwaysOnTop (true);
  57096. }
  57097. ~DragImageComponent()
  57098. {
  57099. if (owner->dragImageComponent == this)
  57100. owner->dragImageComponent.release();
  57101. if (mouseDragSource != 0)
  57102. {
  57103. mouseDragSource->removeMouseListener (this);
  57104. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57105. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57106. }
  57107. }
  57108. void paint (Graphics& g)
  57109. {
  57110. if (isOpaque())
  57111. g.fillAll (Colours::white);
  57112. if (drawImage)
  57113. {
  57114. g.setOpacity (1.0f);
  57115. g.drawImageAt (image, 0, 0);
  57116. }
  57117. }
  57118. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57119. {
  57120. Component* hit = getParentComponent();
  57121. if (hit == 0)
  57122. {
  57123. hit = Desktop::getInstance().findComponentAt (screenPos);
  57124. }
  57125. else
  57126. {
  57127. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  57128. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57129. }
  57130. // (note: use a local copy of the dragDesc member in case the callback runs
  57131. // a modal loop and deletes this object before the method completes)
  57132. const String dragDescLocal (dragDesc);
  57133. while (hit != 0)
  57134. {
  57135. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57136. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57137. {
  57138. relativePos = hit->getLocalPoint (0, screenPos);
  57139. return ddt;
  57140. }
  57141. hit = hit->getParentComponent();
  57142. }
  57143. return 0;
  57144. }
  57145. void mouseUp (const MouseEvent& e)
  57146. {
  57147. if (e.originalComponent != this)
  57148. {
  57149. if (mouseDragSource != 0)
  57150. mouseDragSource->removeMouseListener (this);
  57151. bool dropAccepted = false;
  57152. DragAndDropTarget* ddt = 0;
  57153. Point<int> relPos;
  57154. if (isVisible())
  57155. {
  57156. setVisible (false);
  57157. ddt = findTarget (e.getScreenPosition(), relPos);
  57158. // fade this component and remove it - it'll be deleted later by the timer callback
  57159. dropAccepted = ddt != 0;
  57160. setVisible (true);
  57161. if (dropAccepted || source == 0)
  57162. {
  57163. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  57164. }
  57165. else
  57166. {
  57167. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  57168. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  57169. Desktop::getInstance().getAnimator().animateComponent (this,
  57170. getBounds() + (target - ourCentre),
  57171. 0.0f, 120,
  57172. true, 1.0, 1.0);
  57173. }
  57174. }
  57175. if (getParentComponent() != 0)
  57176. getParentComponent()->removeChildComponent (this);
  57177. if (dropAccepted && ddt != 0)
  57178. {
  57179. // (note: use a local copy of the dragDesc member in case the callback runs
  57180. // a modal loop and deletes this object before the method completes)
  57181. const String dragDescLocal (dragDesc);
  57182. currentlyOverComp = 0;
  57183. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57184. }
  57185. // careful - this object could now be deleted..
  57186. }
  57187. }
  57188. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57189. {
  57190. // (note: use a local copy of the dragDesc member in case the callback runs
  57191. // a modal loop and deletes this object before it returns)
  57192. const String dragDescLocal (dragDesc);
  57193. Point<int> newPos (screenPos + imageOffset);
  57194. if (getParentComponent() != 0)
  57195. newPos = getParentComponent()->getLocalPoint (0, newPos);
  57196. //if (newX != getX() || newY != getY())
  57197. {
  57198. setTopLeftPosition (newPos.getX(), newPos.getY());
  57199. Point<int> relPos;
  57200. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57201. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57202. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57203. if (ddtComp != currentlyOverComp)
  57204. {
  57205. if (currentlyOverComp != 0 && source != 0
  57206. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57207. {
  57208. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57209. }
  57210. currentlyOverComp = ddtComp;
  57211. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57212. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57213. }
  57214. DragAndDropTarget* target = getCurrentlyOver();
  57215. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57216. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57217. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57218. {
  57219. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57220. {
  57221. hasCheckedForExternalDrag = true;
  57222. StringArray files;
  57223. bool canMoveFiles = false;
  57224. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57225. && files.size() > 0)
  57226. {
  57227. WeakReference<Component> cdw (this);
  57228. setVisible (false);
  57229. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57230. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57231. if (cdw != 0)
  57232. delete this;
  57233. return;
  57234. }
  57235. }
  57236. }
  57237. }
  57238. }
  57239. void mouseDrag (const MouseEvent& e)
  57240. {
  57241. if (e.originalComponent != this)
  57242. updateLocation (true, e.getScreenPosition());
  57243. }
  57244. void timerCallback()
  57245. {
  57246. if (source == 0)
  57247. {
  57248. delete this;
  57249. }
  57250. else if (! isMouseButtonDownAnywhere())
  57251. {
  57252. if (mouseDragSource != 0)
  57253. mouseDragSource->removeMouseListener (this);
  57254. delete this;
  57255. }
  57256. }
  57257. private:
  57258. Image image;
  57259. WeakReference<Component> source;
  57260. WeakReference<Component> mouseDragSource;
  57261. DragAndDropContainer* const owner;
  57262. WeakReference<Component> currentlyOverComp;
  57263. DragAndDropTarget* getCurrentlyOver()
  57264. {
  57265. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  57266. }
  57267. String dragDesc;
  57268. const Point<int> imageOffset;
  57269. bool hasCheckedForExternalDrag, drawImage;
  57270. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  57271. };
  57272. DragAndDropContainer::DragAndDropContainer()
  57273. {
  57274. }
  57275. DragAndDropContainer::~DragAndDropContainer()
  57276. {
  57277. dragImageComponent = 0;
  57278. }
  57279. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57280. Component* sourceComponent,
  57281. const Image& dragImage_,
  57282. const bool allowDraggingToExternalWindows,
  57283. const Point<int>* imageOffsetFromMouse)
  57284. {
  57285. Image dragImage (dragImage_);
  57286. if (dragImageComponent == 0)
  57287. {
  57288. Component* const thisComp = dynamic_cast <Component*> (this);
  57289. if (thisComp == 0)
  57290. {
  57291. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57292. return;
  57293. }
  57294. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57295. if (draggingSource == 0 || ! draggingSource->isDragging())
  57296. {
  57297. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57298. return;
  57299. }
  57300. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57301. Point<int> imageOffset;
  57302. if (dragImage.isNull())
  57303. {
  57304. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57305. .convertedToFormat (Image::ARGB);
  57306. dragImage.multiplyAllAlphas (0.6f);
  57307. const int lo = 150;
  57308. const int hi = 400;
  57309. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57310. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57311. for (int y = dragImage.getHeight(); --y >= 0;)
  57312. {
  57313. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57314. for (int x = dragImage.getWidth(); --x >= 0;)
  57315. {
  57316. const int dx = x - clipped.getX();
  57317. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57318. if (distance > lo)
  57319. {
  57320. const float alpha = (distance > hi) ? 0
  57321. : (hi - distance) / (float) (hi - lo)
  57322. + Random::getSystemRandom().nextFloat() * 0.008f;
  57323. dragImage.multiplyAlphaAt (x, y, alpha);
  57324. }
  57325. }
  57326. }
  57327. imageOffset = -clipped;
  57328. }
  57329. else
  57330. {
  57331. if (imageOffsetFromMouse == 0)
  57332. imageOffset = -dragImage.getBounds().getCentre();
  57333. else
  57334. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57335. }
  57336. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57337. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57338. currentDragDesc = sourceDescription;
  57339. if (allowDraggingToExternalWindows)
  57340. {
  57341. if (! Desktop::canUseSemiTransparentWindows())
  57342. dragImageComponent->setOpaque (true);
  57343. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57344. | ComponentPeer::windowIsTemporary
  57345. | ComponentPeer::windowIgnoresKeyPresses);
  57346. }
  57347. else
  57348. thisComp->addChildComponent (dragImageComponent);
  57349. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57350. dragImageComponent->setVisible (true);
  57351. }
  57352. }
  57353. bool DragAndDropContainer::isDragAndDropActive() const
  57354. {
  57355. return dragImageComponent != 0;
  57356. }
  57357. const String DragAndDropContainer::getCurrentDragDescription() const
  57358. {
  57359. return (dragImageComponent != 0) ? currentDragDesc
  57360. : String::empty;
  57361. }
  57362. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57363. {
  57364. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57365. }
  57366. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57367. {
  57368. return false;
  57369. }
  57370. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57371. {
  57372. }
  57373. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57374. {
  57375. }
  57376. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57377. {
  57378. }
  57379. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57380. {
  57381. return true;
  57382. }
  57383. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57384. {
  57385. }
  57386. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57387. {
  57388. }
  57389. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57390. {
  57391. }
  57392. END_JUCE_NAMESPACE
  57393. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57394. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57395. BEGIN_JUCE_NAMESPACE
  57396. class MouseCursor::SharedCursorHandle
  57397. {
  57398. public:
  57399. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57400. : handle (createStandardMouseCursor (type)),
  57401. refCount (1),
  57402. standardType (type),
  57403. isStandard (true)
  57404. {
  57405. }
  57406. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57407. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57408. refCount (1),
  57409. standardType (MouseCursor::NormalCursor),
  57410. isStandard (false)
  57411. {
  57412. }
  57413. ~SharedCursorHandle()
  57414. {
  57415. deleteMouseCursor (handle, isStandard);
  57416. }
  57417. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57418. {
  57419. const ScopedLock sl (getLock());
  57420. for (int i = 0; i < getCursors().size(); ++i)
  57421. {
  57422. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57423. if (sc->standardType == type)
  57424. return sc->retain();
  57425. }
  57426. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57427. getCursors().add (sc);
  57428. return sc;
  57429. }
  57430. SharedCursorHandle* retain() throw()
  57431. {
  57432. ++refCount;
  57433. return this;
  57434. }
  57435. void release()
  57436. {
  57437. if (--refCount == 0)
  57438. {
  57439. if (isStandard)
  57440. {
  57441. const ScopedLock sl (getLock());
  57442. getCursors().removeValue (this);
  57443. }
  57444. delete this;
  57445. }
  57446. }
  57447. void* getHandle() const throw() { return handle; }
  57448. private:
  57449. void* const handle;
  57450. Atomic <int> refCount;
  57451. const MouseCursor::StandardCursorType standardType;
  57452. const bool isStandard;
  57453. static CriticalSection& getLock()
  57454. {
  57455. static CriticalSection lock;
  57456. return lock;
  57457. }
  57458. static Array <SharedCursorHandle*>& getCursors()
  57459. {
  57460. static Array <SharedCursorHandle*> cursors;
  57461. return cursors;
  57462. }
  57463. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57464. };
  57465. MouseCursor::MouseCursor()
  57466. : cursorHandle (0)
  57467. {
  57468. }
  57469. MouseCursor::MouseCursor (const StandardCursorType type)
  57470. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57471. {
  57472. }
  57473. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57474. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57475. {
  57476. }
  57477. MouseCursor::MouseCursor (const MouseCursor& other)
  57478. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57479. {
  57480. }
  57481. MouseCursor::~MouseCursor()
  57482. {
  57483. if (cursorHandle != 0)
  57484. cursorHandle->release();
  57485. }
  57486. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57487. {
  57488. if (other.cursorHandle != 0)
  57489. other.cursorHandle->retain();
  57490. if (cursorHandle != 0)
  57491. cursorHandle->release();
  57492. cursorHandle = other.cursorHandle;
  57493. return *this;
  57494. }
  57495. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57496. {
  57497. return getHandle() == other.getHandle();
  57498. }
  57499. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57500. {
  57501. return getHandle() != other.getHandle();
  57502. }
  57503. void* MouseCursor::getHandle() const throw()
  57504. {
  57505. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57506. }
  57507. void MouseCursor::showWaitCursor()
  57508. {
  57509. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57510. }
  57511. void MouseCursor::hideWaitCursor()
  57512. {
  57513. Desktop::getInstance().getMainMouseSource().revealCursor();
  57514. }
  57515. END_JUCE_NAMESPACE
  57516. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57517. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57518. BEGIN_JUCE_NAMESPACE
  57519. MouseEvent::MouseEvent (MouseInputSource& source_,
  57520. const Point<int>& position,
  57521. const ModifierKeys& mods_,
  57522. Component* const eventComponent_,
  57523. Component* const originator,
  57524. const Time& eventTime_,
  57525. const Point<int> mouseDownPos_,
  57526. const Time& mouseDownTime_,
  57527. const int numberOfClicks_,
  57528. const bool mouseWasDragged) throw()
  57529. : x (position.getX()),
  57530. y (position.getY()),
  57531. mods (mods_),
  57532. eventComponent (eventComponent_),
  57533. originalComponent (originator),
  57534. eventTime (eventTime_),
  57535. source (source_),
  57536. mouseDownPos (mouseDownPos_),
  57537. mouseDownTime (mouseDownTime_),
  57538. numberOfClicks (numberOfClicks_),
  57539. wasMovedSinceMouseDown (mouseWasDragged)
  57540. {
  57541. }
  57542. MouseEvent::~MouseEvent() throw()
  57543. {
  57544. }
  57545. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57546. {
  57547. if (otherComponent == 0)
  57548. {
  57549. jassertfalse;
  57550. return *this;
  57551. }
  57552. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57553. mods, otherComponent, originalComponent, eventTime,
  57554. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57555. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57556. }
  57557. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57558. {
  57559. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57560. eventTime, mouseDownPos, mouseDownTime,
  57561. numberOfClicks, wasMovedSinceMouseDown);
  57562. }
  57563. bool MouseEvent::mouseWasClicked() const throw()
  57564. {
  57565. return ! wasMovedSinceMouseDown;
  57566. }
  57567. int MouseEvent::getMouseDownX() const throw()
  57568. {
  57569. return mouseDownPos.getX();
  57570. }
  57571. int MouseEvent::getMouseDownY() const throw()
  57572. {
  57573. return mouseDownPos.getY();
  57574. }
  57575. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57576. {
  57577. return mouseDownPos;
  57578. }
  57579. int MouseEvent::getDistanceFromDragStartX() const throw()
  57580. {
  57581. return x - mouseDownPos.getX();
  57582. }
  57583. int MouseEvent::getDistanceFromDragStartY() const throw()
  57584. {
  57585. return y - mouseDownPos.getY();
  57586. }
  57587. int MouseEvent::getDistanceFromDragStart() const throw()
  57588. {
  57589. return mouseDownPos.getDistanceFrom (getPosition());
  57590. }
  57591. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57592. {
  57593. return getPosition() - mouseDownPos;
  57594. }
  57595. int MouseEvent::getLengthOfMousePress() const throw()
  57596. {
  57597. if (mouseDownTime.toMilliseconds() > 0)
  57598. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57599. return 0;
  57600. }
  57601. const Point<int> MouseEvent::getPosition() const throw()
  57602. {
  57603. return Point<int> (x, y);
  57604. }
  57605. int MouseEvent::getScreenX() const
  57606. {
  57607. return getScreenPosition().getX();
  57608. }
  57609. int MouseEvent::getScreenY() const
  57610. {
  57611. return getScreenPosition().getY();
  57612. }
  57613. const Point<int> MouseEvent::getScreenPosition() const
  57614. {
  57615. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57616. }
  57617. int MouseEvent::getMouseDownScreenX() const
  57618. {
  57619. return getMouseDownScreenPosition().getX();
  57620. }
  57621. int MouseEvent::getMouseDownScreenY() const
  57622. {
  57623. return getMouseDownScreenPosition().getY();
  57624. }
  57625. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57626. {
  57627. return eventComponent->localPointToGlobal (mouseDownPos);
  57628. }
  57629. int MouseEvent::doubleClickTimeOutMs = 400;
  57630. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57631. {
  57632. doubleClickTimeOutMs = newTime;
  57633. }
  57634. int MouseEvent::getDoubleClickTimeout() throw()
  57635. {
  57636. return doubleClickTimeOutMs;
  57637. }
  57638. END_JUCE_NAMESPACE
  57639. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57640. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57641. BEGIN_JUCE_NAMESPACE
  57642. class MouseInputSourceInternal : public AsyncUpdater
  57643. {
  57644. public:
  57645. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57646. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57647. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57648. mouseEventCounter (0)
  57649. {
  57650. }
  57651. bool isDragging() const throw()
  57652. {
  57653. return buttonState.isAnyMouseButtonDown();
  57654. }
  57655. Component* getComponentUnderMouse() const
  57656. {
  57657. return static_cast <Component*> (componentUnderMouse);
  57658. }
  57659. const ModifierKeys getCurrentModifiers() const
  57660. {
  57661. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57662. }
  57663. ComponentPeer* getPeer()
  57664. {
  57665. if (! ComponentPeer::isValidPeer (lastPeer))
  57666. lastPeer = 0;
  57667. return lastPeer;
  57668. }
  57669. Component* findComponentAt (const Point<int>& screenPos)
  57670. {
  57671. ComponentPeer* const peer = getPeer();
  57672. if (peer != 0)
  57673. {
  57674. Component* const comp = peer->getComponent();
  57675. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57676. // (the contains() call is needed to test for overlapping desktop windows)
  57677. if (comp->contains (relativePos))
  57678. return comp->getComponentAt (relativePos);
  57679. }
  57680. return 0;
  57681. }
  57682. const Point<int> getScreenPosition() const
  57683. {
  57684. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57685. // value, because that can cause continuity problems.
  57686. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57687. : lastScreenPos);
  57688. }
  57689. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57690. {
  57691. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57692. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57693. }
  57694. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57695. {
  57696. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57697. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57698. }
  57699. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57700. {
  57701. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57702. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57703. }
  57704. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57705. {
  57706. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57707. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57708. }
  57709. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57710. {
  57711. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57712. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57713. }
  57714. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57715. {
  57716. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57717. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57718. }
  57719. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57720. {
  57721. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57722. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57723. }
  57724. // (returns true if the button change caused a modal event loop)
  57725. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57726. {
  57727. if (buttonState == newButtonState)
  57728. return false;
  57729. setScreenPos (screenPos, time, false);
  57730. // (ignore secondary clicks when there's already a button down)
  57731. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57732. {
  57733. buttonState = newButtonState;
  57734. return false;
  57735. }
  57736. const int lastCounter = mouseEventCounter;
  57737. if (buttonState.isAnyMouseButtonDown())
  57738. {
  57739. Component* const current = getComponentUnderMouse();
  57740. if (current != 0)
  57741. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57742. enableUnboundedMouseMovement (false, false);
  57743. }
  57744. buttonState = newButtonState;
  57745. if (buttonState.isAnyMouseButtonDown())
  57746. {
  57747. Desktop::getInstance().incrementMouseClickCounter();
  57748. Component* const current = getComponentUnderMouse();
  57749. if (current != 0)
  57750. {
  57751. registerMouseDown (screenPos, time, current, buttonState);
  57752. sendMouseDown (current, screenPos, time);
  57753. }
  57754. }
  57755. return lastCounter != mouseEventCounter;
  57756. }
  57757. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57758. {
  57759. Component* current = getComponentUnderMouse();
  57760. if (newComponent != current)
  57761. {
  57762. WeakReference<Component> safeNewComp (newComponent);
  57763. const ModifierKeys originalButtonState (buttonState);
  57764. if (current != 0)
  57765. {
  57766. setButtons (screenPos, time, ModifierKeys());
  57767. sendMouseExit (current, screenPos, time);
  57768. buttonState = originalButtonState;
  57769. }
  57770. componentUnderMouse = safeNewComp;
  57771. current = getComponentUnderMouse();
  57772. if (current != 0)
  57773. sendMouseEnter (current, screenPos, time);
  57774. revealCursor (false);
  57775. setButtons (screenPos, time, originalButtonState);
  57776. }
  57777. }
  57778. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57779. {
  57780. ModifierKeys::updateCurrentModifiers();
  57781. if (newPeer != lastPeer)
  57782. {
  57783. setComponentUnderMouse (0, screenPos, time);
  57784. lastPeer = newPeer;
  57785. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57786. }
  57787. }
  57788. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57789. {
  57790. if (! isDragging())
  57791. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57792. if (newScreenPos != lastScreenPos || forceUpdate)
  57793. {
  57794. cancelPendingUpdate();
  57795. lastScreenPos = newScreenPos;
  57796. Component* const current = getComponentUnderMouse();
  57797. if (current != 0)
  57798. {
  57799. if (isDragging())
  57800. {
  57801. registerMouseDrag (newScreenPos);
  57802. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57803. if (isUnboundedMouseModeOn)
  57804. handleUnboundedDrag (current);
  57805. }
  57806. else
  57807. {
  57808. sendMouseMove (current, newScreenPos, time);
  57809. }
  57810. }
  57811. revealCursor (false);
  57812. }
  57813. }
  57814. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57815. {
  57816. jassert (newPeer != 0);
  57817. lastTime = time;
  57818. ++mouseEventCounter;
  57819. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57820. if (isDragging() && newMods.isAnyMouseButtonDown())
  57821. {
  57822. setScreenPos (screenPos, time, false);
  57823. }
  57824. else
  57825. {
  57826. setPeer (newPeer, screenPos, time);
  57827. ComponentPeer* peer = getPeer();
  57828. if (peer != 0)
  57829. {
  57830. if (setButtons (screenPos, time, newMods))
  57831. return; // some modal events have been dispatched, so the current event is now out-of-date
  57832. peer = getPeer();
  57833. if (peer != 0)
  57834. setScreenPos (screenPos, time, false);
  57835. }
  57836. }
  57837. }
  57838. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57839. {
  57840. jassert (peer != 0);
  57841. lastTime = time;
  57842. ++mouseEventCounter;
  57843. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57844. setPeer (peer, screenPos, time);
  57845. setScreenPos (screenPos, time, false);
  57846. triggerFakeMove();
  57847. if (! isDragging())
  57848. {
  57849. Component* current = getComponentUnderMouse();
  57850. if (current != 0)
  57851. sendMouseWheel (current, screenPos, time, x, y);
  57852. }
  57853. }
  57854. const Time getLastMouseDownTime() const throw()
  57855. {
  57856. return Time (mouseDowns[0].time);
  57857. }
  57858. const Point<int> getLastMouseDownPosition() const throw()
  57859. {
  57860. return mouseDowns[0].position;
  57861. }
  57862. int getNumberOfMultipleClicks() const throw()
  57863. {
  57864. int numClicks = 0;
  57865. if (mouseDowns[0].time != Time())
  57866. {
  57867. if (! mouseMovedSignificantlySincePressed)
  57868. ++numClicks;
  57869. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57870. {
  57871. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57872. ++numClicks;
  57873. else
  57874. break;
  57875. }
  57876. }
  57877. return numClicks;
  57878. }
  57879. bool hasMouseMovedSignificantlySincePressed() const throw()
  57880. {
  57881. return mouseMovedSignificantlySincePressed
  57882. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57883. }
  57884. void triggerFakeMove()
  57885. {
  57886. triggerAsyncUpdate();
  57887. }
  57888. void handleAsyncUpdate()
  57889. {
  57890. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57891. }
  57892. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57893. {
  57894. enable = enable && isDragging();
  57895. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57896. if (enable != isUnboundedMouseModeOn)
  57897. {
  57898. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57899. {
  57900. // when released, return the mouse to within the component's bounds
  57901. Component* current = getComponentUnderMouse();
  57902. if (current != 0)
  57903. Desktop::setMousePosition (current->getScreenBounds()
  57904. .getConstrainedPoint (lastScreenPos));
  57905. }
  57906. isUnboundedMouseModeOn = enable;
  57907. unboundedMouseOffset = Point<int>();
  57908. revealCursor (true);
  57909. }
  57910. }
  57911. void handleUnboundedDrag (Component* current)
  57912. {
  57913. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57914. if (! screenArea.contains (lastScreenPos))
  57915. {
  57916. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57917. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57918. Desktop::setMousePosition (componentCentre);
  57919. }
  57920. else if (isCursorVisibleUntilOffscreen
  57921. && (! unboundedMouseOffset.isOrigin())
  57922. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57923. {
  57924. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57925. unboundedMouseOffset = Point<int>();
  57926. }
  57927. }
  57928. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57929. {
  57930. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57931. {
  57932. cursor = MouseCursor::NoCursor;
  57933. forcedUpdate = true;
  57934. }
  57935. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57936. {
  57937. currentCursorHandle = cursor.getHandle();
  57938. cursor.showInWindow (getPeer());
  57939. }
  57940. }
  57941. void hideCursor()
  57942. {
  57943. showMouseCursor (MouseCursor::NoCursor, true);
  57944. }
  57945. void revealCursor (bool forcedUpdate)
  57946. {
  57947. MouseCursor mc (MouseCursor::NormalCursor);
  57948. Component* current = getComponentUnderMouse();
  57949. if (current != 0)
  57950. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57951. showMouseCursor (mc, forcedUpdate);
  57952. }
  57953. const int index;
  57954. const bool isMouseDevice;
  57955. Point<int> lastScreenPos;
  57956. ModifierKeys buttonState;
  57957. private:
  57958. MouseInputSource& source;
  57959. WeakReference<Component> componentUnderMouse;
  57960. ComponentPeer* lastPeer;
  57961. Point<int> unboundedMouseOffset;
  57962. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57963. void* currentCursorHandle;
  57964. int mouseEventCounter;
  57965. struct RecentMouseDown
  57966. {
  57967. RecentMouseDown() : component (0)
  57968. {
  57969. }
  57970. Point<int> position;
  57971. Time time;
  57972. Component* component;
  57973. ModifierKeys buttons;
  57974. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57975. {
  57976. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57977. && abs (position.getX() - other.position.getX()) < 8
  57978. && abs (position.getY() - other.position.getY()) < 8
  57979. && buttons == other.buttons;;
  57980. }
  57981. };
  57982. RecentMouseDown mouseDowns[4];
  57983. bool mouseMovedSignificantlySincePressed;
  57984. Time lastTime;
  57985. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57986. Component* const component, const ModifierKeys& modifiers) throw()
  57987. {
  57988. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57989. mouseDowns[i] = mouseDowns[i - 1];
  57990. mouseDowns[0].position = screenPos;
  57991. mouseDowns[0].time = time;
  57992. mouseDowns[0].component = component;
  57993. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57994. mouseMovedSignificantlySincePressed = false;
  57995. }
  57996. void registerMouseDrag (const Point<int>& screenPos) throw()
  57997. {
  57998. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57999. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58000. }
  58001. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  58002. };
  58003. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58004. {
  58005. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58006. }
  58007. MouseInputSource::~MouseInputSource()
  58008. {
  58009. }
  58010. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58011. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58012. bool MouseInputSource::canHover() const { return isMouse(); }
  58013. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58014. int MouseInputSource::getIndex() const { return pimpl->index; }
  58015. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58016. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58017. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58018. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58019. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58020. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58021. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58022. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58023. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58024. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58025. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58026. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58027. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58028. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58029. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58030. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58031. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58032. {
  58033. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  58034. }
  58035. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58036. {
  58037. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  58038. }
  58039. END_JUCE_NAMESPACE
  58040. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58041. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58042. BEGIN_JUCE_NAMESPACE
  58043. void MouseListener::mouseEnter (const MouseEvent&)
  58044. {
  58045. }
  58046. void MouseListener::mouseExit (const MouseEvent&)
  58047. {
  58048. }
  58049. void MouseListener::mouseDown (const MouseEvent&)
  58050. {
  58051. }
  58052. void MouseListener::mouseUp (const MouseEvent&)
  58053. {
  58054. }
  58055. void MouseListener::mouseDrag (const MouseEvent&)
  58056. {
  58057. }
  58058. void MouseListener::mouseMove (const MouseEvent&)
  58059. {
  58060. }
  58061. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58062. {
  58063. }
  58064. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58065. {
  58066. }
  58067. END_JUCE_NAMESPACE
  58068. /*** End of inlined file: juce_MouseListener.cpp ***/
  58069. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58070. BEGIN_JUCE_NAMESPACE
  58071. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58072. const String& buttonTextWhenTrue,
  58073. const String& buttonTextWhenFalse)
  58074. : PropertyComponent (name),
  58075. onText (buttonTextWhenTrue),
  58076. offText (buttonTextWhenFalse)
  58077. {
  58078. addAndMakeVisible (&button);
  58079. button.setClickingTogglesState (false);
  58080. button.addListener (this);
  58081. }
  58082. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58083. const String& name,
  58084. const String& buttonText)
  58085. : PropertyComponent (name),
  58086. onText (buttonText),
  58087. offText (buttonText)
  58088. {
  58089. addAndMakeVisible (&button);
  58090. button.setClickingTogglesState (false);
  58091. button.setButtonText (buttonText);
  58092. button.getToggleStateValue().referTo (valueToControl);
  58093. button.setClickingTogglesState (true);
  58094. }
  58095. BooleanPropertyComponent::~BooleanPropertyComponent()
  58096. {
  58097. }
  58098. void BooleanPropertyComponent::setState (const bool newState)
  58099. {
  58100. button.setToggleState (newState, true);
  58101. }
  58102. bool BooleanPropertyComponent::getState() const
  58103. {
  58104. return button.getToggleState();
  58105. }
  58106. void BooleanPropertyComponent::paint (Graphics& g)
  58107. {
  58108. PropertyComponent::paint (g);
  58109. g.setColour (Colours::white);
  58110. g.fillRect (button.getBounds());
  58111. g.setColour (findColour (ComboBox::outlineColourId));
  58112. g.drawRect (button.getBounds());
  58113. }
  58114. void BooleanPropertyComponent::refresh()
  58115. {
  58116. button.setToggleState (getState(), false);
  58117. button.setButtonText (button.getToggleState() ? onText : offText);
  58118. }
  58119. void BooleanPropertyComponent::buttonClicked (Button*)
  58120. {
  58121. setState (! getState());
  58122. }
  58123. END_JUCE_NAMESPACE
  58124. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58125. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58126. BEGIN_JUCE_NAMESPACE
  58127. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58128. const bool triggerOnMouseDown)
  58129. : PropertyComponent (name)
  58130. {
  58131. addAndMakeVisible (&button);
  58132. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58133. button.addListener (this);
  58134. }
  58135. ButtonPropertyComponent::~ButtonPropertyComponent()
  58136. {
  58137. }
  58138. void ButtonPropertyComponent::refresh()
  58139. {
  58140. button.setButtonText (getButtonText());
  58141. }
  58142. void ButtonPropertyComponent::buttonClicked (Button*)
  58143. {
  58144. buttonClicked();
  58145. }
  58146. END_JUCE_NAMESPACE
  58147. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58148. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58149. BEGIN_JUCE_NAMESPACE
  58150. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58151. public ValueListener
  58152. {
  58153. public:
  58154. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58155. : sourceValue (sourceValue_),
  58156. mappings (mappings_)
  58157. {
  58158. sourceValue.addListener (this);
  58159. }
  58160. ~RemapperValueSource() {}
  58161. const var getValue() const
  58162. {
  58163. return mappings.indexOf (sourceValue.getValue()) + 1;
  58164. }
  58165. void setValue (const var& newValue)
  58166. {
  58167. const var remappedVal (mappings [(int) newValue - 1]);
  58168. if (remappedVal != sourceValue)
  58169. sourceValue = remappedVal;
  58170. }
  58171. void valueChanged (Value&)
  58172. {
  58173. sendChangeMessage (true);
  58174. }
  58175. protected:
  58176. Value sourceValue;
  58177. Array<var> mappings;
  58178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  58179. };
  58180. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58181. : PropertyComponent (name),
  58182. isCustomClass (true)
  58183. {
  58184. }
  58185. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58186. const String& name,
  58187. const StringArray& choices_,
  58188. const Array <var>& correspondingValues)
  58189. : PropertyComponent (name),
  58190. choices (choices_),
  58191. isCustomClass (false)
  58192. {
  58193. // The array of corresponding values must contain one value for each of the items in
  58194. // the choices array!
  58195. jassert (correspondingValues.size() == choices.size());
  58196. createComboBox();
  58197. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58198. }
  58199. ChoicePropertyComponent::~ChoicePropertyComponent()
  58200. {
  58201. }
  58202. void ChoicePropertyComponent::createComboBox()
  58203. {
  58204. addAndMakeVisible (&comboBox);
  58205. for (int i = 0; i < choices.size(); ++i)
  58206. {
  58207. if (choices[i].isNotEmpty())
  58208. comboBox.addItem (choices[i], i + 1);
  58209. else
  58210. comboBox.addSeparator();
  58211. }
  58212. comboBox.setEditableText (false);
  58213. }
  58214. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58215. {
  58216. jassertfalse; // you need to override this method in your subclass!
  58217. }
  58218. int ChoicePropertyComponent::getIndex() const
  58219. {
  58220. jassertfalse; // you need to override this method in your subclass!
  58221. return -1;
  58222. }
  58223. const StringArray& ChoicePropertyComponent::getChoices() const
  58224. {
  58225. return choices;
  58226. }
  58227. void ChoicePropertyComponent::refresh()
  58228. {
  58229. if (isCustomClass)
  58230. {
  58231. if (! comboBox.isVisible())
  58232. {
  58233. createComboBox();
  58234. comboBox.addListener (this);
  58235. }
  58236. comboBox.setSelectedId (getIndex() + 1, true);
  58237. }
  58238. }
  58239. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58240. {
  58241. if (isCustomClass)
  58242. {
  58243. const int newIndex = comboBox.getSelectedId() - 1;
  58244. if (newIndex != getIndex())
  58245. setIndex (newIndex);
  58246. }
  58247. }
  58248. END_JUCE_NAMESPACE
  58249. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58250. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58251. BEGIN_JUCE_NAMESPACE
  58252. PropertyComponent::PropertyComponent (const String& name,
  58253. const int preferredHeight_)
  58254. : Component (name),
  58255. preferredHeight (preferredHeight_)
  58256. {
  58257. jassert (name.isNotEmpty());
  58258. }
  58259. PropertyComponent::~PropertyComponent()
  58260. {
  58261. }
  58262. void PropertyComponent::paint (Graphics& g)
  58263. {
  58264. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58265. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58266. }
  58267. void PropertyComponent::resized()
  58268. {
  58269. if (getNumChildComponents() > 0)
  58270. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58271. }
  58272. void PropertyComponent::enablementChanged()
  58273. {
  58274. repaint();
  58275. }
  58276. END_JUCE_NAMESPACE
  58277. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58278. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58279. BEGIN_JUCE_NAMESPACE
  58280. class PropertySectionComponent : public Component
  58281. {
  58282. public:
  58283. PropertySectionComponent (const String& sectionTitle,
  58284. const Array <PropertyComponent*>& newProperties,
  58285. const bool sectionIsOpen_)
  58286. : Component (sectionTitle),
  58287. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58288. sectionIsOpen (sectionIsOpen_)
  58289. {
  58290. propertyComps.addArray (newProperties);
  58291. for (int i = propertyComps.size(); --i >= 0;)
  58292. {
  58293. addAndMakeVisible (propertyComps.getUnchecked(i));
  58294. propertyComps.getUnchecked(i)->refresh();
  58295. }
  58296. }
  58297. ~PropertySectionComponent()
  58298. {
  58299. propertyComps.clear();
  58300. }
  58301. void paint (Graphics& g)
  58302. {
  58303. if (titleHeight > 0)
  58304. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58305. }
  58306. void resized()
  58307. {
  58308. int y = titleHeight;
  58309. for (int i = 0; i < propertyComps.size(); ++i)
  58310. {
  58311. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58312. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58313. y = pec->getBottom();
  58314. }
  58315. }
  58316. int getPreferredHeight() const
  58317. {
  58318. int y = titleHeight;
  58319. if (isOpen())
  58320. {
  58321. for (int i = propertyComps.size(); --i >= 0;)
  58322. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58323. }
  58324. return y;
  58325. }
  58326. void setOpen (const bool open)
  58327. {
  58328. if (sectionIsOpen != open)
  58329. {
  58330. sectionIsOpen = open;
  58331. for (int i = propertyComps.size(); --i >= 0;)
  58332. propertyComps.getUnchecked(i)->setVisible (open);
  58333. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58334. if (pp != 0)
  58335. pp->resized();
  58336. }
  58337. }
  58338. bool isOpen() const
  58339. {
  58340. return sectionIsOpen;
  58341. }
  58342. void refreshAll() const
  58343. {
  58344. for (int i = propertyComps.size(); --i >= 0;)
  58345. propertyComps.getUnchecked (i)->refresh();
  58346. }
  58347. void mouseUp (const MouseEvent& e)
  58348. {
  58349. if (e.getMouseDownX() < titleHeight
  58350. && e.x < titleHeight
  58351. && e.y < titleHeight
  58352. && e.getNumberOfClicks() != 2)
  58353. {
  58354. setOpen (! isOpen());
  58355. }
  58356. }
  58357. void mouseDoubleClick (const MouseEvent& e)
  58358. {
  58359. if (e.y < titleHeight)
  58360. setOpen (! isOpen());
  58361. }
  58362. private:
  58363. OwnedArray <PropertyComponent> propertyComps;
  58364. int titleHeight;
  58365. bool sectionIsOpen;
  58366. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58367. };
  58368. class PropertyPanel::PropertyHolderComponent : public Component
  58369. {
  58370. public:
  58371. PropertyHolderComponent() {}
  58372. void paint (Graphics&) {}
  58373. void updateLayout (int width)
  58374. {
  58375. int y = 0;
  58376. for (int i = 0; i < sections.size(); ++i)
  58377. {
  58378. PropertySectionComponent* const section = sections.getUnchecked(i);
  58379. section->setBounds (0, y, width, section->getPreferredHeight());
  58380. y = section->getBottom();
  58381. }
  58382. setSize (width, y);
  58383. repaint();
  58384. }
  58385. void refreshAll() const
  58386. {
  58387. for (int i = 0; i < sections.size(); ++i)
  58388. sections.getUnchecked(i)->refreshAll();
  58389. }
  58390. void clear()
  58391. {
  58392. sections.clear();
  58393. }
  58394. void addSection (PropertySectionComponent* newSection)
  58395. {
  58396. sections.add (newSection);
  58397. addAndMakeVisible (newSection, 0);
  58398. }
  58399. int getNumSections() const throw() { return sections.size(); }
  58400. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58401. private:
  58402. OwnedArray<PropertySectionComponent> sections;
  58403. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58404. };
  58405. PropertyPanel::PropertyPanel()
  58406. {
  58407. messageWhenEmpty = TRANS("(nothing selected)");
  58408. addAndMakeVisible (&viewport);
  58409. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58410. viewport.setFocusContainer (true);
  58411. }
  58412. PropertyPanel::~PropertyPanel()
  58413. {
  58414. clear();
  58415. }
  58416. void PropertyPanel::paint (Graphics& g)
  58417. {
  58418. if (propertyHolderComponent->getNumSections() == 0)
  58419. {
  58420. g.setColour (Colours::black.withAlpha (0.5f));
  58421. g.setFont (14.0f);
  58422. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58423. Justification::centred, true);
  58424. }
  58425. }
  58426. void PropertyPanel::resized()
  58427. {
  58428. viewport.setBounds (getLocalBounds());
  58429. updatePropHolderLayout();
  58430. }
  58431. void PropertyPanel::clear()
  58432. {
  58433. if (propertyHolderComponent->getNumSections() > 0)
  58434. {
  58435. propertyHolderComponent->clear();
  58436. repaint();
  58437. }
  58438. }
  58439. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58440. {
  58441. if (propertyHolderComponent->getNumSections() == 0)
  58442. repaint();
  58443. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58444. updatePropHolderLayout();
  58445. }
  58446. void PropertyPanel::addSection (const String& sectionTitle,
  58447. const Array <PropertyComponent*>& newProperties,
  58448. const bool shouldBeOpen)
  58449. {
  58450. jassert (sectionTitle.isNotEmpty());
  58451. if (propertyHolderComponent->getNumSections() == 0)
  58452. repaint();
  58453. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58454. updatePropHolderLayout();
  58455. }
  58456. void PropertyPanel::updatePropHolderLayout() const
  58457. {
  58458. const int maxWidth = viewport.getMaximumVisibleWidth();
  58459. propertyHolderComponent->updateLayout (maxWidth);
  58460. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58461. if (maxWidth != newMaxWidth)
  58462. {
  58463. // need to do this twice because of scrollbars changing the size, etc.
  58464. propertyHolderComponent->updateLayout (newMaxWidth);
  58465. }
  58466. }
  58467. void PropertyPanel::refreshAll() const
  58468. {
  58469. propertyHolderComponent->refreshAll();
  58470. }
  58471. const StringArray PropertyPanel::getSectionNames() const
  58472. {
  58473. StringArray s;
  58474. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58475. {
  58476. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58477. if (section->getName().isNotEmpty())
  58478. s.add (section->getName());
  58479. }
  58480. return s;
  58481. }
  58482. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58483. {
  58484. int index = 0;
  58485. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58486. {
  58487. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58488. if (section->getName().isNotEmpty())
  58489. {
  58490. if (index == sectionIndex)
  58491. return section->isOpen();
  58492. ++index;
  58493. }
  58494. }
  58495. return false;
  58496. }
  58497. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58498. {
  58499. int index = 0;
  58500. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58501. {
  58502. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58503. if (section->getName().isNotEmpty())
  58504. {
  58505. if (index == sectionIndex)
  58506. {
  58507. section->setOpen (shouldBeOpen);
  58508. break;
  58509. }
  58510. ++index;
  58511. }
  58512. }
  58513. }
  58514. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58515. {
  58516. int index = 0;
  58517. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58518. {
  58519. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58520. if (section->getName().isNotEmpty())
  58521. {
  58522. if (index == sectionIndex)
  58523. {
  58524. section->setEnabled (shouldBeEnabled);
  58525. break;
  58526. }
  58527. ++index;
  58528. }
  58529. }
  58530. }
  58531. XmlElement* PropertyPanel::getOpennessState() const
  58532. {
  58533. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58534. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58535. const StringArray sections (getSectionNames());
  58536. for (int i = 0; i < sections.size(); ++i)
  58537. {
  58538. if (sections[i].isNotEmpty())
  58539. {
  58540. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58541. e->setAttribute ("name", sections[i]);
  58542. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58543. }
  58544. }
  58545. return xml;
  58546. }
  58547. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58548. {
  58549. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58550. {
  58551. const StringArray sections (getSectionNames());
  58552. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58553. {
  58554. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58555. e->getBoolAttribute ("open"));
  58556. }
  58557. viewport.setViewPosition (viewport.getViewPositionX(),
  58558. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58559. }
  58560. }
  58561. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58562. {
  58563. if (messageWhenEmpty != newMessage)
  58564. {
  58565. messageWhenEmpty = newMessage;
  58566. repaint();
  58567. }
  58568. }
  58569. const String& PropertyPanel::getMessageWhenEmpty() const
  58570. {
  58571. return messageWhenEmpty;
  58572. }
  58573. END_JUCE_NAMESPACE
  58574. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58575. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58576. BEGIN_JUCE_NAMESPACE
  58577. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58578. const double rangeMin,
  58579. const double rangeMax,
  58580. const double interval,
  58581. const double skewFactor)
  58582. : PropertyComponent (name)
  58583. {
  58584. addAndMakeVisible (&slider);
  58585. slider.setRange (rangeMin, rangeMax, interval);
  58586. slider.setSkewFactor (skewFactor);
  58587. slider.setSliderStyle (Slider::LinearBar);
  58588. slider.addListener (this);
  58589. }
  58590. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58591. const String& name,
  58592. const double rangeMin,
  58593. const double rangeMax,
  58594. const double interval,
  58595. const double skewFactor)
  58596. : PropertyComponent (name)
  58597. {
  58598. addAndMakeVisible (&slider);
  58599. slider.setRange (rangeMin, rangeMax, interval);
  58600. slider.setSkewFactor (skewFactor);
  58601. slider.setSliderStyle (Slider::LinearBar);
  58602. slider.getValueObject().referTo (valueToControl);
  58603. }
  58604. SliderPropertyComponent::~SliderPropertyComponent()
  58605. {
  58606. }
  58607. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58608. {
  58609. }
  58610. double SliderPropertyComponent::getValue() const
  58611. {
  58612. return slider.getValue();
  58613. }
  58614. void SliderPropertyComponent::refresh()
  58615. {
  58616. slider.setValue (getValue(), false);
  58617. }
  58618. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58619. {
  58620. if (getValue() != slider.getValue())
  58621. setValue (slider.getValue());
  58622. }
  58623. END_JUCE_NAMESPACE
  58624. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58625. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58626. BEGIN_JUCE_NAMESPACE
  58627. class TextPropLabel : public Label
  58628. {
  58629. public:
  58630. TextPropLabel (TextPropertyComponent& owner_,
  58631. const int maxChars_, const bool isMultiline_)
  58632. : Label (String::empty, String::empty),
  58633. owner (owner_),
  58634. maxChars (maxChars_),
  58635. isMultiline (isMultiline_)
  58636. {
  58637. setEditable (true, true, false);
  58638. setColour (backgroundColourId, Colours::white);
  58639. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58640. }
  58641. TextEditor* createEditorComponent()
  58642. {
  58643. TextEditor* const textEditor = Label::createEditorComponent();
  58644. textEditor->setInputRestrictions (maxChars);
  58645. if (isMultiline)
  58646. {
  58647. textEditor->setMultiLine (true, true);
  58648. textEditor->setReturnKeyStartsNewLine (true);
  58649. }
  58650. return textEditor;
  58651. }
  58652. void textWasEdited()
  58653. {
  58654. owner.textWasEdited();
  58655. }
  58656. private:
  58657. TextPropertyComponent& owner;
  58658. int maxChars;
  58659. bool isMultiline;
  58660. };
  58661. TextPropertyComponent::TextPropertyComponent (const String& name,
  58662. const int maxNumChars,
  58663. const bool isMultiLine)
  58664. : PropertyComponent (name)
  58665. {
  58666. createEditor (maxNumChars, isMultiLine);
  58667. }
  58668. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58669. const String& name,
  58670. const int maxNumChars,
  58671. const bool isMultiLine)
  58672. : PropertyComponent (name)
  58673. {
  58674. createEditor (maxNumChars, isMultiLine);
  58675. textEditor->getTextValue().referTo (valueToControl);
  58676. }
  58677. TextPropertyComponent::~TextPropertyComponent()
  58678. {
  58679. }
  58680. void TextPropertyComponent::setText (const String& newText)
  58681. {
  58682. textEditor->setText (newText, true);
  58683. }
  58684. const String TextPropertyComponent::getText() const
  58685. {
  58686. return textEditor->getText();
  58687. }
  58688. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58689. {
  58690. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58691. if (isMultiLine)
  58692. {
  58693. textEditor->setJustificationType (Justification::topLeft);
  58694. preferredHeight = 120;
  58695. }
  58696. }
  58697. void TextPropertyComponent::refresh()
  58698. {
  58699. textEditor->setText (getText(), false);
  58700. }
  58701. void TextPropertyComponent::textWasEdited()
  58702. {
  58703. const String newText (textEditor->getText());
  58704. if (getText() != newText)
  58705. setText (newText);
  58706. }
  58707. END_JUCE_NAMESPACE
  58708. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58709. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58710. BEGIN_JUCE_NAMESPACE
  58711. class SimpleDeviceManagerInputLevelMeter : public Component,
  58712. public Timer
  58713. {
  58714. public:
  58715. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58716. : manager (manager_),
  58717. level (0)
  58718. {
  58719. startTimer (50);
  58720. manager->enableInputLevelMeasurement (true);
  58721. }
  58722. ~SimpleDeviceManagerInputLevelMeter()
  58723. {
  58724. manager->enableInputLevelMeasurement (false);
  58725. }
  58726. void timerCallback()
  58727. {
  58728. const float newLevel = (float) manager->getCurrentInputLevel();
  58729. if (std::abs (level - newLevel) > 0.005f)
  58730. {
  58731. level = newLevel;
  58732. repaint();
  58733. }
  58734. }
  58735. void paint (Graphics& g)
  58736. {
  58737. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58738. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58739. }
  58740. private:
  58741. AudioDeviceManager* const manager;
  58742. float level;
  58743. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58744. };
  58745. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58746. public ListBoxModel
  58747. {
  58748. public:
  58749. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58750. const String& noItemsMessage_,
  58751. const int minNumber_,
  58752. const int maxNumber_)
  58753. : ListBox (String::empty, 0),
  58754. deviceManager (deviceManager_),
  58755. noItemsMessage (noItemsMessage_),
  58756. minNumber (minNumber_),
  58757. maxNumber (maxNumber_)
  58758. {
  58759. items = MidiInput::getDevices();
  58760. setModel (this);
  58761. setOutlineThickness (1);
  58762. }
  58763. ~MidiInputSelectorComponentListBox()
  58764. {
  58765. }
  58766. int getNumRows()
  58767. {
  58768. return items.size();
  58769. }
  58770. void paintListBoxItem (int row,
  58771. Graphics& g,
  58772. int width, int height,
  58773. bool rowIsSelected)
  58774. {
  58775. if (isPositiveAndBelow (row, items.size()))
  58776. {
  58777. if (rowIsSelected)
  58778. g.fillAll (findColour (TextEditor::highlightColourId)
  58779. .withMultipliedAlpha (0.3f));
  58780. const String item (items [row]);
  58781. bool enabled = deviceManager.isMidiInputEnabled (item);
  58782. const int x = getTickX();
  58783. const float tickW = height * 0.75f;
  58784. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58785. enabled, true, true, false);
  58786. g.setFont (height * 0.6f);
  58787. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58788. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58789. }
  58790. }
  58791. void listBoxItemClicked (int row, const MouseEvent& e)
  58792. {
  58793. selectRow (row);
  58794. if (e.x < getTickX())
  58795. flipEnablement (row);
  58796. }
  58797. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58798. {
  58799. flipEnablement (row);
  58800. }
  58801. void returnKeyPressed (int row)
  58802. {
  58803. flipEnablement (row);
  58804. }
  58805. void paint (Graphics& g)
  58806. {
  58807. ListBox::paint (g);
  58808. if (items.size() == 0)
  58809. {
  58810. g.setColour (Colours::grey);
  58811. g.setFont (13.0f);
  58812. g.drawText (noItemsMessage,
  58813. 0, 0, getWidth(), getHeight() / 2,
  58814. Justification::centred, true);
  58815. }
  58816. }
  58817. int getBestHeight (const int preferredHeight)
  58818. {
  58819. const int extra = getOutlineThickness() * 2;
  58820. return jmax (getRowHeight() * 2 + extra,
  58821. jmin (getRowHeight() * getNumRows() + extra,
  58822. preferredHeight));
  58823. }
  58824. private:
  58825. AudioDeviceManager& deviceManager;
  58826. const String noItemsMessage;
  58827. StringArray items;
  58828. int minNumber, maxNumber;
  58829. void flipEnablement (const int row)
  58830. {
  58831. if (isPositiveAndBelow (row, items.size()))
  58832. {
  58833. const String item (items [row]);
  58834. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58835. }
  58836. }
  58837. int getTickX() const
  58838. {
  58839. return getRowHeight() + 5;
  58840. }
  58841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58842. };
  58843. class AudioDeviceSettingsPanel : public Component,
  58844. public ChangeListener,
  58845. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58846. public ButtonListener
  58847. {
  58848. public:
  58849. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58850. AudioIODeviceType::DeviceSetupDetails& setup_,
  58851. const bool hideAdvancedOptionsWithButton)
  58852. : type (type_),
  58853. setup (setup_)
  58854. {
  58855. if (hideAdvancedOptionsWithButton)
  58856. {
  58857. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58858. showAdvancedSettingsButton->addListener (this);
  58859. }
  58860. type->scanForDevices();
  58861. setup.manager->addChangeListener (this);
  58862. changeListenerCallback (0);
  58863. }
  58864. ~AudioDeviceSettingsPanel()
  58865. {
  58866. setup.manager->removeChangeListener (this);
  58867. }
  58868. void resized()
  58869. {
  58870. const int lx = proportionOfWidth (0.35f);
  58871. const int w = proportionOfWidth (0.4f);
  58872. const int h = 24;
  58873. const int space = 6;
  58874. const int dh = h + space;
  58875. int y = 0;
  58876. if (outputDeviceDropDown != 0)
  58877. {
  58878. outputDeviceDropDown->setBounds (lx, y, w, h);
  58879. if (testButton != 0)
  58880. testButton->setBounds (proportionOfWidth (0.77f),
  58881. outputDeviceDropDown->getY(),
  58882. proportionOfWidth (0.18f),
  58883. h);
  58884. y += dh;
  58885. }
  58886. if (inputDeviceDropDown != 0)
  58887. {
  58888. inputDeviceDropDown->setBounds (lx, y, w, h);
  58889. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58890. inputDeviceDropDown->getY(),
  58891. proportionOfWidth (0.18f),
  58892. h);
  58893. y += dh;
  58894. }
  58895. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58896. if (outputChanList != 0)
  58897. {
  58898. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58899. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58900. y += bh + space;
  58901. }
  58902. if (inputChanList != 0)
  58903. {
  58904. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58905. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58906. y += bh + space;
  58907. }
  58908. y += space * 2;
  58909. if (showAdvancedSettingsButton != 0)
  58910. {
  58911. showAdvancedSettingsButton->changeWidthToFitText (h);
  58912. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58913. }
  58914. if (sampleRateDropDown != 0)
  58915. {
  58916. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58917. || ! showAdvancedSettingsButton->isVisible());
  58918. sampleRateDropDown->setBounds (lx, y, w, h);
  58919. y += dh;
  58920. }
  58921. if (bufferSizeDropDown != 0)
  58922. {
  58923. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58924. || ! showAdvancedSettingsButton->isVisible());
  58925. bufferSizeDropDown->setBounds (lx, y, w, h);
  58926. y += dh;
  58927. }
  58928. if (showUIButton != 0)
  58929. {
  58930. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58931. || ! showAdvancedSettingsButton->isVisible());
  58932. showUIButton->changeWidthToFitText (h);
  58933. showUIButton->setTopLeftPosition (lx, y);
  58934. }
  58935. }
  58936. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58937. {
  58938. if (comboBoxThatHasChanged == 0)
  58939. return;
  58940. AudioDeviceManager::AudioDeviceSetup config;
  58941. setup.manager->getAudioDeviceSetup (config);
  58942. String error;
  58943. if (comboBoxThatHasChanged == outputDeviceDropDown
  58944. || comboBoxThatHasChanged == inputDeviceDropDown)
  58945. {
  58946. if (outputDeviceDropDown != 0)
  58947. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58948. : outputDeviceDropDown->getText();
  58949. if (inputDeviceDropDown != 0)
  58950. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58951. : inputDeviceDropDown->getText();
  58952. if (! type->hasSeparateInputsAndOutputs())
  58953. config.inputDeviceName = config.outputDeviceName;
  58954. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58955. config.useDefaultInputChannels = true;
  58956. else
  58957. config.useDefaultOutputChannels = true;
  58958. error = setup.manager->setAudioDeviceSetup (config, true);
  58959. showCorrectDeviceName (inputDeviceDropDown, true);
  58960. showCorrectDeviceName (outputDeviceDropDown, false);
  58961. updateControlPanelButton();
  58962. resized();
  58963. }
  58964. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58965. {
  58966. if (sampleRateDropDown->getSelectedId() > 0)
  58967. {
  58968. config.sampleRate = sampleRateDropDown->getSelectedId();
  58969. error = setup.manager->setAudioDeviceSetup (config, true);
  58970. }
  58971. }
  58972. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58973. {
  58974. if (bufferSizeDropDown->getSelectedId() > 0)
  58975. {
  58976. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58977. error = setup.manager->setAudioDeviceSetup (config, true);
  58978. }
  58979. }
  58980. if (error.isNotEmpty())
  58981. {
  58982. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  58983. "Error when trying to open audio device!",
  58984. error);
  58985. }
  58986. }
  58987. void buttonClicked (Button* button)
  58988. {
  58989. if (button == showAdvancedSettingsButton)
  58990. {
  58991. showAdvancedSettingsButton->setVisible (false);
  58992. resized();
  58993. }
  58994. else if (button == showUIButton)
  58995. {
  58996. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58997. if (device != 0 && device->showControlPanel())
  58998. {
  58999. setup.manager->closeAudioDevice();
  59000. setup.manager->restartLastAudioDevice();
  59001. getTopLevelComponent()->toFront (true);
  59002. }
  59003. }
  59004. else if (button == testButton && testButton != 0)
  59005. {
  59006. setup.manager->playTestSound();
  59007. }
  59008. }
  59009. void updateControlPanelButton()
  59010. {
  59011. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59012. showUIButton = 0;
  59013. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59014. {
  59015. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59016. TRANS ("opens the device's own control panel")));
  59017. showUIButton->addListener (this);
  59018. }
  59019. resized();
  59020. }
  59021. void changeListenerCallback (ChangeBroadcaster*)
  59022. {
  59023. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59024. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59025. {
  59026. if (outputDeviceDropDown == 0)
  59027. {
  59028. outputDeviceDropDown = new ComboBox (String::empty);
  59029. outputDeviceDropDown->addListener (this);
  59030. addAndMakeVisible (outputDeviceDropDown);
  59031. outputDeviceLabel = new Label (String::empty,
  59032. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59033. : TRANS ("device:"));
  59034. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59035. if (setup.maxNumOutputChannels > 0)
  59036. {
  59037. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59038. testButton->addListener (this);
  59039. }
  59040. }
  59041. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59042. }
  59043. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59044. {
  59045. if (inputDeviceDropDown == 0)
  59046. {
  59047. inputDeviceDropDown = new ComboBox (String::empty);
  59048. inputDeviceDropDown->addListener (this);
  59049. addAndMakeVisible (inputDeviceDropDown);
  59050. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59051. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59052. addAndMakeVisible (inputLevelMeter
  59053. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59054. }
  59055. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59056. }
  59057. updateControlPanelButton();
  59058. showCorrectDeviceName (inputDeviceDropDown, true);
  59059. showCorrectDeviceName (outputDeviceDropDown, false);
  59060. if (currentDevice != 0)
  59061. {
  59062. if (setup.maxNumOutputChannels > 0
  59063. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59064. {
  59065. if (outputChanList == 0)
  59066. {
  59067. addAndMakeVisible (outputChanList
  59068. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59069. TRANS ("(no audio output channels found)")));
  59070. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59071. outputChanLabel->attachToComponent (outputChanList, true);
  59072. }
  59073. outputChanList->refresh();
  59074. }
  59075. else
  59076. {
  59077. outputChanLabel = 0;
  59078. outputChanList = 0;
  59079. }
  59080. if (setup.maxNumInputChannels > 0
  59081. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59082. {
  59083. if (inputChanList == 0)
  59084. {
  59085. addAndMakeVisible (inputChanList
  59086. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59087. TRANS ("(no audio input channels found)")));
  59088. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59089. inputChanLabel->attachToComponent (inputChanList, true);
  59090. }
  59091. inputChanList->refresh();
  59092. }
  59093. else
  59094. {
  59095. inputChanLabel = 0;
  59096. inputChanList = 0;
  59097. }
  59098. // sample rate..
  59099. {
  59100. if (sampleRateDropDown == 0)
  59101. {
  59102. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59103. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59104. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59105. }
  59106. else
  59107. {
  59108. sampleRateDropDown->clear();
  59109. sampleRateDropDown->removeListener (this);
  59110. }
  59111. const int numRates = currentDevice->getNumSampleRates();
  59112. for (int i = 0; i < numRates; ++i)
  59113. {
  59114. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59115. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59116. }
  59117. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59118. sampleRateDropDown->addListener (this);
  59119. }
  59120. // buffer size
  59121. {
  59122. if (bufferSizeDropDown == 0)
  59123. {
  59124. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59125. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59126. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59127. }
  59128. else
  59129. {
  59130. bufferSizeDropDown->clear();
  59131. bufferSizeDropDown->removeListener (this);
  59132. }
  59133. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59134. double currentRate = currentDevice->getCurrentSampleRate();
  59135. if (currentRate == 0)
  59136. currentRate = 48000.0;
  59137. for (int i = 0; i < numBufferSizes; ++i)
  59138. {
  59139. const int bs = currentDevice->getBufferSizeSamples (i);
  59140. bufferSizeDropDown->addItem (String (bs)
  59141. + " samples ("
  59142. + String (bs * 1000.0 / currentRate, 1)
  59143. + " ms)",
  59144. bs);
  59145. }
  59146. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59147. bufferSizeDropDown->addListener (this);
  59148. }
  59149. }
  59150. else
  59151. {
  59152. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59153. sampleRateLabel = 0;
  59154. bufferSizeLabel = 0;
  59155. sampleRateDropDown = 0;
  59156. bufferSizeDropDown = 0;
  59157. if (outputDeviceDropDown != 0)
  59158. outputDeviceDropDown->setSelectedId (-1, true);
  59159. if (inputDeviceDropDown != 0)
  59160. inputDeviceDropDown->setSelectedId (-1, true);
  59161. }
  59162. resized();
  59163. setSize (getWidth(), getLowestY() + 4);
  59164. }
  59165. private:
  59166. AudioIODeviceType* const type;
  59167. const AudioIODeviceType::DeviceSetupDetails setup;
  59168. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59169. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59170. ScopedPointer<TextButton> testButton;
  59171. ScopedPointer<Component> inputLevelMeter;
  59172. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59173. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59174. {
  59175. if (box != 0)
  59176. {
  59177. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59178. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59179. box->setSelectedId (index + 1, true);
  59180. if (testButton != 0 && ! isInput)
  59181. testButton->setEnabled (index >= 0);
  59182. }
  59183. }
  59184. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59185. {
  59186. const StringArray devs (type->getDeviceNames (isInputs));
  59187. combo.clear (true);
  59188. for (int i = 0; i < devs.size(); ++i)
  59189. combo.addItem (devs[i], i + 1);
  59190. combo.addItem (TRANS("<< none >>"), -1);
  59191. combo.setSelectedId (-1, true);
  59192. }
  59193. int getLowestY() const
  59194. {
  59195. int y = 0;
  59196. for (int i = getNumChildComponents(); --i >= 0;)
  59197. y = jmax (y, getChildComponent (i)->getBottom());
  59198. return y;
  59199. }
  59200. public:
  59201. class ChannelSelectorListBox : public ListBox,
  59202. public ListBoxModel
  59203. {
  59204. public:
  59205. enum BoxType
  59206. {
  59207. audioInputType,
  59208. audioOutputType
  59209. };
  59210. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59211. const BoxType type_,
  59212. const String& noItemsMessage_)
  59213. : ListBox (String::empty, 0),
  59214. setup (setup_),
  59215. type (type_),
  59216. noItemsMessage (noItemsMessage_)
  59217. {
  59218. refresh();
  59219. setModel (this);
  59220. setOutlineThickness (1);
  59221. }
  59222. ~ChannelSelectorListBox()
  59223. {
  59224. }
  59225. void refresh()
  59226. {
  59227. items.clear();
  59228. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59229. if (currentDevice != 0)
  59230. {
  59231. if (type == audioInputType)
  59232. items = currentDevice->getInputChannelNames();
  59233. else if (type == audioOutputType)
  59234. items = currentDevice->getOutputChannelNames();
  59235. if (setup.useStereoPairs)
  59236. {
  59237. StringArray pairs;
  59238. for (int i = 0; i < items.size(); i += 2)
  59239. {
  59240. const String name (items[i]);
  59241. const String name2 (items[i + 1]);
  59242. String commonBit;
  59243. for (int j = 0; j < name.length(); ++j)
  59244. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59245. commonBit = name.substring (0, j);
  59246. // Make sure we only split the name at a space, because otherwise, things
  59247. // like "input 11" + "input 12" would become "input 11 + 2"
  59248. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59249. commonBit = commonBit.dropLastCharacters (1);
  59250. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59251. }
  59252. items = pairs;
  59253. }
  59254. }
  59255. updateContent();
  59256. repaint();
  59257. }
  59258. int getNumRows()
  59259. {
  59260. return items.size();
  59261. }
  59262. void paintListBoxItem (int row,
  59263. Graphics& g,
  59264. int width, int height,
  59265. bool rowIsSelected)
  59266. {
  59267. if (isPositiveAndBelow (row, items.size()))
  59268. {
  59269. if (rowIsSelected)
  59270. g.fillAll (findColour (TextEditor::highlightColourId)
  59271. .withMultipliedAlpha (0.3f));
  59272. const String item (items [row]);
  59273. bool enabled = false;
  59274. AudioDeviceManager::AudioDeviceSetup config;
  59275. setup.manager->getAudioDeviceSetup (config);
  59276. if (setup.useStereoPairs)
  59277. {
  59278. if (type == audioInputType)
  59279. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59280. else if (type == audioOutputType)
  59281. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59282. }
  59283. else
  59284. {
  59285. if (type == audioInputType)
  59286. enabled = config.inputChannels [row];
  59287. else if (type == audioOutputType)
  59288. enabled = config.outputChannels [row];
  59289. }
  59290. const int x = getTickX();
  59291. const float tickW = height * 0.75f;
  59292. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59293. enabled, true, true, false);
  59294. g.setFont (height * 0.6f);
  59295. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59296. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59297. }
  59298. }
  59299. void listBoxItemClicked (int row, const MouseEvent& e)
  59300. {
  59301. selectRow (row);
  59302. if (e.x < getTickX())
  59303. flipEnablement (row);
  59304. }
  59305. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59306. {
  59307. flipEnablement (row);
  59308. }
  59309. void returnKeyPressed (int row)
  59310. {
  59311. flipEnablement (row);
  59312. }
  59313. void paint (Graphics& g)
  59314. {
  59315. ListBox::paint (g);
  59316. if (items.size() == 0)
  59317. {
  59318. g.setColour (Colours::grey);
  59319. g.setFont (13.0f);
  59320. g.drawText (noItemsMessage,
  59321. 0, 0, getWidth(), getHeight() / 2,
  59322. Justification::centred, true);
  59323. }
  59324. }
  59325. int getBestHeight (int maxHeight)
  59326. {
  59327. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59328. getNumRows())
  59329. + getOutlineThickness() * 2;
  59330. }
  59331. private:
  59332. const AudioIODeviceType::DeviceSetupDetails setup;
  59333. const BoxType type;
  59334. const String noItemsMessage;
  59335. StringArray items;
  59336. void flipEnablement (const int row)
  59337. {
  59338. jassert (type == audioInputType || type == audioOutputType);
  59339. if (isPositiveAndBelow (row, items.size()))
  59340. {
  59341. AudioDeviceManager::AudioDeviceSetup config;
  59342. setup.manager->getAudioDeviceSetup (config);
  59343. if (setup.useStereoPairs)
  59344. {
  59345. BigInteger bits;
  59346. BigInteger& original = (type == audioInputType ? config.inputChannels
  59347. : config.outputChannels);
  59348. int i;
  59349. for (i = 0; i < 256; i += 2)
  59350. bits.setBit (i / 2, original [i] || original [i + 1]);
  59351. if (type == audioInputType)
  59352. {
  59353. config.useDefaultInputChannels = false;
  59354. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59355. }
  59356. else
  59357. {
  59358. config.useDefaultOutputChannels = false;
  59359. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59360. }
  59361. for (i = 0; i < 256; ++i)
  59362. original.setBit (i, bits [i / 2]);
  59363. }
  59364. else
  59365. {
  59366. if (type == audioInputType)
  59367. {
  59368. config.useDefaultInputChannels = false;
  59369. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59370. }
  59371. else
  59372. {
  59373. config.useDefaultOutputChannels = false;
  59374. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59375. }
  59376. }
  59377. String error (setup.manager->setAudioDeviceSetup (config, true));
  59378. if (! error.isEmpty())
  59379. {
  59380. //xxx
  59381. }
  59382. }
  59383. }
  59384. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59385. {
  59386. const int numActive = chans.countNumberOfSetBits();
  59387. if (chans [index])
  59388. {
  59389. if (numActive > minNumber)
  59390. chans.setBit (index, false);
  59391. }
  59392. else
  59393. {
  59394. if (numActive >= maxNumber)
  59395. {
  59396. const int firstActiveChan = chans.findNextSetBit();
  59397. chans.setBit (index > firstActiveChan
  59398. ? firstActiveChan : chans.getHighestBit(),
  59399. false);
  59400. }
  59401. chans.setBit (index, true);
  59402. }
  59403. }
  59404. int getTickX() const
  59405. {
  59406. return getRowHeight() + 5;
  59407. }
  59408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59409. };
  59410. private:
  59411. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59412. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59413. };
  59414. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59415. const int minInputChannels_,
  59416. const int maxInputChannels_,
  59417. const int minOutputChannels_,
  59418. const int maxOutputChannels_,
  59419. const bool showMidiInputOptions,
  59420. const bool showMidiOutputSelector,
  59421. const bool showChannelsAsStereoPairs_,
  59422. const bool hideAdvancedOptionsWithButton_)
  59423. : deviceManager (deviceManager_),
  59424. deviceTypeDropDown (0),
  59425. deviceTypeDropDownLabel (0),
  59426. minOutputChannels (minOutputChannels_),
  59427. maxOutputChannels (maxOutputChannels_),
  59428. minInputChannels (minInputChannels_),
  59429. maxInputChannels (maxInputChannels_),
  59430. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59431. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59432. {
  59433. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59434. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59435. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59436. {
  59437. deviceTypeDropDown = new ComboBox (String::empty);
  59438. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59439. {
  59440. deviceTypeDropDown
  59441. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59442. i + 1);
  59443. }
  59444. addAndMakeVisible (deviceTypeDropDown);
  59445. deviceTypeDropDown->addListener (this);
  59446. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59447. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59448. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59449. }
  59450. if (showMidiInputOptions)
  59451. {
  59452. addAndMakeVisible (midiInputsList
  59453. = new MidiInputSelectorComponentListBox (deviceManager,
  59454. TRANS("(no midi inputs available)"),
  59455. 0, 0));
  59456. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59457. midiInputsLabel->setJustificationType (Justification::topRight);
  59458. midiInputsLabel->attachToComponent (midiInputsList, true);
  59459. }
  59460. else
  59461. {
  59462. midiInputsList = 0;
  59463. midiInputsLabel = 0;
  59464. }
  59465. if (showMidiOutputSelector)
  59466. {
  59467. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59468. midiOutputSelector->addListener (this);
  59469. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59470. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59471. }
  59472. else
  59473. {
  59474. midiOutputSelector = 0;
  59475. midiOutputLabel = 0;
  59476. }
  59477. deviceManager_.addChangeListener (this);
  59478. changeListenerCallback (0);
  59479. }
  59480. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59481. {
  59482. deviceManager.removeChangeListener (this);
  59483. }
  59484. void AudioDeviceSelectorComponent::resized()
  59485. {
  59486. const int lx = proportionOfWidth (0.35f);
  59487. const int w = proportionOfWidth (0.4f);
  59488. const int h = 24;
  59489. const int space = 6;
  59490. const int dh = h + space;
  59491. int y = 15;
  59492. if (deviceTypeDropDown != 0)
  59493. {
  59494. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59495. y += dh + space * 2;
  59496. }
  59497. if (audioDeviceSettingsComp != 0)
  59498. {
  59499. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59500. y += audioDeviceSettingsComp->getHeight() + space;
  59501. }
  59502. if (midiInputsList != 0)
  59503. {
  59504. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59505. midiInputsList->setBounds (lx, y, w, bh);
  59506. y += bh + space;
  59507. }
  59508. if (midiOutputSelector != 0)
  59509. midiOutputSelector->setBounds (lx, y, w, h);
  59510. }
  59511. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59512. {
  59513. if (child == audioDeviceSettingsComp)
  59514. resized();
  59515. }
  59516. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59517. {
  59518. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59519. if (device != 0 && device->hasControlPanel())
  59520. {
  59521. if (device->showControlPanel())
  59522. deviceManager.restartLastAudioDevice();
  59523. getTopLevelComponent()->toFront (true);
  59524. }
  59525. }
  59526. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59527. {
  59528. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59529. {
  59530. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59531. if (type != 0)
  59532. {
  59533. audioDeviceSettingsComp = 0;
  59534. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59535. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59536. }
  59537. }
  59538. else if (comboBoxThatHasChanged == midiOutputSelector)
  59539. {
  59540. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59541. }
  59542. }
  59543. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59544. {
  59545. if (deviceTypeDropDown != 0)
  59546. {
  59547. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59548. }
  59549. if (audioDeviceSettingsComp == 0
  59550. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59551. {
  59552. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59553. audioDeviceSettingsComp = 0;
  59554. AudioIODeviceType* const type
  59555. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59556. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59557. if (type != 0)
  59558. {
  59559. AudioIODeviceType::DeviceSetupDetails details;
  59560. details.manager = &deviceManager;
  59561. details.minNumInputChannels = minInputChannels;
  59562. details.maxNumInputChannels = maxInputChannels;
  59563. details.minNumOutputChannels = minOutputChannels;
  59564. details.maxNumOutputChannels = maxOutputChannels;
  59565. details.useStereoPairs = showChannelsAsStereoPairs;
  59566. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59567. if (audioDeviceSettingsComp != 0)
  59568. {
  59569. addAndMakeVisible (audioDeviceSettingsComp);
  59570. audioDeviceSettingsComp->resized();
  59571. }
  59572. }
  59573. }
  59574. if (midiInputsList != 0)
  59575. {
  59576. midiInputsList->updateContent();
  59577. midiInputsList->repaint();
  59578. }
  59579. if (midiOutputSelector != 0)
  59580. {
  59581. midiOutputSelector->clear();
  59582. const StringArray midiOuts (MidiOutput::getDevices());
  59583. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59584. midiOutputSelector->addSeparator();
  59585. for (int i = 0; i < midiOuts.size(); ++i)
  59586. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59587. int current = -1;
  59588. if (deviceManager.getDefaultMidiOutput() != 0)
  59589. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59590. midiOutputSelector->setSelectedId (current, true);
  59591. }
  59592. resized();
  59593. }
  59594. END_JUCE_NAMESPACE
  59595. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59596. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59597. BEGIN_JUCE_NAMESPACE
  59598. BubbleComponent::BubbleComponent()
  59599. : side (0),
  59600. allowablePlacements (above | below | left | right),
  59601. arrowTipX (0.0f),
  59602. arrowTipY (0.0f)
  59603. {
  59604. setInterceptsMouseClicks (false, false);
  59605. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59606. setComponentEffect (&shadow);
  59607. }
  59608. BubbleComponent::~BubbleComponent()
  59609. {
  59610. }
  59611. void BubbleComponent::paint (Graphics& g)
  59612. {
  59613. int x = content.getX();
  59614. int y = content.getY();
  59615. int w = content.getWidth();
  59616. int h = content.getHeight();
  59617. int cw, ch;
  59618. getContentSize (cw, ch);
  59619. if (side == 3)
  59620. x += w - cw;
  59621. else if (side != 1)
  59622. x += (w - cw) / 2;
  59623. w = cw;
  59624. if (side == 2)
  59625. y += h - ch;
  59626. else if (side != 0)
  59627. y += (h - ch) / 2;
  59628. h = ch;
  59629. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59630. (float) x, (float) y,
  59631. (float) w, (float) h);
  59632. const int cx = x + (w - cw) / 2;
  59633. const int cy = y + (h - ch) / 2;
  59634. const int indent = 3;
  59635. g.setOrigin (cx + indent, cy + indent);
  59636. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59637. paintContent (g, cw - indent * 2, ch - indent * 2);
  59638. }
  59639. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59640. {
  59641. allowablePlacements = newPlacement;
  59642. }
  59643. void BubbleComponent::setPosition (Component* componentToPointTo)
  59644. {
  59645. jassert (componentToPointTo != 0);
  59646. Point<int> pos;
  59647. if (getParentComponent() != 0)
  59648. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59649. else
  59650. pos = componentToPointTo->localPointToGlobal (pos);
  59651. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59652. }
  59653. void BubbleComponent::setPosition (const int arrowTipX_,
  59654. const int arrowTipY_)
  59655. {
  59656. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59657. }
  59658. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59659. {
  59660. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59661. : getParentMonitorArea());
  59662. int x = 0;
  59663. int y = 0;
  59664. int w = 150;
  59665. int h = 30;
  59666. getContentSize (w, h);
  59667. w += 30;
  59668. h += 30;
  59669. const float edgeIndent = 2.0f;
  59670. const int arrowLength = jmin (10, h / 3, w / 3);
  59671. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59672. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59673. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59674. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59675. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59676. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59677. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59678. {
  59679. spaceLeft = spaceRight = 0;
  59680. }
  59681. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59682. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59683. {
  59684. spaceAbove = spaceBelow = 0;
  59685. }
  59686. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59687. {
  59688. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59689. arrowTipX = w * 0.5f;
  59690. content.setSize (w, h - arrowLength);
  59691. if (spaceAbove >= spaceBelow)
  59692. {
  59693. // above
  59694. y = rectangleToPointTo.getY() - h;
  59695. content.setPosition (0, 0);
  59696. arrowTipY = h - edgeIndent;
  59697. side = 2;
  59698. }
  59699. else
  59700. {
  59701. // below
  59702. y = rectangleToPointTo.getBottom();
  59703. content.setPosition (0, arrowLength);
  59704. arrowTipY = edgeIndent;
  59705. side = 0;
  59706. }
  59707. }
  59708. else
  59709. {
  59710. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59711. arrowTipY = h * 0.5f;
  59712. content.setSize (w - arrowLength, h);
  59713. if (spaceLeft > spaceRight)
  59714. {
  59715. // on the left
  59716. x = rectangleToPointTo.getX() - w;
  59717. content.setPosition (0, 0);
  59718. arrowTipX = w - edgeIndent;
  59719. side = 3;
  59720. }
  59721. else
  59722. {
  59723. // on the right
  59724. x = rectangleToPointTo.getRight();
  59725. content.setPosition (arrowLength, 0);
  59726. arrowTipX = edgeIndent;
  59727. side = 1;
  59728. }
  59729. }
  59730. setBounds (x, y, w, h);
  59731. }
  59732. END_JUCE_NAMESPACE
  59733. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59734. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59735. BEGIN_JUCE_NAMESPACE
  59736. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59737. : fadeOutLength (fadeOutLengthMs),
  59738. deleteAfterUse (false)
  59739. {
  59740. }
  59741. BubbleMessageComponent::~BubbleMessageComponent()
  59742. {
  59743. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59744. }
  59745. void BubbleMessageComponent::showAt (int x, int y,
  59746. const String& text,
  59747. const int numMillisecondsBeforeRemoving,
  59748. const bool removeWhenMouseClicked,
  59749. const bool deleteSelfAfterUse)
  59750. {
  59751. textLayout.clear();
  59752. textLayout.setText (text, Font (14.0f));
  59753. textLayout.layout (256, Justification::centredLeft, true);
  59754. setPosition (x, y);
  59755. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59756. }
  59757. void BubbleMessageComponent::showAt (Component* const component,
  59758. const String& text,
  59759. const int numMillisecondsBeforeRemoving,
  59760. const bool removeWhenMouseClicked,
  59761. const bool deleteSelfAfterUse)
  59762. {
  59763. textLayout.clear();
  59764. textLayout.setText (text, Font (14.0f));
  59765. textLayout.layout (256, Justification::centredLeft, true);
  59766. setPosition (component);
  59767. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59768. }
  59769. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59770. const bool removeWhenMouseClicked,
  59771. const bool deleteSelfAfterUse)
  59772. {
  59773. setVisible (true);
  59774. deleteAfterUse = deleteSelfAfterUse;
  59775. if (numMillisecondsBeforeRemoving > 0)
  59776. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59777. else
  59778. expiryTime = 0;
  59779. startTimer (77);
  59780. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59781. if (! (removeWhenMouseClicked && isShowing()))
  59782. mouseClickCounter += 0xfffff;
  59783. repaint();
  59784. }
  59785. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59786. {
  59787. w = textLayout.getWidth() + 16;
  59788. h = textLayout.getHeight() + 16;
  59789. }
  59790. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59791. {
  59792. g.setColour (findColour (TooltipWindow::textColourId));
  59793. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59794. }
  59795. void BubbleMessageComponent::timerCallback()
  59796. {
  59797. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59798. {
  59799. stopTimer();
  59800. setVisible (false);
  59801. if (deleteAfterUse)
  59802. delete this;
  59803. }
  59804. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59805. {
  59806. stopTimer();
  59807. if (deleteAfterUse)
  59808. delete this;
  59809. else
  59810. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59811. }
  59812. }
  59813. END_JUCE_NAMESPACE
  59814. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59815. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59816. BEGIN_JUCE_NAMESPACE
  59817. class ColourComponentSlider : public Slider
  59818. {
  59819. public:
  59820. ColourComponentSlider (const String& name)
  59821. : Slider (name)
  59822. {
  59823. setRange (0.0, 255.0, 1.0);
  59824. }
  59825. const String getTextFromValue (double value)
  59826. {
  59827. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59828. }
  59829. double getValueFromText (const String& text)
  59830. {
  59831. return (double) text.getHexValue32();
  59832. }
  59833. private:
  59834. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59835. };
  59836. class ColourSpaceMarker : public Component
  59837. {
  59838. public:
  59839. ColourSpaceMarker()
  59840. {
  59841. setInterceptsMouseClicks (false, false);
  59842. }
  59843. void paint (Graphics& g)
  59844. {
  59845. g.setColour (Colour::greyLevel (0.1f));
  59846. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59847. g.setColour (Colour::greyLevel (0.9f));
  59848. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59849. }
  59850. private:
  59851. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59852. };
  59853. class ColourSelector::ColourSpaceView : public Component
  59854. {
  59855. public:
  59856. ColourSpaceView (ColourSelector& owner_,
  59857. float& h_, float& s_, float& v_,
  59858. const int edgeSize)
  59859. : owner (owner_),
  59860. h (h_), s (s_), v (v_),
  59861. lastHue (0.0f),
  59862. edge (edgeSize)
  59863. {
  59864. addAndMakeVisible (&marker);
  59865. setMouseCursor (MouseCursor::CrosshairCursor);
  59866. }
  59867. void paint (Graphics& g)
  59868. {
  59869. if (colours.isNull())
  59870. {
  59871. const int width = getWidth() / 2;
  59872. const int height = getHeight() / 2;
  59873. colours = Image (Image::RGB, width, height, false);
  59874. Image::BitmapData pixels (colours, Image::BitmapData::writeOnly);
  59875. for (int y = 0; y < height; ++y)
  59876. {
  59877. const float val = 1.0f - y / (float) height;
  59878. for (int x = 0; x < width; ++x)
  59879. {
  59880. const float sat = x / (float) width;
  59881. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59882. }
  59883. }
  59884. }
  59885. g.setOpacity (1.0f);
  59886. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59887. 0, 0, colours.getWidth(), colours.getHeight());
  59888. }
  59889. void mouseDown (const MouseEvent& e)
  59890. {
  59891. mouseDrag (e);
  59892. }
  59893. void mouseDrag (const MouseEvent& e)
  59894. {
  59895. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59896. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59897. owner.setSV (sat, val);
  59898. }
  59899. void updateIfNeeded()
  59900. {
  59901. if (lastHue != h)
  59902. {
  59903. lastHue = h;
  59904. colours = Image::null;
  59905. repaint();
  59906. }
  59907. updateMarker();
  59908. }
  59909. void resized()
  59910. {
  59911. colours = Image::null;
  59912. updateMarker();
  59913. }
  59914. private:
  59915. ColourSelector& owner;
  59916. float& h;
  59917. float& s;
  59918. float& v;
  59919. float lastHue;
  59920. ColourSpaceMarker marker;
  59921. const int edge;
  59922. Image colours;
  59923. void updateMarker()
  59924. {
  59925. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59926. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59927. edge * 2, edge * 2);
  59928. }
  59929. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59930. };
  59931. class HueSelectorMarker : public Component
  59932. {
  59933. public:
  59934. HueSelectorMarker()
  59935. {
  59936. setInterceptsMouseClicks (false, false);
  59937. }
  59938. void paint (Graphics& g)
  59939. {
  59940. Path p;
  59941. p.addTriangle (1.0f, 1.0f,
  59942. getWidth() * 0.3f, getHeight() * 0.5f,
  59943. 1.0f, getHeight() - 1.0f);
  59944. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59945. getWidth() * 0.7f, getHeight() * 0.5f,
  59946. getWidth() - 1.0f, getHeight() - 1.0f);
  59947. g.setColour (Colours::white.withAlpha (0.75f));
  59948. g.fillPath (p);
  59949. g.setColour (Colours::black.withAlpha (0.75f));
  59950. g.strokePath (p, PathStrokeType (1.2f));
  59951. }
  59952. private:
  59953. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59954. };
  59955. class ColourSelector::HueSelectorComp : public Component
  59956. {
  59957. public:
  59958. HueSelectorComp (ColourSelector& owner_,
  59959. float& h_, float& s_, float& v_,
  59960. const int edgeSize)
  59961. : owner (owner_),
  59962. h (h_), s (s_), v (v_),
  59963. lastHue (0.0f),
  59964. edge (edgeSize)
  59965. {
  59966. addAndMakeVisible (&marker);
  59967. }
  59968. void paint (Graphics& g)
  59969. {
  59970. const float yScale = 1.0f / (getHeight() - edge * 2);
  59971. const Rectangle<int> clip (g.getClipBounds());
  59972. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59973. {
  59974. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59975. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59976. }
  59977. }
  59978. void resized()
  59979. {
  59980. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59981. getWidth(), edge * 2);
  59982. }
  59983. void mouseDown (const MouseEvent& e)
  59984. {
  59985. mouseDrag (e);
  59986. }
  59987. void mouseDrag (const MouseEvent& e)
  59988. {
  59989. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59990. }
  59991. void updateIfNeeded()
  59992. {
  59993. resized();
  59994. }
  59995. private:
  59996. ColourSelector& owner;
  59997. float& h;
  59998. float& s;
  59999. float& v;
  60000. float lastHue;
  60001. HueSelectorMarker marker;
  60002. const int edge;
  60003. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  60004. };
  60005. class ColourSelector::SwatchComponent : public Component
  60006. {
  60007. public:
  60008. SwatchComponent (ColourSelector& owner_, int index_)
  60009. : owner (owner_), index (index_)
  60010. {
  60011. }
  60012. void paint (Graphics& g)
  60013. {
  60014. const Colour colour (owner.getSwatchColour (index));
  60015. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60016. Colour (0xffdddddd).overlaidWith (colour),
  60017. Colour (0xffffffff).overlaidWith (colour));
  60018. }
  60019. void mouseDown (const MouseEvent&)
  60020. {
  60021. PopupMenu m;
  60022. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60023. m.addSeparator();
  60024. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60025. m.showMenuAsync (PopupMenu::Options().withTargetComponent (this),
  60026. ModalCallbackFunction::forComponent (menuStaticCallback, this));
  60027. }
  60028. private:
  60029. ColourSelector& owner;
  60030. const int index;
  60031. static void menuStaticCallback (int result, SwatchComponent* comp)
  60032. {
  60033. if (comp != 0)
  60034. {
  60035. if (result == 1)
  60036. comp->setColourFromSwatch();
  60037. else if (result == 2)
  60038. comp->setSwatchFromColour();
  60039. }
  60040. }
  60041. void setColourFromSwatch()
  60042. {
  60043. owner.setCurrentColour (owner.getSwatchColour (index));
  60044. }
  60045. void setSwatchFromColour()
  60046. {
  60047. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  60048. {
  60049. owner.setSwatchColour (index, owner.getCurrentColour());
  60050. repaint();
  60051. }
  60052. }
  60053. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  60054. };
  60055. ColourSelector::ColourSelector (const int flags_,
  60056. const int edgeGap_,
  60057. const int gapAroundColourSpaceComponent)
  60058. : colour (Colours::white),
  60059. flags (flags_),
  60060. edgeGap (edgeGap_)
  60061. {
  60062. // not much point having a selector with no components in it!
  60063. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60064. updateHSV();
  60065. if ((flags & showSliders) != 0)
  60066. {
  60067. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60068. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60069. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60070. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60071. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60072. for (int i = 4; --i >= 0;)
  60073. sliders[i]->addListener (this);
  60074. }
  60075. if ((flags & showColourspace) != 0)
  60076. {
  60077. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  60078. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  60079. }
  60080. update();
  60081. }
  60082. ColourSelector::~ColourSelector()
  60083. {
  60084. dispatchPendingMessages();
  60085. swatchComponents.clear();
  60086. }
  60087. const Colour ColourSelector::getCurrentColour() const
  60088. {
  60089. return ((flags & showAlphaChannel) != 0) ? colour
  60090. : colour.withAlpha ((uint8) 0xff);
  60091. }
  60092. void ColourSelector::setCurrentColour (const Colour& c)
  60093. {
  60094. if (c != colour)
  60095. {
  60096. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60097. updateHSV();
  60098. update();
  60099. }
  60100. }
  60101. void ColourSelector::setHue (float newH)
  60102. {
  60103. newH = jlimit (0.0f, 1.0f, newH);
  60104. if (h != newH)
  60105. {
  60106. h = newH;
  60107. colour = Colour (h, s, v, colour.getFloatAlpha());
  60108. update();
  60109. }
  60110. }
  60111. void ColourSelector::setSV (float newS, float newV)
  60112. {
  60113. newS = jlimit (0.0f, 1.0f, newS);
  60114. newV = jlimit (0.0f, 1.0f, newV);
  60115. if (s != newS || v != newV)
  60116. {
  60117. s = newS;
  60118. v = newV;
  60119. colour = Colour (h, s, v, colour.getFloatAlpha());
  60120. update();
  60121. }
  60122. }
  60123. void ColourSelector::updateHSV()
  60124. {
  60125. colour.getHSB (h, s, v);
  60126. }
  60127. void ColourSelector::update()
  60128. {
  60129. if (sliders[0] != 0)
  60130. {
  60131. sliders[0]->setValue ((int) colour.getRed());
  60132. sliders[1]->setValue ((int) colour.getGreen());
  60133. sliders[2]->setValue ((int) colour.getBlue());
  60134. sliders[3]->setValue ((int) colour.getAlpha());
  60135. }
  60136. if (colourSpace != 0)
  60137. {
  60138. colourSpace->updateIfNeeded();
  60139. hueSelector->updateIfNeeded();
  60140. }
  60141. if ((flags & showColourAtTop) != 0)
  60142. repaint (previewArea);
  60143. sendChangeMessage();
  60144. }
  60145. void ColourSelector::paint (Graphics& g)
  60146. {
  60147. g.fillAll (findColour (backgroundColourId));
  60148. if ((flags & showColourAtTop) != 0)
  60149. {
  60150. const Colour currentColour (getCurrentColour());
  60151. g.fillCheckerBoard (previewArea, 10, 10,
  60152. Colour (0xffdddddd).overlaidWith (currentColour),
  60153. Colour (0xffffffff).overlaidWith (currentColour));
  60154. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60155. g.setFont (14.0f, true);
  60156. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60157. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60158. Justification::centred, false);
  60159. }
  60160. if ((flags & showSliders) != 0)
  60161. {
  60162. g.setColour (findColour (labelTextColourId));
  60163. g.setFont (11.0f);
  60164. for (int i = 4; --i >= 0;)
  60165. {
  60166. if (sliders[i]->isVisible())
  60167. g.drawText (sliders[i]->getName() + ":",
  60168. 0, sliders[i]->getY(),
  60169. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60170. Justification::centredRight, false);
  60171. }
  60172. }
  60173. }
  60174. void ColourSelector::resized()
  60175. {
  60176. const int swatchesPerRow = 8;
  60177. const int swatchHeight = 22;
  60178. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60179. const int numSwatches = getNumSwatches();
  60180. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60181. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60182. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60183. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60184. int y = topSpace;
  60185. if ((flags & showColourspace) != 0)
  60186. {
  60187. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60188. colourSpace->setBounds (edgeGap, y,
  60189. getWidth() - hueWidth - edgeGap - 4,
  60190. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60191. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60192. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60193. colourSpace->getHeight());
  60194. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60195. }
  60196. if ((flags & showSliders) != 0)
  60197. {
  60198. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60199. for (int i = 0; i < numSliders; ++i)
  60200. {
  60201. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60202. proportionOfWidth (0.72f), sliderHeight - 2);
  60203. y += sliderHeight;
  60204. }
  60205. }
  60206. if (numSwatches > 0)
  60207. {
  60208. const int startX = 8;
  60209. const int xGap = 4;
  60210. const int yGap = 4;
  60211. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60212. y += edgeGap;
  60213. if (swatchComponents.size() != numSwatches)
  60214. {
  60215. swatchComponents.clear();
  60216. for (int i = 0; i < numSwatches; ++i)
  60217. {
  60218. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60219. swatchComponents.add (sc);
  60220. addAndMakeVisible (sc);
  60221. }
  60222. }
  60223. int x = startX;
  60224. for (int i = 0; i < swatchComponents.size(); ++i)
  60225. {
  60226. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60227. sc->setBounds (x + xGap / 2,
  60228. y + yGap / 2,
  60229. swatchWidth - xGap,
  60230. swatchHeight - yGap);
  60231. if (((i + 1) % swatchesPerRow) == 0)
  60232. {
  60233. x = startX;
  60234. y += swatchHeight;
  60235. }
  60236. else
  60237. {
  60238. x += swatchWidth;
  60239. }
  60240. }
  60241. }
  60242. }
  60243. void ColourSelector::sliderValueChanged (Slider*)
  60244. {
  60245. if (sliders[0] != 0)
  60246. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60247. (uint8) sliders[1]->getValue(),
  60248. (uint8) sliders[2]->getValue(),
  60249. (uint8) sliders[3]->getValue()));
  60250. }
  60251. int ColourSelector::getNumSwatches() const
  60252. {
  60253. return 0;
  60254. }
  60255. const Colour ColourSelector::getSwatchColour (const int) const
  60256. {
  60257. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60258. return Colours::black;
  60259. }
  60260. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60261. {
  60262. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60263. }
  60264. END_JUCE_NAMESPACE
  60265. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60266. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60267. BEGIN_JUCE_NAMESPACE
  60268. class ShadowWindow : public Component
  60269. {
  60270. public:
  60271. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60272. : topLeft (shadowImageSections [type_ * 3]),
  60273. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60274. filler (shadowImageSections [type_ * 3 + 2]),
  60275. type (type_)
  60276. {
  60277. setInterceptsMouseClicks (false, false);
  60278. if (owner.isOnDesktop())
  60279. {
  60280. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60281. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60282. | ComponentPeer::windowIsTemporary
  60283. | ComponentPeer::windowIgnoresKeyPresses);
  60284. }
  60285. else if (owner.getParentComponent() != 0)
  60286. {
  60287. owner.getParentComponent()->addChildComponent (this);
  60288. }
  60289. }
  60290. void paint (Graphics& g)
  60291. {
  60292. g.setOpacity (1.0f);
  60293. if (type < 2)
  60294. {
  60295. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60296. g.drawImage (topLeft,
  60297. 0, 0, topLeft.getWidth(), imH,
  60298. 0, 0, topLeft.getWidth(), imH);
  60299. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60300. g.drawImage (bottomRight,
  60301. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60302. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60303. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60304. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60305. }
  60306. else
  60307. {
  60308. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60309. g.drawImage (topLeft,
  60310. 0, 0, imW, topLeft.getHeight(),
  60311. 0, 0, imW, topLeft.getHeight());
  60312. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60313. g.drawImage (bottomRight,
  60314. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60315. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60316. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60317. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60318. }
  60319. }
  60320. void resized()
  60321. {
  60322. repaint(); // (needed for correct repainting)
  60323. }
  60324. private:
  60325. const Image topLeft, bottomRight, filler;
  60326. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60327. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60328. };
  60329. DropShadower::DropShadower (const float alpha_,
  60330. const int xOffset_,
  60331. const int yOffset_,
  60332. const float blurRadius_)
  60333. : owner (0),
  60334. xOffset (xOffset_),
  60335. yOffset (yOffset_),
  60336. alpha (alpha_),
  60337. blurRadius (blurRadius_),
  60338. reentrant (false)
  60339. {
  60340. }
  60341. DropShadower::~DropShadower()
  60342. {
  60343. if (owner != 0)
  60344. owner->removeComponentListener (this);
  60345. reentrant = true;
  60346. shadowWindows.clear();
  60347. }
  60348. void DropShadower::setOwner (Component* componentToFollow)
  60349. {
  60350. if (componentToFollow != owner)
  60351. {
  60352. if (owner != 0)
  60353. owner->removeComponentListener (this);
  60354. // (the component can't be null)
  60355. jassert (componentToFollow != 0);
  60356. owner = componentToFollow;
  60357. jassert (owner != 0);
  60358. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60359. owner->addComponentListener (this);
  60360. updateShadows();
  60361. }
  60362. }
  60363. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60364. {
  60365. updateShadows();
  60366. }
  60367. void DropShadower::componentBroughtToFront (Component&)
  60368. {
  60369. bringShadowWindowsToFront();
  60370. }
  60371. void DropShadower::componentParentHierarchyChanged (Component&)
  60372. {
  60373. shadowWindows.clear();
  60374. updateShadows();
  60375. }
  60376. void DropShadower::componentVisibilityChanged (Component&)
  60377. {
  60378. updateShadows();
  60379. }
  60380. void DropShadower::updateShadows()
  60381. {
  60382. if (reentrant || owner == 0)
  60383. return;
  60384. ComponentPeer* const peer = owner->getPeer();
  60385. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60386. const bool createShadowWindows = shadowWindows.size() == 0
  60387. && owner->getWidth() > 0
  60388. && owner->getHeight() > 0
  60389. && isOwnerVisible
  60390. && (Desktop::canUseSemiTransparentWindows()
  60391. || owner->getParentComponent() != 0);
  60392. {
  60393. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60394. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60395. if (createShadowWindows)
  60396. {
  60397. // keep a cached version of the image to save doing the gaussian too often
  60398. String imageId;
  60399. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60400. const int hash = imageId.hashCode();
  60401. Image bigIm (ImageCache::getFromHashCode (hash));
  60402. if (bigIm.isNull())
  60403. {
  60404. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60405. Graphics bigG (bigIm);
  60406. bigG.setColour (Colours::black.withAlpha (alpha));
  60407. bigG.fillRect (shadowEdge + xOffset,
  60408. shadowEdge + yOffset,
  60409. bigIm.getWidth() - (shadowEdge * 2),
  60410. bigIm.getHeight() - (shadowEdge * 2));
  60411. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60412. blurKernel.createGaussianBlur (blurRadius);
  60413. blurKernel.applyToImage (bigIm, bigIm,
  60414. Rectangle<int> (xOffset, yOffset,
  60415. bigIm.getWidth(), bigIm.getHeight()));
  60416. ImageCache::addImageToCache (bigIm, hash);
  60417. }
  60418. const int iw = bigIm.getWidth();
  60419. const int ih = bigIm.getHeight();
  60420. const int shadowEdge2 = shadowEdge * 2;
  60421. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60422. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60423. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60424. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60425. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60426. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60427. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60428. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60429. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60430. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60431. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60432. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60433. for (int i = 0; i < 4; ++i)
  60434. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60435. }
  60436. if (shadowWindows.size() >= 4)
  60437. {
  60438. for (int i = shadowWindows.size(); --i >= 0;)
  60439. {
  60440. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60441. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60442. }
  60443. const int x = owner->getX();
  60444. const int y = owner->getY() - shadowEdge;
  60445. const int w = owner->getWidth();
  60446. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60447. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60448. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60449. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60450. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60451. }
  60452. }
  60453. if (createShadowWindows)
  60454. bringShadowWindowsToFront();
  60455. }
  60456. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60457. const int sx, const int sy)
  60458. {
  60459. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60460. Graphics g (shadowImageSections[num]);
  60461. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60462. }
  60463. void DropShadower::bringShadowWindowsToFront()
  60464. {
  60465. if (! reentrant)
  60466. {
  60467. updateShadows();
  60468. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60469. for (int i = shadowWindows.size(); --i >= 0;)
  60470. shadowWindows.getUnchecked(i)->toBehind (owner);
  60471. }
  60472. }
  60473. END_JUCE_NAMESPACE
  60474. /*** End of inlined file: juce_DropShadower.cpp ***/
  60475. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60476. BEGIN_JUCE_NAMESPACE
  60477. class MidiKeyboardUpDownButton : public Button
  60478. {
  60479. public:
  60480. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60481. : Button (String::empty),
  60482. owner (owner_),
  60483. delta (delta_)
  60484. {
  60485. setOpaque (true);
  60486. }
  60487. void clicked()
  60488. {
  60489. int note = owner.getLowestVisibleKey();
  60490. if (delta < 0)
  60491. note = (note - 1) / 12;
  60492. else
  60493. note = note / 12 + 1;
  60494. owner.setLowestVisibleKey (note * 12);
  60495. }
  60496. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60497. {
  60498. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60499. isMouseOverButton, isButtonDown,
  60500. delta > 0);
  60501. }
  60502. private:
  60503. MidiKeyboardComponent& owner;
  60504. const int delta;
  60505. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60506. };
  60507. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60508. const Orientation orientation_)
  60509. : state (state_),
  60510. xOffset (0),
  60511. blackNoteLength (1),
  60512. keyWidth (16.0f),
  60513. orientation (orientation_),
  60514. midiChannel (1),
  60515. midiInChannelMask (0xffff),
  60516. velocity (1.0f),
  60517. noteUnderMouse (-1),
  60518. mouseDownNote (-1),
  60519. rangeStart (0),
  60520. rangeEnd (127),
  60521. firstKey (12 * 4),
  60522. canScroll (true),
  60523. mouseDragging (false),
  60524. useMousePositionForVelocity (true),
  60525. keyMappingOctave (6),
  60526. octaveNumForMiddleC (3)
  60527. {
  60528. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60529. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60530. // initialise with a default set of querty key-mappings..
  60531. const char* const keymap = "awsedftgyhujkolp;";
  60532. for (int i = String (keymap).length(); --i >= 0;)
  60533. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60534. setOpaque (true);
  60535. setWantsKeyboardFocus (true);
  60536. state.addListener (this);
  60537. }
  60538. MidiKeyboardComponent::~MidiKeyboardComponent()
  60539. {
  60540. state.removeListener (this);
  60541. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60542. }
  60543. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60544. {
  60545. keyWidth = widthInPixels;
  60546. resized();
  60547. }
  60548. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60549. {
  60550. if (orientation != newOrientation)
  60551. {
  60552. orientation = newOrientation;
  60553. resized();
  60554. }
  60555. }
  60556. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60557. const int highestNote)
  60558. {
  60559. jassert (lowestNote >= 0 && lowestNote <= 127);
  60560. jassert (highestNote >= 0 && highestNote <= 127);
  60561. jassert (lowestNote <= highestNote);
  60562. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60563. {
  60564. rangeStart = jlimit (0, 127, lowestNote);
  60565. rangeEnd = jlimit (0, 127, highestNote);
  60566. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60567. resized();
  60568. }
  60569. }
  60570. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60571. {
  60572. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60573. if (noteNumber != firstKey)
  60574. {
  60575. firstKey = noteNumber;
  60576. sendChangeMessage();
  60577. resized();
  60578. }
  60579. }
  60580. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60581. {
  60582. if (canScroll != canScroll_)
  60583. {
  60584. canScroll = canScroll_;
  60585. resized();
  60586. }
  60587. }
  60588. void MidiKeyboardComponent::colourChanged()
  60589. {
  60590. repaint();
  60591. }
  60592. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60593. {
  60594. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60595. if (midiChannel != midiChannelNumber)
  60596. {
  60597. resetAnyKeysInUse();
  60598. midiChannel = jlimit (1, 16, midiChannelNumber);
  60599. }
  60600. }
  60601. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60602. {
  60603. midiInChannelMask = midiChannelMask;
  60604. triggerAsyncUpdate();
  60605. }
  60606. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60607. {
  60608. velocity = jlimit (0.0f, 1.0f, velocity_);
  60609. useMousePositionForVelocity = useMousePositionForVelocity_;
  60610. }
  60611. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60612. {
  60613. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60614. static const float blackNoteWidth = 0.7f;
  60615. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60616. 1.0f, 2 - blackNoteWidth * 0.4f,
  60617. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60618. 4.0f, 5 - blackNoteWidth * 0.5f,
  60619. 5.0f, 6 - blackNoteWidth * 0.3f,
  60620. 6.0f };
  60621. static const float widths[] = { 1.0f, blackNoteWidth,
  60622. 1.0f, blackNoteWidth,
  60623. 1.0f, 1.0f, blackNoteWidth,
  60624. 1.0f, blackNoteWidth,
  60625. 1.0f, blackNoteWidth,
  60626. 1.0f };
  60627. const int octave = midiNoteNumber / 12;
  60628. const int note = midiNoteNumber % 12;
  60629. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60630. w = roundToInt (widths [note] * keyWidth_);
  60631. }
  60632. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60633. {
  60634. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60635. int rx, rw;
  60636. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60637. x -= xOffset + rx;
  60638. }
  60639. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60640. {
  60641. int x, y;
  60642. getKeyPos (midiNoteNumber, x, y);
  60643. return x;
  60644. }
  60645. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60646. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60647. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60648. {
  60649. if (! reallyContains (pos, false))
  60650. return -1;
  60651. Point<int> p (pos);
  60652. if (orientation != horizontalKeyboard)
  60653. {
  60654. p = Point<int> (p.getY(), p.getX());
  60655. if (orientation == verticalKeyboardFacingLeft)
  60656. p = Point<int> (p.getX(), getWidth() - p.getY());
  60657. else
  60658. p = Point<int> (getHeight() - p.getX(), p.getY());
  60659. }
  60660. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60661. }
  60662. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60663. {
  60664. if (pos.getY() < blackNoteLength)
  60665. {
  60666. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60667. {
  60668. for (int i = 0; i < 5; ++i)
  60669. {
  60670. const int note = octaveStart + blackNotes [i];
  60671. if (note >= rangeStart && note <= rangeEnd)
  60672. {
  60673. int kx, kw;
  60674. getKeyPos (note, kx, kw);
  60675. kx += xOffset;
  60676. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60677. {
  60678. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60679. return note;
  60680. }
  60681. }
  60682. }
  60683. }
  60684. }
  60685. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60686. {
  60687. for (int i = 0; i < 7; ++i)
  60688. {
  60689. const int note = octaveStart + whiteNotes [i];
  60690. if (note >= rangeStart && note <= rangeEnd)
  60691. {
  60692. int kx, kw;
  60693. getKeyPos (note, kx, kw);
  60694. kx += xOffset;
  60695. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60696. {
  60697. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60698. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60699. return note;
  60700. }
  60701. }
  60702. }
  60703. }
  60704. mousePositionVelocity = 0;
  60705. return -1;
  60706. }
  60707. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60708. {
  60709. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60710. {
  60711. int x, w;
  60712. getKeyPos (noteNum, x, w);
  60713. if (orientation == horizontalKeyboard)
  60714. repaint (x, 0, w, getHeight());
  60715. else if (orientation == verticalKeyboardFacingLeft)
  60716. repaint (0, x, getWidth(), w);
  60717. else if (orientation == verticalKeyboardFacingRight)
  60718. repaint (0, getHeight() - x - w, getWidth(), w);
  60719. }
  60720. }
  60721. void MidiKeyboardComponent::paint (Graphics& g)
  60722. {
  60723. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60724. const Colour lineColour (findColour (keySeparatorLineColourId));
  60725. const Colour textColour (findColour (textLabelColourId));
  60726. int x, w, octave;
  60727. for (octave = 0; octave < 128; octave += 12)
  60728. {
  60729. for (int white = 0; white < 7; ++white)
  60730. {
  60731. const int noteNum = octave + whiteNotes [white];
  60732. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60733. {
  60734. getKeyPos (noteNum, x, w);
  60735. if (orientation == horizontalKeyboard)
  60736. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60737. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60738. noteUnderMouse == noteNum,
  60739. lineColour, textColour);
  60740. else if (orientation == verticalKeyboardFacingLeft)
  60741. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60742. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60743. noteUnderMouse == noteNum,
  60744. lineColour, textColour);
  60745. else if (orientation == verticalKeyboardFacingRight)
  60746. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60747. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60748. noteUnderMouse == noteNum,
  60749. lineColour, textColour);
  60750. }
  60751. }
  60752. }
  60753. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60754. if (orientation == verticalKeyboardFacingLeft)
  60755. {
  60756. x1 = getWidth() - 1.0f;
  60757. x2 = getWidth() - 5.0f;
  60758. }
  60759. else if (orientation == verticalKeyboardFacingRight)
  60760. x2 = 5.0f;
  60761. else
  60762. y2 = 5.0f;
  60763. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60764. Colours::transparentBlack, x2, y2, false));
  60765. getKeyPos (rangeEnd, x, w);
  60766. x += w;
  60767. if (orientation == verticalKeyboardFacingLeft)
  60768. g.fillRect (getWidth() - 5, 0, 5, x);
  60769. else if (orientation == verticalKeyboardFacingRight)
  60770. g.fillRect (0, 0, 5, x);
  60771. else
  60772. g.fillRect (0, 0, x, 5);
  60773. g.setColour (lineColour);
  60774. if (orientation == verticalKeyboardFacingLeft)
  60775. g.fillRect (0, 0, 1, x);
  60776. else if (orientation == verticalKeyboardFacingRight)
  60777. g.fillRect (getWidth() - 1, 0, 1, x);
  60778. else
  60779. g.fillRect (0, getHeight() - 1, x, 1);
  60780. const Colour blackNoteColour (findColour (blackNoteColourId));
  60781. for (octave = 0; octave < 128; octave += 12)
  60782. {
  60783. for (int black = 0; black < 5; ++black)
  60784. {
  60785. const int noteNum = octave + blackNotes [black];
  60786. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60787. {
  60788. getKeyPos (noteNum, x, w);
  60789. if (orientation == horizontalKeyboard)
  60790. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60791. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60792. noteUnderMouse == noteNum,
  60793. blackNoteColour);
  60794. else if (orientation == verticalKeyboardFacingLeft)
  60795. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60796. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60797. noteUnderMouse == noteNum,
  60798. blackNoteColour);
  60799. else if (orientation == verticalKeyboardFacingRight)
  60800. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60801. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60802. noteUnderMouse == noteNum,
  60803. blackNoteColour);
  60804. }
  60805. }
  60806. }
  60807. }
  60808. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60809. Graphics& g, int x, int y, int w, int h,
  60810. bool isDown, bool isOver,
  60811. const Colour& lineColour,
  60812. const Colour& textColour)
  60813. {
  60814. Colour c (Colours::transparentWhite);
  60815. if (isDown)
  60816. c = findColour (keyDownOverlayColourId);
  60817. if (isOver)
  60818. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60819. g.setColour (c);
  60820. g.fillRect (x, y, w, h);
  60821. const String text (getWhiteNoteText (midiNoteNumber));
  60822. if (! text.isEmpty())
  60823. {
  60824. g.setColour (textColour);
  60825. Font f (jmin (12.0f, keyWidth * 0.9f));
  60826. f.setHorizontalScale (0.8f);
  60827. g.setFont (f);
  60828. Justification justification (Justification::centredBottom);
  60829. if (orientation == verticalKeyboardFacingLeft)
  60830. justification = Justification::centredLeft;
  60831. else if (orientation == verticalKeyboardFacingRight)
  60832. justification = Justification::centredRight;
  60833. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60834. }
  60835. g.setColour (lineColour);
  60836. if (orientation == horizontalKeyboard)
  60837. g.fillRect (x, y, 1, h);
  60838. else if (orientation == verticalKeyboardFacingLeft)
  60839. g.fillRect (x, y, w, 1);
  60840. else if (orientation == verticalKeyboardFacingRight)
  60841. g.fillRect (x, y + h - 1, w, 1);
  60842. if (midiNoteNumber == rangeEnd)
  60843. {
  60844. if (orientation == horizontalKeyboard)
  60845. g.fillRect (x + w, y, 1, h);
  60846. else if (orientation == verticalKeyboardFacingLeft)
  60847. g.fillRect (x, y + h, w, 1);
  60848. else if (orientation == verticalKeyboardFacingRight)
  60849. g.fillRect (x, y - 1, w, 1);
  60850. }
  60851. }
  60852. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60853. Graphics& g, int x, int y, int w, int h,
  60854. bool isDown, bool isOver,
  60855. const Colour& noteFillColour)
  60856. {
  60857. Colour c (noteFillColour);
  60858. if (isDown)
  60859. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60860. if (isOver)
  60861. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60862. g.setColour (c);
  60863. g.fillRect (x, y, w, h);
  60864. if (isDown)
  60865. {
  60866. g.setColour (noteFillColour);
  60867. g.drawRect (x, y, w, h);
  60868. }
  60869. else
  60870. {
  60871. const int xIndent = jmax (1, jmin (w, h) / 8);
  60872. g.setColour (c.brighter());
  60873. if (orientation == horizontalKeyboard)
  60874. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60875. else if (orientation == verticalKeyboardFacingLeft)
  60876. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60877. else if (orientation == verticalKeyboardFacingRight)
  60878. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60879. }
  60880. }
  60881. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60882. {
  60883. octaveNumForMiddleC = octaveNumForMiddleC_;
  60884. repaint();
  60885. }
  60886. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60887. {
  60888. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60889. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60890. return String::empty;
  60891. }
  60892. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60893. const bool isMouseOver_,
  60894. const bool isButtonDown,
  60895. const bool movesOctavesUp)
  60896. {
  60897. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60898. float angle;
  60899. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60900. angle = movesOctavesUp ? 0.0f : 0.5f;
  60901. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60902. angle = movesOctavesUp ? 0.25f : 0.75f;
  60903. else
  60904. angle = movesOctavesUp ? 0.75f : 0.25f;
  60905. Path path;
  60906. path.lineTo (0.0f, 1.0f);
  60907. path.lineTo (1.0f, 0.5f);
  60908. path.closeSubPath();
  60909. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60910. g.setColour (findColour (upDownButtonArrowColourId)
  60911. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60912. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60913. w - 2.0f,
  60914. h - 2.0f,
  60915. true));
  60916. }
  60917. void MidiKeyboardComponent::resized()
  60918. {
  60919. int w = getWidth();
  60920. int h = getHeight();
  60921. if (w > 0 && h > 0)
  60922. {
  60923. if (orientation != horizontalKeyboard)
  60924. swapVariables (w, h);
  60925. blackNoteLength = roundToInt (h * 0.7f);
  60926. int kx2, kw2;
  60927. getKeyPos (rangeEnd, kx2, kw2);
  60928. kx2 += kw2;
  60929. if (firstKey != rangeStart)
  60930. {
  60931. int kx1, kw1;
  60932. getKeyPos (rangeStart, kx1, kw1);
  60933. if (kx2 - kx1 <= w)
  60934. {
  60935. firstKey = rangeStart;
  60936. sendChangeMessage();
  60937. repaint();
  60938. }
  60939. }
  60940. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60941. scrollDown->setVisible (showScrollButtons);
  60942. scrollUp->setVisible (showScrollButtons);
  60943. xOffset = 0;
  60944. if (showScrollButtons)
  60945. {
  60946. const int scrollButtonW = jmin (12, w / 2);
  60947. if (orientation == horizontalKeyboard)
  60948. {
  60949. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60950. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60951. }
  60952. else if (orientation == verticalKeyboardFacingLeft)
  60953. {
  60954. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60955. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60956. }
  60957. else if (orientation == verticalKeyboardFacingRight)
  60958. {
  60959. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60960. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60961. }
  60962. int endOfLastKey, kw;
  60963. getKeyPos (rangeEnd, endOfLastKey, kw);
  60964. endOfLastKey += kw;
  60965. float mousePositionVelocity;
  60966. const int spaceAvailable = w - scrollButtonW * 2;
  60967. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60968. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60969. {
  60970. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60971. sendChangeMessage();
  60972. }
  60973. int newOffset = 0;
  60974. getKeyPos (firstKey, newOffset, kw);
  60975. xOffset = newOffset - scrollButtonW;
  60976. }
  60977. else
  60978. {
  60979. firstKey = rangeStart;
  60980. }
  60981. timerCallback();
  60982. repaint();
  60983. }
  60984. }
  60985. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60986. {
  60987. triggerAsyncUpdate();
  60988. }
  60989. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60990. {
  60991. triggerAsyncUpdate();
  60992. }
  60993. void MidiKeyboardComponent::handleAsyncUpdate()
  60994. {
  60995. for (int i = rangeStart; i <= rangeEnd; ++i)
  60996. {
  60997. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60998. {
  60999. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61000. repaintNote (i);
  61001. }
  61002. }
  61003. }
  61004. void MidiKeyboardComponent::resetAnyKeysInUse()
  61005. {
  61006. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61007. {
  61008. state.allNotesOff (midiChannel);
  61009. keysPressed.clear();
  61010. mouseDownNote = -1;
  61011. }
  61012. }
  61013. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61014. {
  61015. float mousePositionVelocity = 0.0f;
  61016. const int newNote = (mouseDragging || isMouseOver())
  61017. ? xyToNote (pos, mousePositionVelocity) : -1;
  61018. if (noteUnderMouse != newNote)
  61019. {
  61020. if (mouseDownNote >= 0)
  61021. {
  61022. state.noteOff (midiChannel, mouseDownNote);
  61023. mouseDownNote = -1;
  61024. }
  61025. if (mouseDragging && newNote >= 0)
  61026. {
  61027. if (! useMousePositionForVelocity)
  61028. mousePositionVelocity = 1.0f;
  61029. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61030. mouseDownNote = newNote;
  61031. }
  61032. repaintNote (noteUnderMouse);
  61033. noteUnderMouse = newNote;
  61034. repaintNote (noteUnderMouse);
  61035. }
  61036. else if (mouseDownNote >= 0 && ! mouseDragging)
  61037. {
  61038. state.noteOff (midiChannel, mouseDownNote);
  61039. mouseDownNote = -1;
  61040. }
  61041. }
  61042. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61043. {
  61044. updateNoteUnderMouse (e.getPosition());
  61045. stopTimer();
  61046. }
  61047. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61048. {
  61049. float mousePositionVelocity;
  61050. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61051. if (newNote >= 0)
  61052. mouseDraggedToKey (newNote, e);
  61053. updateNoteUnderMouse (e.getPosition());
  61054. }
  61055. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61056. {
  61057. return true;
  61058. }
  61059. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61060. {
  61061. }
  61062. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61063. {
  61064. float mousePositionVelocity;
  61065. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61066. mouseDragging = false;
  61067. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61068. {
  61069. repaintNote (noteUnderMouse);
  61070. noteUnderMouse = -1;
  61071. mouseDragging = true;
  61072. updateNoteUnderMouse (e.getPosition());
  61073. startTimer (500);
  61074. }
  61075. }
  61076. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61077. {
  61078. mouseDragging = false;
  61079. updateNoteUnderMouse (e.getPosition());
  61080. stopTimer();
  61081. }
  61082. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61083. {
  61084. updateNoteUnderMouse (e.getPosition());
  61085. }
  61086. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61087. {
  61088. updateNoteUnderMouse (e.getPosition());
  61089. }
  61090. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61091. {
  61092. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61093. }
  61094. void MidiKeyboardComponent::timerCallback()
  61095. {
  61096. updateNoteUnderMouse (getMouseXYRelative());
  61097. }
  61098. void MidiKeyboardComponent::clearKeyMappings()
  61099. {
  61100. resetAnyKeysInUse();
  61101. keyPressNotes.clear();
  61102. keyPresses.clear();
  61103. }
  61104. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61105. const int midiNoteOffsetFromC)
  61106. {
  61107. removeKeyPressForNote (midiNoteOffsetFromC);
  61108. keyPressNotes.add (midiNoteOffsetFromC);
  61109. keyPresses.add (key);
  61110. }
  61111. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61112. {
  61113. for (int i = keyPressNotes.size(); --i >= 0;)
  61114. {
  61115. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61116. {
  61117. keyPressNotes.remove (i);
  61118. keyPresses.remove (i);
  61119. }
  61120. }
  61121. }
  61122. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61123. {
  61124. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61125. keyMappingOctave = newOctaveNumber;
  61126. }
  61127. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61128. {
  61129. bool keyPressUsed = false;
  61130. for (int i = keyPresses.size(); --i >= 0;)
  61131. {
  61132. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61133. if (keyPresses.getReference(i).isCurrentlyDown())
  61134. {
  61135. if (! keysPressed [note])
  61136. {
  61137. keysPressed.setBit (note);
  61138. state.noteOn (midiChannel, note, velocity);
  61139. keyPressUsed = true;
  61140. }
  61141. }
  61142. else
  61143. {
  61144. if (keysPressed [note])
  61145. {
  61146. keysPressed.clearBit (note);
  61147. state.noteOff (midiChannel, note);
  61148. keyPressUsed = true;
  61149. }
  61150. }
  61151. }
  61152. return keyPressUsed;
  61153. }
  61154. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61155. {
  61156. resetAnyKeysInUse();
  61157. }
  61158. END_JUCE_NAMESPACE
  61159. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61160. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61161. #if JUCE_OPENGL
  61162. BEGIN_JUCE_NAMESPACE
  61163. extern void juce_glViewport (const int w, const int h);
  61164. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61165. const int alphaBits_,
  61166. const int depthBufferBits_,
  61167. const int stencilBufferBits_)
  61168. : redBits (bitsPerRGBComponent),
  61169. greenBits (bitsPerRGBComponent),
  61170. blueBits (bitsPerRGBComponent),
  61171. alphaBits (alphaBits_),
  61172. depthBufferBits (depthBufferBits_),
  61173. stencilBufferBits (stencilBufferBits_),
  61174. accumulationBufferRedBits (0),
  61175. accumulationBufferGreenBits (0),
  61176. accumulationBufferBlueBits (0),
  61177. accumulationBufferAlphaBits (0),
  61178. fullSceneAntiAliasingNumSamples (0)
  61179. {
  61180. }
  61181. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61182. : redBits (other.redBits),
  61183. greenBits (other.greenBits),
  61184. blueBits (other.blueBits),
  61185. alphaBits (other.alphaBits),
  61186. depthBufferBits (other.depthBufferBits),
  61187. stencilBufferBits (other.stencilBufferBits),
  61188. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61189. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61190. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61191. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61192. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61193. {
  61194. }
  61195. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61196. {
  61197. redBits = other.redBits;
  61198. greenBits = other.greenBits;
  61199. blueBits = other.blueBits;
  61200. alphaBits = other.alphaBits;
  61201. depthBufferBits = other.depthBufferBits;
  61202. stencilBufferBits = other.stencilBufferBits;
  61203. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61204. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61205. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61206. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61207. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61208. return *this;
  61209. }
  61210. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61211. {
  61212. return redBits == other.redBits
  61213. && greenBits == other.greenBits
  61214. && blueBits == other.blueBits
  61215. && alphaBits == other.alphaBits
  61216. && depthBufferBits == other.depthBufferBits
  61217. && stencilBufferBits == other.stencilBufferBits
  61218. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61219. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61220. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61221. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61222. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61223. }
  61224. static Array<OpenGLContext*> knownContexts;
  61225. OpenGLContext::OpenGLContext() throw()
  61226. {
  61227. knownContexts.add (this);
  61228. }
  61229. OpenGLContext::~OpenGLContext()
  61230. {
  61231. knownContexts.removeValue (this);
  61232. }
  61233. OpenGLContext* OpenGLContext::getCurrentContext()
  61234. {
  61235. for (int i = knownContexts.size(); --i >= 0;)
  61236. {
  61237. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61238. if (oglc->isActive())
  61239. return oglc;
  61240. }
  61241. return 0;
  61242. }
  61243. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61244. {
  61245. public:
  61246. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61247. : ComponentMovementWatcher (owner_),
  61248. owner (owner_)
  61249. {
  61250. }
  61251. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61252. {
  61253. owner->updateContextPosition();
  61254. }
  61255. void componentPeerChanged()
  61256. {
  61257. const ScopedLock sl (owner->getContextLock());
  61258. owner->deleteContext();
  61259. }
  61260. void componentVisibilityChanged()
  61261. {
  61262. if (! owner->isShowing())
  61263. {
  61264. const ScopedLock sl (owner->getContextLock());
  61265. owner->deleteContext();
  61266. }
  61267. }
  61268. private:
  61269. OpenGLComponent* const owner;
  61270. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61271. };
  61272. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61273. : type (type_),
  61274. contextToShareListsWith (0),
  61275. needToUpdateViewport (true)
  61276. {
  61277. setOpaque (true);
  61278. componentWatcher = new OpenGLComponentWatcher (this);
  61279. }
  61280. OpenGLComponent::~OpenGLComponent()
  61281. {
  61282. deleteContext();
  61283. componentWatcher = 0;
  61284. }
  61285. void OpenGLComponent::deleteContext()
  61286. {
  61287. const ScopedLock sl (contextLock);
  61288. context = 0;
  61289. }
  61290. void OpenGLComponent::updateContextPosition()
  61291. {
  61292. needToUpdateViewport = true;
  61293. if (getWidth() > 0 && getHeight() > 0)
  61294. {
  61295. Component* const topComp = getTopLevelComponent();
  61296. if (topComp->getPeer() != 0)
  61297. {
  61298. const ScopedLock sl (contextLock);
  61299. if (context != 0)
  61300. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61301. getScreenY() - topComp->getScreenY(),
  61302. getWidth(),
  61303. getHeight(),
  61304. topComp->getHeight());
  61305. }
  61306. }
  61307. }
  61308. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61309. {
  61310. OpenGLPixelFormat pf;
  61311. const ScopedLock sl (contextLock);
  61312. if (context != 0)
  61313. pf = context->getPixelFormat();
  61314. return pf;
  61315. }
  61316. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61317. {
  61318. if (! (preferredPixelFormat == formatToUse))
  61319. {
  61320. const ScopedLock sl (contextLock);
  61321. deleteContext();
  61322. preferredPixelFormat = formatToUse;
  61323. }
  61324. }
  61325. void OpenGLComponent::shareWith (OpenGLContext* c)
  61326. {
  61327. if (contextToShareListsWith != c)
  61328. {
  61329. const ScopedLock sl (contextLock);
  61330. deleteContext();
  61331. contextToShareListsWith = c;
  61332. }
  61333. }
  61334. bool OpenGLComponent::makeCurrentContextActive()
  61335. {
  61336. if (context == 0)
  61337. {
  61338. const ScopedLock sl (contextLock);
  61339. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61340. {
  61341. context = createContext();
  61342. if (context != 0)
  61343. {
  61344. updateContextPosition();
  61345. if (context->makeActive())
  61346. newOpenGLContextCreated();
  61347. }
  61348. }
  61349. }
  61350. return context != 0 && context->makeActive();
  61351. }
  61352. void OpenGLComponent::makeCurrentContextInactive()
  61353. {
  61354. if (context != 0)
  61355. context->makeInactive();
  61356. }
  61357. bool OpenGLComponent::isActiveContext() const throw()
  61358. {
  61359. return context != 0 && context->isActive();
  61360. }
  61361. void OpenGLComponent::swapBuffers()
  61362. {
  61363. if (context != 0)
  61364. context->swapBuffers();
  61365. }
  61366. void OpenGLComponent::paint (Graphics&)
  61367. {
  61368. if (renderAndSwapBuffers())
  61369. {
  61370. ComponentPeer* const peer = getPeer();
  61371. if (peer != 0)
  61372. {
  61373. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61374. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61375. }
  61376. }
  61377. }
  61378. bool OpenGLComponent::renderAndSwapBuffers()
  61379. {
  61380. const ScopedLock sl (contextLock);
  61381. if (! makeCurrentContextActive())
  61382. return false;
  61383. if (needToUpdateViewport)
  61384. {
  61385. needToUpdateViewport = false;
  61386. juce_glViewport (getWidth(), getHeight());
  61387. }
  61388. renderOpenGL();
  61389. swapBuffers();
  61390. return true;
  61391. }
  61392. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61393. {
  61394. Component::internalRepaint (x, y, w, h);
  61395. if (context != 0)
  61396. context->repaint();
  61397. }
  61398. END_JUCE_NAMESPACE
  61399. #endif
  61400. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61401. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61402. BEGIN_JUCE_NAMESPACE
  61403. PreferencesPanel::PreferencesPanel()
  61404. : buttonSize (70)
  61405. {
  61406. }
  61407. PreferencesPanel::~PreferencesPanel()
  61408. {
  61409. }
  61410. void PreferencesPanel::addSettingsPage (const String& title,
  61411. const Drawable* icon,
  61412. const Drawable* overIcon,
  61413. const Drawable* downIcon)
  61414. {
  61415. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61416. buttons.add (button);
  61417. button->setImages (icon, overIcon, downIcon);
  61418. button->setRadioGroupId (1);
  61419. button->addListener (this);
  61420. button->setClickingTogglesState (true);
  61421. button->setWantsKeyboardFocus (false);
  61422. addAndMakeVisible (button);
  61423. resized();
  61424. if (currentPage == 0)
  61425. setCurrentPage (title);
  61426. }
  61427. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61428. {
  61429. DrawableImage icon, iconOver, iconDown;
  61430. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61431. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61432. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61433. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61434. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61435. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61436. }
  61437. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61438. {
  61439. setSize (dialogWidth, dialogHeight);
  61440. DialogWindow::showDialog (dialogTitle, this, 0, backgroundColour, false);
  61441. }
  61442. void PreferencesPanel::resized()
  61443. {
  61444. for (int i = 0; i < buttons.size(); ++i)
  61445. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61446. if (currentPage != 0)
  61447. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61448. }
  61449. void PreferencesPanel::paint (Graphics& g)
  61450. {
  61451. g.setColour (Colours::grey);
  61452. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61453. }
  61454. void PreferencesPanel::setCurrentPage (const String& pageName)
  61455. {
  61456. if (currentPageName != pageName)
  61457. {
  61458. currentPageName = pageName;
  61459. currentPage = 0;
  61460. currentPage = createComponentForPage (pageName);
  61461. if (currentPage != 0)
  61462. {
  61463. addAndMakeVisible (currentPage);
  61464. currentPage->toBack();
  61465. resized();
  61466. }
  61467. for (int i = 0; i < buttons.size(); ++i)
  61468. {
  61469. if (buttons.getUnchecked(i)->getName() == pageName)
  61470. {
  61471. buttons.getUnchecked(i)->setToggleState (true, false);
  61472. break;
  61473. }
  61474. }
  61475. }
  61476. }
  61477. void PreferencesPanel::buttonClicked (Button*)
  61478. {
  61479. for (int i = 0; i < buttons.size(); ++i)
  61480. {
  61481. if (buttons.getUnchecked(i)->getToggleState())
  61482. {
  61483. setCurrentPage (buttons.getUnchecked(i)->getName());
  61484. break;
  61485. }
  61486. }
  61487. }
  61488. END_JUCE_NAMESPACE
  61489. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61490. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61491. #if JUCE_WINDOWS || JUCE_LINUX
  61492. BEGIN_JUCE_NAMESPACE
  61493. SystemTrayIconComponent::SystemTrayIconComponent()
  61494. {
  61495. addToDesktop (0);
  61496. }
  61497. SystemTrayIconComponent::~SystemTrayIconComponent()
  61498. {
  61499. }
  61500. END_JUCE_NAMESPACE
  61501. #endif
  61502. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61503. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61504. BEGIN_JUCE_NAMESPACE
  61505. class AlertWindowTextEditor : public TextEditor
  61506. {
  61507. public:
  61508. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61509. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61510. {
  61511. setSelectAllWhenFocused (true);
  61512. }
  61513. void returnPressed()
  61514. {
  61515. // pass these up the component hierarchy to be trigger the buttons
  61516. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61517. }
  61518. void escapePressed()
  61519. {
  61520. // pass these up the component hierarchy to be trigger the buttons
  61521. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61522. }
  61523. private:
  61524. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61525. static juce_wchar getDefaultPasswordChar() throw()
  61526. {
  61527. #if JUCE_LINUX
  61528. return 0x2022;
  61529. #else
  61530. return 0x25cf;
  61531. #endif
  61532. }
  61533. };
  61534. AlertWindow::AlertWindow (const String& title,
  61535. const String& message,
  61536. AlertIconType iconType,
  61537. Component* associatedComponent_)
  61538. : TopLevelWindow (title, true),
  61539. alertIconType (iconType),
  61540. associatedComponent (associatedComponent_)
  61541. {
  61542. if (message.isEmpty())
  61543. text = " "; // to force an update if the message is empty
  61544. setMessage (message);
  61545. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61546. {
  61547. Component* const c = Desktop::getInstance().getComponent (i);
  61548. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61549. {
  61550. setAlwaysOnTop (true);
  61551. break;
  61552. }
  61553. }
  61554. if (! JUCEApplication::isStandaloneApp())
  61555. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61556. lookAndFeelChanged();
  61557. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61558. }
  61559. AlertWindow::~AlertWindow()
  61560. {
  61561. removeAllChildren();
  61562. }
  61563. void AlertWindow::userTriedToCloseWindow()
  61564. {
  61565. exitModalState (0);
  61566. }
  61567. void AlertWindow::setMessage (const String& message)
  61568. {
  61569. const String newMessage (message.substring (0, 2048));
  61570. if (text != newMessage)
  61571. {
  61572. text = newMessage;
  61573. font = getLookAndFeel().getAlertWindowMessageFont();
  61574. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61575. textLayout.setText (getName() + "\n\n", titleFont);
  61576. textLayout.appendText (text, font);
  61577. updateLayout (true);
  61578. repaint();
  61579. }
  61580. }
  61581. void AlertWindow::buttonClicked (Button* button)
  61582. {
  61583. if (button->getParentComponent() != 0)
  61584. button->getParentComponent()->exitModalState (button->getCommandID());
  61585. }
  61586. void AlertWindow::addButton (const String& name,
  61587. const int returnValue,
  61588. const KeyPress& shortcutKey1,
  61589. const KeyPress& shortcutKey2)
  61590. {
  61591. TextButton* const b = new TextButton (name, String::empty);
  61592. buttons.add (b);
  61593. b->setWantsKeyboardFocus (true);
  61594. b->setMouseClickGrabsKeyboardFocus (false);
  61595. b->setCommandToTrigger (0, returnValue, false);
  61596. b->addShortcut (shortcutKey1);
  61597. b->addShortcut (shortcutKey2);
  61598. b->addListener (this);
  61599. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61600. addAndMakeVisible (b, 0);
  61601. updateLayout (false);
  61602. }
  61603. int AlertWindow::getNumButtons() const
  61604. {
  61605. return buttons.size();
  61606. }
  61607. void AlertWindow::triggerButtonClick (const String& buttonName)
  61608. {
  61609. for (int i = buttons.size(); --i >= 0;)
  61610. {
  61611. TextButton* const b = buttons.getUnchecked(i);
  61612. if (buttonName == b->getName())
  61613. {
  61614. b->triggerClick();
  61615. break;
  61616. }
  61617. }
  61618. }
  61619. void AlertWindow::addTextEditor (const String& name,
  61620. const String& initialContents,
  61621. const String& onScreenLabel,
  61622. const bool isPasswordBox)
  61623. {
  61624. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61625. textBoxes.add (tc);
  61626. allComps.add (tc);
  61627. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61628. tc->setFont (font);
  61629. tc->setText (initialContents);
  61630. tc->setCaretPosition (initialContents.length());
  61631. addAndMakeVisible (tc);
  61632. textboxNames.add (onScreenLabel);
  61633. updateLayout (false);
  61634. }
  61635. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61636. {
  61637. for (int i = textBoxes.size(); --i >= 0;)
  61638. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61639. return textBoxes.getUnchecked(i);
  61640. return 0;
  61641. }
  61642. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61643. {
  61644. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61645. return t != 0 ? t->getText() : String::empty;
  61646. }
  61647. void AlertWindow::addComboBox (const String& name,
  61648. const StringArray& items,
  61649. const String& onScreenLabel)
  61650. {
  61651. ComboBox* const cb = new ComboBox (name);
  61652. comboBoxes.add (cb);
  61653. allComps.add (cb);
  61654. for (int i = 0; i < items.size(); ++i)
  61655. cb->addItem (items[i], i + 1);
  61656. addAndMakeVisible (cb);
  61657. cb->setSelectedItemIndex (0);
  61658. comboBoxNames.add (onScreenLabel);
  61659. updateLayout (false);
  61660. }
  61661. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61662. {
  61663. for (int i = comboBoxes.size(); --i >= 0;)
  61664. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61665. return comboBoxes.getUnchecked(i);
  61666. return 0;
  61667. }
  61668. class AlertTextComp : public TextEditor
  61669. {
  61670. public:
  61671. AlertTextComp (const String& message,
  61672. const Font& font)
  61673. {
  61674. setReadOnly (true);
  61675. setMultiLine (true, true);
  61676. setCaretVisible (false);
  61677. setScrollbarsShown (true);
  61678. lookAndFeelChanged();
  61679. setWantsKeyboardFocus (false);
  61680. setFont (font);
  61681. setText (message, false);
  61682. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61683. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61684. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61685. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61686. }
  61687. ~AlertTextComp()
  61688. {
  61689. }
  61690. int getPreferredWidth() const throw() { return bestWidth; }
  61691. void updateLayout (const int width)
  61692. {
  61693. TextLayout text;
  61694. text.appendText (getText(), getFont());
  61695. text.layout (width - 8, Justification::topLeft, true);
  61696. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61697. }
  61698. private:
  61699. int bestWidth;
  61700. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61701. };
  61702. void AlertWindow::addTextBlock (const String& textBlock)
  61703. {
  61704. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61705. textBlocks.add (c);
  61706. allComps.add (c);
  61707. addAndMakeVisible (c);
  61708. updateLayout (false);
  61709. }
  61710. void AlertWindow::addProgressBarComponent (double& progressValue)
  61711. {
  61712. ProgressBar* const pb = new ProgressBar (progressValue);
  61713. progressBars.add (pb);
  61714. allComps.add (pb);
  61715. addAndMakeVisible (pb);
  61716. updateLayout (false);
  61717. }
  61718. void AlertWindow::addCustomComponent (Component* const component)
  61719. {
  61720. customComps.add (component);
  61721. allComps.add (component);
  61722. addAndMakeVisible (component);
  61723. updateLayout (false);
  61724. }
  61725. int AlertWindow::getNumCustomComponents() const
  61726. {
  61727. return customComps.size();
  61728. }
  61729. Component* AlertWindow::getCustomComponent (const int index) const
  61730. {
  61731. return customComps [index];
  61732. }
  61733. Component* AlertWindow::removeCustomComponent (const int index)
  61734. {
  61735. Component* const c = getCustomComponent (index);
  61736. if (c != 0)
  61737. {
  61738. customComps.removeValue (c);
  61739. allComps.removeValue (c);
  61740. removeChildComponent (c);
  61741. updateLayout (false);
  61742. }
  61743. return c;
  61744. }
  61745. void AlertWindow::paint (Graphics& g)
  61746. {
  61747. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61748. g.setColour (findColour (textColourId));
  61749. g.setFont (getLookAndFeel().getAlertWindowFont());
  61750. int i;
  61751. for (i = textBoxes.size(); --i >= 0;)
  61752. {
  61753. const TextEditor* const te = textBoxes.getUnchecked(i);
  61754. g.drawFittedText (textboxNames[i],
  61755. te->getX(), te->getY() - 14,
  61756. te->getWidth(), 14,
  61757. Justification::centredLeft, 1);
  61758. }
  61759. for (i = comboBoxNames.size(); --i >= 0;)
  61760. {
  61761. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61762. g.drawFittedText (comboBoxNames[i],
  61763. cb->getX(), cb->getY() - 14,
  61764. cb->getWidth(), 14,
  61765. Justification::centredLeft, 1);
  61766. }
  61767. for (i = customComps.size(); --i >= 0;)
  61768. {
  61769. const Component* const c = customComps.getUnchecked(i);
  61770. g.drawFittedText (c->getName(),
  61771. c->getX(), c->getY() - 14,
  61772. c->getWidth(), 14,
  61773. Justification::centredLeft, 1);
  61774. }
  61775. }
  61776. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61777. {
  61778. const int titleH = 24;
  61779. const int iconWidth = 80;
  61780. const int wid = jmax (font.getStringWidth (text),
  61781. font.getStringWidth (getName()));
  61782. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61783. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61784. const int edgeGap = 10;
  61785. const int labelHeight = 18;
  61786. int iconSpace;
  61787. if (alertIconType == NoIcon)
  61788. {
  61789. textLayout.layout (w, Justification::horizontallyCentred, true);
  61790. iconSpace = 0;
  61791. }
  61792. else
  61793. {
  61794. textLayout.layout (w, Justification::left, true);
  61795. iconSpace = iconWidth;
  61796. }
  61797. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61798. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61799. const int textLayoutH = textLayout.getHeight();
  61800. const int textBottom = 16 + titleH + textLayoutH;
  61801. int h = textBottom;
  61802. int buttonW = 40;
  61803. int i;
  61804. for (i = 0; i < buttons.size(); ++i)
  61805. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61806. w = jmax (buttonW, w);
  61807. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61808. if (buttons.size() > 0)
  61809. h += 20 + buttons.getUnchecked(0)->getHeight();
  61810. for (i = customComps.size(); --i >= 0;)
  61811. {
  61812. Component* c = customComps.getUnchecked(i);
  61813. w = jmax (w, (c->getWidth() * 100) / 80);
  61814. h += 10 + c->getHeight();
  61815. if (c->getName().isNotEmpty())
  61816. h += labelHeight;
  61817. }
  61818. for (i = textBlocks.size(); --i >= 0;)
  61819. {
  61820. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61821. w = jmax (w, ac->getPreferredWidth());
  61822. }
  61823. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61824. for (i = textBlocks.size(); --i >= 0;)
  61825. {
  61826. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61827. ac->updateLayout ((int) (w * 0.8f));
  61828. h += ac->getHeight() + 10;
  61829. }
  61830. h = jmin (getParentHeight() - 50, h);
  61831. if (onlyIncreaseSize)
  61832. {
  61833. w = jmax (w, getWidth());
  61834. h = jmax (h, getHeight());
  61835. }
  61836. if (! isVisible())
  61837. {
  61838. centreAroundComponent (associatedComponent, w, h);
  61839. }
  61840. else
  61841. {
  61842. const int cx = getX() + getWidth() / 2;
  61843. const int cy = getY() + getHeight() / 2;
  61844. setBounds (cx - w / 2,
  61845. cy - h / 2,
  61846. w, h);
  61847. }
  61848. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61849. const int spacer = 16;
  61850. int totalWidth = -spacer;
  61851. for (i = buttons.size(); --i >= 0;)
  61852. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61853. int x = (w - totalWidth) / 2;
  61854. int y = (int) (getHeight() * 0.95f);
  61855. for (i = 0; i < buttons.size(); ++i)
  61856. {
  61857. TextButton* const c = buttons.getUnchecked(i);
  61858. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61859. c->setTopLeftPosition (x, ny);
  61860. if (ny < y)
  61861. y = ny;
  61862. x += c->getWidth() + spacer;
  61863. c->toFront (false);
  61864. }
  61865. y = textBottom;
  61866. for (i = 0; i < allComps.size(); ++i)
  61867. {
  61868. Component* const c = allComps.getUnchecked(i);
  61869. h = 22;
  61870. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61871. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61872. y += labelHeight;
  61873. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61874. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61875. y += labelHeight;
  61876. if (customComps.contains (c))
  61877. {
  61878. if (c->getName().isNotEmpty())
  61879. y += labelHeight;
  61880. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61881. h = c->getHeight();
  61882. }
  61883. else if (textBlocks.contains (c))
  61884. {
  61885. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61886. h = c->getHeight();
  61887. }
  61888. else
  61889. {
  61890. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61891. }
  61892. y += h + 10;
  61893. }
  61894. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61895. }
  61896. bool AlertWindow::containsAnyExtraComponents() const
  61897. {
  61898. return allComps.size() > 0;
  61899. }
  61900. void AlertWindow::mouseDown (const MouseEvent& e)
  61901. {
  61902. dragger.startDraggingComponent (this, e);
  61903. }
  61904. void AlertWindow::mouseDrag (const MouseEvent& e)
  61905. {
  61906. dragger.dragComponent (this, e, &constrainer);
  61907. }
  61908. bool AlertWindow::keyPressed (const KeyPress& key)
  61909. {
  61910. for (int i = buttons.size(); --i >= 0;)
  61911. {
  61912. TextButton* const b = buttons.getUnchecked(i);
  61913. if (b->isRegisteredForShortcut (key))
  61914. {
  61915. b->triggerClick();
  61916. return true;
  61917. }
  61918. }
  61919. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61920. {
  61921. exitModalState (0);
  61922. return true;
  61923. }
  61924. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61925. {
  61926. buttons.getUnchecked(0)->triggerClick();
  61927. return true;
  61928. }
  61929. return false;
  61930. }
  61931. void AlertWindow::lookAndFeelChanged()
  61932. {
  61933. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61934. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61935. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61936. }
  61937. int AlertWindow::getDesktopWindowStyleFlags() const
  61938. {
  61939. return getLookAndFeel().getAlertBoxWindowFlags();
  61940. }
  61941. class AlertWindowInfo
  61942. {
  61943. public:
  61944. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61945. AlertWindow::AlertIconType iconType_, int numButtons_,
  61946. ModalComponentManager::Callback* callback_, bool modal_)
  61947. : title (title_), message (message_), iconType (iconType_),
  61948. numButtons (numButtons_), returnValue (0), associatedComponent (component),
  61949. callback (callback_), modal (modal_)
  61950. {
  61951. }
  61952. String title, message, button1, button2, button3;
  61953. int invoke() const
  61954. {
  61955. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61956. return returnValue;
  61957. }
  61958. private:
  61959. AlertWindow::AlertIconType iconType;
  61960. int numButtons, returnValue;
  61961. WeakReference<Component> associatedComponent;
  61962. ModalComponentManager::Callback* callback;
  61963. bool modal;
  61964. void show()
  61965. {
  61966. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61967. : LookAndFeel::getDefaultLookAndFeel();
  61968. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61969. iconType, numButtons, associatedComponent));
  61970. jassert (alertBox != 0); // you have to return one of these!
  61971. #if JUCE_MODAL_LOOPS_PERMITTED
  61972. if (modal)
  61973. {
  61974. returnValue = alertBox->runModalLoop();
  61975. }
  61976. else
  61977. #endif
  61978. {
  61979. alertBox->enterModalState (true, callback, true);
  61980. alertBox.release();
  61981. }
  61982. }
  61983. static void* showCallback (void* userData)
  61984. {
  61985. static_cast <AlertWindowInfo*> (userData)->show();
  61986. return 0;
  61987. }
  61988. };
  61989. #if JUCE_MODAL_LOOPS_PERMITTED
  61990. void AlertWindow::showMessageBox (AlertIconType iconType,
  61991. const String& title,
  61992. const String& message,
  61993. const String& buttonText,
  61994. Component* associatedComponent)
  61995. {
  61996. AlertWindowInfo info (title, message, associatedComponent, iconType, 1, 0, true);
  61997. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61998. info.invoke();
  61999. }
  62000. #endif
  62001. void AlertWindow::showMessageBoxAsync (AlertIconType iconType,
  62002. const String& title,
  62003. const String& message,
  62004. const String& buttonText,
  62005. Component* associatedComponent)
  62006. {
  62007. AlertWindowInfo info (title, message, associatedComponent, iconType, 1, 0, false);
  62008. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62009. info.invoke();
  62010. }
  62011. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62012. const String& title,
  62013. const String& message,
  62014. const String& button1Text,
  62015. const String& button2Text,
  62016. Component* associatedComponent,
  62017. ModalComponentManager::Callback* callback)
  62018. {
  62019. AlertWindowInfo info (title, message, associatedComponent, iconType, 2, callback, callback == 0);
  62020. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62021. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62022. return info.invoke() != 0;
  62023. }
  62024. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62025. const String& title,
  62026. const String& message,
  62027. const String& button1Text,
  62028. const String& button2Text,
  62029. const String& button3Text,
  62030. Component* associatedComponent,
  62031. ModalComponentManager::Callback* callback)
  62032. {
  62033. AlertWindowInfo info (title, message, associatedComponent, iconType, 3, callback, callback == 0);
  62034. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62035. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62036. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62037. return info.invoke();
  62038. }
  62039. END_JUCE_NAMESPACE
  62040. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62041. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62042. BEGIN_JUCE_NAMESPACE
  62043. CallOutBox::CallOutBox (Component& contentComponent,
  62044. Component& componentToPointTo,
  62045. Component* const parentComponent)
  62046. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62047. {
  62048. addAndMakeVisible (&content);
  62049. if (parentComponent != 0)
  62050. {
  62051. parentComponent->addChildComponent (this);
  62052. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62053. parentComponent->getLocalBounds());
  62054. setVisible (true);
  62055. }
  62056. else
  62057. {
  62058. if (! JUCEApplication::isStandaloneApp())
  62059. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62060. updatePosition (componentToPointTo.getScreenBounds(),
  62061. componentToPointTo.getParentMonitorArea());
  62062. addToDesktop (ComponentPeer::windowIsTemporary);
  62063. }
  62064. }
  62065. CallOutBox::~CallOutBox()
  62066. {
  62067. }
  62068. void CallOutBox::setArrowSize (const float newSize)
  62069. {
  62070. arrowSize = newSize;
  62071. borderSpace = jmax (20, (int) arrowSize);
  62072. refreshPath();
  62073. }
  62074. void CallOutBox::paint (Graphics& g)
  62075. {
  62076. if (background.isNull())
  62077. {
  62078. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62079. Graphics g2 (background);
  62080. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  62081. }
  62082. g.setColour (Colours::black);
  62083. g.drawImageAt (background, 0, 0);
  62084. }
  62085. void CallOutBox::resized()
  62086. {
  62087. content.setTopLeftPosition (borderSpace, borderSpace);
  62088. refreshPath();
  62089. }
  62090. void CallOutBox::moved()
  62091. {
  62092. refreshPath();
  62093. }
  62094. void CallOutBox::childBoundsChanged (Component*)
  62095. {
  62096. updatePosition (targetArea, availableArea);
  62097. }
  62098. bool CallOutBox::hitTest (int x, int y)
  62099. {
  62100. return outline.contains ((float) x, (float) y);
  62101. }
  62102. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62103. void CallOutBox::inputAttemptWhenModal()
  62104. {
  62105. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62106. if (targetArea.contains (mousePos))
  62107. {
  62108. // if you click on the area that originally popped-up the callout, you expect it
  62109. // to get rid of the box, but deleting the box here allows the click to pass through and
  62110. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62111. postCommandMessage (callOutBoxDismissCommandId);
  62112. }
  62113. else
  62114. {
  62115. exitModalState (0);
  62116. setVisible (false);
  62117. }
  62118. }
  62119. void CallOutBox::handleCommandMessage (int commandId)
  62120. {
  62121. Component::handleCommandMessage (commandId);
  62122. if (commandId == callOutBoxDismissCommandId)
  62123. {
  62124. exitModalState (0);
  62125. setVisible (false);
  62126. }
  62127. }
  62128. bool CallOutBox::keyPressed (const KeyPress& key)
  62129. {
  62130. if (key.isKeyCode (KeyPress::escapeKey))
  62131. {
  62132. inputAttemptWhenModal();
  62133. return true;
  62134. }
  62135. return false;
  62136. }
  62137. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62138. {
  62139. targetArea = newAreaToPointTo;
  62140. availableArea = newAreaToFitIn;
  62141. Rectangle<int> bounds (0, 0,
  62142. content.getWidth() + borderSpace * 2,
  62143. content.getHeight() + borderSpace * 2);
  62144. const int hw = bounds.getWidth() / 2;
  62145. const int hh = bounds.getHeight() / 2;
  62146. const float hwReduced = (float) (hw - borderSpace * 3);
  62147. const float hhReduced = (float) (hh - borderSpace * 3);
  62148. const float arrowIndent = borderSpace - arrowSize;
  62149. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62150. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62151. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62152. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62153. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62154. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62155. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62156. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62157. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62158. float nearest = 1.0e9f;
  62159. for (int i = 0; i < 4; ++i)
  62160. {
  62161. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62162. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62163. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62164. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62165. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62166. distanceFromCentre *= 2.0f;
  62167. if (distanceFromCentre < nearest)
  62168. {
  62169. nearest = distanceFromCentre;
  62170. targetPoint = targets[i];
  62171. bounds.setPosition ((int) (centre.getX() - hw),
  62172. (int) (centre.getY() - hh));
  62173. }
  62174. }
  62175. setBounds (bounds);
  62176. }
  62177. void CallOutBox::refreshPath()
  62178. {
  62179. repaint();
  62180. background = Image::null;
  62181. outline.clear();
  62182. const float gap = 4.5f;
  62183. const float cornerSize = 9.0f;
  62184. const float cornerSize2 = 2.0f * cornerSize;
  62185. const float arrowBaseWidth = arrowSize * 0.7f;
  62186. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62187. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62188. outline.startNewSubPath (left + cornerSize, top);
  62189. if (targetY <= top)
  62190. {
  62191. outline.lineTo (targetX - arrowBaseWidth, top);
  62192. outline.lineTo (targetX, targetY);
  62193. outline.lineTo (targetX + arrowBaseWidth, top);
  62194. }
  62195. outline.lineTo (right - cornerSize, top);
  62196. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62197. if (targetX >= right)
  62198. {
  62199. outline.lineTo (right, targetY - arrowBaseWidth);
  62200. outline.lineTo (targetX, targetY);
  62201. outline.lineTo (right, targetY + arrowBaseWidth);
  62202. }
  62203. outline.lineTo (right, bottom - cornerSize);
  62204. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62205. if (targetY >= bottom)
  62206. {
  62207. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62208. outline.lineTo (targetX, targetY);
  62209. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62210. }
  62211. outline.lineTo (left + cornerSize, bottom);
  62212. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62213. if (targetX <= left)
  62214. {
  62215. outline.lineTo (left, targetY + arrowBaseWidth);
  62216. outline.lineTo (targetX, targetY);
  62217. outline.lineTo (left, targetY - arrowBaseWidth);
  62218. }
  62219. outline.lineTo (left, top + cornerSize);
  62220. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62221. outline.closeSubPath();
  62222. }
  62223. END_JUCE_NAMESPACE
  62224. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62225. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62226. BEGIN_JUCE_NAMESPACE
  62227. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62228. static Array <ComponentPeer*> heavyweightPeers;
  62229. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62230. : component (component_),
  62231. styleFlags (styleFlags_),
  62232. lastPaintTime (0),
  62233. constrainer (0),
  62234. lastDragAndDropCompUnderMouse (0),
  62235. fakeMouseMessageSent (false),
  62236. isWindowMinimised (false)
  62237. {
  62238. heavyweightPeers.add (this);
  62239. }
  62240. ComponentPeer::~ComponentPeer()
  62241. {
  62242. heavyweightPeers.removeValue (this);
  62243. Desktop::getInstance().triggerFocusCallback();
  62244. }
  62245. int ComponentPeer::getNumPeers() throw()
  62246. {
  62247. return heavyweightPeers.size();
  62248. }
  62249. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62250. {
  62251. return heavyweightPeers [index];
  62252. }
  62253. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62254. {
  62255. for (int i = heavyweightPeers.size(); --i >= 0;)
  62256. {
  62257. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62258. if (peer->getComponent() == component)
  62259. return peer;
  62260. }
  62261. return 0;
  62262. }
  62263. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62264. {
  62265. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62266. }
  62267. void ComponentPeer::updateCurrentModifiers() throw()
  62268. {
  62269. ModifierKeys::updateCurrentModifiers();
  62270. }
  62271. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62272. {
  62273. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62274. jassert (mouse != 0); // not enough sources!
  62275. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62276. }
  62277. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62278. {
  62279. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62280. jassert (mouse != 0); // not enough sources!
  62281. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62282. }
  62283. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62284. {
  62285. Graphics g (&contextToPaintTo);
  62286. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62287. g.saveState();
  62288. #endif
  62289. JUCE_TRY
  62290. {
  62291. component->paintEntireComponent (g, true);
  62292. }
  62293. JUCE_CATCH_EXCEPTION
  62294. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62295. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62296. // clearly when things are being repainted.
  62297. g.restoreState();
  62298. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62299. (uint8) Random::getSystemRandom().nextInt (255),
  62300. (uint8) Random::getSystemRandom().nextInt (255),
  62301. (uint8) 0x50));
  62302. #endif
  62303. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62304. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62305. mess up a lot of the calculations that the library needs to do.
  62306. */
  62307. jassert (roundToInt (10.1f) == 10);
  62308. }
  62309. bool ComponentPeer::handleKeyPress (const int keyCode,
  62310. const juce_wchar textCharacter)
  62311. {
  62312. updateCurrentModifiers();
  62313. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62314. ? Component::getCurrentlyFocusedComponent()
  62315. : component;
  62316. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62317. {
  62318. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62319. if (currentModalComp != 0)
  62320. target = currentModalComp;
  62321. }
  62322. const KeyPress keyInfo (keyCode,
  62323. ModifierKeys::getCurrentModifiers().getRawFlags()
  62324. & ModifierKeys::allKeyboardModifiers,
  62325. textCharacter);
  62326. bool keyWasUsed = false;
  62327. while (target != 0)
  62328. {
  62329. const WeakReference<Component> deletionChecker (target);
  62330. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62331. if (keyListeners != 0)
  62332. {
  62333. for (int i = keyListeners->size(); --i >= 0;)
  62334. {
  62335. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  62336. if (keyWasUsed || deletionChecker == 0)
  62337. return keyWasUsed;
  62338. i = jmin (i, keyListeners->size());
  62339. }
  62340. }
  62341. keyWasUsed = target->keyPressed (keyInfo);
  62342. if (keyWasUsed || deletionChecker == 0)
  62343. break;
  62344. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62345. {
  62346. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62347. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62348. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62349. break;
  62350. }
  62351. target = target->getParentComponent();
  62352. }
  62353. return keyWasUsed;
  62354. }
  62355. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62356. {
  62357. updateCurrentModifiers();
  62358. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62359. ? Component::getCurrentlyFocusedComponent()
  62360. : component;
  62361. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62362. {
  62363. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62364. if (currentModalComp != 0)
  62365. target = currentModalComp;
  62366. }
  62367. bool keyWasUsed = false;
  62368. while (target != 0)
  62369. {
  62370. const WeakReference<Component> deletionChecker (target);
  62371. keyWasUsed = target->keyStateChanged (isKeyDown);
  62372. if (keyWasUsed || deletionChecker == 0)
  62373. break;
  62374. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62375. if (keyListeners != 0)
  62376. {
  62377. for (int i = keyListeners->size(); --i >= 0;)
  62378. {
  62379. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62380. if (keyWasUsed || deletionChecker == 0)
  62381. return keyWasUsed;
  62382. i = jmin (i, keyListeners->size());
  62383. }
  62384. }
  62385. target = target->getParentComponent();
  62386. }
  62387. return keyWasUsed;
  62388. }
  62389. void ComponentPeer::handleModifierKeysChange()
  62390. {
  62391. updateCurrentModifiers();
  62392. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62393. if (target == 0)
  62394. target = Component::getCurrentlyFocusedComponent();
  62395. if (target == 0)
  62396. target = component;
  62397. if (target != 0)
  62398. target->internalModifierKeysChanged();
  62399. }
  62400. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62401. {
  62402. Component* const c = Component::getCurrentlyFocusedComponent();
  62403. if (component->isParentOf (c))
  62404. {
  62405. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62406. if (ti != 0 && ti->isTextInputActive())
  62407. return ti;
  62408. }
  62409. return 0;
  62410. }
  62411. void ComponentPeer::handleBroughtToFront()
  62412. {
  62413. updateCurrentModifiers();
  62414. if (component != 0)
  62415. component->internalBroughtToFront();
  62416. }
  62417. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62418. {
  62419. constrainer = newConstrainer;
  62420. }
  62421. void ComponentPeer::handleMovedOrResized()
  62422. {
  62423. updateCurrentModifiers();
  62424. const bool nowMinimised = isMinimised();
  62425. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62426. {
  62427. const WeakReference<Component> deletionChecker (component);
  62428. const Rectangle<int> newBounds (getBounds());
  62429. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62430. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62431. if (wasMoved || wasResized)
  62432. {
  62433. component->bounds = newBounds;
  62434. if (wasResized)
  62435. component->repaint();
  62436. component->sendMovedResizedMessages (wasMoved, wasResized);
  62437. if (deletionChecker == 0)
  62438. return;
  62439. }
  62440. }
  62441. if (isWindowMinimised != nowMinimised)
  62442. {
  62443. isWindowMinimised = nowMinimised;
  62444. component->minimisationStateChanged (nowMinimised);
  62445. component->sendVisibilityChangeMessage();
  62446. }
  62447. if (! isFullScreen())
  62448. lastNonFullscreenBounds = component->getBounds();
  62449. }
  62450. void ComponentPeer::handleFocusGain()
  62451. {
  62452. updateCurrentModifiers();
  62453. if (component->isParentOf (lastFocusedComponent))
  62454. {
  62455. Component::currentlyFocusedComponent = lastFocusedComponent;
  62456. Desktop::getInstance().triggerFocusCallback();
  62457. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62458. }
  62459. else
  62460. {
  62461. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62462. component->grabKeyboardFocus();
  62463. else
  62464. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62465. }
  62466. }
  62467. void ComponentPeer::handleFocusLoss()
  62468. {
  62469. updateCurrentModifiers();
  62470. if (component->hasKeyboardFocus (true))
  62471. {
  62472. lastFocusedComponent = Component::currentlyFocusedComponent;
  62473. if (lastFocusedComponent != 0)
  62474. {
  62475. Component::currentlyFocusedComponent = 0;
  62476. Desktop::getInstance().triggerFocusCallback();
  62477. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62478. }
  62479. }
  62480. }
  62481. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62482. {
  62483. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62484. ? static_cast <Component*> (lastFocusedComponent)
  62485. : component;
  62486. }
  62487. void ComponentPeer::handleScreenSizeChange()
  62488. {
  62489. updateCurrentModifiers();
  62490. component->parentSizeChanged();
  62491. handleMovedOrResized();
  62492. }
  62493. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62494. {
  62495. lastNonFullscreenBounds = newBounds;
  62496. }
  62497. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62498. {
  62499. return lastNonFullscreenBounds;
  62500. }
  62501. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62502. {
  62503. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62504. }
  62505. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62506. {
  62507. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62508. }
  62509. namespace ComponentPeerHelpers
  62510. {
  62511. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62512. const StringArray& files,
  62513. FileDragAndDropTarget* const lastOne)
  62514. {
  62515. while (c != 0)
  62516. {
  62517. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62518. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62519. return t;
  62520. c = c->getParentComponent();
  62521. }
  62522. return 0;
  62523. }
  62524. }
  62525. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62526. {
  62527. updateCurrentModifiers();
  62528. FileDragAndDropTarget* lastTarget
  62529. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62530. FileDragAndDropTarget* newTarget = 0;
  62531. Component* const compUnderMouse = component->getComponentAt (position);
  62532. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62533. {
  62534. lastDragAndDropCompUnderMouse = compUnderMouse;
  62535. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62536. if (newTarget != lastTarget)
  62537. {
  62538. if (lastTarget != 0)
  62539. lastTarget->fileDragExit (files);
  62540. dragAndDropTargetComponent = 0;
  62541. if (newTarget != 0)
  62542. {
  62543. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62544. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62545. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62546. }
  62547. }
  62548. }
  62549. else
  62550. {
  62551. newTarget = lastTarget;
  62552. }
  62553. if (newTarget != 0)
  62554. {
  62555. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62556. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62557. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62558. }
  62559. }
  62560. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62561. {
  62562. handleFileDragMove (files, Point<int> (-1, -1));
  62563. jassert (dragAndDropTargetComponent == 0);
  62564. lastDragAndDropCompUnderMouse = 0;
  62565. }
  62566. // We'll use an async message to deliver the drop, because if the target decides
  62567. // to run a modal loop, it can gum-up the operating system..
  62568. class AsyncFileDropMessage : public CallbackMessage
  62569. {
  62570. public:
  62571. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62572. const Point<int>& position_, const StringArray& files_)
  62573. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62574. {
  62575. }
  62576. void messageCallback()
  62577. {
  62578. if (target != 0)
  62579. dropTarget->filesDropped (files, position.getX(), position.getY());
  62580. }
  62581. private:
  62582. WeakReference<Component> target;
  62583. FileDragAndDropTarget* const dropTarget;
  62584. const Point<int> position;
  62585. const StringArray files;
  62586. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62587. };
  62588. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62589. {
  62590. handleFileDragMove (files, position);
  62591. if (dragAndDropTargetComponent != 0)
  62592. {
  62593. FileDragAndDropTarget* const target
  62594. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62595. dragAndDropTargetComponent = 0;
  62596. lastDragAndDropCompUnderMouse = 0;
  62597. if (target != 0)
  62598. {
  62599. Component* const targetComp = dynamic_cast <Component*> (target);
  62600. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62601. {
  62602. targetComp->internalModalInputAttempt();
  62603. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62604. return;
  62605. }
  62606. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62607. }
  62608. }
  62609. }
  62610. void ComponentPeer::handleUserClosingWindow()
  62611. {
  62612. updateCurrentModifiers();
  62613. component->userTriedToCloseWindow();
  62614. }
  62615. void ComponentPeer::clearMaskedRegion()
  62616. {
  62617. maskedRegion.clear();
  62618. }
  62619. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62620. {
  62621. maskedRegion.add (x, y, w, h);
  62622. }
  62623. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62624. {
  62625. StringArray s;
  62626. s.add ("Software Renderer");
  62627. return s;
  62628. }
  62629. int ComponentPeer::getCurrentRenderingEngine() throw()
  62630. {
  62631. return 0;
  62632. }
  62633. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62634. {
  62635. }
  62636. END_JUCE_NAMESPACE
  62637. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62638. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62639. BEGIN_JUCE_NAMESPACE
  62640. DialogWindow::DialogWindow (const String& name,
  62641. const Colour& backgroundColour_,
  62642. const bool escapeKeyTriggersCloseButton_,
  62643. const bool addToDesktop_)
  62644. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62645. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62646. {
  62647. }
  62648. DialogWindow::~DialogWindow()
  62649. {
  62650. }
  62651. void DialogWindow::resized()
  62652. {
  62653. DocumentWindow::resized();
  62654. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62655. if (escapeKeyTriggersCloseButton
  62656. && getCloseButton() != 0
  62657. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62658. {
  62659. getCloseButton()->addShortcut (esc);
  62660. }
  62661. }
  62662. class TempDialogWindow : public DialogWindow
  62663. {
  62664. public:
  62665. TempDialogWindow (const String& title,
  62666. Component* contentComponent,
  62667. Component* componentToCentreAround,
  62668. const Colour& colour,
  62669. const bool escapeKeyTriggersCloseButton,
  62670. const bool shouldBeResizable,
  62671. const bool useBottomRightCornerResizer)
  62672. : DialogWindow (title, colour, escapeKeyTriggersCloseButton, true)
  62673. {
  62674. if (! JUCEApplication::isStandaloneApp())
  62675. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62676. setContentNonOwned (contentComponent, true);
  62677. centreAroundComponent (componentToCentreAround, getWidth(), getHeight());
  62678. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62679. }
  62680. void closeButtonPressed()
  62681. {
  62682. setVisible (false);
  62683. }
  62684. private:
  62685. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62686. };
  62687. void DialogWindow::showDialog (const String& dialogTitle,
  62688. Component* const contentComponent,
  62689. Component* const componentToCentreAround,
  62690. const Colour& backgroundColour,
  62691. const bool escapeKeyTriggersCloseButton,
  62692. const bool shouldBeResizable,
  62693. const bool useBottomRightCornerResizer)
  62694. {
  62695. TempDialogWindow* dw = new TempDialogWindow (dialogTitle, contentComponent, componentToCentreAround,
  62696. backgroundColour, escapeKeyTriggersCloseButton,
  62697. shouldBeResizable, useBottomRightCornerResizer);
  62698. dw->enterModalState (true, 0, true);
  62699. }
  62700. #if JUCE_MODAL_LOOPS_PERMITTED
  62701. int DialogWindow::showModalDialog (const String& dialogTitle,
  62702. Component* const contentComponent,
  62703. Component* const componentToCentreAround,
  62704. const Colour& backgroundColour,
  62705. const bool escapeKeyTriggersCloseButton,
  62706. const bool shouldBeResizable,
  62707. const bool useBottomRightCornerResizer)
  62708. {
  62709. TempDialogWindow dw (dialogTitle, contentComponent, componentToCentreAround,
  62710. backgroundColour, escapeKeyTriggersCloseButton,
  62711. shouldBeResizable, useBottomRightCornerResizer);
  62712. return dw.runModalLoop();
  62713. }
  62714. #endif
  62715. END_JUCE_NAMESPACE
  62716. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62717. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62718. BEGIN_JUCE_NAMESPACE
  62719. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62720. {
  62721. public:
  62722. ButtonListenerProxy (DocumentWindow& owner_)
  62723. : owner (owner_)
  62724. {
  62725. }
  62726. void buttonClicked (Button* button)
  62727. {
  62728. if (button == owner.getMinimiseButton())
  62729. owner.minimiseButtonPressed();
  62730. else if (button == owner.getMaximiseButton())
  62731. owner.maximiseButtonPressed();
  62732. else if (button == owner.getCloseButton())
  62733. owner.closeButtonPressed();
  62734. }
  62735. private:
  62736. DocumentWindow& owner;
  62737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62738. };
  62739. DocumentWindow::DocumentWindow (const String& title,
  62740. const Colour& backgroundColour,
  62741. const int requiredButtons_,
  62742. const bool addToDesktop_)
  62743. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62744. titleBarHeight (26),
  62745. menuBarHeight (24),
  62746. requiredButtons (requiredButtons_),
  62747. #if JUCE_MAC
  62748. positionTitleBarButtonsOnLeft (true),
  62749. #else
  62750. positionTitleBarButtonsOnLeft (false),
  62751. #endif
  62752. drawTitleTextCentred (true),
  62753. menuBarModel (0)
  62754. {
  62755. setResizeLimits (128, 128, 32768, 32768);
  62756. lookAndFeelChanged();
  62757. }
  62758. DocumentWindow::~DocumentWindow()
  62759. {
  62760. // Don't delete or remove the resizer components yourself! They're managed by the
  62761. // DocumentWindow, and you should leave them alone! You may have deleted them
  62762. // accidentally by careless use of deleteAllChildren()..?
  62763. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62764. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62765. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62766. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62767. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62768. titleBarButtons[i] = 0;
  62769. menuBar = 0;
  62770. }
  62771. void DocumentWindow::repaintTitleBar()
  62772. {
  62773. repaint (getTitleBarArea());
  62774. }
  62775. void DocumentWindow::setName (const String& newName)
  62776. {
  62777. if (newName != getName())
  62778. {
  62779. Component::setName (newName);
  62780. repaintTitleBar();
  62781. }
  62782. }
  62783. void DocumentWindow::setIcon (const Image& imageToUse)
  62784. {
  62785. titleBarIcon = imageToUse;
  62786. repaintTitleBar();
  62787. }
  62788. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62789. {
  62790. titleBarHeight = newHeight;
  62791. resized();
  62792. repaintTitleBar();
  62793. }
  62794. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62795. const bool positionTitleBarButtonsOnLeft_)
  62796. {
  62797. requiredButtons = requiredButtons_;
  62798. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62799. lookAndFeelChanged();
  62800. }
  62801. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62802. {
  62803. drawTitleTextCentred = textShouldBeCentred;
  62804. repaintTitleBar();
  62805. }
  62806. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62807. {
  62808. if (menuBarModel != newMenuBarModel)
  62809. {
  62810. menuBar = 0;
  62811. menuBarModel = newMenuBarModel;
  62812. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62813. : getLookAndFeel().getDefaultMenuBarHeight();
  62814. if (menuBarModel != 0)
  62815. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62816. resized();
  62817. }
  62818. }
  62819. Component* DocumentWindow::getMenuBarComponent() const throw()
  62820. {
  62821. return menuBar;
  62822. }
  62823. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62824. {
  62825. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62826. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62827. if (menuBar != 0)
  62828. menuBar->setEnabled (isActiveWindow());
  62829. resized();
  62830. }
  62831. void DocumentWindow::closeButtonPressed()
  62832. {
  62833. /* If you've got a close button, you have to override this method to get
  62834. rid of your window!
  62835. If the window is just a pop-up, you should override this method and make
  62836. it delete the window in whatever way is appropriate for your app. E.g. you
  62837. might just want to call "delete this".
  62838. If your app is centred around this window such that the whole app should quit when
  62839. the window is closed, then you will probably want to use this method as an opportunity
  62840. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62841. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62842. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62843. or closing it via the taskbar icon on Windows).
  62844. */
  62845. jassertfalse;
  62846. }
  62847. void DocumentWindow::minimiseButtonPressed()
  62848. {
  62849. setMinimised (true);
  62850. }
  62851. void DocumentWindow::maximiseButtonPressed()
  62852. {
  62853. setFullScreen (! isFullScreen());
  62854. }
  62855. void DocumentWindow::paint (Graphics& g)
  62856. {
  62857. ResizableWindow::paint (g);
  62858. if (resizableBorder == 0)
  62859. {
  62860. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62861. const BorderSize<int> border (getBorderThickness());
  62862. g.fillRect (0, 0, getWidth(), border.getTop());
  62863. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62864. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62865. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62866. }
  62867. const Rectangle<int> titleBarArea (getTitleBarArea());
  62868. g.reduceClipRegion (titleBarArea);
  62869. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62870. int titleSpaceX1 = 6;
  62871. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62872. for (int i = 0; i < 3; ++i)
  62873. {
  62874. if (titleBarButtons[i] != 0)
  62875. {
  62876. if (positionTitleBarButtonsOnLeft)
  62877. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62878. else
  62879. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62880. }
  62881. }
  62882. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62883. titleBarArea.getWidth(),
  62884. titleBarArea.getHeight(),
  62885. titleSpaceX1,
  62886. jmax (1, titleSpaceX2 - titleSpaceX1),
  62887. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62888. ! drawTitleTextCentred);
  62889. }
  62890. void DocumentWindow::resized()
  62891. {
  62892. ResizableWindow::resized();
  62893. if (titleBarButtons[1] != 0)
  62894. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62895. const Rectangle<int> titleBarArea (getTitleBarArea());
  62896. getLookAndFeel()
  62897. .positionDocumentWindowButtons (*this,
  62898. titleBarArea.getX(), titleBarArea.getY(),
  62899. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62900. titleBarButtons[0],
  62901. titleBarButtons[1],
  62902. titleBarButtons[2],
  62903. positionTitleBarButtonsOnLeft);
  62904. if (menuBar != 0)
  62905. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62906. titleBarArea.getWidth(), menuBarHeight);
  62907. }
  62908. const BorderSize<int> DocumentWindow::getBorderThickness()
  62909. {
  62910. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62911. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62912. }
  62913. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62914. {
  62915. BorderSize<int> border (getBorderThickness());
  62916. border.setTop (border.getTop()
  62917. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62918. + (menuBar != 0 ? menuBarHeight : 0));
  62919. return border;
  62920. }
  62921. int DocumentWindow::getTitleBarHeight() const
  62922. {
  62923. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62924. }
  62925. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62926. {
  62927. const BorderSize<int> border (getBorderThickness());
  62928. return Rectangle<int> (border.getLeft(), border.getTop(),
  62929. getWidth() - border.getLeftAndRight(),
  62930. getTitleBarHeight());
  62931. }
  62932. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62933. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62934. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62935. int DocumentWindow::getDesktopWindowStyleFlags() const
  62936. {
  62937. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62938. if ((requiredButtons & minimiseButton) != 0)
  62939. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62940. if ((requiredButtons & maximiseButton) != 0)
  62941. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62942. if ((requiredButtons & closeButton) != 0)
  62943. styleFlags |= ComponentPeer::windowHasCloseButton;
  62944. return styleFlags;
  62945. }
  62946. void DocumentWindow::lookAndFeelChanged()
  62947. {
  62948. int i;
  62949. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62950. titleBarButtons[i] = 0;
  62951. if (! isUsingNativeTitleBar())
  62952. {
  62953. LookAndFeel& lf = getLookAndFeel();
  62954. if ((requiredButtons & minimiseButton) != 0)
  62955. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62956. if ((requiredButtons & maximiseButton) != 0)
  62957. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62958. if ((requiredButtons & closeButton) != 0)
  62959. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62960. for (i = 0; i < 3; ++i)
  62961. {
  62962. if (titleBarButtons[i] != 0)
  62963. {
  62964. if (buttonListener == 0)
  62965. buttonListener = new ButtonListenerProxy (*this);
  62966. titleBarButtons[i]->addListener (buttonListener);
  62967. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62968. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62969. Component::addAndMakeVisible (titleBarButtons[i]);
  62970. }
  62971. }
  62972. if (getCloseButton() != 0)
  62973. {
  62974. #if JUCE_MAC
  62975. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62976. #else
  62977. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62978. #endif
  62979. }
  62980. }
  62981. activeWindowStatusChanged();
  62982. ResizableWindow::lookAndFeelChanged();
  62983. }
  62984. void DocumentWindow::parentHierarchyChanged()
  62985. {
  62986. lookAndFeelChanged();
  62987. }
  62988. void DocumentWindow::activeWindowStatusChanged()
  62989. {
  62990. ResizableWindow::activeWindowStatusChanged();
  62991. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62992. if (titleBarButtons[i] != 0)
  62993. titleBarButtons[i]->setEnabled (isActiveWindow());
  62994. if (menuBar != 0)
  62995. menuBar->setEnabled (isActiveWindow());
  62996. }
  62997. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62998. {
  62999. if (getTitleBarArea().contains (e.x, e.y)
  63000. && getMaximiseButton() != 0)
  63001. {
  63002. getMaximiseButton()->triggerClick();
  63003. }
  63004. }
  63005. void DocumentWindow::userTriedToCloseWindow()
  63006. {
  63007. closeButtonPressed();
  63008. }
  63009. END_JUCE_NAMESPACE
  63010. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63011. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63012. BEGIN_JUCE_NAMESPACE
  63013. ResizableWindow::ResizableWindow (const String& name,
  63014. const bool addToDesktop_)
  63015. : TopLevelWindow (name, addToDesktop_),
  63016. ownsContentComponent (false),
  63017. resizeToFitContent (false),
  63018. fullscreen (false),
  63019. lastNonFullScreenPos (50, 50, 256, 256),
  63020. constrainer (0)
  63021. #if JUCE_DEBUG
  63022. , hasBeenResized (false)
  63023. #endif
  63024. {
  63025. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63026. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63027. if (addToDesktop_)
  63028. Component::addToDesktop (getDesktopWindowStyleFlags());
  63029. }
  63030. ResizableWindow::ResizableWindow (const String& name,
  63031. const Colour& backgroundColour_,
  63032. const bool addToDesktop_)
  63033. : TopLevelWindow (name, addToDesktop_),
  63034. ownsContentComponent (false),
  63035. resizeToFitContent (false),
  63036. fullscreen (false),
  63037. lastNonFullScreenPos (50, 50, 256, 256),
  63038. constrainer (0)
  63039. #if JUCE_DEBUG
  63040. , hasBeenResized (false)
  63041. #endif
  63042. {
  63043. setBackgroundColour (backgroundColour_);
  63044. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63045. if (addToDesktop_)
  63046. Component::addToDesktop (getDesktopWindowStyleFlags());
  63047. }
  63048. ResizableWindow::~ResizableWindow()
  63049. {
  63050. // Don't delete or remove the resizer components yourself! They're managed by the
  63051. // ResizableWindow, and you should leave them alone! You may have deleted them
  63052. // accidentally by careless use of deleteAllChildren()..?
  63053. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  63054. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  63055. resizableCorner = 0;
  63056. resizableBorder = 0;
  63057. clearContentComponent();
  63058. // have you been adding your own components directly to this window..? tut tut tut.
  63059. // Read the instructions for using a ResizableWindow!
  63060. jassert (getNumChildComponents() == 0);
  63061. }
  63062. int ResizableWindow::getDesktopWindowStyleFlags() const
  63063. {
  63064. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63065. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63066. styleFlags |= ComponentPeer::windowIsResizable;
  63067. return styleFlags;
  63068. }
  63069. void ResizableWindow::clearContentComponent()
  63070. {
  63071. if (ownsContentComponent)
  63072. {
  63073. contentComponent.deleteAndZero();
  63074. }
  63075. else
  63076. {
  63077. removeChildComponent (contentComponent);
  63078. contentComponent = 0;
  63079. }
  63080. }
  63081. void ResizableWindow::setContent (Component* newContentComponent,
  63082. const bool takeOwnership,
  63083. const bool resizeToFitWhenContentChangesSize)
  63084. {
  63085. if (newContentComponent != contentComponent)
  63086. {
  63087. clearContentComponent();
  63088. contentComponent = newContentComponent;
  63089. Component::addAndMakeVisible (contentComponent);
  63090. }
  63091. ownsContentComponent = takeOwnership;
  63092. resizeToFitContent = resizeToFitWhenContentChangesSize;
  63093. if (resizeToFitWhenContentChangesSize)
  63094. childBoundsChanged (contentComponent);
  63095. resized(); // must always be called to position the new content comp
  63096. }
  63097. void ResizableWindow::setContentOwned (Component* newContentComponent, const bool resizeToFitWhenContentChangesSize)
  63098. {
  63099. setContent (newContentComponent, true, resizeToFitWhenContentChangesSize);
  63100. }
  63101. void ResizableWindow::setContentNonOwned (Component* newContentComponent, const bool resizeToFitWhenContentChangesSize)
  63102. {
  63103. setContent (newContentComponent, false, resizeToFitWhenContentChangesSize);
  63104. }
  63105. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63106. const bool deleteOldOne,
  63107. const bool resizeToFitWhenContentChangesSize)
  63108. {
  63109. if (newContentComponent != contentComponent)
  63110. {
  63111. if (deleteOldOne)
  63112. {
  63113. contentComponent.deleteAndZero();
  63114. }
  63115. else
  63116. {
  63117. removeChildComponent (contentComponent);
  63118. contentComponent = 0;
  63119. }
  63120. }
  63121. setContent (newContentComponent, true, resizeToFitWhenContentChangesSize);
  63122. }
  63123. void ResizableWindow::setContentComponentSize (int width, int height)
  63124. {
  63125. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63126. const BorderSize<int> border (getContentComponentBorder());
  63127. setSize (width + border.getLeftAndRight(),
  63128. height + border.getTopAndBottom());
  63129. }
  63130. const BorderSize<int> ResizableWindow::getBorderThickness()
  63131. {
  63132. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63133. }
  63134. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  63135. {
  63136. return getBorderThickness();
  63137. }
  63138. void ResizableWindow::moved()
  63139. {
  63140. updateLastPos();
  63141. }
  63142. void ResizableWindow::visibilityChanged()
  63143. {
  63144. TopLevelWindow::visibilityChanged();
  63145. updateLastPos();
  63146. }
  63147. void ResizableWindow::resized()
  63148. {
  63149. if (resizableBorder != 0)
  63150. {
  63151. #if JUCE_WINDOWS || JUCE_LINUX
  63152. // hide the resizable border if the OS already provides one..
  63153. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63154. #else
  63155. resizableBorder->setVisible (! isFullScreen());
  63156. #endif
  63157. resizableBorder->setBorderThickness (getBorderThickness());
  63158. resizableBorder->setSize (getWidth(), getHeight());
  63159. resizableBorder->toBack();
  63160. }
  63161. if (resizableCorner != 0)
  63162. {
  63163. #if JUCE_MAC
  63164. // hide the resizable border if the OS already provides one..
  63165. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63166. #else
  63167. resizableCorner->setVisible (! isFullScreen());
  63168. #endif
  63169. const int resizerSize = 18;
  63170. resizableCorner->setBounds (getWidth() - resizerSize,
  63171. getHeight() - resizerSize,
  63172. resizerSize, resizerSize);
  63173. }
  63174. if (contentComponent != 0)
  63175. contentComponent->setBoundsInset (getContentComponentBorder());
  63176. updateLastPos();
  63177. #if JUCE_DEBUG
  63178. hasBeenResized = true;
  63179. #endif
  63180. }
  63181. void ResizableWindow::childBoundsChanged (Component* child)
  63182. {
  63183. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63184. {
  63185. // not going to look very good if this component has a zero size..
  63186. jassert (child->getWidth() > 0);
  63187. jassert (child->getHeight() > 0);
  63188. const BorderSize<int> borders (getContentComponentBorder());
  63189. setSize (child->getWidth() + borders.getLeftAndRight(),
  63190. child->getHeight() + borders.getTopAndBottom());
  63191. }
  63192. }
  63193. void ResizableWindow::activeWindowStatusChanged()
  63194. {
  63195. const BorderSize<int> border (getContentComponentBorder());
  63196. Rectangle<int> area (getLocalBounds());
  63197. repaint (area.removeFromTop (border.getTop()));
  63198. repaint (area.removeFromLeft (border.getLeft()));
  63199. repaint (area.removeFromRight (border.getRight()));
  63200. repaint (area.removeFromBottom (border.getBottom()));
  63201. }
  63202. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63203. const bool useBottomRightCornerResizer)
  63204. {
  63205. if (shouldBeResizable)
  63206. {
  63207. if (useBottomRightCornerResizer)
  63208. {
  63209. resizableBorder = 0;
  63210. if (resizableCorner == 0)
  63211. {
  63212. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63213. resizableCorner->setAlwaysOnTop (true);
  63214. }
  63215. }
  63216. else
  63217. {
  63218. resizableCorner = 0;
  63219. if (resizableBorder == 0)
  63220. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63221. }
  63222. }
  63223. else
  63224. {
  63225. resizableCorner = 0;
  63226. resizableBorder = 0;
  63227. }
  63228. if (isUsingNativeTitleBar())
  63229. recreateDesktopWindow();
  63230. childBoundsChanged (contentComponent);
  63231. resized();
  63232. }
  63233. bool ResizableWindow::isResizable() const throw()
  63234. {
  63235. return resizableCorner != 0
  63236. || resizableBorder != 0;
  63237. }
  63238. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63239. const int newMinimumHeight,
  63240. const int newMaximumWidth,
  63241. const int newMaximumHeight) throw()
  63242. {
  63243. // if you've set up a custom constrainer then these settings won't have any effect..
  63244. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63245. if (constrainer == 0)
  63246. setConstrainer (&defaultConstrainer);
  63247. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63248. newMaximumWidth, newMaximumHeight);
  63249. setBoundsConstrained (getBounds());
  63250. }
  63251. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63252. {
  63253. if (constrainer != newConstrainer)
  63254. {
  63255. constrainer = newConstrainer;
  63256. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63257. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63258. resizableCorner = 0;
  63259. resizableBorder = 0;
  63260. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63261. ComponentPeer* const peer = getPeer();
  63262. if (peer != 0)
  63263. peer->setConstrainer (newConstrainer);
  63264. }
  63265. }
  63266. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63267. {
  63268. if (constrainer != 0)
  63269. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63270. else
  63271. setBounds (bounds);
  63272. }
  63273. void ResizableWindow::paint (Graphics& g)
  63274. {
  63275. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63276. getBorderThickness(), *this);
  63277. if (! isFullScreen())
  63278. {
  63279. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63280. getBorderThickness(), *this);
  63281. }
  63282. #if JUCE_DEBUG
  63283. /* If this fails, then you've probably written a subclass with a resized()
  63284. callback but forgotten to make it call its parent class's resized() method.
  63285. It's important when you override methods like resized(), moved(),
  63286. etc., that you make sure the base class methods also get called.
  63287. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63288. because your content should all be inside the content component - and it's the
  63289. content component's resized() method that you should be using to do your
  63290. layout.
  63291. */
  63292. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63293. #endif
  63294. }
  63295. void ResizableWindow::lookAndFeelChanged()
  63296. {
  63297. resized();
  63298. if (isOnDesktop())
  63299. {
  63300. Component::addToDesktop (getDesktopWindowStyleFlags());
  63301. ComponentPeer* const peer = getPeer();
  63302. if (peer != 0)
  63303. peer->setConstrainer (constrainer);
  63304. }
  63305. }
  63306. const Colour ResizableWindow::getBackgroundColour() const throw()
  63307. {
  63308. return findColour (backgroundColourId, false);
  63309. }
  63310. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63311. {
  63312. Colour backgroundColour (newColour);
  63313. if (! Desktop::canUseSemiTransparentWindows())
  63314. backgroundColour = newColour.withAlpha (1.0f);
  63315. setColour (backgroundColourId, backgroundColour);
  63316. setOpaque (backgroundColour.isOpaque());
  63317. repaint();
  63318. }
  63319. bool ResizableWindow::isFullScreen() const
  63320. {
  63321. if (isOnDesktop())
  63322. {
  63323. ComponentPeer* const peer = getPeer();
  63324. return peer != 0 && peer->isFullScreen();
  63325. }
  63326. return fullscreen;
  63327. }
  63328. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63329. {
  63330. if (shouldBeFullScreen != isFullScreen())
  63331. {
  63332. updateLastPos();
  63333. fullscreen = shouldBeFullScreen;
  63334. if (isOnDesktop())
  63335. {
  63336. ComponentPeer* const peer = getPeer();
  63337. if (peer != 0)
  63338. {
  63339. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63340. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63341. peer->setFullScreen (shouldBeFullScreen);
  63342. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63343. setBounds (lastPos);
  63344. }
  63345. else
  63346. {
  63347. jassertfalse;
  63348. }
  63349. }
  63350. else
  63351. {
  63352. if (shouldBeFullScreen)
  63353. setBounds (0, 0, getParentWidth(), getParentHeight());
  63354. else
  63355. setBounds (lastNonFullScreenPos);
  63356. }
  63357. resized();
  63358. }
  63359. }
  63360. bool ResizableWindow::isMinimised() const
  63361. {
  63362. ComponentPeer* const peer = getPeer();
  63363. return (peer != 0) && peer->isMinimised();
  63364. }
  63365. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63366. {
  63367. if (shouldMinimise != isMinimised())
  63368. {
  63369. ComponentPeer* const peer = getPeer();
  63370. if (peer != 0)
  63371. {
  63372. updateLastPos();
  63373. peer->setMinimised (shouldMinimise);
  63374. }
  63375. else
  63376. {
  63377. jassertfalse;
  63378. }
  63379. }
  63380. }
  63381. void ResizableWindow::updateLastPos()
  63382. {
  63383. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63384. {
  63385. lastNonFullScreenPos = getBounds();
  63386. }
  63387. }
  63388. void ResizableWindow::parentSizeChanged()
  63389. {
  63390. if (isFullScreen() && getParentComponent() != 0)
  63391. {
  63392. setBounds (0, 0, getParentWidth(), getParentHeight());
  63393. }
  63394. }
  63395. const String ResizableWindow::getWindowStateAsString()
  63396. {
  63397. updateLastPos();
  63398. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63399. }
  63400. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63401. {
  63402. StringArray tokens;
  63403. tokens.addTokens (s, false);
  63404. tokens.removeEmptyStrings();
  63405. tokens.trim();
  63406. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63407. const int firstCoord = fs ? 1 : 0;
  63408. if (tokens.size() != firstCoord + 4)
  63409. return false;
  63410. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63411. tokens[firstCoord + 1].getIntValue(),
  63412. tokens[firstCoord + 2].getIntValue(),
  63413. tokens[firstCoord + 3].getIntValue());
  63414. if (newPos.isEmpty())
  63415. return false;
  63416. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63417. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63418. if (peer != 0)
  63419. peer->getFrameSize().addTo (newPos);
  63420. if (! screen.contains (newPos))
  63421. {
  63422. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63423. jmin (newPos.getHeight(), screen.getHeight()));
  63424. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63425. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63426. }
  63427. if (peer != 0)
  63428. {
  63429. peer->getFrameSize().subtractFrom (newPos);
  63430. peer->setNonFullScreenBounds (newPos);
  63431. }
  63432. lastNonFullScreenPos = newPos;
  63433. setFullScreen (fs);
  63434. if (! fs)
  63435. setBoundsConstrained (newPos);
  63436. return true;
  63437. }
  63438. void ResizableWindow::mouseDown (const MouseEvent& e)
  63439. {
  63440. if (! isFullScreen())
  63441. dragger.startDraggingComponent (this, e);
  63442. }
  63443. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63444. {
  63445. if (! isFullScreen())
  63446. dragger.dragComponent (this, e, constrainer);
  63447. }
  63448. #if JUCE_DEBUG
  63449. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63450. {
  63451. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63452. manages its child components automatically, and if you add your own it'll cause
  63453. trouble. Instead, use setContentComponent() to give it a component which
  63454. will be automatically resized and kept in the right place - then you can add
  63455. subcomponents to the content comp. See the notes for the ResizableWindow class
  63456. for more info.
  63457. If you really know what you're doing and want to avoid this assertion, just call
  63458. Component::addChildComponent directly.
  63459. */
  63460. jassertfalse;
  63461. Component::addChildComponent (child, zOrder);
  63462. }
  63463. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63464. {
  63465. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63466. manages its child components automatically, and if you add your own it'll cause
  63467. trouble. Instead, use setContentComponent() to give it a component which
  63468. will be automatically resized and kept in the right place - then you can add
  63469. subcomponents to the content comp. See the notes for the ResizableWindow class
  63470. for more info.
  63471. If you really know what you're doing and want to avoid this assertion, just call
  63472. Component::addAndMakeVisible directly.
  63473. */
  63474. jassertfalse;
  63475. Component::addAndMakeVisible (child, zOrder);
  63476. }
  63477. #endif
  63478. END_JUCE_NAMESPACE
  63479. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63480. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63481. BEGIN_JUCE_NAMESPACE
  63482. SplashScreen::SplashScreen()
  63483. {
  63484. setOpaque (true);
  63485. }
  63486. SplashScreen::~SplashScreen()
  63487. {
  63488. }
  63489. void SplashScreen::show (const String& title,
  63490. const Image& backgroundImage_,
  63491. const int minimumTimeToDisplayFor,
  63492. const bool useDropShadow,
  63493. const bool removeOnMouseClick)
  63494. {
  63495. backgroundImage = backgroundImage_;
  63496. jassert (backgroundImage_.isValid());
  63497. if (backgroundImage_.isValid())
  63498. {
  63499. setOpaque (! backgroundImage_.hasAlphaChannel());
  63500. show (title,
  63501. backgroundImage_.getWidth(),
  63502. backgroundImage_.getHeight(),
  63503. minimumTimeToDisplayFor,
  63504. useDropShadow,
  63505. removeOnMouseClick);
  63506. }
  63507. }
  63508. void SplashScreen::show (const String& title,
  63509. const int width,
  63510. const int height,
  63511. const int minimumTimeToDisplayFor,
  63512. const bool useDropShadow,
  63513. const bool removeOnMouseClick)
  63514. {
  63515. setName (title);
  63516. setAlwaysOnTop (true);
  63517. setVisible (true);
  63518. centreWithSize (width, height);
  63519. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63520. toFront (false);
  63521. #if JUCE_MODAL_LOOPS_PERMITTED
  63522. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63523. #endif
  63524. repaint();
  63525. originalClickCounter = removeOnMouseClick
  63526. ? Desktop::getMouseButtonClickCounter()
  63527. : std::numeric_limits<int>::max();
  63528. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63529. startTimer (50);
  63530. }
  63531. void SplashScreen::paint (Graphics& g)
  63532. {
  63533. g.setOpacity (1.0f);
  63534. g.drawImage (backgroundImage,
  63535. 0, 0, getWidth(), getHeight(),
  63536. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63537. }
  63538. void SplashScreen::timerCallback()
  63539. {
  63540. if (Time::getCurrentTime() > earliestTimeToDelete
  63541. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63542. {
  63543. delete this;
  63544. }
  63545. }
  63546. END_JUCE_NAMESPACE
  63547. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63548. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63549. BEGIN_JUCE_NAMESPACE
  63550. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63551. const bool hasProgressBar,
  63552. const bool hasCancelButton,
  63553. const int timeOutMsWhenCancelling_,
  63554. const String& cancelButtonText)
  63555. : Thread ("Juce Progress Window"),
  63556. progress (0.0),
  63557. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63558. {
  63559. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63560. .createAlertWindow (title, String::empty, cancelButtonText,
  63561. String::empty, String::empty,
  63562. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63563. if (hasProgressBar)
  63564. alertWindow->addProgressBarComponent (progress);
  63565. }
  63566. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63567. {
  63568. stopThread (timeOutMsWhenCancelling);
  63569. }
  63570. #if JUCE_MODAL_LOOPS_PERMITTED
  63571. bool ThreadWithProgressWindow::runThread (const int priority)
  63572. {
  63573. startThread (priority);
  63574. startTimer (100);
  63575. {
  63576. const ScopedLock sl (messageLock);
  63577. alertWindow->setMessage (message);
  63578. }
  63579. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63580. stopThread (timeOutMsWhenCancelling);
  63581. alertWindow->setVisible (false);
  63582. return finishedNaturally;
  63583. }
  63584. #endif
  63585. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63586. {
  63587. progress = newProgress;
  63588. }
  63589. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63590. {
  63591. const ScopedLock sl (messageLock);
  63592. message = newStatusMessage;
  63593. }
  63594. void ThreadWithProgressWindow::timerCallback()
  63595. {
  63596. if (! isThreadRunning())
  63597. {
  63598. // thread has finished normally..
  63599. alertWindow->exitModalState (1);
  63600. alertWindow->setVisible (false);
  63601. }
  63602. else
  63603. {
  63604. const ScopedLock sl (messageLock);
  63605. alertWindow->setMessage (message);
  63606. }
  63607. }
  63608. END_JUCE_NAMESPACE
  63609. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63610. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63611. BEGIN_JUCE_NAMESPACE
  63612. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63613. const int millisecondsBeforeTipAppears_)
  63614. : Component ("tooltip"),
  63615. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63616. mouseClicks (0),
  63617. lastHideTime (0),
  63618. lastComponentUnderMouse (0),
  63619. changedCompsSinceShown (true)
  63620. {
  63621. if (Desktop::getInstance().getMainMouseSource().canHover())
  63622. startTimer (123);
  63623. setAlwaysOnTop (true);
  63624. setOpaque (true);
  63625. if (parentComponent != 0)
  63626. parentComponent->addChildComponent (this);
  63627. }
  63628. TooltipWindow::~TooltipWindow()
  63629. {
  63630. hide();
  63631. }
  63632. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63633. {
  63634. millisecondsBeforeTipAppears = newTimeMs;
  63635. }
  63636. void TooltipWindow::paint (Graphics& g)
  63637. {
  63638. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63639. }
  63640. void TooltipWindow::mouseEnter (const MouseEvent&)
  63641. {
  63642. hide();
  63643. }
  63644. void TooltipWindow::showFor (const String& tip)
  63645. {
  63646. jassert (tip.isNotEmpty());
  63647. if (tipShowing != tip)
  63648. repaint();
  63649. tipShowing = tip;
  63650. Point<int> mousePos (Desktop::getMousePosition());
  63651. if (getParentComponent() != 0)
  63652. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63653. int x, y, w, h;
  63654. getLookAndFeel().getTooltipSize (tip, w, h);
  63655. if (mousePos.getX() > getParentWidth() / 2)
  63656. x = mousePos.getX() - (w + 12);
  63657. else
  63658. x = mousePos.getX() + 24;
  63659. if (mousePos.getY() > getParentHeight() / 2)
  63660. y = mousePos.getY() - (h + 6);
  63661. else
  63662. y = mousePos.getY() + 6;
  63663. setBounds (x, y, w, h);
  63664. setVisible (true);
  63665. if (getParentComponent() == 0)
  63666. {
  63667. addToDesktop (ComponentPeer::windowHasDropShadow
  63668. | ComponentPeer::windowIsTemporary
  63669. | ComponentPeer::windowIgnoresKeyPresses);
  63670. }
  63671. toFront (false);
  63672. }
  63673. const String TooltipWindow::getTipFor (Component* const c)
  63674. {
  63675. if (c != 0
  63676. && Process::isForegroundProcess()
  63677. && ! Component::isMouseButtonDownAnywhere())
  63678. {
  63679. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63680. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63681. return ttc->getTooltip();
  63682. }
  63683. return String::empty;
  63684. }
  63685. void TooltipWindow::hide()
  63686. {
  63687. tipShowing = String::empty;
  63688. removeFromDesktop();
  63689. setVisible (false);
  63690. }
  63691. void TooltipWindow::timerCallback()
  63692. {
  63693. const unsigned int now = Time::getApproximateMillisecondCounter();
  63694. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63695. const String newTip (getTipFor (newComp));
  63696. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63697. lastComponentUnderMouse = newComp;
  63698. lastTipUnderMouse = newTip;
  63699. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63700. const bool mouseWasClicked = clickCount > mouseClicks;
  63701. mouseClicks = clickCount;
  63702. const Point<int> mousePos (Desktop::getMousePosition());
  63703. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63704. lastMousePos = mousePos;
  63705. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63706. lastCompChangeTime = now;
  63707. if (isVisible() || now < lastHideTime + 500)
  63708. {
  63709. // if a tip is currently visible (or has just disappeared), update to a new one
  63710. // immediately if needed..
  63711. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63712. {
  63713. if (isVisible())
  63714. {
  63715. lastHideTime = now;
  63716. hide();
  63717. }
  63718. }
  63719. else if (tipChanged)
  63720. {
  63721. showFor (newTip);
  63722. }
  63723. }
  63724. else
  63725. {
  63726. // if there isn't currently a tip, but one is needed, only let it
  63727. // appear after a timeout..
  63728. if (newTip.isNotEmpty()
  63729. && newTip != tipShowing
  63730. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63731. {
  63732. showFor (newTip);
  63733. }
  63734. }
  63735. }
  63736. END_JUCE_NAMESPACE
  63737. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63738. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63739. BEGIN_JUCE_NAMESPACE
  63740. /** Keeps track of the active top level window.
  63741. */
  63742. class TopLevelWindowManager : public Timer,
  63743. public DeletedAtShutdown
  63744. {
  63745. public:
  63746. TopLevelWindowManager()
  63747. : currentActive (0)
  63748. {
  63749. }
  63750. ~TopLevelWindowManager()
  63751. {
  63752. clearSingletonInstance();
  63753. }
  63754. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63755. void timerCallback()
  63756. {
  63757. startTimer (jmin (1731, getTimerInterval() * 2));
  63758. TopLevelWindow* active = 0;
  63759. if (Process::isForegroundProcess())
  63760. {
  63761. active = currentActive;
  63762. Component* const c = Component::getCurrentlyFocusedComponent();
  63763. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63764. if (tlw == 0 && c != 0)
  63765. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63766. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63767. if (tlw != 0)
  63768. active = tlw;
  63769. }
  63770. if (active != currentActive)
  63771. {
  63772. currentActive = active;
  63773. for (int i = windows.size(); --i >= 0;)
  63774. {
  63775. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63776. tlw->setWindowActive (isWindowActive (tlw));
  63777. i = jmin (i, windows.size() - 1);
  63778. }
  63779. Desktop::getInstance().triggerFocusCallback();
  63780. }
  63781. }
  63782. bool addWindow (TopLevelWindow* const w)
  63783. {
  63784. windows.add (w);
  63785. startTimer (10);
  63786. return isWindowActive (w);
  63787. }
  63788. void removeWindow (TopLevelWindow* const w)
  63789. {
  63790. startTimer (10);
  63791. if (currentActive == w)
  63792. currentActive = 0;
  63793. windows.removeValue (w);
  63794. if (windows.size() == 0)
  63795. deleteInstance();
  63796. }
  63797. Array <TopLevelWindow*> windows;
  63798. private:
  63799. TopLevelWindow* currentActive;
  63800. bool isWindowActive (TopLevelWindow* const tlw) const
  63801. {
  63802. return (tlw == currentActive
  63803. || tlw->isParentOf (currentActive)
  63804. || tlw->hasKeyboardFocus (true))
  63805. && tlw->isShowing();
  63806. }
  63807. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63808. };
  63809. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63810. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63811. {
  63812. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63813. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63814. }
  63815. TopLevelWindow::TopLevelWindow (const String& name,
  63816. const bool addToDesktop_)
  63817. : Component (name),
  63818. useDropShadow (true),
  63819. useNativeTitleBar (false),
  63820. windowIsActive_ (false)
  63821. {
  63822. setOpaque (true);
  63823. if (addToDesktop_)
  63824. Component::addToDesktop (getDesktopWindowStyleFlags());
  63825. else
  63826. setDropShadowEnabled (true);
  63827. setWantsKeyboardFocus (true);
  63828. setBroughtToFrontOnMouseClick (true);
  63829. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63830. }
  63831. TopLevelWindow::~TopLevelWindow()
  63832. {
  63833. shadower = 0;
  63834. TopLevelWindowManager::getInstance()->removeWindow (this);
  63835. }
  63836. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63837. {
  63838. if (hasKeyboardFocus (true))
  63839. TopLevelWindowManager::getInstance()->timerCallback();
  63840. else
  63841. TopLevelWindowManager::getInstance()->startTimer (10);
  63842. }
  63843. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63844. {
  63845. if (windowIsActive_ != isNowActive)
  63846. {
  63847. windowIsActive_ = isNowActive;
  63848. activeWindowStatusChanged();
  63849. }
  63850. }
  63851. void TopLevelWindow::activeWindowStatusChanged()
  63852. {
  63853. }
  63854. void TopLevelWindow::visibilityChanged()
  63855. {
  63856. if (isShowing()
  63857. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63858. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63859. {
  63860. toFront (true);
  63861. }
  63862. }
  63863. void TopLevelWindow::parentHierarchyChanged()
  63864. {
  63865. setDropShadowEnabled (useDropShadow);
  63866. }
  63867. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63868. {
  63869. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63870. if (useDropShadow)
  63871. styleFlags |= ComponentPeer::windowHasDropShadow;
  63872. if (useNativeTitleBar)
  63873. styleFlags |= ComponentPeer::windowHasTitleBar;
  63874. return styleFlags;
  63875. }
  63876. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63877. {
  63878. useDropShadow = useShadow;
  63879. if (isOnDesktop())
  63880. {
  63881. shadower = 0;
  63882. Component::addToDesktop (getDesktopWindowStyleFlags());
  63883. }
  63884. else
  63885. {
  63886. if (useShadow && isOpaque())
  63887. {
  63888. if (shadower == 0)
  63889. {
  63890. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63891. if (shadower != 0)
  63892. shadower->setOwner (this);
  63893. }
  63894. }
  63895. else
  63896. {
  63897. shadower = 0;
  63898. }
  63899. }
  63900. }
  63901. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63902. {
  63903. if (useNativeTitleBar != useNativeTitleBar_)
  63904. {
  63905. useNativeTitleBar = useNativeTitleBar_;
  63906. recreateDesktopWindow();
  63907. sendLookAndFeelChange();
  63908. }
  63909. }
  63910. void TopLevelWindow::recreateDesktopWindow()
  63911. {
  63912. if (isOnDesktop())
  63913. {
  63914. Component::addToDesktop (getDesktopWindowStyleFlags());
  63915. toFront (true);
  63916. }
  63917. }
  63918. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63919. {
  63920. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63921. because this class needs to make sure its layout corresponds with settings like whether
  63922. it's got a native title bar or not.
  63923. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63924. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63925. method, then add or remove whatever flags are necessary from this value before returning it.
  63926. */
  63927. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63928. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63929. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63930. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63931. sendLookAndFeelChange();
  63932. }
  63933. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63934. {
  63935. if (c == 0)
  63936. c = TopLevelWindow::getActiveTopLevelWindow();
  63937. if (c == 0)
  63938. {
  63939. centreWithSize (width, height);
  63940. }
  63941. else
  63942. {
  63943. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63944. Rectangle<int> parentArea (c->getParentMonitorArea());
  63945. if (getParentComponent() != 0)
  63946. {
  63947. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63948. parentArea = getParentComponent()->getLocalBounds();
  63949. }
  63950. parentArea.reduce (12, 12);
  63951. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63952. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63953. width, height);
  63954. }
  63955. }
  63956. int TopLevelWindow::getNumTopLevelWindows() throw()
  63957. {
  63958. return TopLevelWindowManager::getInstance()->windows.size();
  63959. }
  63960. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63961. {
  63962. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63963. }
  63964. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63965. {
  63966. TopLevelWindow* best = 0;
  63967. int bestNumTWLParents = -1;
  63968. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63969. {
  63970. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63971. if (tlw->isActiveWindow())
  63972. {
  63973. int numTWLParents = 0;
  63974. const Component* c = tlw->getParentComponent();
  63975. while (c != 0)
  63976. {
  63977. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63978. ++numTWLParents;
  63979. c = c->getParentComponent();
  63980. }
  63981. if (bestNumTWLParents < numTWLParents)
  63982. {
  63983. best = tlw;
  63984. bestNumTWLParents = numTWLParents;
  63985. }
  63986. }
  63987. }
  63988. return best;
  63989. }
  63990. END_JUCE_NAMESPACE
  63991. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63992. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63993. BEGIN_JUCE_NAMESPACE
  63994. MarkerList::MarkerList()
  63995. {
  63996. }
  63997. MarkerList::MarkerList (const MarkerList& other)
  63998. {
  63999. operator= (other);
  64000. }
  64001. MarkerList& MarkerList::operator= (const MarkerList& other)
  64002. {
  64003. if (other != *this)
  64004. {
  64005. markers.clear();
  64006. markers.addCopiesOf (other.markers);
  64007. markersHaveChanged();
  64008. }
  64009. return *this;
  64010. }
  64011. MarkerList::~MarkerList()
  64012. {
  64013. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  64014. }
  64015. bool MarkerList::operator== (const MarkerList& other) const throw()
  64016. {
  64017. if (other.markers.size() != markers.size())
  64018. return false;
  64019. for (int i = markers.size(); --i >= 0;)
  64020. {
  64021. const Marker* const m1 = markers.getUnchecked(i);
  64022. jassert (m1 != 0);
  64023. const Marker* const m2 = other.getMarker (m1->name);
  64024. if (m2 == 0 || *m1 != *m2)
  64025. return false;
  64026. }
  64027. return true;
  64028. }
  64029. bool MarkerList::operator!= (const MarkerList& other) const throw()
  64030. {
  64031. return ! operator== (other);
  64032. }
  64033. int MarkerList::getNumMarkers() const throw()
  64034. {
  64035. return markers.size();
  64036. }
  64037. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  64038. {
  64039. return markers [index];
  64040. }
  64041. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  64042. {
  64043. for (int i = 0; i < markers.size(); ++i)
  64044. {
  64045. const Marker* const m = markers.getUnchecked(i);
  64046. if (m->name == name)
  64047. return m;
  64048. }
  64049. return 0;
  64050. }
  64051. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  64052. {
  64053. Marker* const m = const_cast <Marker*> (getMarker (name));
  64054. if (m != 0)
  64055. {
  64056. if (m->position != position)
  64057. {
  64058. m->position = position;
  64059. markersHaveChanged();
  64060. }
  64061. return;
  64062. }
  64063. markers.add (new Marker (name, position));
  64064. markersHaveChanged();
  64065. }
  64066. void MarkerList::removeMarker (const int index)
  64067. {
  64068. if (isPositiveAndBelow (index, markers.size()))
  64069. {
  64070. markers.remove (index);
  64071. markersHaveChanged();
  64072. }
  64073. }
  64074. void MarkerList::removeMarker (const String& name)
  64075. {
  64076. for (int i = 0; i < markers.size(); ++i)
  64077. {
  64078. const Marker* const m = markers.getUnchecked(i);
  64079. if (m->name == name)
  64080. {
  64081. markers.remove (i);
  64082. markersHaveChanged();
  64083. }
  64084. }
  64085. }
  64086. void MarkerList::markersHaveChanged()
  64087. {
  64088. listeners.call (&MarkerList::Listener::markersChanged, this);
  64089. }
  64090. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  64091. {
  64092. }
  64093. void MarkerList::addListener (Listener* listener)
  64094. {
  64095. listeners.add (listener);
  64096. }
  64097. void MarkerList::removeListener (Listener* listener)
  64098. {
  64099. listeners.remove (listener);
  64100. }
  64101. MarkerList::Marker::Marker (const Marker& other)
  64102. : name (other.name), position (other.position)
  64103. {
  64104. }
  64105. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  64106. : name (name_), position (position_)
  64107. {
  64108. }
  64109. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  64110. {
  64111. return name == other.name && position == other.position;
  64112. }
  64113. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  64114. {
  64115. return ! operator== (other);
  64116. }
  64117. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  64118. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  64119. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  64120. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  64121. : state (state_)
  64122. {
  64123. }
  64124. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  64125. {
  64126. return state.getNumChildren();
  64127. }
  64128. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  64129. {
  64130. return state.getChild (index);
  64131. }
  64132. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  64133. {
  64134. return state.getChildWithProperty (nameProperty, name);
  64135. }
  64136. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  64137. {
  64138. return marker.isAChildOf (state);
  64139. }
  64140. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  64141. {
  64142. jassert (containsMarker (marker));
  64143. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  64144. }
  64145. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  64146. {
  64147. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  64148. if (marker.isValid())
  64149. {
  64150. marker.setProperty (posProperty, m.position.toString(), undoManager);
  64151. }
  64152. else
  64153. {
  64154. marker = ValueTree (markerTag);
  64155. marker.setProperty (nameProperty, m.name, 0);
  64156. marker.setProperty (posProperty, m.position.toString(), 0);
  64157. state.addChild (marker, -1, undoManager);
  64158. }
  64159. }
  64160. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  64161. {
  64162. state.removeChild (marker, undoManager);
  64163. }
  64164. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  64165. {
  64166. if (parentComponent != 0)
  64167. {
  64168. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  64169. return marker.position.resolve (&scope);
  64170. }
  64171. else
  64172. {
  64173. return marker.position.resolve (0);
  64174. }
  64175. }
  64176. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  64177. {
  64178. const int numMarkers = getNumMarkers();
  64179. StringArray updatedMarkers;
  64180. int i;
  64181. for (i = 0; i < numMarkers; ++i)
  64182. {
  64183. const ValueTree marker (state.getChild (i));
  64184. const String name (marker [nameProperty].toString());
  64185. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  64186. updatedMarkers.add (name);
  64187. }
  64188. for (i = markerList.getNumMarkers(); --i >= 0;)
  64189. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  64190. markerList.removeMarker (i);
  64191. }
  64192. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  64193. {
  64194. state.removeAllChildren (undoManager);
  64195. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  64196. setMarker (*markerList.getMarker(i), undoManager);
  64197. }
  64198. END_JUCE_NAMESPACE
  64199. /*** End of inlined file: juce_MarkerList.cpp ***/
  64200. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64201. BEGIN_JUCE_NAMESPACE
  64202. const String RelativeCoordinate::Strings::parent ("parent");
  64203. const String RelativeCoordinate::Strings::left ("left");
  64204. const String RelativeCoordinate::Strings::right ("right");
  64205. const String RelativeCoordinate::Strings::top ("top");
  64206. const String RelativeCoordinate::Strings::bottom ("bottom");
  64207. const String RelativeCoordinate::Strings::x ("x");
  64208. const String RelativeCoordinate::Strings::y ("y");
  64209. const String RelativeCoordinate::Strings::width ("width");
  64210. const String RelativeCoordinate::Strings::height ("height");
  64211. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  64212. {
  64213. if (s == Strings::left) return left;
  64214. if (s == Strings::right) return right;
  64215. if (s == Strings::top) return top;
  64216. if (s == Strings::bottom) return bottom;
  64217. if (s == Strings::x) return x;
  64218. if (s == Strings::y) return y;
  64219. if (s == Strings::width) return width;
  64220. if (s == Strings::height) return height;
  64221. if (s == Strings::parent) return parent;
  64222. return unknown;
  64223. }
  64224. RelativeCoordinate::RelativeCoordinate()
  64225. {
  64226. }
  64227. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64228. : term (term_)
  64229. {
  64230. }
  64231. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64232. : term (other.term)
  64233. {
  64234. }
  64235. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64236. {
  64237. term = other.term;
  64238. return *this;
  64239. }
  64240. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64241. : term (absoluteDistanceFromOrigin)
  64242. {
  64243. }
  64244. RelativeCoordinate::RelativeCoordinate (const String& s)
  64245. {
  64246. try
  64247. {
  64248. term = Expression (s);
  64249. }
  64250. catch (...)
  64251. {}
  64252. }
  64253. RelativeCoordinate::~RelativeCoordinate()
  64254. {
  64255. }
  64256. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64257. {
  64258. return term.toString() == other.term.toString();
  64259. }
  64260. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64261. {
  64262. return ! operator== (other);
  64263. }
  64264. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  64265. {
  64266. try
  64267. {
  64268. if (scope != 0)
  64269. return term.evaluate (*scope);
  64270. else
  64271. return term.evaluate();
  64272. }
  64273. catch (...)
  64274. {}
  64275. return 0.0;
  64276. }
  64277. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  64278. {
  64279. try
  64280. {
  64281. if (scope != 0)
  64282. term.evaluate (*scope);
  64283. else
  64284. term.evaluate();
  64285. }
  64286. catch (...)
  64287. {
  64288. return true;
  64289. }
  64290. return false;
  64291. }
  64292. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  64293. {
  64294. try
  64295. {
  64296. if (scope != 0)
  64297. {
  64298. term = term.adjustedToGiveNewResult (newPos, *scope);
  64299. }
  64300. else
  64301. {
  64302. Expression::Scope defaultScope;
  64303. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  64304. }
  64305. }
  64306. catch (...)
  64307. {}
  64308. }
  64309. bool RelativeCoordinate::isDynamic() const
  64310. {
  64311. return term.usesAnySymbols();
  64312. }
  64313. const String RelativeCoordinate::toString() const
  64314. {
  64315. return term.toString();
  64316. }
  64317. END_JUCE_NAMESPACE
  64318. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64319. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  64320. BEGIN_JUCE_NAMESPACE
  64321. namespace RelativePointHelpers
  64322. {
  64323. inline void skipComma (String::CharPointerType& s)
  64324. {
  64325. s = s.findEndOfWhitespace();
  64326. if (*s == ',')
  64327. ++s;
  64328. }
  64329. }
  64330. RelativePoint::RelativePoint()
  64331. {
  64332. }
  64333. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64334. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64335. {
  64336. }
  64337. RelativePoint::RelativePoint (const float x_, const float y_)
  64338. : x (x_), y (y_)
  64339. {
  64340. }
  64341. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64342. : x (x_), y (y_)
  64343. {
  64344. }
  64345. RelativePoint::RelativePoint (const String& s)
  64346. {
  64347. String::CharPointerType text (s.getCharPointer());
  64348. x = RelativeCoordinate (Expression::parse (text));
  64349. RelativePointHelpers::skipComma (text);
  64350. y = RelativeCoordinate (Expression::parse (text));
  64351. }
  64352. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64353. {
  64354. return x == other.x && y == other.y;
  64355. }
  64356. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64357. {
  64358. return ! operator== (other);
  64359. }
  64360. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  64361. {
  64362. return Point<float> ((float) x.resolve (scope),
  64363. (float) y.resolve (scope));
  64364. }
  64365. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  64366. {
  64367. x.moveToAbsolute (newPos.getX(), scope);
  64368. y.moveToAbsolute (newPos.getY(), scope);
  64369. }
  64370. const String RelativePoint::toString() const
  64371. {
  64372. return x.toString() + ", " + y.toString();
  64373. }
  64374. bool RelativePoint::isDynamic() const
  64375. {
  64376. return x.isDynamic() || y.isDynamic();
  64377. }
  64378. END_JUCE_NAMESPACE
  64379. /*** End of inlined file: juce_RelativePoint.cpp ***/
  64380. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  64381. BEGIN_JUCE_NAMESPACE
  64382. namespace RelativeRectangleHelpers
  64383. {
  64384. inline void skipComma (String::CharPointerType& s)
  64385. {
  64386. s = s.findEndOfWhitespace();
  64387. if (*s == ',')
  64388. ++s;
  64389. }
  64390. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  64391. {
  64392. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  64393. return true;
  64394. if (e.getType() == Expression::symbolType)
  64395. {
  64396. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  64397. {
  64398. case RelativeCoordinate::StandardStrings::x:
  64399. case RelativeCoordinate::StandardStrings::y:
  64400. case RelativeCoordinate::StandardStrings::left:
  64401. case RelativeCoordinate::StandardStrings::right:
  64402. case RelativeCoordinate::StandardStrings::top:
  64403. case RelativeCoordinate::StandardStrings::bottom: return false;
  64404. default: break;
  64405. }
  64406. return true;
  64407. }
  64408. else
  64409. {
  64410. for (int i = e.getNumInputs(); --i >= 0;)
  64411. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  64412. return true;
  64413. }
  64414. return false;
  64415. }
  64416. }
  64417. RelativeRectangle::RelativeRectangle()
  64418. {
  64419. }
  64420. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64421. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64422. : left (left_), right (right_), top (top_), bottom (bottom_)
  64423. {
  64424. }
  64425. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  64426. : left (rect.getX()),
  64427. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64428. top (rect.getY()),
  64429. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64430. {
  64431. }
  64432. RelativeRectangle::RelativeRectangle (const String& s)
  64433. {
  64434. String::CharPointerType text (s.getCharPointer());
  64435. left = RelativeCoordinate (Expression::parse (text));
  64436. RelativeRectangleHelpers::skipComma (text);
  64437. top = RelativeCoordinate (Expression::parse (text));
  64438. RelativeRectangleHelpers::skipComma (text);
  64439. right = RelativeCoordinate (Expression::parse (text));
  64440. RelativeRectangleHelpers::skipComma (text);
  64441. bottom = RelativeCoordinate (Expression::parse (text));
  64442. }
  64443. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64444. {
  64445. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64446. }
  64447. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64448. {
  64449. return ! operator== (other);
  64450. }
  64451. // An expression context that can evaluate expressions using "this"
  64452. class RelativeRectangleLocalScope : public Expression::Scope
  64453. {
  64454. public:
  64455. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  64456. const Expression getSymbolValue (const String& symbol) const
  64457. {
  64458. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64459. {
  64460. case RelativeCoordinate::StandardStrings::x:
  64461. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  64462. case RelativeCoordinate::StandardStrings::y:
  64463. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  64464. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  64465. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  64466. default: break;
  64467. }
  64468. return Expression::Scope::getSymbolValue (symbol);
  64469. }
  64470. private:
  64471. const RelativeRectangle& rect;
  64472. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  64473. };
  64474. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  64475. {
  64476. if (scope == 0)
  64477. {
  64478. RelativeRectangleLocalScope scope (*this);
  64479. return resolve (&scope);
  64480. }
  64481. else
  64482. {
  64483. const double l = left.resolve (scope);
  64484. const double r = right.resolve (scope);
  64485. const double t = top.resolve (scope);
  64486. const double b = bottom.resolve (scope);
  64487. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64488. }
  64489. }
  64490. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  64491. {
  64492. left.moveToAbsolute (newPos.getX(), scope);
  64493. right.moveToAbsolute (newPos.getRight(), scope);
  64494. top.moveToAbsolute (newPos.getY(), scope);
  64495. bottom.moveToAbsolute (newPos.getBottom(), scope);
  64496. }
  64497. bool RelativeRectangle::isDynamic() const
  64498. {
  64499. using namespace RelativeRectangleHelpers;
  64500. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64501. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64502. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64503. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64504. }
  64505. const String RelativeRectangle::toString() const
  64506. {
  64507. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64508. }
  64509. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  64510. {
  64511. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64512. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64513. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64514. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64515. }
  64516. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64517. {
  64518. public:
  64519. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64520. : RelativeCoordinatePositionerBase (component_),
  64521. rectangle (rectangle_)
  64522. {
  64523. }
  64524. bool registerCoordinates()
  64525. {
  64526. bool ok = addCoordinate (rectangle.left);
  64527. ok = addCoordinate (rectangle.right) && ok;
  64528. ok = addCoordinate (rectangle.top) && ok;
  64529. ok = addCoordinate (rectangle.bottom) && ok;
  64530. return ok;
  64531. }
  64532. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64533. {
  64534. return rectangle == other;
  64535. }
  64536. void applyToComponentBounds()
  64537. {
  64538. for (int i = 4; --i >= 0;)
  64539. {
  64540. ComponentScope scope (getComponent());
  64541. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64542. if (newBounds == getComponent().getBounds())
  64543. return;
  64544. getComponent().setBounds (newBounds);
  64545. }
  64546. jassertfalse; // must be a recursive reference!
  64547. }
  64548. void applyNewBounds (const Rectangle<int>& newBounds)
  64549. {
  64550. if (newBounds != getComponent().getBounds())
  64551. {
  64552. ComponentScope scope (getComponent());
  64553. rectangle.moveToAbsolute (newBounds.toFloat(), &scope);
  64554. applyToComponentBounds();
  64555. }
  64556. }
  64557. private:
  64558. RelativeRectangle rectangle;
  64559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64560. };
  64561. void RelativeRectangle::applyToComponent (Component& component) const
  64562. {
  64563. if (isDynamic())
  64564. {
  64565. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64566. if (current == 0 || ! current->isUsingRectangle (*this))
  64567. {
  64568. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64569. component.setPositioner (p);
  64570. p->apply();
  64571. }
  64572. }
  64573. else
  64574. {
  64575. component.setPositioner (0);
  64576. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64577. }
  64578. }
  64579. END_JUCE_NAMESPACE
  64580. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64581. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64582. BEGIN_JUCE_NAMESPACE
  64583. RelativePointPath::RelativePointPath()
  64584. : usesNonZeroWinding (true),
  64585. containsDynamicPoints (false)
  64586. {
  64587. }
  64588. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64589. : usesNonZeroWinding (true),
  64590. containsDynamicPoints (false)
  64591. {
  64592. for (int i = 0; i < other.elements.size(); ++i)
  64593. elements.add (other.elements.getUnchecked(i)->clone());
  64594. }
  64595. RelativePointPath::RelativePointPath (const Path& path)
  64596. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64597. containsDynamicPoints (false)
  64598. {
  64599. for (Path::Iterator i (path); i.next();)
  64600. {
  64601. switch (i.elementType)
  64602. {
  64603. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64604. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64605. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64606. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64607. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64608. default: jassertfalse; break;
  64609. }
  64610. }
  64611. }
  64612. RelativePointPath::~RelativePointPath()
  64613. {
  64614. }
  64615. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64616. {
  64617. if (elements.size() != other.elements.size()
  64618. || usesNonZeroWinding != other.usesNonZeroWinding
  64619. || containsDynamicPoints != other.containsDynamicPoints)
  64620. return false;
  64621. for (int i = 0; i < elements.size(); ++i)
  64622. {
  64623. ElementBase* const e1 = elements.getUnchecked(i);
  64624. ElementBase* const e2 = other.elements.getUnchecked(i);
  64625. if (e1->type != e2->type)
  64626. return false;
  64627. int numPoints1, numPoints2;
  64628. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64629. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64630. jassert (numPoints1 == numPoints2);
  64631. for (int j = numPoints1; --j >= 0;)
  64632. if (points1[j] != points2[j])
  64633. return false;
  64634. }
  64635. return true;
  64636. }
  64637. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64638. {
  64639. return ! operator== (other);
  64640. }
  64641. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64642. {
  64643. elements.swapWithArray (other.elements);
  64644. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64645. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64646. }
  64647. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64648. {
  64649. for (int i = 0; i < elements.size(); ++i)
  64650. elements.getUnchecked(i)->addToPath (path, scope);
  64651. }
  64652. bool RelativePointPath::containsAnyDynamicPoints() const
  64653. {
  64654. return containsDynamicPoints;
  64655. }
  64656. void RelativePointPath::addElement (ElementBase* newElement)
  64657. {
  64658. if (newElement != 0)
  64659. {
  64660. elements.add (newElement);
  64661. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64662. }
  64663. }
  64664. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64665. {
  64666. }
  64667. bool RelativePointPath::ElementBase::isDynamic()
  64668. {
  64669. int numPoints;
  64670. const RelativePoint* const points = getControlPoints (numPoints);
  64671. for (int i = numPoints; --i >= 0;)
  64672. if (points[i].isDynamic())
  64673. return true;
  64674. return false;
  64675. }
  64676. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64677. : ElementBase (startSubPathElement), startPos (pos)
  64678. {
  64679. }
  64680. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64681. {
  64682. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64683. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64684. return v;
  64685. }
  64686. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64687. {
  64688. path.startNewSubPath (startPos.resolve (scope));
  64689. }
  64690. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64691. {
  64692. numPoints = 1;
  64693. return &startPos;
  64694. }
  64695. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64696. {
  64697. return new StartSubPath (startPos);
  64698. }
  64699. RelativePointPath::CloseSubPath::CloseSubPath()
  64700. : ElementBase (closeSubPathElement)
  64701. {
  64702. }
  64703. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64704. {
  64705. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64706. }
  64707. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64708. {
  64709. path.closeSubPath();
  64710. }
  64711. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64712. {
  64713. numPoints = 0;
  64714. return 0;
  64715. }
  64716. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64717. {
  64718. return new CloseSubPath();
  64719. }
  64720. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64721. : ElementBase (lineToElement), endPoint (endPoint_)
  64722. {
  64723. }
  64724. const ValueTree RelativePointPath::LineTo::createTree() const
  64725. {
  64726. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64727. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64728. return v;
  64729. }
  64730. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64731. {
  64732. path.lineTo (endPoint.resolve (scope));
  64733. }
  64734. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64735. {
  64736. numPoints = 1;
  64737. return &endPoint;
  64738. }
  64739. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64740. {
  64741. return new LineTo (endPoint);
  64742. }
  64743. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64744. : ElementBase (quadraticToElement)
  64745. {
  64746. controlPoints[0] = controlPoint;
  64747. controlPoints[1] = endPoint;
  64748. }
  64749. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64750. {
  64751. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64752. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64753. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64754. return v;
  64755. }
  64756. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64757. {
  64758. path.quadraticTo (controlPoints[0].resolve (scope),
  64759. controlPoints[1].resolve (scope));
  64760. }
  64761. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64762. {
  64763. numPoints = 2;
  64764. return controlPoints;
  64765. }
  64766. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64767. {
  64768. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64769. }
  64770. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64771. : ElementBase (cubicToElement)
  64772. {
  64773. controlPoints[0] = controlPoint1;
  64774. controlPoints[1] = controlPoint2;
  64775. controlPoints[2] = endPoint;
  64776. }
  64777. const ValueTree RelativePointPath::CubicTo::createTree() const
  64778. {
  64779. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64780. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64781. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64782. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64783. return v;
  64784. }
  64785. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64786. {
  64787. path.cubicTo (controlPoints[0].resolve (scope),
  64788. controlPoints[1].resolve (scope),
  64789. controlPoints[2].resolve (scope));
  64790. }
  64791. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64792. {
  64793. numPoints = 3;
  64794. return controlPoints;
  64795. }
  64796. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64797. {
  64798. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64799. }
  64800. END_JUCE_NAMESPACE
  64801. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64802. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64803. BEGIN_JUCE_NAMESPACE
  64804. RelativeParallelogram::RelativeParallelogram()
  64805. {
  64806. }
  64807. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64808. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64809. {
  64810. }
  64811. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64812. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64813. {
  64814. }
  64815. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64816. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64817. {
  64818. }
  64819. RelativeParallelogram::~RelativeParallelogram()
  64820. {
  64821. }
  64822. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64823. {
  64824. points[0] = topLeft.resolve (scope);
  64825. points[1] = topRight.resolve (scope);
  64826. points[2] = bottomLeft.resolve (scope);
  64827. }
  64828. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64829. {
  64830. resolveThreePoints (points, scope);
  64831. points[3] = points[1] + (points[2] - points[0]);
  64832. }
  64833. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64834. {
  64835. Point<float> points[4];
  64836. resolveFourCorners (points, scope);
  64837. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64838. }
  64839. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64840. {
  64841. Point<float> points[4];
  64842. resolveFourCorners (points, scope);
  64843. path.startNewSubPath (points[0]);
  64844. path.lineTo (points[1]);
  64845. path.lineTo (points[3]);
  64846. path.lineTo (points[2]);
  64847. path.closeSubPath();
  64848. }
  64849. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64850. {
  64851. Point<float> corners[3];
  64852. resolveThreePoints (corners, scope);
  64853. const Line<float> top (corners[0], corners[1]);
  64854. const Line<float> left (corners[0], corners[2]);
  64855. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64856. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64857. topRight.moveToAbsolute (newTopRight, scope);
  64858. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64859. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64860. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64861. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64862. }
  64863. bool RelativeParallelogram::isDynamic() const
  64864. {
  64865. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64866. }
  64867. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64868. {
  64869. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64870. }
  64871. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64872. {
  64873. return ! operator== (other);
  64874. }
  64875. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64876. {
  64877. const Point<float> tr (corners[1] - corners[0]);
  64878. const Point<float> bl (corners[2] - corners[0]);
  64879. target -= corners[0];
  64880. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64881. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64882. }
  64883. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64884. {
  64885. return corners[0]
  64886. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64887. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64888. }
  64889. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64890. {
  64891. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64892. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64893. }
  64894. END_JUCE_NAMESPACE
  64895. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64896. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64897. BEGIN_JUCE_NAMESPACE
  64898. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64899. : component (component_)
  64900. {
  64901. }
  64902. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64903. {
  64904. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64905. {
  64906. case RelativeCoordinate::StandardStrings::x:
  64907. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64908. case RelativeCoordinate::StandardStrings::y:
  64909. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64910. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64911. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64912. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64913. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64914. default: break;
  64915. }
  64916. MarkerList* list;
  64917. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64918. if (marker != 0)
  64919. return marker->position.getExpression();
  64920. return Expression::Scope::getSymbolValue (symbol);
  64921. }
  64922. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64923. {
  64924. Component* targetComp = 0;
  64925. if (scopeName == RelativeCoordinate::Strings::parent)
  64926. targetComp = component.getParentComponent();
  64927. else
  64928. targetComp = findSiblingComponent (scopeName);
  64929. if (targetComp != 0)
  64930. visitor.visit (ComponentScope (*targetComp));
  64931. else
  64932. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64933. }
  64934. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64935. {
  64936. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64937. }
  64938. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64939. {
  64940. Component* const parent = component.getParentComponent();
  64941. if (parent != 0)
  64942. {
  64943. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64944. {
  64945. Component* const c = parent->getChildComponent(i);
  64946. if (c->getComponentID() == componentID)
  64947. return c;
  64948. }
  64949. }
  64950. return 0;
  64951. }
  64952. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64953. {
  64954. const MarkerList::Marker* marker = 0;
  64955. Component* const parent = component.getParentComponent();
  64956. if (parent != 0)
  64957. {
  64958. list = parent->getMarkers (true);
  64959. if (list != 0)
  64960. marker = list->getMarker (name);
  64961. if (marker == 0)
  64962. {
  64963. list = parent->getMarkers (false);
  64964. if (list != 0)
  64965. marker = list->getMarker (name);
  64966. }
  64967. }
  64968. return marker;
  64969. }
  64970. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64971. {
  64972. public:
  64973. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64974. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64975. {
  64976. }
  64977. const Expression getSymbolValue (const String& symbol) const
  64978. {
  64979. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  64980. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  64981. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  64982. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  64983. {
  64984. positioner.registerComponentListener (component);
  64985. }
  64986. else
  64987. {
  64988. MarkerList* list;
  64989. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64990. if (marker != 0)
  64991. {
  64992. positioner.registerMarkerListListener (list);
  64993. }
  64994. else
  64995. {
  64996. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64997. positioner.registerMarkerListListener (component.getMarkers (true));
  64998. positioner.registerMarkerListListener (component.getMarkers (false));
  64999. ok = false;
  65000. }
  65001. }
  65002. return ComponentScope::getSymbolValue (symbol);
  65003. }
  65004. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  65005. {
  65006. Component* targetComp = 0;
  65007. if (scopeName == RelativeCoordinate::Strings::parent)
  65008. targetComp = component.getParentComponent();
  65009. else
  65010. targetComp = findSiblingComponent (scopeName);
  65011. if (targetComp != 0)
  65012. {
  65013. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  65014. }
  65015. else
  65016. {
  65017. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  65018. Component* const parent = component.getParentComponent();
  65019. if (parent != 0)
  65020. positioner.registerComponentListener (*parent);
  65021. positioner.registerComponentListener (component);
  65022. ok = false;
  65023. }
  65024. }
  65025. private:
  65026. RelativeCoordinatePositionerBase& positioner;
  65027. bool& ok;
  65028. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  65029. };
  65030. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  65031. : Component::Positioner (component_), registeredOk (false)
  65032. {
  65033. }
  65034. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  65035. {
  65036. unregisterListeners();
  65037. }
  65038. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  65039. {
  65040. apply();
  65041. }
  65042. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  65043. {
  65044. apply();
  65045. }
  65046. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  65047. {
  65048. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  65049. apply();
  65050. }
  65051. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  65052. {
  65053. jassert (sourceComponents.contains (&component));
  65054. sourceComponents.removeValue (&component);
  65055. registeredOk = false;
  65056. }
  65057. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  65058. {
  65059. apply();
  65060. }
  65061. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  65062. {
  65063. jassert (sourceMarkerLists.contains (markerList));
  65064. sourceMarkerLists.removeValue (markerList);
  65065. }
  65066. void RelativeCoordinatePositionerBase::apply()
  65067. {
  65068. if (! registeredOk)
  65069. {
  65070. unregisterListeners();
  65071. registeredOk = registerCoordinates();
  65072. }
  65073. applyToComponentBounds();
  65074. }
  65075. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  65076. {
  65077. bool ok = true;
  65078. DependencyFinderScope finderScope (getComponent(), *this, ok);
  65079. coord.getExpression().evaluate (finderScope);
  65080. return ok;
  65081. }
  65082. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  65083. {
  65084. const bool ok = addCoordinate (point.x);
  65085. return addCoordinate (point.y) && ok;
  65086. }
  65087. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  65088. {
  65089. if (! sourceComponents.contains (&comp))
  65090. {
  65091. comp.addComponentListener (this);
  65092. sourceComponents.add (&comp);
  65093. }
  65094. }
  65095. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  65096. {
  65097. if (list != 0 && ! sourceMarkerLists.contains (list))
  65098. {
  65099. list->addListener (this);
  65100. sourceMarkerLists.add (list);
  65101. }
  65102. }
  65103. void RelativeCoordinatePositionerBase::unregisterListeners()
  65104. {
  65105. int i;
  65106. for (i = sourceComponents.size(); --i >= 0;)
  65107. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  65108. for (i = sourceMarkerLists.size(); --i >= 0;)
  65109. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  65110. sourceComponents.clear();
  65111. sourceMarkerLists.clear();
  65112. }
  65113. END_JUCE_NAMESPACE
  65114. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  65115. #endif
  65116. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  65117. /*** Start of inlined file: juce_Colour.cpp ***/
  65118. BEGIN_JUCE_NAMESPACE
  65119. namespace ColourHelpers
  65120. {
  65121. uint8 floatAlphaToInt (const float alpha) throw()
  65122. {
  65123. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  65124. }
  65125. void convertHSBtoRGB (float h, float s, float v,
  65126. uint8& r, uint8& g, uint8& b) throw()
  65127. {
  65128. v = jlimit (0.0f, 1.0f, v);
  65129. v *= 255.0f;
  65130. const uint8 intV = (uint8) roundToInt (v);
  65131. if (s <= 0)
  65132. {
  65133. r = intV;
  65134. g = intV;
  65135. b = intV;
  65136. }
  65137. else
  65138. {
  65139. s = jmin (1.0f, s);
  65140. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  65141. const float f = h - std::floor (h);
  65142. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  65143. if (h < 1.0f)
  65144. {
  65145. r = intV;
  65146. g = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65147. b = x;
  65148. }
  65149. else if (h < 2.0f)
  65150. {
  65151. r = (uint8) roundToInt (v * (1.0f - s * f));
  65152. g = intV;
  65153. b = x;
  65154. }
  65155. else if (h < 3.0f)
  65156. {
  65157. r = x;
  65158. g = intV;
  65159. b = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65160. }
  65161. else if (h < 4.0f)
  65162. {
  65163. r = x;
  65164. g = (uint8) roundToInt (v * (1.0f - s * f));
  65165. b = intV;
  65166. }
  65167. else if (h < 5.0f)
  65168. {
  65169. r = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65170. g = x;
  65171. b = intV;
  65172. }
  65173. else
  65174. {
  65175. r = intV;
  65176. g = x;
  65177. b = (uint8) roundToInt (v * (1.0f - s * f));
  65178. }
  65179. }
  65180. }
  65181. }
  65182. Colour::Colour() throw()
  65183. : argb (0)
  65184. {
  65185. }
  65186. Colour::Colour (const Colour& other) throw()
  65187. : argb (other.argb)
  65188. {
  65189. }
  65190. Colour& Colour::operator= (const Colour& other) throw()
  65191. {
  65192. argb = other.argb;
  65193. return *this;
  65194. }
  65195. bool Colour::operator== (const Colour& other) const throw()
  65196. {
  65197. return argb.getARGB() == other.argb.getARGB();
  65198. }
  65199. bool Colour::operator!= (const Colour& other) const throw()
  65200. {
  65201. return argb.getARGB() != other.argb.getARGB();
  65202. }
  65203. Colour::Colour (const uint32 argb_) throw()
  65204. : argb (argb_)
  65205. {
  65206. }
  65207. Colour::Colour (const uint8 red,
  65208. const uint8 green,
  65209. const uint8 blue) throw()
  65210. {
  65211. argb.setARGB (0xff, red, green, blue);
  65212. }
  65213. const Colour Colour::fromRGB (const uint8 red,
  65214. const uint8 green,
  65215. const uint8 blue) throw()
  65216. {
  65217. return Colour (red, green, blue);
  65218. }
  65219. Colour::Colour (const uint8 red,
  65220. const uint8 green,
  65221. const uint8 blue,
  65222. const uint8 alpha) throw()
  65223. {
  65224. argb.setARGB (alpha, red, green, blue);
  65225. }
  65226. const Colour Colour::fromRGBA (const uint8 red,
  65227. const uint8 green,
  65228. const uint8 blue,
  65229. const uint8 alpha) throw()
  65230. {
  65231. return Colour (red, green, blue, alpha);
  65232. }
  65233. Colour::Colour (const uint8 red,
  65234. const uint8 green,
  65235. const uint8 blue,
  65236. const float alpha) throw()
  65237. {
  65238. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65239. }
  65240. const Colour Colour::fromRGBAFloat (const uint8 red,
  65241. const uint8 green,
  65242. const uint8 blue,
  65243. const float alpha) throw()
  65244. {
  65245. return Colour (red, green, blue, alpha);
  65246. }
  65247. Colour::Colour (const float hue,
  65248. const float saturation,
  65249. const float brightness,
  65250. const float alpha) throw()
  65251. {
  65252. uint8 r, g, b;
  65253. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65254. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65255. }
  65256. const Colour Colour::fromHSV (const float hue,
  65257. const float saturation,
  65258. const float brightness,
  65259. const float alpha) throw()
  65260. {
  65261. return Colour (hue, saturation, brightness, alpha);
  65262. }
  65263. Colour::Colour (const float hue,
  65264. const float saturation,
  65265. const float brightness,
  65266. const uint8 alpha) throw()
  65267. {
  65268. uint8 r, g, b;
  65269. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65270. argb.setARGB (alpha, r, g, b);
  65271. }
  65272. Colour::~Colour() throw()
  65273. {
  65274. }
  65275. const PixelARGB Colour::getPixelARGB() const throw()
  65276. {
  65277. PixelARGB p (argb);
  65278. p.premultiply();
  65279. return p;
  65280. }
  65281. uint32 Colour::getARGB() const throw()
  65282. {
  65283. return argb.getARGB();
  65284. }
  65285. bool Colour::isTransparent() const throw()
  65286. {
  65287. return getAlpha() == 0;
  65288. }
  65289. bool Colour::isOpaque() const throw()
  65290. {
  65291. return getAlpha() == 0xff;
  65292. }
  65293. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65294. {
  65295. PixelARGB newCol (argb);
  65296. newCol.setAlpha (newAlpha);
  65297. return Colour (newCol.getARGB());
  65298. }
  65299. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65300. {
  65301. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65302. PixelARGB newCol (argb);
  65303. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65304. return Colour (newCol.getARGB());
  65305. }
  65306. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65307. {
  65308. jassert (alphaMultiplier >= 0);
  65309. PixelARGB newCol (argb);
  65310. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65311. return Colour (newCol.getARGB());
  65312. }
  65313. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65314. {
  65315. const int destAlpha = getAlpha();
  65316. if (destAlpha > 0)
  65317. {
  65318. const int invA = 0xff - (int) src.getAlpha();
  65319. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65320. if (resA > 0)
  65321. {
  65322. const int da = (invA * destAlpha) / resA;
  65323. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65324. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65325. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65326. (uint8) resA);
  65327. }
  65328. return *this;
  65329. }
  65330. else
  65331. {
  65332. return src;
  65333. }
  65334. }
  65335. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65336. {
  65337. if (proportionOfOther <= 0)
  65338. return *this;
  65339. if (proportionOfOther >= 1.0f)
  65340. return other;
  65341. PixelARGB c1 (getPixelARGB());
  65342. const PixelARGB c2 (other.getPixelARGB());
  65343. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65344. c1.unpremultiply();
  65345. return Colour (c1.getARGB());
  65346. }
  65347. float Colour::getFloatRed() const throw()
  65348. {
  65349. return getRed() / 255.0f;
  65350. }
  65351. float Colour::getFloatGreen() const throw()
  65352. {
  65353. return getGreen() / 255.0f;
  65354. }
  65355. float Colour::getFloatBlue() const throw()
  65356. {
  65357. return getBlue() / 255.0f;
  65358. }
  65359. float Colour::getFloatAlpha() const throw()
  65360. {
  65361. return getAlpha() / 255.0f;
  65362. }
  65363. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65364. {
  65365. const int r = getRed();
  65366. const int g = getGreen();
  65367. const int b = getBlue();
  65368. const int hi = jmax (r, g, b);
  65369. const int lo = jmin (r, g, b);
  65370. if (hi != 0)
  65371. {
  65372. s = (hi - lo) / (float) hi;
  65373. if (s > 0)
  65374. {
  65375. const float invDiff = 1.0f / (hi - lo);
  65376. const float red = (hi - r) * invDiff;
  65377. const float green = (hi - g) * invDiff;
  65378. const float blue = (hi - b) * invDiff;
  65379. if (r == hi)
  65380. h = blue - green;
  65381. else if (g == hi)
  65382. h = 2.0f + red - blue;
  65383. else
  65384. h = 4.0f + green - red;
  65385. h *= 1.0f / 6.0f;
  65386. if (h < 0)
  65387. ++h;
  65388. }
  65389. else
  65390. {
  65391. h = 0;
  65392. }
  65393. }
  65394. else
  65395. {
  65396. s = 0;
  65397. h = 0;
  65398. }
  65399. v = hi / 255.0f;
  65400. }
  65401. float Colour::getHue() const throw()
  65402. {
  65403. float h, s, b;
  65404. getHSB (h, s, b);
  65405. return h;
  65406. }
  65407. const Colour Colour::withHue (const float hue) const throw()
  65408. {
  65409. float h, s, b;
  65410. getHSB (h, s, b);
  65411. return Colour (hue, s, b, getAlpha());
  65412. }
  65413. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65414. {
  65415. float h, s, b;
  65416. getHSB (h, s, b);
  65417. return Colour (h + amountToRotate, s, b, getAlpha());
  65418. }
  65419. float Colour::getSaturation() const throw()
  65420. {
  65421. float h, s, b;
  65422. getHSB (h, s, b);
  65423. return s;
  65424. }
  65425. const Colour Colour::withSaturation (const float saturation) const throw()
  65426. {
  65427. float h, s, b;
  65428. getHSB (h, s, b);
  65429. return Colour (h, saturation, b, getAlpha());
  65430. }
  65431. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65432. {
  65433. float h, s, b;
  65434. getHSB (h, s, b);
  65435. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65436. }
  65437. float Colour::getBrightness() const throw()
  65438. {
  65439. float h, s, b;
  65440. getHSB (h, s, b);
  65441. return b;
  65442. }
  65443. const Colour Colour::withBrightness (const float brightness) const throw()
  65444. {
  65445. float h, s, b;
  65446. getHSB (h, s, b);
  65447. return Colour (h, s, brightness, getAlpha());
  65448. }
  65449. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65450. {
  65451. float h, s, b;
  65452. getHSB (h, s, b);
  65453. b *= amount;
  65454. if (b > 1.0f)
  65455. b = 1.0f;
  65456. return Colour (h, s, b, getAlpha());
  65457. }
  65458. const Colour Colour::brighter (float amount) const throw()
  65459. {
  65460. amount = 1.0f / (1.0f + amount);
  65461. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65462. (uint8) (255 - (amount * (255 - getGreen()))),
  65463. (uint8) (255 - (amount * (255 - getBlue()))),
  65464. getAlpha());
  65465. }
  65466. const Colour Colour::darker (float amount) const throw()
  65467. {
  65468. amount = 1.0f / (1.0f + amount);
  65469. return Colour ((uint8) (amount * getRed()),
  65470. (uint8) (amount * getGreen()),
  65471. (uint8) (amount * getBlue()),
  65472. getAlpha());
  65473. }
  65474. const Colour Colour::greyLevel (const float brightness) throw()
  65475. {
  65476. const uint8 level
  65477. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65478. return Colour (level, level, level);
  65479. }
  65480. const Colour Colour::contrasting (const float amount) const throw()
  65481. {
  65482. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65483. ? Colours::black
  65484. : Colours::white).withAlpha (amount));
  65485. }
  65486. const Colour Colour::contrasting (const Colour& colour1,
  65487. const Colour& colour2) throw()
  65488. {
  65489. const float b1 = colour1.getBrightness();
  65490. const float b2 = colour2.getBrightness();
  65491. float best = 0.0f;
  65492. float bestDist = 0.0f;
  65493. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65494. {
  65495. const float d1 = std::abs (i - b1);
  65496. const float d2 = std::abs (i - b2);
  65497. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65498. if (dist > bestDist)
  65499. {
  65500. best = i;
  65501. bestDist = dist;
  65502. }
  65503. }
  65504. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65505. .withBrightness (best);
  65506. }
  65507. const String Colour::toString() const
  65508. {
  65509. return String::toHexString ((int) argb.getARGB());
  65510. }
  65511. const Colour Colour::fromString (const String& encodedColourString)
  65512. {
  65513. return Colour ((uint32) encodedColourString.getHexValue32());
  65514. }
  65515. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65516. {
  65517. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65518. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65519. .toUpperCase();
  65520. }
  65521. END_JUCE_NAMESPACE
  65522. /*** End of inlined file: juce_Colour.cpp ***/
  65523. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65524. BEGIN_JUCE_NAMESPACE
  65525. ColourGradient::ColourGradient() throw()
  65526. {
  65527. #if JUCE_DEBUG
  65528. point1.setX (987654.0f);
  65529. #endif
  65530. }
  65531. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65532. const Colour& colour2, const float x2_, const float y2_,
  65533. const bool isRadial_)
  65534. : point1 (x1_, y1_),
  65535. point2 (x2_, y2_),
  65536. isRadial (isRadial_)
  65537. {
  65538. colours.add (ColourPoint (0.0, colour1));
  65539. colours.add (ColourPoint (1.0, colour2));
  65540. }
  65541. ColourGradient::~ColourGradient()
  65542. {
  65543. }
  65544. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65545. {
  65546. return point1 == other.point1 && point2 == other.point2
  65547. && isRadial == other.isRadial
  65548. && colours == other.colours;
  65549. }
  65550. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65551. {
  65552. return ! operator== (other);
  65553. }
  65554. void ColourGradient::clearColours()
  65555. {
  65556. colours.clear();
  65557. }
  65558. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65559. {
  65560. // must be within the two end-points
  65561. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65562. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65563. int i;
  65564. for (i = 0; i < colours.size(); ++i)
  65565. if (colours.getReference(i).position > pos)
  65566. break;
  65567. colours.insert (i, ColourPoint (pos, colour));
  65568. return i;
  65569. }
  65570. void ColourGradient::removeColour (int index)
  65571. {
  65572. jassert (index > 0 && index < colours.size() - 1);
  65573. colours.remove (index);
  65574. }
  65575. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65576. {
  65577. for (int i = 0; i < colours.size(); ++i)
  65578. {
  65579. Colour& c = colours.getReference(i).colour;
  65580. c = c.withMultipliedAlpha (multiplier);
  65581. }
  65582. }
  65583. int ColourGradient::getNumColours() const throw()
  65584. {
  65585. return colours.size();
  65586. }
  65587. double ColourGradient::getColourPosition (const int index) const throw()
  65588. {
  65589. if (isPositiveAndBelow (index, colours.size()))
  65590. return colours.getReference (index).position;
  65591. return 0;
  65592. }
  65593. const Colour ColourGradient::getColour (const int index) const throw()
  65594. {
  65595. if (isPositiveAndBelow (index, colours.size()))
  65596. return colours.getReference (index).colour;
  65597. return Colour();
  65598. }
  65599. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65600. {
  65601. if (isPositiveAndBelow (index, colours.size()))
  65602. colours.getReference (index).colour = newColour;
  65603. }
  65604. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65605. {
  65606. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65607. if (position <= 0 || colours.size() <= 1)
  65608. return colours.getReference(0).colour;
  65609. int i = colours.size() - 1;
  65610. while (position < colours.getReference(i).position)
  65611. --i;
  65612. const ColourPoint& p1 = colours.getReference (i);
  65613. if (i >= colours.size() - 1)
  65614. return p1.colour;
  65615. const ColourPoint& p2 = colours.getReference (i + 1);
  65616. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65617. }
  65618. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65619. {
  65620. #if JUCE_DEBUG
  65621. // trying to use the object without setting its co-ordinates? Have a careful read of
  65622. // the comments for the constructors.
  65623. jassert (point1.getX() != 987654.0f);
  65624. #endif
  65625. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65626. 3 * (int) point1.transformedBy (transform)
  65627. .getDistanceFrom (point2.transformedBy (transform)));
  65628. lookupTable.malloc (numEntries);
  65629. if (colours.size() >= 2)
  65630. {
  65631. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65632. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65633. int index = 0;
  65634. for (int j = 1; j < colours.size(); ++j)
  65635. {
  65636. const ColourPoint& p = colours.getReference (j);
  65637. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65638. const PixelARGB pix2 (p.colour.getPixelARGB());
  65639. for (int i = 0; i < numToDo; ++i)
  65640. {
  65641. jassert (index >= 0 && index < numEntries);
  65642. lookupTable[index] = pix1;
  65643. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65644. ++index;
  65645. }
  65646. pix1 = pix2;
  65647. }
  65648. while (index < numEntries)
  65649. lookupTable [index++] = pix1;
  65650. }
  65651. else
  65652. {
  65653. jassertfalse; // no colours specified!
  65654. }
  65655. return numEntries;
  65656. }
  65657. bool ColourGradient::isOpaque() const throw()
  65658. {
  65659. for (int i = 0; i < colours.size(); ++i)
  65660. if (! colours.getReference(i).colour.isOpaque())
  65661. return false;
  65662. return true;
  65663. }
  65664. bool ColourGradient::isInvisible() const throw()
  65665. {
  65666. for (int i = 0; i < colours.size(); ++i)
  65667. if (! colours.getReference(i).colour.isTransparent())
  65668. return false;
  65669. return true;
  65670. }
  65671. bool ColourGradient::ColourPoint::operator== (const ColourPoint& other) const throw()
  65672. {
  65673. return position == other.position && colour == other.colour;
  65674. }
  65675. bool ColourGradient::ColourPoint::operator!= (const ColourPoint& other) const throw()
  65676. {
  65677. return position != other.position || colour != other.colour;
  65678. }
  65679. END_JUCE_NAMESPACE
  65680. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65681. /*** Start of inlined file: juce_Colours.cpp ***/
  65682. BEGIN_JUCE_NAMESPACE
  65683. const Colour Colours::transparentBlack (0);
  65684. const Colour Colours::transparentWhite (0x00ffffff);
  65685. const Colour Colours::aliceblue (0xfff0f8ff);
  65686. const Colour Colours::antiquewhite (0xfffaebd7);
  65687. const Colour Colours::aqua (0xff00ffff);
  65688. const Colour Colours::aquamarine (0xff7fffd4);
  65689. const Colour Colours::azure (0xfff0ffff);
  65690. const Colour Colours::beige (0xfff5f5dc);
  65691. const Colour Colours::bisque (0xffffe4c4);
  65692. const Colour Colours::black (0xff000000);
  65693. const Colour Colours::blanchedalmond (0xffffebcd);
  65694. const Colour Colours::blue (0xff0000ff);
  65695. const Colour Colours::blueviolet (0xff8a2be2);
  65696. const Colour Colours::brown (0xffa52a2a);
  65697. const Colour Colours::burlywood (0xffdeb887);
  65698. const Colour Colours::cadetblue (0xff5f9ea0);
  65699. const Colour Colours::chartreuse (0xff7fff00);
  65700. const Colour Colours::chocolate (0xffd2691e);
  65701. const Colour Colours::coral (0xffff7f50);
  65702. const Colour Colours::cornflowerblue (0xff6495ed);
  65703. const Colour Colours::cornsilk (0xfffff8dc);
  65704. const Colour Colours::crimson (0xffdc143c);
  65705. const Colour Colours::cyan (0xff00ffff);
  65706. const Colour Colours::darkblue (0xff00008b);
  65707. const Colour Colours::darkcyan (0xff008b8b);
  65708. const Colour Colours::darkgoldenrod (0xffb8860b);
  65709. const Colour Colours::darkgrey (0xff555555);
  65710. const Colour Colours::darkgreen (0xff006400);
  65711. const Colour Colours::darkkhaki (0xffbdb76b);
  65712. const Colour Colours::darkmagenta (0xff8b008b);
  65713. const Colour Colours::darkolivegreen (0xff556b2f);
  65714. const Colour Colours::darkorange (0xffff8c00);
  65715. const Colour Colours::darkorchid (0xff9932cc);
  65716. const Colour Colours::darkred (0xff8b0000);
  65717. const Colour Colours::darksalmon (0xffe9967a);
  65718. const Colour Colours::darkseagreen (0xff8fbc8f);
  65719. const Colour Colours::darkslateblue (0xff483d8b);
  65720. const Colour Colours::darkslategrey (0xff2f4f4f);
  65721. const Colour Colours::darkturquoise (0xff00ced1);
  65722. const Colour Colours::darkviolet (0xff9400d3);
  65723. const Colour Colours::deeppink (0xffff1493);
  65724. const Colour Colours::deepskyblue (0xff00bfff);
  65725. const Colour Colours::dimgrey (0xff696969);
  65726. const Colour Colours::dodgerblue (0xff1e90ff);
  65727. const Colour Colours::firebrick (0xffb22222);
  65728. const Colour Colours::floralwhite (0xfffffaf0);
  65729. const Colour Colours::forestgreen (0xff228b22);
  65730. const Colour Colours::fuchsia (0xffff00ff);
  65731. const Colour Colours::gainsboro (0xffdcdcdc);
  65732. const Colour Colours::gold (0xffffd700);
  65733. const Colour Colours::goldenrod (0xffdaa520);
  65734. const Colour Colours::grey (0xff808080);
  65735. const Colour Colours::green (0xff008000);
  65736. const Colour Colours::greenyellow (0xffadff2f);
  65737. const Colour Colours::honeydew (0xfff0fff0);
  65738. const Colour Colours::hotpink (0xffff69b4);
  65739. const Colour Colours::indianred (0xffcd5c5c);
  65740. const Colour Colours::indigo (0xff4b0082);
  65741. const Colour Colours::ivory (0xfffffff0);
  65742. const Colour Colours::khaki (0xfff0e68c);
  65743. const Colour Colours::lavender (0xffe6e6fa);
  65744. const Colour Colours::lavenderblush (0xfffff0f5);
  65745. const Colour Colours::lemonchiffon (0xfffffacd);
  65746. const Colour Colours::lightblue (0xffadd8e6);
  65747. const Colour Colours::lightcoral (0xfff08080);
  65748. const Colour Colours::lightcyan (0xffe0ffff);
  65749. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65750. const Colour Colours::lightgreen (0xff90ee90);
  65751. const Colour Colours::lightgrey (0xffd3d3d3);
  65752. const Colour Colours::lightpink (0xffffb6c1);
  65753. const Colour Colours::lightsalmon (0xffffa07a);
  65754. const Colour Colours::lightseagreen (0xff20b2aa);
  65755. const Colour Colours::lightskyblue (0xff87cefa);
  65756. const Colour Colours::lightslategrey (0xff778899);
  65757. const Colour Colours::lightsteelblue (0xffb0c4de);
  65758. const Colour Colours::lightyellow (0xffffffe0);
  65759. const Colour Colours::lime (0xff00ff00);
  65760. const Colour Colours::limegreen (0xff32cd32);
  65761. const Colour Colours::linen (0xfffaf0e6);
  65762. const Colour Colours::magenta (0xffff00ff);
  65763. const Colour Colours::maroon (0xff800000);
  65764. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65765. const Colour Colours::mediumblue (0xff0000cd);
  65766. const Colour Colours::mediumorchid (0xffba55d3);
  65767. const Colour Colours::mediumpurple (0xff9370db);
  65768. const Colour Colours::mediumseagreen (0xff3cb371);
  65769. const Colour Colours::mediumslateblue (0xff7b68ee);
  65770. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65771. const Colour Colours::mediumturquoise (0xff48d1cc);
  65772. const Colour Colours::mediumvioletred (0xffc71585);
  65773. const Colour Colours::midnightblue (0xff191970);
  65774. const Colour Colours::mintcream (0xfff5fffa);
  65775. const Colour Colours::mistyrose (0xffffe4e1);
  65776. const Colour Colours::navajowhite (0xffffdead);
  65777. const Colour Colours::navy (0xff000080);
  65778. const Colour Colours::oldlace (0xfffdf5e6);
  65779. const Colour Colours::olive (0xff808000);
  65780. const Colour Colours::olivedrab (0xff6b8e23);
  65781. const Colour Colours::orange (0xffffa500);
  65782. const Colour Colours::orangered (0xffff4500);
  65783. const Colour Colours::orchid (0xffda70d6);
  65784. const Colour Colours::palegoldenrod (0xffeee8aa);
  65785. const Colour Colours::palegreen (0xff98fb98);
  65786. const Colour Colours::paleturquoise (0xffafeeee);
  65787. const Colour Colours::palevioletred (0xffdb7093);
  65788. const Colour Colours::papayawhip (0xffffefd5);
  65789. const Colour Colours::peachpuff (0xffffdab9);
  65790. const Colour Colours::peru (0xffcd853f);
  65791. const Colour Colours::pink (0xffffc0cb);
  65792. const Colour Colours::plum (0xffdda0dd);
  65793. const Colour Colours::powderblue (0xffb0e0e6);
  65794. const Colour Colours::purple (0xff800080);
  65795. const Colour Colours::red (0xffff0000);
  65796. const Colour Colours::rosybrown (0xffbc8f8f);
  65797. const Colour Colours::royalblue (0xff4169e1);
  65798. const Colour Colours::saddlebrown (0xff8b4513);
  65799. const Colour Colours::salmon (0xfffa8072);
  65800. const Colour Colours::sandybrown (0xfff4a460);
  65801. const Colour Colours::seagreen (0xff2e8b57);
  65802. const Colour Colours::seashell (0xfffff5ee);
  65803. const Colour Colours::sienna (0xffa0522d);
  65804. const Colour Colours::silver (0xffc0c0c0);
  65805. const Colour Colours::skyblue (0xff87ceeb);
  65806. const Colour Colours::slateblue (0xff6a5acd);
  65807. const Colour Colours::slategrey (0xff708090);
  65808. const Colour Colours::snow (0xfffffafa);
  65809. const Colour Colours::springgreen (0xff00ff7f);
  65810. const Colour Colours::steelblue (0xff4682b4);
  65811. const Colour Colours::tan (0xffd2b48c);
  65812. const Colour Colours::teal (0xff008080);
  65813. const Colour Colours::thistle (0xffd8bfd8);
  65814. const Colour Colours::tomato (0xffff6347);
  65815. const Colour Colours::turquoise (0xff40e0d0);
  65816. const Colour Colours::violet (0xffee82ee);
  65817. const Colour Colours::wheat (0xfff5deb3);
  65818. const Colour Colours::white (0xffffffff);
  65819. const Colour Colours::whitesmoke (0xfff5f5f5);
  65820. const Colour Colours::yellow (0xffffff00);
  65821. const Colour Colours::yellowgreen (0xff9acd32);
  65822. const Colour Colours::findColourForName (const String& colourName,
  65823. const Colour& defaultColour)
  65824. {
  65825. static const int presets[] =
  65826. {
  65827. // (first value is the string's hashcode, second is ARGB)
  65828. 0x05978fff, 0xff000000, /* black */
  65829. 0x06bdcc29, 0xffffffff, /* white */
  65830. 0x002e305a, 0xff0000ff, /* blue */
  65831. 0x00308adf, 0xff808080, /* grey */
  65832. 0x05e0cf03, 0xff008000, /* green */
  65833. 0x0001b891, 0xffff0000, /* red */
  65834. 0xd43c6474, 0xffffff00, /* yellow */
  65835. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65836. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65837. 0x002dcebc, 0xff00ffff, /* aqua */
  65838. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65839. 0x0590228f, 0xfff0ffff, /* azure */
  65840. 0x05947fe4, 0xfff5f5dc, /* beige */
  65841. 0xad388e35, 0xffffe4c4, /* bisque */
  65842. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65843. 0x39129959, 0xff8a2be2, /* blueviolet */
  65844. 0x059a8136, 0xffa52a2a, /* brown */
  65845. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65846. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65847. 0x6b748956, 0xff7fff00, /* chartreuse */
  65848. 0x2903623c, 0xffd2691e, /* chocolate */
  65849. 0x05a74431, 0xffff7f50, /* coral */
  65850. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65851. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65852. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65853. 0x002ed323, 0xff00ffff, /* cyan */
  65854. 0x67cc74d0, 0xff00008b, /* darkblue */
  65855. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65856. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65857. 0x67cecf55, 0xff555555, /* darkgrey */
  65858. 0x920b194d, 0xff006400, /* darkgreen */
  65859. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65860. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65861. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65862. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65863. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65864. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65865. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65866. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65867. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65868. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65869. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65870. 0xc8769375, 0xff9400d3, /* darkviolet */
  65871. 0x25832862, 0xffff1493, /* deeppink */
  65872. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65873. 0x634c8b67, 0xff696969, /* dimgrey */
  65874. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65875. 0xef19e3cb, 0xffb22222, /* firebrick */
  65876. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65877. 0xd086fd06, 0xff228b22, /* forestgreen */
  65878. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65879. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65880. 0x00308060, 0xffffd700, /* gold */
  65881. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65882. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65883. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65884. 0x41892743, 0xffff69b4, /* hotpink */
  65885. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65886. 0xb969fed2, 0xff4b0082, /* indigo */
  65887. 0x05fef6a9, 0xfffffff0, /* ivory */
  65888. 0x06149302, 0xfff0e68c, /* khaki */
  65889. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65890. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65891. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65892. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65893. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65894. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65895. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65896. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65897. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65898. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65899. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65900. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65901. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65902. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65903. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65904. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65905. 0x0032afd5, 0xff00ff00, /* lime */
  65906. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65907. 0x06234efa, 0xfffaf0e6, /* linen */
  65908. 0x316858a9, 0xffff00ff, /* magenta */
  65909. 0xbf8ca470, 0xff800000, /* maroon */
  65910. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65911. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65912. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65913. 0x07556b71, 0xff9370db, /* mediumpurple */
  65914. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65915. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65916. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65917. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65918. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65919. 0x168eb32a, 0xff191970, /* midnightblue */
  65920. 0x4306b960, 0xfff5fffa, /* mintcream */
  65921. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65922. 0xe97218a6, 0xffffdead, /* navajowhite */
  65923. 0x00337bb6, 0xff000080, /* navy */
  65924. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65925. 0x064ee1db, 0xff808000, /* olive */
  65926. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65927. 0xc3de262e, 0xffffa500, /* orange */
  65928. 0x58bebba3, 0xffff4500, /* orangered */
  65929. 0xc3def8a3, 0xffda70d6, /* orchid */
  65930. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65931. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65932. 0x74022737, 0xffafeeee, /* paleturquoise */
  65933. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65934. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65935. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65936. 0x003472f8, 0xffcd853f, /* peru */
  65937. 0x00348176, 0xffffc0cb, /* pink */
  65938. 0x00348d94, 0xffdda0dd, /* plum */
  65939. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65940. 0xc5c507bc, 0xff800080, /* purple */
  65941. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65942. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65943. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65944. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65945. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65946. 0x34636c14, 0xff2e8b57, /* seagreen */
  65947. 0x3507fb41, 0xfffff5ee, /* seashell */
  65948. 0xca348772, 0xffa0522d, /* sienna */
  65949. 0xca37d30d, 0xffc0c0c0, /* silver */
  65950. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65951. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65952. 0x44ab37f8, 0xff708090, /* slategrey */
  65953. 0x0035f183, 0xfffffafa, /* snow */
  65954. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65955. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65956. 0x0001bfa1, 0xffd2b48c, /* tan */
  65957. 0x0036425c, 0xff008080, /* teal */
  65958. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65959. 0xcc41600a, 0xffff6347, /* tomato */
  65960. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65961. 0xcf57947f, 0xffee82ee, /* violet */
  65962. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65963. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65964. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65965. };
  65966. const int hash = colourName.trim().toLowerCase().hashCode();
  65967. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65968. if (presets [i] == hash)
  65969. return Colour (presets [i + 1]);
  65970. return defaultColour;
  65971. }
  65972. END_JUCE_NAMESPACE
  65973. /*** End of inlined file: juce_Colours.cpp ***/
  65974. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65975. BEGIN_JUCE_NAMESPACE
  65976. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65977. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65978. const Path& path, const AffineTransform& transform)
  65979. : bounds (bounds_),
  65980. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65981. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65982. needToCheckEmptinesss (true)
  65983. {
  65984. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65985. int* t = table;
  65986. for (int i = bounds.getHeight(); --i >= 0;)
  65987. {
  65988. *t = 0;
  65989. t += lineStrideElements;
  65990. }
  65991. const int topLimit = bounds.getY() << 8;
  65992. const int heightLimit = bounds.getHeight() << 8;
  65993. const int leftLimit = bounds.getX() << 8;
  65994. const int rightLimit = bounds.getRight() << 8;
  65995. PathFlatteningIterator iter (path, transform);
  65996. while (iter.next())
  65997. {
  65998. int y1 = roundToInt (iter.y1 * 256.0f);
  65999. int y2 = roundToInt (iter.y2 * 256.0f);
  66000. if (y1 != y2)
  66001. {
  66002. y1 -= topLimit;
  66003. y2 -= topLimit;
  66004. const int startY = y1;
  66005. int direction = -1;
  66006. if (y1 > y2)
  66007. {
  66008. swapVariables (y1, y2);
  66009. direction = 1;
  66010. }
  66011. if (y1 < 0)
  66012. y1 = 0;
  66013. if (y2 > heightLimit)
  66014. y2 = heightLimit;
  66015. if (y1 < y2)
  66016. {
  66017. const double startX = 256.0f * iter.x1;
  66018. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  66019. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  66020. do
  66021. {
  66022. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  66023. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  66024. if (x < leftLimit)
  66025. x = leftLimit;
  66026. else if (x >= rightLimit)
  66027. x = rightLimit - 1;
  66028. addEdgePoint (x, y1 >> 8, direction * step);
  66029. y1 += step;
  66030. }
  66031. while (y1 < y2);
  66032. }
  66033. }
  66034. }
  66035. sanitiseLevels (path.isUsingNonZeroWinding());
  66036. }
  66037. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  66038. : bounds (rectangleToAdd),
  66039. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66040. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66041. needToCheckEmptinesss (true)
  66042. {
  66043. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66044. table[0] = 0;
  66045. const int x1 = rectangleToAdd.getX() << 8;
  66046. const int x2 = rectangleToAdd.getRight() << 8;
  66047. int* t = table;
  66048. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  66049. {
  66050. t[0] = 2;
  66051. t[1] = x1;
  66052. t[2] = 255;
  66053. t[3] = x2;
  66054. t[4] = 0;
  66055. t += lineStrideElements;
  66056. }
  66057. }
  66058. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  66059. : bounds (rectanglesToAdd.getBounds()),
  66060. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66061. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66062. needToCheckEmptinesss (true)
  66063. {
  66064. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66065. int* t = table;
  66066. for (int i = bounds.getHeight(); --i >= 0;)
  66067. {
  66068. *t = 0;
  66069. t += lineStrideElements;
  66070. }
  66071. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  66072. {
  66073. const Rectangle<int>* const r = iter.getRectangle();
  66074. const int x1 = r->getX() << 8;
  66075. const int x2 = r->getRight() << 8;
  66076. int y = r->getY() - bounds.getY();
  66077. for (int j = r->getHeight(); --j >= 0;)
  66078. {
  66079. addEdgePoint (x1, y, 255);
  66080. addEdgePoint (x2, y, -255);
  66081. ++y;
  66082. }
  66083. }
  66084. sanitiseLevels (true);
  66085. }
  66086. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  66087. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  66088. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  66089. 2 + (int) rectangleToAdd.getWidth(),
  66090. 2 + (int) rectangleToAdd.getHeight())),
  66091. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66092. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66093. needToCheckEmptinesss (true)
  66094. {
  66095. jassert (! rectangleToAdd.isEmpty());
  66096. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66097. table[0] = 0;
  66098. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  66099. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  66100. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  66101. jassert (y1 < 256);
  66102. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  66103. if (x2 <= x1 || y2 <= y1)
  66104. {
  66105. bounds.setHeight (0);
  66106. return;
  66107. }
  66108. int lineY = 0;
  66109. int* t = table;
  66110. if ((y1 >> 8) == (y2 >> 8))
  66111. {
  66112. t[0] = 2;
  66113. t[1] = x1;
  66114. t[2] = y2 - y1;
  66115. t[3] = x2;
  66116. t[4] = 0;
  66117. ++lineY;
  66118. t += lineStrideElements;
  66119. }
  66120. else
  66121. {
  66122. t[0] = 2;
  66123. t[1] = x1;
  66124. t[2] = 255 - (y1 & 255);
  66125. t[3] = x2;
  66126. t[4] = 0;
  66127. ++lineY;
  66128. t += lineStrideElements;
  66129. while (lineY < (y2 >> 8))
  66130. {
  66131. t[0] = 2;
  66132. t[1] = x1;
  66133. t[2] = 255;
  66134. t[3] = x2;
  66135. t[4] = 0;
  66136. ++lineY;
  66137. t += lineStrideElements;
  66138. }
  66139. jassert (lineY < bounds.getHeight());
  66140. t[0] = 2;
  66141. t[1] = x1;
  66142. t[2] = y2 & 255;
  66143. t[3] = x2;
  66144. t[4] = 0;
  66145. ++lineY;
  66146. t += lineStrideElements;
  66147. }
  66148. while (lineY < bounds.getHeight())
  66149. {
  66150. t[0] = 0;
  66151. t += lineStrideElements;
  66152. ++lineY;
  66153. }
  66154. }
  66155. EdgeTable::EdgeTable (const EdgeTable& other)
  66156. {
  66157. operator= (other);
  66158. }
  66159. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  66160. {
  66161. bounds = other.bounds;
  66162. maxEdgesPerLine = other.maxEdgesPerLine;
  66163. lineStrideElements = other.lineStrideElements;
  66164. needToCheckEmptinesss = other.needToCheckEmptinesss;
  66165. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66166. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  66167. return *this;
  66168. }
  66169. EdgeTable::~EdgeTable()
  66170. {
  66171. }
  66172. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66173. {
  66174. while (--numLines >= 0)
  66175. {
  66176. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66177. src += srcLineStride;
  66178. dest += destLineStride;
  66179. }
  66180. }
  66181. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66182. {
  66183. // Convert the table from relative windings to absolute levels..
  66184. int* lineStart = table;
  66185. for (int i = bounds.getHeight(); --i >= 0;)
  66186. {
  66187. int* line = lineStart;
  66188. lineStart += lineStrideElements;
  66189. int num = *line;
  66190. if (num == 0)
  66191. continue;
  66192. int level = 0;
  66193. if (useNonZeroWinding)
  66194. {
  66195. while (--num > 0)
  66196. {
  66197. line += 2;
  66198. level += *line;
  66199. int corrected = abs (level);
  66200. if (corrected >> 8)
  66201. corrected = 255;
  66202. *line = corrected;
  66203. }
  66204. }
  66205. else
  66206. {
  66207. while (--num > 0)
  66208. {
  66209. line += 2;
  66210. level += *line;
  66211. int corrected = abs (level);
  66212. if (corrected >> 8)
  66213. {
  66214. corrected &= 511;
  66215. if (corrected >> 8)
  66216. corrected = 511 - corrected;
  66217. }
  66218. *line = corrected;
  66219. }
  66220. }
  66221. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66222. }
  66223. }
  66224. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  66225. {
  66226. if (newNumEdgesPerLine != maxEdgesPerLine)
  66227. {
  66228. maxEdgesPerLine = newNumEdgesPerLine;
  66229. jassert (bounds.getHeight() > 0);
  66230. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66231. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66232. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66233. table.swapWith (newTable);
  66234. lineStrideElements = newLineStrideElements;
  66235. }
  66236. }
  66237. void EdgeTable::optimiseTable()
  66238. {
  66239. int maxLineElements = 0;
  66240. for (int i = bounds.getHeight(); --i >= 0;)
  66241. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66242. remapTableForNumEdges (maxLineElements);
  66243. }
  66244. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  66245. {
  66246. jassert (y >= 0 && y < bounds.getHeight());
  66247. int* line = table + lineStrideElements * y;
  66248. const int numPoints = line[0];
  66249. int n = numPoints << 1;
  66250. if (n > 0)
  66251. {
  66252. while (n > 0)
  66253. {
  66254. const int cx = line [n - 1];
  66255. if (cx <= x)
  66256. {
  66257. if (cx == x)
  66258. {
  66259. line [n] += winding;
  66260. return;
  66261. }
  66262. break;
  66263. }
  66264. n -= 2;
  66265. }
  66266. if (numPoints >= maxEdgesPerLine)
  66267. {
  66268. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66269. jassert (numPoints < maxEdgesPerLine);
  66270. line = table + lineStrideElements * y;
  66271. }
  66272. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66273. }
  66274. line [n + 1] = x;
  66275. line [n + 2] = winding;
  66276. line[0]++;
  66277. }
  66278. void EdgeTable::translate (float dx, const int dy) throw()
  66279. {
  66280. bounds.translate ((int) std::floor (dx), dy);
  66281. int* lineStart = table;
  66282. const int intDx = (int) (dx * 256.0f);
  66283. for (int i = bounds.getHeight(); --i >= 0;)
  66284. {
  66285. int* line = lineStart;
  66286. lineStart += lineStrideElements;
  66287. int num = *line++;
  66288. while (--num >= 0)
  66289. {
  66290. *line += intDx;
  66291. line += 2;
  66292. }
  66293. }
  66294. }
  66295. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  66296. {
  66297. jassert (y >= 0 && y < bounds.getHeight());
  66298. int* dest = table + lineStrideElements * y;
  66299. if (dest[0] == 0)
  66300. return;
  66301. int otherNumPoints = *otherLine;
  66302. if (otherNumPoints == 0)
  66303. {
  66304. *dest = 0;
  66305. return;
  66306. }
  66307. const int right = bounds.getRight() << 8;
  66308. // optimise for the common case where our line lies entirely within a
  66309. // single pair of points, as happens when clipping to a simple rect.
  66310. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66311. {
  66312. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66313. return;
  66314. }
  66315. ++otherLine;
  66316. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66317. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66318. memcpy (temp, dest, lineSizeBytes);
  66319. const int* src1 = temp;
  66320. int srcNum1 = *src1++;
  66321. int x1 = *src1++;
  66322. const int* src2 = otherLine;
  66323. int srcNum2 = otherNumPoints;
  66324. int x2 = *src2++;
  66325. int destIndex = 0, destTotal = 0;
  66326. int level1 = 0, level2 = 0;
  66327. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66328. while (srcNum1 > 0 && srcNum2 > 0)
  66329. {
  66330. int nextX;
  66331. if (x1 < x2)
  66332. {
  66333. nextX = x1;
  66334. level1 = *src1++;
  66335. x1 = *src1++;
  66336. --srcNum1;
  66337. }
  66338. else if (x1 == x2)
  66339. {
  66340. nextX = x1;
  66341. level1 = *src1++;
  66342. level2 = *src2++;
  66343. x1 = *src1++;
  66344. x2 = *src2++;
  66345. --srcNum1;
  66346. --srcNum2;
  66347. }
  66348. else
  66349. {
  66350. nextX = x2;
  66351. level2 = *src2++;
  66352. x2 = *src2++;
  66353. --srcNum2;
  66354. }
  66355. if (nextX > lastX)
  66356. {
  66357. if (nextX >= right)
  66358. break;
  66359. lastX = nextX;
  66360. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66361. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  66362. if (nextLevel != lastLevel)
  66363. {
  66364. if (destTotal >= maxEdgesPerLine)
  66365. {
  66366. dest[0] = destTotal;
  66367. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66368. dest = table + lineStrideElements * y;
  66369. }
  66370. ++destTotal;
  66371. lastLevel = nextLevel;
  66372. dest[++destIndex] = nextX;
  66373. dest[++destIndex] = nextLevel;
  66374. }
  66375. }
  66376. }
  66377. if (lastLevel > 0)
  66378. {
  66379. if (destTotal >= maxEdgesPerLine)
  66380. {
  66381. dest[0] = destTotal;
  66382. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66383. dest = table + lineStrideElements * y;
  66384. }
  66385. ++destTotal;
  66386. dest[++destIndex] = right;
  66387. dest[++destIndex] = 0;
  66388. }
  66389. dest[0] = destTotal;
  66390. #if JUCE_DEBUG
  66391. int last = std::numeric_limits<int>::min();
  66392. for (int i = 0; i < dest[0]; ++i)
  66393. {
  66394. jassert (dest[i * 2 + 1] > last);
  66395. last = dest[i * 2 + 1];
  66396. }
  66397. jassert (dest [dest[0] * 2] == 0);
  66398. #endif
  66399. }
  66400. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66401. {
  66402. int* lastItem = dest + (dest[0] * 2 - 1);
  66403. if (x2 < lastItem[0])
  66404. {
  66405. if (x2 <= dest[1])
  66406. {
  66407. dest[0] = 0;
  66408. return;
  66409. }
  66410. while (x2 < lastItem[-2])
  66411. {
  66412. --(dest[0]);
  66413. lastItem -= 2;
  66414. }
  66415. lastItem[0] = x2;
  66416. lastItem[1] = 0;
  66417. }
  66418. if (x1 > dest[1])
  66419. {
  66420. while (lastItem[0] > x1)
  66421. lastItem -= 2;
  66422. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66423. if (itemsRemoved > 0)
  66424. {
  66425. dest[0] -= itemsRemoved;
  66426. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66427. }
  66428. dest[1] = x1;
  66429. }
  66430. }
  66431. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  66432. {
  66433. const Rectangle<int> clipped (r.getIntersection (bounds));
  66434. if (clipped.isEmpty())
  66435. {
  66436. needToCheckEmptinesss = false;
  66437. bounds.setHeight (0);
  66438. }
  66439. else
  66440. {
  66441. const int top = clipped.getY() - bounds.getY();
  66442. const int bottom = clipped.getBottom() - bounds.getY();
  66443. if (bottom < bounds.getHeight())
  66444. bounds.setHeight (bottom);
  66445. if (clipped.getRight() < bounds.getRight())
  66446. bounds.setRight (clipped.getRight());
  66447. for (int i = top; --i >= 0;)
  66448. table [lineStrideElements * i] = 0;
  66449. if (clipped.getX() > bounds.getX())
  66450. {
  66451. const int x1 = clipped.getX() << 8;
  66452. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66453. int* line = table + lineStrideElements * top;
  66454. for (int i = bottom - top; --i >= 0;)
  66455. {
  66456. if (line[0] != 0)
  66457. clipEdgeTableLineToRange (line, x1, x2);
  66458. line += lineStrideElements;
  66459. }
  66460. }
  66461. needToCheckEmptinesss = true;
  66462. }
  66463. }
  66464. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66465. {
  66466. const Rectangle<int> clipped (r.getIntersection (bounds));
  66467. if (! clipped.isEmpty())
  66468. {
  66469. const int top = clipped.getY() - bounds.getY();
  66470. const int bottom = clipped.getBottom() - bounds.getY();
  66471. //XXX optimise here by shortening the table if it fills top or bottom
  66472. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66473. clipped.getX() << 8, 0,
  66474. clipped.getRight() << 8, 255,
  66475. std::numeric_limits<int>::max(), 0 };
  66476. for (int i = top; i < bottom; ++i)
  66477. intersectWithEdgeTableLine (i, rectLine);
  66478. needToCheckEmptinesss = true;
  66479. }
  66480. }
  66481. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66482. {
  66483. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66484. if (clipped.isEmpty())
  66485. {
  66486. needToCheckEmptinesss = false;
  66487. bounds.setHeight (0);
  66488. }
  66489. else
  66490. {
  66491. const int top = clipped.getY() - bounds.getY();
  66492. const int bottom = clipped.getBottom() - bounds.getY();
  66493. if (bottom < bounds.getHeight())
  66494. bounds.setHeight (bottom);
  66495. if (clipped.getRight() < bounds.getRight())
  66496. bounds.setRight (clipped.getRight());
  66497. int i = 0;
  66498. for (i = top; --i >= 0;)
  66499. table [lineStrideElements * i] = 0;
  66500. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66501. for (i = top; i < bottom; ++i)
  66502. {
  66503. intersectWithEdgeTableLine (i, otherLine);
  66504. otherLine += other.lineStrideElements;
  66505. }
  66506. needToCheckEmptinesss = true;
  66507. }
  66508. }
  66509. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66510. {
  66511. y -= bounds.getY();
  66512. if (y < 0 || y >= bounds.getHeight())
  66513. return;
  66514. needToCheckEmptinesss = true;
  66515. if (numPixels <= 0)
  66516. {
  66517. table [lineStrideElements * y] = 0;
  66518. return;
  66519. }
  66520. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66521. int destIndex = 0, lastLevel = 0;
  66522. while (--numPixels >= 0)
  66523. {
  66524. const int alpha = *mask;
  66525. mask += maskStride;
  66526. if (alpha != lastLevel)
  66527. {
  66528. tempLine[++destIndex] = (x << 8);
  66529. tempLine[++destIndex] = alpha;
  66530. lastLevel = alpha;
  66531. }
  66532. ++x;
  66533. }
  66534. if (lastLevel > 0)
  66535. {
  66536. tempLine[++destIndex] = (x << 8);
  66537. tempLine[++destIndex] = 0;
  66538. }
  66539. tempLine[0] = destIndex >> 1;
  66540. intersectWithEdgeTableLine (y, tempLine);
  66541. }
  66542. bool EdgeTable::isEmpty() throw()
  66543. {
  66544. if (needToCheckEmptinesss)
  66545. {
  66546. needToCheckEmptinesss = false;
  66547. int* t = table;
  66548. for (int i = bounds.getHeight(); --i >= 0;)
  66549. {
  66550. if (t[0] > 1)
  66551. return false;
  66552. t += lineStrideElements;
  66553. }
  66554. bounds.setHeight (0);
  66555. }
  66556. return bounds.getHeight() == 0;
  66557. }
  66558. END_JUCE_NAMESPACE
  66559. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66560. /*** Start of inlined file: juce_FillType.cpp ***/
  66561. BEGIN_JUCE_NAMESPACE
  66562. FillType::FillType() throw()
  66563. : colour (0xff000000), image (0)
  66564. {
  66565. }
  66566. FillType::FillType (const Colour& colour_) throw()
  66567. : colour (colour_), image (0)
  66568. {
  66569. }
  66570. FillType::FillType (const ColourGradient& gradient_)
  66571. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66572. {
  66573. }
  66574. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66575. : colour (0xff000000), image (image_), transform (transform_)
  66576. {
  66577. }
  66578. FillType::FillType (const FillType& other)
  66579. : colour (other.colour),
  66580. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66581. image (other.image), transform (other.transform)
  66582. {
  66583. }
  66584. FillType& FillType::operator= (const FillType& other)
  66585. {
  66586. if (this != &other)
  66587. {
  66588. colour = other.colour;
  66589. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66590. image = other.image;
  66591. transform = other.transform;
  66592. }
  66593. return *this;
  66594. }
  66595. FillType::~FillType() throw()
  66596. {
  66597. }
  66598. bool FillType::operator== (const FillType& other) const
  66599. {
  66600. return colour == other.colour && image == other.image
  66601. && transform == other.transform
  66602. && (gradient == other.gradient
  66603. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66604. }
  66605. bool FillType::operator!= (const FillType& other) const
  66606. {
  66607. return ! operator== (other);
  66608. }
  66609. void FillType::setColour (const Colour& newColour) throw()
  66610. {
  66611. gradient = 0;
  66612. image = Image::null;
  66613. colour = newColour;
  66614. }
  66615. void FillType::setGradient (const ColourGradient& newGradient)
  66616. {
  66617. if (gradient != 0)
  66618. {
  66619. *gradient = newGradient;
  66620. }
  66621. else
  66622. {
  66623. image = Image::null;
  66624. gradient = new ColourGradient (newGradient);
  66625. colour = Colours::black;
  66626. }
  66627. }
  66628. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66629. {
  66630. gradient = 0;
  66631. image = image_;
  66632. transform = transform_;
  66633. colour = Colours::black;
  66634. }
  66635. void FillType::setOpacity (const float newOpacity) throw()
  66636. {
  66637. colour = colour.withAlpha (newOpacity);
  66638. }
  66639. bool FillType::isInvisible() const throw()
  66640. {
  66641. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66642. }
  66643. END_JUCE_NAMESPACE
  66644. /*** End of inlined file: juce_FillType.cpp ***/
  66645. /*** Start of inlined file: juce_Graphics.cpp ***/
  66646. BEGIN_JUCE_NAMESPACE
  66647. namespace
  66648. {
  66649. template <typename Type>
  66650. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66651. {
  66652. const int maxVal = 0x3fffffff;
  66653. return (int) x >= -maxVal && (int) x <= maxVal
  66654. && (int) y >= -maxVal && (int) y <= maxVal
  66655. && (int) w >= -maxVal && (int) w <= maxVal
  66656. && (int) h >= -maxVal && (int) h <= maxVal;
  66657. }
  66658. }
  66659. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66660. {
  66661. }
  66662. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66663. {
  66664. }
  66665. Graphics::Graphics (const Image& imageToDrawOnto)
  66666. : context (imageToDrawOnto.createLowLevelContext()),
  66667. contextToDelete (context),
  66668. saveStatePending (false)
  66669. {
  66670. }
  66671. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66672. : context (internalContext),
  66673. saveStatePending (false)
  66674. {
  66675. }
  66676. Graphics::~Graphics()
  66677. {
  66678. }
  66679. void Graphics::resetToDefaultState()
  66680. {
  66681. saveStateIfPending();
  66682. context->setFill (FillType());
  66683. context->setFont (Font());
  66684. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66685. }
  66686. bool Graphics::isVectorDevice() const
  66687. {
  66688. return context->isVectorDevice();
  66689. }
  66690. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66691. {
  66692. saveStateIfPending();
  66693. return context->clipToRectangle (area);
  66694. }
  66695. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66696. {
  66697. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66698. }
  66699. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66700. {
  66701. saveStateIfPending();
  66702. return context->clipToRectangleList (clipRegion);
  66703. }
  66704. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66705. {
  66706. saveStateIfPending();
  66707. context->clipToPath (path, transform);
  66708. return ! context->isClipEmpty();
  66709. }
  66710. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66711. {
  66712. saveStateIfPending();
  66713. context->clipToImageAlpha (image, transform);
  66714. return ! context->isClipEmpty();
  66715. }
  66716. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66717. {
  66718. saveStateIfPending();
  66719. context->excludeClipRectangle (rectangleToExclude);
  66720. }
  66721. bool Graphics::isClipEmpty() const
  66722. {
  66723. return context->isClipEmpty();
  66724. }
  66725. const Rectangle<int> Graphics::getClipBounds() const
  66726. {
  66727. return context->getClipBounds();
  66728. }
  66729. void Graphics::saveState()
  66730. {
  66731. saveStateIfPending();
  66732. saveStatePending = true;
  66733. }
  66734. void Graphics::restoreState()
  66735. {
  66736. if (saveStatePending)
  66737. saveStatePending = false;
  66738. else
  66739. context->restoreState();
  66740. }
  66741. void Graphics::saveStateIfPending()
  66742. {
  66743. if (saveStatePending)
  66744. {
  66745. saveStatePending = false;
  66746. context->saveState();
  66747. }
  66748. }
  66749. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66750. {
  66751. saveStateIfPending();
  66752. context->setOrigin (newOriginX, newOriginY);
  66753. }
  66754. void Graphics::addTransform (const AffineTransform& transform)
  66755. {
  66756. saveStateIfPending();
  66757. context->addTransform (transform);
  66758. }
  66759. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66760. {
  66761. return context->clipRegionIntersects (area);
  66762. }
  66763. void Graphics::beginTransparencyLayer (float layerOpacity)
  66764. {
  66765. saveStateIfPending();
  66766. context->beginTransparencyLayer (layerOpacity);
  66767. }
  66768. void Graphics::endTransparencyLayer()
  66769. {
  66770. context->endTransparencyLayer();
  66771. }
  66772. void Graphics::setColour (const Colour& newColour)
  66773. {
  66774. saveStateIfPending();
  66775. context->setFill (newColour);
  66776. }
  66777. void Graphics::setOpacity (const float newOpacity)
  66778. {
  66779. saveStateIfPending();
  66780. context->setOpacity (newOpacity);
  66781. }
  66782. void Graphics::setGradientFill (const ColourGradient& gradient)
  66783. {
  66784. setFillType (gradient);
  66785. }
  66786. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66787. {
  66788. saveStateIfPending();
  66789. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66790. context->setOpacity (opacity);
  66791. }
  66792. void Graphics::setFillType (const FillType& newFill)
  66793. {
  66794. saveStateIfPending();
  66795. context->setFill (newFill);
  66796. }
  66797. void Graphics::setFont (const Font& newFont)
  66798. {
  66799. saveStateIfPending();
  66800. context->setFont (newFont);
  66801. }
  66802. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66803. {
  66804. saveStateIfPending();
  66805. Font f (context->getFont());
  66806. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66807. context->setFont (f);
  66808. }
  66809. const Font Graphics::getCurrentFont() const
  66810. {
  66811. return context->getFont();
  66812. }
  66813. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66814. {
  66815. if (text.isNotEmpty()
  66816. && startX < context->getClipBounds().getRight())
  66817. {
  66818. GlyphArrangement arr;
  66819. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66820. arr.draw (*this);
  66821. }
  66822. }
  66823. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66824. {
  66825. if (text.isNotEmpty())
  66826. {
  66827. GlyphArrangement arr;
  66828. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66829. arr.draw (*this, transform);
  66830. }
  66831. }
  66832. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66833. {
  66834. if (text.isNotEmpty()
  66835. && startX < context->getClipBounds().getRight())
  66836. {
  66837. GlyphArrangement arr;
  66838. arr.addJustifiedText (context->getFont(), text,
  66839. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66840. Justification::left);
  66841. arr.draw (*this);
  66842. }
  66843. }
  66844. void Graphics::drawText (const String& text,
  66845. const int x, const int y, const int width, const int height,
  66846. const Justification& justificationType,
  66847. const bool useEllipsesIfTooBig) const
  66848. {
  66849. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66850. {
  66851. GlyphArrangement arr;
  66852. arr.addCurtailedLineOfText (context->getFont(), text,
  66853. 0.0f, 0.0f, (float) width,
  66854. useEllipsesIfTooBig);
  66855. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66856. (float) x, (float) y, (float) width, (float) height,
  66857. justificationType);
  66858. arr.draw (*this);
  66859. }
  66860. }
  66861. void Graphics::drawFittedText (const String& text,
  66862. const int x, const int y, const int width, const int height,
  66863. const Justification& justification,
  66864. const int maximumNumberOfLines,
  66865. const float minimumHorizontalScale) const
  66866. {
  66867. if (text.isNotEmpty()
  66868. && width > 0 && height > 0
  66869. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66870. {
  66871. GlyphArrangement arr;
  66872. arr.addFittedText (context->getFont(), text,
  66873. (float) x, (float) y, (float) width, (float) height,
  66874. justification,
  66875. maximumNumberOfLines,
  66876. minimumHorizontalScale);
  66877. arr.draw (*this);
  66878. }
  66879. }
  66880. void Graphics::fillRect (int x, int y, int width, int height) const
  66881. {
  66882. // passing in a silly number can cause maths problems in rendering!
  66883. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66884. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66885. }
  66886. void Graphics::fillRect (const Rectangle<int>& r) const
  66887. {
  66888. context->fillRect (r, false);
  66889. }
  66890. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66891. {
  66892. // passing in a silly number can cause maths problems in rendering!
  66893. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66894. Path p;
  66895. p.addRectangle (x, y, width, height);
  66896. fillPath (p);
  66897. }
  66898. void Graphics::setPixel (int x, int y) const
  66899. {
  66900. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66901. }
  66902. void Graphics::fillAll() const
  66903. {
  66904. fillRect (context->getClipBounds());
  66905. }
  66906. void Graphics::fillAll (const Colour& colourToUse) const
  66907. {
  66908. if (! colourToUse.isTransparent())
  66909. {
  66910. const Rectangle<int> clip (context->getClipBounds());
  66911. context->saveState();
  66912. context->setFill (colourToUse);
  66913. context->fillRect (clip, false);
  66914. context->restoreState();
  66915. }
  66916. }
  66917. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66918. {
  66919. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66920. context->fillPath (path, transform);
  66921. }
  66922. void Graphics::strokePath (const Path& path,
  66923. const PathStrokeType& strokeType,
  66924. const AffineTransform& transform) const
  66925. {
  66926. Path stroke;
  66927. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66928. fillPath (stroke);
  66929. }
  66930. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66931. const int lineThickness) const
  66932. {
  66933. // passing in a silly number can cause maths problems in rendering!
  66934. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66935. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66936. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66937. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66938. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66939. }
  66940. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66941. {
  66942. // passing in a silly number can cause maths problems in rendering!
  66943. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66944. Path p;
  66945. p.addRectangle (x, y, width, lineThickness);
  66946. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66947. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66948. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66949. fillPath (p);
  66950. }
  66951. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66952. {
  66953. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66954. }
  66955. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66956. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66957. const bool useGradient, const bool sharpEdgeOnOutside) const
  66958. {
  66959. // passing in a silly number can cause maths problems in rendering!
  66960. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66961. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66962. {
  66963. context->saveState();
  66964. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66965. const float ramp = oldOpacity / bevelThickness;
  66966. for (int i = bevelThickness; --i >= 0;)
  66967. {
  66968. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66969. : oldOpacity;
  66970. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66971. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66972. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66973. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66974. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66975. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66976. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66977. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66978. }
  66979. context->restoreState();
  66980. }
  66981. }
  66982. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66983. {
  66984. // passing in a silly number can cause maths problems in rendering!
  66985. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66986. Path p;
  66987. p.addEllipse (x, y, width, height);
  66988. fillPath (p);
  66989. }
  66990. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66991. const float lineThickness) const
  66992. {
  66993. // passing in a silly number can cause maths problems in rendering!
  66994. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66995. Path p;
  66996. p.addEllipse (x, y, width, height);
  66997. strokePath (p, PathStrokeType (lineThickness));
  66998. }
  66999. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  67000. {
  67001. // passing in a silly number can cause maths problems in rendering!
  67002. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67003. Path p;
  67004. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67005. fillPath (p);
  67006. }
  67007. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  67008. {
  67009. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  67010. }
  67011. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  67012. const float cornerSize, const float lineThickness) const
  67013. {
  67014. // passing in a silly number can cause maths problems in rendering!
  67015. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67016. Path p;
  67017. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67018. strokePath (p, PathStrokeType (lineThickness));
  67019. }
  67020. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  67021. {
  67022. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  67023. }
  67024. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  67025. {
  67026. Path p;
  67027. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  67028. fillPath (p);
  67029. }
  67030. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  67031. const int checkWidth, const int checkHeight,
  67032. const Colour& colour1, const Colour& colour2) const
  67033. {
  67034. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  67035. if (checkWidth > 0 && checkHeight > 0)
  67036. {
  67037. context->saveState();
  67038. if (colour1 == colour2)
  67039. {
  67040. context->setFill (colour1);
  67041. context->fillRect (area, false);
  67042. }
  67043. else
  67044. {
  67045. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  67046. if (! clipped.isEmpty())
  67047. {
  67048. context->clipToRectangle (clipped);
  67049. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  67050. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  67051. const int startX = area.getX() + checkNumX * checkWidth;
  67052. const int startY = area.getY() + checkNumY * checkHeight;
  67053. const int right = clipped.getRight();
  67054. const int bottom = clipped.getBottom();
  67055. for (int i = 0; i < 2; ++i)
  67056. {
  67057. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  67058. int cy = i;
  67059. for (int y = startY; y < bottom; y += checkHeight)
  67060. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  67061. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  67062. }
  67063. }
  67064. }
  67065. context->restoreState();
  67066. }
  67067. }
  67068. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  67069. {
  67070. context->drawVerticalLine (x, top, bottom);
  67071. }
  67072. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  67073. {
  67074. context->drawHorizontalLine (y, left, right);
  67075. }
  67076. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  67077. {
  67078. context->drawLine (Line<float> (x1, y1, x2, y2));
  67079. }
  67080. void Graphics::drawLine (const Line<float>& line) const
  67081. {
  67082. context->drawLine (line);
  67083. }
  67084. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  67085. {
  67086. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  67087. }
  67088. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  67089. {
  67090. Path p;
  67091. p.addLineSegment (line, lineThickness);
  67092. fillPath (p);
  67093. }
  67094. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  67095. const int numDashLengths, const float lineThickness, int n) const
  67096. {
  67097. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  67098. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  67099. const double totalLen = delta.getDistanceFromOrigin();
  67100. if (totalLen >= 0.1)
  67101. {
  67102. const double onePixAlpha = 1.0 / totalLen;
  67103. for (double alpha = 0.0; alpha < 1.0;)
  67104. {
  67105. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  67106. const double lastAlpha = alpha;
  67107. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  67108. n = (n + 1) % numDashLengths;
  67109. if ((n & 1) != 0)
  67110. {
  67111. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  67112. line.getStart() + (delta * alpha).toFloat());
  67113. if (lineThickness != 1.0f)
  67114. drawLine (segment, lineThickness);
  67115. else
  67116. context->drawLine (segment);
  67117. }
  67118. }
  67119. }
  67120. }
  67121. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  67122. {
  67123. saveStateIfPending();
  67124. context->setInterpolationQuality (newQuality);
  67125. }
  67126. void Graphics::drawImageAt (const Image& imageToDraw,
  67127. const int topLeftX, const int topLeftY,
  67128. const bool fillAlphaChannelWithCurrentBrush) const
  67129. {
  67130. const int imageW = imageToDraw.getWidth();
  67131. const int imageH = imageToDraw.getHeight();
  67132. drawImage (imageToDraw,
  67133. topLeftX, topLeftY, imageW, imageH,
  67134. 0, 0, imageW, imageH,
  67135. fillAlphaChannelWithCurrentBrush);
  67136. }
  67137. void Graphics::drawImageWithin (const Image& imageToDraw,
  67138. const int destX, const int destY,
  67139. const int destW, const int destH,
  67140. const RectanglePlacement& placementWithinTarget,
  67141. const bool fillAlphaChannelWithCurrentBrush) const
  67142. {
  67143. // passing in a silly number can cause maths problems in rendering!
  67144. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  67145. if (imageToDraw.isValid())
  67146. {
  67147. const int imageW = imageToDraw.getWidth();
  67148. const int imageH = imageToDraw.getHeight();
  67149. if (imageW > 0 && imageH > 0)
  67150. {
  67151. double newX = 0.0, newY = 0.0;
  67152. double newW = imageW;
  67153. double newH = imageH;
  67154. placementWithinTarget.applyTo (newX, newY, newW, newH,
  67155. destX, destY, destW, destH);
  67156. if (newW > 0 && newH > 0)
  67157. {
  67158. drawImage (imageToDraw,
  67159. roundToInt (newX), roundToInt (newY),
  67160. roundToInt (newW), roundToInt (newH),
  67161. 0, 0, imageW, imageH,
  67162. fillAlphaChannelWithCurrentBrush);
  67163. }
  67164. }
  67165. }
  67166. }
  67167. void Graphics::drawImage (const Image& imageToDraw,
  67168. int dx, int dy, int dw, int dh,
  67169. int sx, int sy, int sw, int sh,
  67170. const bool fillAlphaChannelWithCurrentBrush) const
  67171. {
  67172. // passing in a silly number can cause maths problems in rendering!
  67173. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  67174. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  67175. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  67176. {
  67177. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  67178. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  67179. .translated ((float) dx, (float) dy),
  67180. fillAlphaChannelWithCurrentBrush);
  67181. }
  67182. }
  67183. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67184. const AffineTransform& transform,
  67185. const bool fillAlphaChannelWithCurrentBrush) const
  67186. {
  67187. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67188. {
  67189. if (fillAlphaChannelWithCurrentBrush)
  67190. {
  67191. context->saveState();
  67192. context->clipToImageAlpha (imageToDraw, transform);
  67193. fillAll();
  67194. context->restoreState();
  67195. }
  67196. else
  67197. {
  67198. context->drawImage (imageToDraw, transform, false);
  67199. }
  67200. }
  67201. }
  67202. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  67203. : context (g)
  67204. {
  67205. context.saveState();
  67206. }
  67207. Graphics::ScopedSaveState::~ScopedSaveState()
  67208. {
  67209. context.restoreState();
  67210. }
  67211. END_JUCE_NAMESPACE
  67212. /*** End of inlined file: juce_Graphics.cpp ***/
  67213. /*** Start of inlined file: juce_Justification.cpp ***/
  67214. BEGIN_JUCE_NAMESPACE
  67215. Justification::Justification (const Justification& other) throw()
  67216. : flags (other.flags)
  67217. {
  67218. }
  67219. Justification& Justification::operator= (const Justification& other) throw()
  67220. {
  67221. flags = other.flags;
  67222. return *this;
  67223. }
  67224. int Justification::getOnlyVerticalFlags() const throw()
  67225. {
  67226. return flags & (top | bottom | verticallyCentred);
  67227. }
  67228. int Justification::getOnlyHorizontalFlags() const throw()
  67229. {
  67230. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67231. }
  67232. END_JUCE_NAMESPACE
  67233. /*** End of inlined file: juce_Justification.cpp ***/
  67234. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67235. BEGIN_JUCE_NAMESPACE
  67236. // this will throw an assertion if you try to draw something that's not
  67237. // possible in postscript
  67238. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67239. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67240. #define notPossibleInPostscriptAssert jassertfalse
  67241. #else
  67242. #define notPossibleInPostscriptAssert
  67243. #endif
  67244. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67245. const String& documentTitle,
  67246. const int totalWidth_,
  67247. const int totalHeight_)
  67248. : out (resultingPostScript),
  67249. totalWidth (totalWidth_),
  67250. totalHeight (totalHeight_),
  67251. needToClip (true)
  67252. {
  67253. stateStack.add (new SavedState());
  67254. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67255. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67256. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67257. "\n%%BoundingBox: 0 0 600 824"
  67258. "\n%%Pages: 0"
  67259. "\n%%Creator: Raw Material Software JUCE"
  67260. "\n%%Title: " << documentTitle <<
  67261. "\n%%CreationDate: none"
  67262. "\n%%LanguageLevel: 2"
  67263. "\n%%EndComments"
  67264. "\n%%BeginProlog"
  67265. "\n%%BeginResource: JRes"
  67266. "\n/bd {bind def} bind def"
  67267. "\n/c {setrgbcolor} bd"
  67268. "\n/m {moveto} bd"
  67269. "\n/l {lineto} bd"
  67270. "\n/rl {rlineto} bd"
  67271. "\n/ct {curveto} bd"
  67272. "\n/cp {closepath} bd"
  67273. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67274. "\n/doclip {initclip newpath} bd"
  67275. "\n/endclip {clip newpath} bd"
  67276. "\n%%EndResource"
  67277. "\n%%EndProlog"
  67278. "\n%%BeginSetup"
  67279. "\n%%EndSetup"
  67280. "\n%%Page: 1 1"
  67281. "\n%%BeginPageSetup"
  67282. "\n%%EndPageSetup\n\n"
  67283. << "40 800 translate\n"
  67284. << scale << ' ' << scale << " scale\n\n";
  67285. }
  67286. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67287. {
  67288. }
  67289. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67290. {
  67291. return true;
  67292. }
  67293. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67294. {
  67295. if (x != 0 || y != 0)
  67296. {
  67297. stateStack.getLast()->xOffset += x;
  67298. stateStack.getLast()->yOffset += y;
  67299. needToClip = true;
  67300. }
  67301. }
  67302. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  67303. {
  67304. //xxx
  67305. jassertfalse;
  67306. }
  67307. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  67308. {
  67309. jassertfalse; //xxx
  67310. return 1.0f;
  67311. }
  67312. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67313. {
  67314. needToClip = true;
  67315. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67316. }
  67317. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67318. {
  67319. needToClip = true;
  67320. return stateStack.getLast()->clip.clipTo (clipRegion);
  67321. }
  67322. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67323. {
  67324. needToClip = true;
  67325. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67326. }
  67327. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67328. {
  67329. writeClip();
  67330. Path p (path);
  67331. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67332. writePath (p);
  67333. out << "clip\n";
  67334. }
  67335. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67336. {
  67337. needToClip = true;
  67338. jassertfalse; // xxx
  67339. }
  67340. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67341. {
  67342. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67343. }
  67344. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67345. {
  67346. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67347. -stateStack.getLast()->yOffset);
  67348. }
  67349. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67350. {
  67351. return stateStack.getLast()->clip.isEmpty();
  67352. }
  67353. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67354. : xOffset (0),
  67355. yOffset (0)
  67356. {
  67357. }
  67358. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67359. {
  67360. }
  67361. void LowLevelGraphicsPostScriptRenderer::saveState()
  67362. {
  67363. stateStack.add (new SavedState (*stateStack.getLast()));
  67364. }
  67365. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67366. {
  67367. jassert (stateStack.size() > 0);
  67368. if (stateStack.size() > 0)
  67369. stateStack.removeLast();
  67370. }
  67371. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  67372. {
  67373. }
  67374. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  67375. {
  67376. }
  67377. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67378. {
  67379. if (needToClip)
  67380. {
  67381. needToClip = false;
  67382. out << "doclip ";
  67383. int itemsOnLine = 0;
  67384. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67385. {
  67386. if (++itemsOnLine == 6)
  67387. {
  67388. itemsOnLine = 0;
  67389. out << '\n';
  67390. }
  67391. const Rectangle<int>& r = *i.getRectangle();
  67392. out << r.getX() << ' ' << -r.getY() << ' '
  67393. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67394. }
  67395. out << "endclip\n";
  67396. }
  67397. }
  67398. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67399. {
  67400. Colour c (Colours::white.overlaidWith (colour));
  67401. if (lastColour != c)
  67402. {
  67403. lastColour = c;
  67404. out << String (c.getFloatRed(), 3) << ' '
  67405. << String (c.getFloatGreen(), 3) << ' '
  67406. << String (c.getFloatBlue(), 3) << " c\n";
  67407. }
  67408. }
  67409. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67410. {
  67411. out << String (x, 2) << ' '
  67412. << String (-y, 2) << ' ';
  67413. }
  67414. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67415. {
  67416. out << "newpath ";
  67417. float lastX = 0.0f;
  67418. float lastY = 0.0f;
  67419. int itemsOnLine = 0;
  67420. Path::Iterator i (path);
  67421. while (i.next())
  67422. {
  67423. if (++itemsOnLine == 4)
  67424. {
  67425. itemsOnLine = 0;
  67426. out << '\n';
  67427. }
  67428. switch (i.elementType)
  67429. {
  67430. case Path::Iterator::startNewSubPath:
  67431. writeXY (i.x1, i.y1);
  67432. lastX = i.x1;
  67433. lastY = i.y1;
  67434. out << "m ";
  67435. break;
  67436. case Path::Iterator::lineTo:
  67437. writeXY (i.x1, i.y1);
  67438. lastX = i.x1;
  67439. lastY = i.y1;
  67440. out << "l ";
  67441. break;
  67442. case Path::Iterator::quadraticTo:
  67443. {
  67444. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67445. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67446. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67447. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67448. writeXY (cp1x, cp1y);
  67449. writeXY (cp2x, cp2y);
  67450. writeXY (i.x2, i.y2);
  67451. out << "ct ";
  67452. lastX = i.x2;
  67453. lastY = i.y2;
  67454. }
  67455. break;
  67456. case Path::Iterator::cubicTo:
  67457. writeXY (i.x1, i.y1);
  67458. writeXY (i.x2, i.y2);
  67459. writeXY (i.x3, i.y3);
  67460. out << "ct ";
  67461. lastX = i.x3;
  67462. lastY = i.y3;
  67463. break;
  67464. case Path::Iterator::closePath:
  67465. out << "cp ";
  67466. break;
  67467. default:
  67468. jassertfalse;
  67469. break;
  67470. }
  67471. }
  67472. out << '\n';
  67473. }
  67474. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67475. {
  67476. out << "[ "
  67477. << trans.mat00 << ' '
  67478. << trans.mat10 << ' '
  67479. << trans.mat01 << ' '
  67480. << trans.mat11 << ' '
  67481. << trans.mat02 << ' '
  67482. << trans.mat12 << " ] concat ";
  67483. }
  67484. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67485. {
  67486. stateStack.getLast()->fillType = fillType;
  67487. }
  67488. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67489. {
  67490. }
  67491. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67492. {
  67493. }
  67494. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67495. {
  67496. if (stateStack.getLast()->fillType.isColour())
  67497. {
  67498. writeClip();
  67499. writeColour (stateStack.getLast()->fillType.colour);
  67500. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67501. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67502. }
  67503. else
  67504. {
  67505. Path p;
  67506. p.addRectangle (r);
  67507. fillPath (p, AffineTransform::identity);
  67508. }
  67509. }
  67510. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67511. {
  67512. if (stateStack.getLast()->fillType.isColour())
  67513. {
  67514. writeClip();
  67515. Path p (path);
  67516. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67517. (float) stateStack.getLast()->yOffset));
  67518. writePath (p);
  67519. writeColour (stateStack.getLast()->fillType.colour);
  67520. out << "fill\n";
  67521. }
  67522. else if (stateStack.getLast()->fillType.isGradient())
  67523. {
  67524. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67525. // postscript can't do semi-transparent ones.
  67526. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67527. writeClip();
  67528. out << "gsave ";
  67529. {
  67530. Path p (path);
  67531. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67532. writePath (p);
  67533. out << "clip\n";
  67534. }
  67535. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67536. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67537. // time-being, this just fills it with the average colour..
  67538. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67539. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67540. out << "grestore\n";
  67541. }
  67542. }
  67543. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67544. const int sx, const int sy,
  67545. const int maxW, const int maxH) const
  67546. {
  67547. out << "{<\n";
  67548. const int w = jmin (maxW, im.getWidth());
  67549. const int h = jmin (maxH, im.getHeight());
  67550. int charsOnLine = 0;
  67551. const Image::BitmapData srcData (im, 0, 0, w, h);
  67552. Colour pixel;
  67553. for (int y = h; --y >= 0;)
  67554. {
  67555. for (int x = 0; x < w; ++x)
  67556. {
  67557. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67558. if (x >= sx && y >= sy)
  67559. {
  67560. if (im.isARGB())
  67561. {
  67562. PixelARGB p (*(const PixelARGB*) pixelData);
  67563. p.unpremultiply();
  67564. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67565. }
  67566. else if (im.isRGB())
  67567. {
  67568. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67569. }
  67570. else
  67571. {
  67572. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67573. }
  67574. }
  67575. else
  67576. {
  67577. pixel = Colours::transparentWhite;
  67578. }
  67579. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67580. out << String::toHexString (pixelValues, 3, 0);
  67581. charsOnLine += 3;
  67582. if (charsOnLine > 100)
  67583. {
  67584. out << '\n';
  67585. charsOnLine = 0;
  67586. }
  67587. }
  67588. }
  67589. out << "\n>}\n";
  67590. }
  67591. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67592. {
  67593. const int w = sourceImage.getWidth();
  67594. const int h = sourceImage.getHeight();
  67595. writeClip();
  67596. out << "gsave ";
  67597. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67598. .scaled (1.0f, -1.0f));
  67599. RectangleList imageClip;
  67600. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67601. out << "newpath ";
  67602. int itemsOnLine = 0;
  67603. for (RectangleList::Iterator i (imageClip); i.next();)
  67604. {
  67605. if (++itemsOnLine == 6)
  67606. {
  67607. out << '\n';
  67608. itemsOnLine = 0;
  67609. }
  67610. const Rectangle<int>& r = *i.getRectangle();
  67611. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67612. }
  67613. out << " clip newpath\n";
  67614. out << w << ' ' << h << " scale\n";
  67615. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67616. writeImage (sourceImage, 0, 0, w, h);
  67617. out << "false 3 colorimage grestore\n";
  67618. needToClip = true;
  67619. }
  67620. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67621. {
  67622. Path p;
  67623. p.addLineSegment (line, 1.0f);
  67624. fillPath (p, AffineTransform::identity);
  67625. }
  67626. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67627. {
  67628. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67629. }
  67630. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67631. {
  67632. drawLine (Line<float> (left, (float) y, right, (float) y));
  67633. }
  67634. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67635. {
  67636. stateStack.getLast()->font = newFont;
  67637. }
  67638. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67639. {
  67640. return stateStack.getLast()->font;
  67641. }
  67642. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67643. {
  67644. Path p;
  67645. Font& font = stateStack.getLast()->font;
  67646. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67647. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67648. }
  67649. END_JUCE_NAMESPACE
  67650. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67651. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67652. BEGIN_JUCE_NAMESPACE
  67653. #if JUCE_MSVC
  67654. #pragma warning (push)
  67655. #pragma warning (disable: 4127) // "expression is constant" warning
  67656. #if JUCE_DEBUG
  67657. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67658. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67659. #endif
  67660. #endif
  67661. namespace SoftwareRendererClasses
  67662. {
  67663. template <class PixelType, bool replaceExisting = false>
  67664. class SolidColourEdgeTableRenderer
  67665. {
  67666. public:
  67667. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67668. : data (data_),
  67669. sourceColour (colour)
  67670. {
  67671. if (sizeof (PixelType) == 3)
  67672. {
  67673. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67674. && sourceColour.getGreen() == sourceColour.getBlue();
  67675. filler[0].set (sourceColour);
  67676. filler[1].set (sourceColour);
  67677. filler[2].set (sourceColour);
  67678. filler[3].set (sourceColour);
  67679. }
  67680. }
  67681. forcedinline void setEdgeTableYPos (const int y) throw()
  67682. {
  67683. linePixels = (PixelType*) data.getLinePointer (y);
  67684. }
  67685. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67686. {
  67687. if (replaceExisting)
  67688. linePixels[x].set (sourceColour);
  67689. else
  67690. linePixels[x].blend (sourceColour, alphaLevel);
  67691. }
  67692. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67693. {
  67694. if (replaceExisting)
  67695. linePixels[x].set (sourceColour);
  67696. else
  67697. linePixels[x].blend (sourceColour);
  67698. }
  67699. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67700. {
  67701. PixelARGB p (sourceColour);
  67702. p.multiplyAlpha (alphaLevel);
  67703. PixelType* dest = linePixels + x;
  67704. if (replaceExisting || p.getAlpha() >= 0xff)
  67705. replaceLine (dest, p, width);
  67706. else
  67707. blendLine (dest, p, width);
  67708. }
  67709. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67710. {
  67711. PixelType* dest = linePixels + x;
  67712. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67713. replaceLine (dest, sourceColour, width);
  67714. else
  67715. blendLine (dest, sourceColour, width);
  67716. }
  67717. private:
  67718. const Image::BitmapData& data;
  67719. PixelType* linePixels;
  67720. PixelARGB sourceColour;
  67721. PixelRGB filler [4];
  67722. bool areRGBComponentsEqual;
  67723. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67724. {
  67725. do
  67726. {
  67727. dest->blend (colour);
  67728. ++dest;
  67729. } while (--width > 0);
  67730. }
  67731. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67732. {
  67733. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67734. {
  67735. memset (dest, colour.getRed(), width * 3);
  67736. }
  67737. else
  67738. {
  67739. if (width >> 5)
  67740. {
  67741. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67742. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67743. {
  67744. dest->set (colour);
  67745. ++dest;
  67746. --width;
  67747. }
  67748. while (width > 4)
  67749. {
  67750. int* d = reinterpret_cast<int*> (dest);
  67751. *d++ = intFiller[0];
  67752. *d++ = intFiller[1];
  67753. *d++ = intFiller[2];
  67754. dest = reinterpret_cast<PixelRGB*> (d);
  67755. width -= 4;
  67756. }
  67757. }
  67758. while (--width >= 0)
  67759. {
  67760. dest->set (colour);
  67761. ++dest;
  67762. }
  67763. }
  67764. }
  67765. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67766. {
  67767. memset (dest, colour.getAlpha(), width);
  67768. }
  67769. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67770. {
  67771. do
  67772. {
  67773. dest->set (colour);
  67774. ++dest;
  67775. } while (--width > 0);
  67776. }
  67777. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67778. };
  67779. class LinearGradientPixelGenerator
  67780. {
  67781. public:
  67782. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67783. : lookupTable (lookupTable_), numEntries (numEntries_)
  67784. {
  67785. jassert (numEntries_ >= 0);
  67786. Point<float> p1 (gradient.point1);
  67787. Point<float> p2 (gradient.point2);
  67788. if (! transform.isIdentity())
  67789. {
  67790. const Line<float> l (p2, p1);
  67791. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67792. p1.applyTransform (transform);
  67793. p2.applyTransform (transform);
  67794. p3.applyTransform (transform);
  67795. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67796. }
  67797. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67798. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67799. if (vertical)
  67800. {
  67801. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67802. start = roundToInt (p1.getY() * scale);
  67803. }
  67804. else if (horizontal)
  67805. {
  67806. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67807. start = roundToInt (p1.getX() * scale);
  67808. }
  67809. else
  67810. {
  67811. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67812. yTerm = p1.getY() - p1.getX() / grad;
  67813. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67814. grad *= scale;
  67815. }
  67816. }
  67817. forcedinline void setY (const int y) throw()
  67818. {
  67819. if (vertical)
  67820. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67821. else if (! horizontal)
  67822. start = roundToInt ((y - yTerm) * grad);
  67823. }
  67824. inline const PixelARGB getPixel (const int x) const throw()
  67825. {
  67826. return vertical ? linePix
  67827. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67828. }
  67829. private:
  67830. const PixelARGB* const lookupTable;
  67831. const int numEntries;
  67832. PixelARGB linePix;
  67833. int start, scale;
  67834. double grad, yTerm;
  67835. bool vertical, horizontal;
  67836. enum { numScaleBits = 12 };
  67837. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67838. };
  67839. class RadialGradientPixelGenerator
  67840. {
  67841. public:
  67842. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67843. const PixelARGB* const lookupTable_, const int numEntries_)
  67844. : lookupTable (lookupTable_),
  67845. numEntries (numEntries_),
  67846. gx1 (gradient.point1.getX()),
  67847. gy1 (gradient.point1.getY())
  67848. {
  67849. jassert (numEntries_ >= 0);
  67850. const Point<float> diff (gradient.point1 - gradient.point2);
  67851. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67852. invScale = numEntries / std::sqrt (maxDist);
  67853. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67854. }
  67855. forcedinline void setY (const int y) throw()
  67856. {
  67857. dy = y - gy1;
  67858. dy *= dy;
  67859. }
  67860. inline const PixelARGB getPixel (const int px) const throw()
  67861. {
  67862. double x = px - gx1;
  67863. x *= x;
  67864. x += dy;
  67865. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67866. }
  67867. protected:
  67868. const PixelARGB* const lookupTable;
  67869. const int numEntries;
  67870. const double gx1, gy1;
  67871. double maxDist, invScale, dy;
  67872. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67873. };
  67874. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67875. {
  67876. public:
  67877. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67878. const PixelARGB* const lookupTable_, const int numEntries_)
  67879. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67880. inverseTransform (transform.inverted())
  67881. {
  67882. tM10 = inverseTransform.mat10;
  67883. tM00 = inverseTransform.mat00;
  67884. }
  67885. forcedinline void setY (const int y) throw()
  67886. {
  67887. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67888. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67889. }
  67890. inline const PixelARGB getPixel (const int px) const throw()
  67891. {
  67892. double x = px;
  67893. const double y = tM10 * x + lineYM11;
  67894. x = tM00 * x + lineYM01;
  67895. x *= x;
  67896. x += y * y;
  67897. if (x >= maxDist)
  67898. return lookupTable [numEntries];
  67899. else
  67900. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67901. }
  67902. private:
  67903. double tM10, tM00, lineYM01, lineYM11;
  67904. const AffineTransform inverseTransform;
  67905. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67906. };
  67907. template <class PixelType, class GradientType>
  67908. class GradientEdgeTableRenderer : public GradientType
  67909. {
  67910. public:
  67911. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67912. const PixelARGB* const lookupTable_, const int numEntries_)
  67913. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67914. destData (destData_)
  67915. {
  67916. }
  67917. forcedinline void setEdgeTableYPos (const int y) throw()
  67918. {
  67919. linePixels = (PixelType*) destData.getLinePointer (y);
  67920. GradientType::setY (y);
  67921. }
  67922. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67923. {
  67924. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67925. }
  67926. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67927. {
  67928. linePixels[x].blend (GradientType::getPixel (x));
  67929. }
  67930. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67931. {
  67932. PixelType* dest = linePixels + x;
  67933. if (alphaLevel < 0xff)
  67934. {
  67935. do
  67936. {
  67937. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67938. } while (--width > 0);
  67939. }
  67940. else
  67941. {
  67942. do
  67943. {
  67944. (dest++)->blend (GradientType::getPixel (x++));
  67945. } while (--width > 0);
  67946. }
  67947. }
  67948. void handleEdgeTableLineFull (int x, int width) const throw()
  67949. {
  67950. PixelType* dest = linePixels + x;
  67951. do
  67952. {
  67953. (dest++)->blend (GradientType::getPixel (x++));
  67954. } while (--width > 0);
  67955. }
  67956. private:
  67957. const Image::BitmapData& destData;
  67958. PixelType* linePixels;
  67959. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67960. };
  67961. namespace RenderingHelpers
  67962. {
  67963. forcedinline int safeModulo (int n, const int divisor) throw()
  67964. {
  67965. jassert (divisor > 0);
  67966. n %= divisor;
  67967. return (n < 0) ? (n + divisor) : n;
  67968. }
  67969. }
  67970. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67971. class ImageFillEdgeTableRenderer
  67972. {
  67973. public:
  67974. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67975. const Image::BitmapData& srcData_,
  67976. const int extraAlpha_,
  67977. const int x, const int y)
  67978. : destData (destData_),
  67979. srcData (srcData_),
  67980. extraAlpha (extraAlpha_ + 1),
  67981. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67982. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67983. {
  67984. }
  67985. forcedinline void setEdgeTableYPos (int y) throw()
  67986. {
  67987. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67988. y -= yOffset;
  67989. if (repeatPattern)
  67990. {
  67991. jassert (y >= 0);
  67992. y %= srcData.height;
  67993. }
  67994. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67995. }
  67996. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67997. {
  67998. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67999. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  68000. }
  68001. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  68002. {
  68003. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  68004. }
  68005. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  68006. {
  68007. DestPixelType* dest = linePixels + x;
  68008. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  68009. x -= xOffset;
  68010. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68011. if (alphaLevel < 0xfe)
  68012. {
  68013. do
  68014. {
  68015. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  68016. } while (--width > 0);
  68017. }
  68018. else
  68019. {
  68020. if (repeatPattern)
  68021. {
  68022. do
  68023. {
  68024. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68025. } while (--width > 0);
  68026. }
  68027. else
  68028. {
  68029. copyRow (dest, sourceLineStart + x, width);
  68030. }
  68031. }
  68032. }
  68033. void handleEdgeTableLineFull (int x, int width) const throw()
  68034. {
  68035. DestPixelType* dest = linePixels + x;
  68036. x -= xOffset;
  68037. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68038. if (extraAlpha < 0xfe)
  68039. {
  68040. do
  68041. {
  68042. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  68043. } while (--width > 0);
  68044. }
  68045. else
  68046. {
  68047. if (repeatPattern)
  68048. {
  68049. do
  68050. {
  68051. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68052. } while (--width > 0);
  68053. }
  68054. else
  68055. {
  68056. copyRow (dest, sourceLineStart + x, width);
  68057. }
  68058. }
  68059. }
  68060. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  68061. {
  68062. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  68063. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  68064. uint8* mask = (uint8*) (s + x - xOffset);
  68065. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  68066. mask += PixelARGB::indexA;
  68067. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  68068. }
  68069. private:
  68070. const Image::BitmapData& destData;
  68071. const Image::BitmapData& srcData;
  68072. const int extraAlpha, xOffset, yOffset;
  68073. DestPixelType* linePixels;
  68074. SrcPixelType* sourceLineStart;
  68075. template <class PixelType1, class PixelType2>
  68076. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  68077. {
  68078. do
  68079. {
  68080. dest++ ->blend (*src++);
  68081. } while (--width > 0);
  68082. }
  68083. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  68084. {
  68085. memcpy (dest, src, width * sizeof (PixelRGB));
  68086. }
  68087. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  68088. };
  68089. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  68090. class TransformedImageFillEdgeTableRenderer
  68091. {
  68092. public:
  68093. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  68094. const Image::BitmapData& srcData_,
  68095. const AffineTransform& transform,
  68096. const int extraAlpha_,
  68097. const bool betterQuality_)
  68098. : interpolator (transform,
  68099. betterQuality_ ? 0.5f : 0.0f,
  68100. betterQuality_ ? -128 : 0),
  68101. destData (destData_),
  68102. srcData (srcData_),
  68103. extraAlpha (extraAlpha_ + 1),
  68104. betterQuality (betterQuality_),
  68105. maxX (srcData_.width - 1),
  68106. maxY (srcData_.height - 1),
  68107. scratchSize (2048)
  68108. {
  68109. scratchBuffer.malloc (scratchSize);
  68110. }
  68111. forcedinline void setEdgeTableYPos (const int newY) throw()
  68112. {
  68113. y = newY;
  68114. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  68115. }
  68116. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  68117. {
  68118. SrcPixelType p;
  68119. generate (&p, x, 1);
  68120. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  68121. }
  68122. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  68123. {
  68124. SrcPixelType p;
  68125. generate (&p, x, 1);
  68126. linePixels[x].blend (p, extraAlpha);
  68127. }
  68128. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  68129. {
  68130. if (width > scratchSize)
  68131. {
  68132. scratchSize = width;
  68133. scratchBuffer.malloc (scratchSize);
  68134. }
  68135. SrcPixelType* span = scratchBuffer;
  68136. generate (span, x, width);
  68137. DestPixelType* dest = linePixels + x;
  68138. alphaLevel *= extraAlpha;
  68139. alphaLevel >>= 8;
  68140. if (alphaLevel < 0xfe)
  68141. {
  68142. do
  68143. {
  68144. dest++ ->blend (*span++, alphaLevel);
  68145. } while (--width > 0);
  68146. }
  68147. else
  68148. {
  68149. do
  68150. {
  68151. dest++ ->blend (*span++);
  68152. } while (--width > 0);
  68153. }
  68154. }
  68155. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  68156. {
  68157. handleEdgeTableLine (x, width, 255);
  68158. }
  68159. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  68160. {
  68161. if (width > scratchSize)
  68162. {
  68163. scratchSize = width;
  68164. scratchBuffer.malloc (scratchSize);
  68165. }
  68166. y = y_;
  68167. generate (scratchBuffer.getData(), x, width);
  68168. et.clipLineToMask (x, y_,
  68169. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  68170. sizeof (SrcPixelType), width);
  68171. }
  68172. private:
  68173. template <class PixelType>
  68174. void generate (PixelType* dest, const int x, int numPixels) throw()
  68175. {
  68176. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  68177. do
  68178. {
  68179. int hiResX, hiResY;
  68180. this->interpolator.next (hiResX, hiResY);
  68181. int loResX = hiResX >> 8;
  68182. int loResY = hiResY >> 8;
  68183. if (repeatPattern)
  68184. {
  68185. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  68186. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  68187. }
  68188. if (betterQuality)
  68189. {
  68190. if (isPositiveAndBelow (loResX, maxX))
  68191. {
  68192. if (isPositiveAndBelow (loResY, maxY))
  68193. {
  68194. // In the centre of the image..
  68195. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  68196. hiResX & 255, hiResY & 255);
  68197. ++dest;
  68198. continue;
  68199. }
  68200. else
  68201. {
  68202. // At a top or bottom edge..
  68203. if (! repeatPattern)
  68204. {
  68205. if (loResY < 0)
  68206. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255);
  68207. else
  68208. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255);
  68209. ++dest;
  68210. continue;
  68211. }
  68212. }
  68213. }
  68214. else
  68215. {
  68216. if (isPositiveAndBelow (loResY, maxY))
  68217. {
  68218. // At a left or right hand edge..
  68219. if (! repeatPattern)
  68220. {
  68221. if (loResX < 0)
  68222. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255);
  68223. else
  68224. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255);
  68225. ++dest;
  68226. continue;
  68227. }
  68228. }
  68229. }
  68230. }
  68231. if (! repeatPattern)
  68232. {
  68233. if (loResX < 0) loResX = 0;
  68234. if (loResY < 0) loResY = 0;
  68235. if (loResX > maxX) loResX = maxX;
  68236. if (loResY > maxY) loResY = maxY;
  68237. }
  68238. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  68239. ++dest;
  68240. } while (--numPixels > 0);
  68241. }
  68242. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68243. {
  68244. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68245. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  68246. c[0] += weight * src[0];
  68247. c[1] += weight * src[1];
  68248. c[2] += weight * src[2];
  68249. c[3] += weight * src[3];
  68250. weight = subPixelX * (256 - subPixelY);
  68251. c[0] += weight * src[4];
  68252. c[1] += weight * src[5];
  68253. c[2] += weight * src[6];
  68254. c[3] += weight * src[7];
  68255. src += this->srcData.lineStride;
  68256. weight = (256 - subPixelX) * subPixelY;
  68257. c[0] += weight * src[0];
  68258. c[1] += weight * src[1];
  68259. c[2] += weight * src[2];
  68260. c[3] += weight * src[3];
  68261. weight = subPixelX * subPixelY;
  68262. c[0] += weight * src[4];
  68263. c[1] += weight * src[5];
  68264. c[2] += weight * src[6];
  68265. c[3] += weight * src[7];
  68266. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68267. (uint8) (c[PixelARGB::indexR] >> 16),
  68268. (uint8) (c[PixelARGB::indexG] >> 16),
  68269. (uint8) (c[PixelARGB::indexB] >> 16));
  68270. }
  68271. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX) throw()
  68272. {
  68273. uint32 c[4] = { 128, 128, 128, 128 };
  68274. uint32 weight = 256 - subPixelX;
  68275. c[0] += weight * src[0];
  68276. c[1] += weight * src[1];
  68277. c[2] += weight * src[2];
  68278. c[3] += weight * src[3];
  68279. weight = subPixelX;
  68280. c[0] += weight * src[4];
  68281. c[1] += weight * src[5];
  68282. c[2] += weight * src[6];
  68283. c[3] += weight * src[7];
  68284. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  68285. (uint8) (c[PixelARGB::indexR] >> 8),
  68286. (uint8) (c[PixelARGB::indexG] >> 8),
  68287. (uint8) (c[PixelARGB::indexB] >> 8));
  68288. }
  68289. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY) throw()
  68290. {
  68291. uint32 c[4] = { 128, 128, 128, 128 };
  68292. uint32 weight = 256 - subPixelY;
  68293. c[0] += weight * src[0];
  68294. c[1] += weight * src[1];
  68295. c[2] += weight * src[2];
  68296. c[3] += weight * src[3];
  68297. src += this->srcData.lineStride;
  68298. weight = subPixelY;
  68299. c[0] += weight * src[0];
  68300. c[1] += weight * src[1];
  68301. c[2] += weight * src[2];
  68302. c[3] += weight * src[3];
  68303. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  68304. (uint8) (c[PixelARGB::indexR] >> 8),
  68305. (uint8) (c[PixelARGB::indexG] >> 8),
  68306. (uint8) (c[PixelARGB::indexB] >> 8));
  68307. }
  68308. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68309. {
  68310. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68311. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  68312. c[0] += weight * src[0];
  68313. c[1] += weight * src[1];
  68314. c[2] += weight * src[2];
  68315. weight = subPixelX * (256 - subPixelY);
  68316. c[0] += weight * src[3];
  68317. c[1] += weight * src[4];
  68318. c[2] += weight * src[5];
  68319. src += this->srcData.lineStride;
  68320. weight = (256 - subPixelX) * subPixelY;
  68321. c[0] += weight * src[0];
  68322. c[1] += weight * src[1];
  68323. c[2] += weight * src[2];
  68324. weight = subPixelX * subPixelY;
  68325. c[0] += weight * src[3];
  68326. c[1] += weight * src[4];
  68327. c[2] += weight * src[5];
  68328. dest->setARGB ((uint8) 255,
  68329. (uint8) (c[PixelRGB::indexR] >> 16),
  68330. (uint8) (c[PixelRGB::indexG] >> 16),
  68331. (uint8) (c[PixelRGB::indexB] >> 16));
  68332. }
  68333. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX) throw()
  68334. {
  68335. uint32 c[3] = { 128, 128, 128 };
  68336. const uint32 weight = 256 - subPixelX;
  68337. c[0] += weight * src[0];
  68338. c[1] += weight * src[1];
  68339. c[2] += weight * src[2];
  68340. c[0] += subPixelX * src[3];
  68341. c[1] += subPixelX * src[4];
  68342. c[2] += subPixelX * src[5];
  68343. dest->setARGB ((uint8) 255,
  68344. (uint8) (c[PixelRGB::indexR] >> 8),
  68345. (uint8) (c[PixelRGB::indexG] >> 8),
  68346. (uint8) (c[PixelRGB::indexB] >> 8));
  68347. }
  68348. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY) throw()
  68349. {
  68350. uint32 c[3] = { 128, 128, 128 };
  68351. const uint32 weight = 256 - subPixelY;
  68352. c[0] += weight * src[0];
  68353. c[1] += weight * src[1];
  68354. c[2] += weight * src[2];
  68355. src += this->srcData.lineStride;
  68356. c[0] += subPixelY * src[0];
  68357. c[1] += subPixelY * src[1];
  68358. c[2] += subPixelY * src[2];
  68359. dest->setARGB ((uint8) 255,
  68360. (uint8) (c[PixelRGB::indexR] >> 8),
  68361. (uint8) (c[PixelRGB::indexG] >> 8),
  68362. (uint8) (c[PixelRGB::indexB] >> 8));
  68363. }
  68364. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68365. {
  68366. uint32 c = 256 * 128;
  68367. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  68368. c += src[1] * (subPixelX * (256 - subPixelY));
  68369. src += this->srcData.lineStride;
  68370. c += src[0] * ((256 - subPixelX) * subPixelY);
  68371. c += src[1] * (subPixelX * subPixelY);
  68372. *((uint8*) dest) = (uint8) (c >> 16);
  68373. }
  68374. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX) throw()
  68375. {
  68376. uint32 c = 128;
  68377. c += src[0] * (256 - subPixelX);
  68378. c += src[1] * subPixelX;
  68379. *((uint8*) dest) = (uint8) (c >> 8);
  68380. }
  68381. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY) throw()
  68382. {
  68383. uint32 c = 128;
  68384. c += src[0] * (256 - subPixelY);
  68385. src += this->srcData.lineStride;
  68386. c += src[0] * subPixelY;
  68387. *((uint8*) dest) = (uint8) (c >> 8);
  68388. }
  68389. class TransformedImageSpanInterpolator
  68390. {
  68391. public:
  68392. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  68393. : inverseTransform (transform.inverted()),
  68394. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  68395. {}
  68396. void setStartOfLine (float x, float y, const int numPixels) throw()
  68397. {
  68398. jassert (numPixels > 0);
  68399. x += pixelOffset;
  68400. y += pixelOffset;
  68401. float x1 = x, y1 = y;
  68402. x += numPixels;
  68403. inverseTransform.transformPoints (x1, y1, x, y);
  68404. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  68405. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  68406. }
  68407. void next (int& x, int& y) throw()
  68408. {
  68409. x = xBresenham.n;
  68410. xBresenham.stepToNext();
  68411. y = yBresenham.n;
  68412. yBresenham.stepToNext();
  68413. }
  68414. private:
  68415. class BresenhamInterpolator
  68416. {
  68417. public:
  68418. BresenhamInterpolator() throw() {}
  68419. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  68420. {
  68421. numSteps = numSteps_;
  68422. step = (n2 - n1) / numSteps;
  68423. remainder = modulo = (n2 - n1) % numSteps;
  68424. n = n1 + pixelOffsetInt;
  68425. if (modulo <= 0)
  68426. {
  68427. modulo += numSteps;
  68428. remainder += numSteps;
  68429. --step;
  68430. }
  68431. modulo -= numSteps;
  68432. }
  68433. forcedinline void stepToNext() throw()
  68434. {
  68435. modulo += remainder;
  68436. n += step;
  68437. if (modulo > 0)
  68438. {
  68439. modulo -= numSteps;
  68440. ++n;
  68441. }
  68442. }
  68443. int n;
  68444. private:
  68445. int numSteps, step, modulo, remainder;
  68446. };
  68447. const AffineTransform inverseTransform;
  68448. BresenhamInterpolator xBresenham, yBresenham;
  68449. const float pixelOffset;
  68450. const int pixelOffsetInt;
  68451. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  68452. };
  68453. TransformedImageSpanInterpolator interpolator;
  68454. const Image::BitmapData& destData;
  68455. const Image::BitmapData& srcData;
  68456. const int extraAlpha;
  68457. const bool betterQuality;
  68458. const int maxX, maxY;
  68459. int y;
  68460. DestPixelType* linePixels;
  68461. HeapBlock <SrcPixelType> scratchBuffer;
  68462. int scratchSize;
  68463. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68464. };
  68465. class ClipRegionBase : public ReferenceCountedObject
  68466. {
  68467. public:
  68468. ClipRegionBase() {}
  68469. virtual ~ClipRegionBase() {}
  68470. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68471. virtual const Ptr clone() const = 0;
  68472. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68473. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68474. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68475. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68476. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68477. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68478. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68479. virtual const Ptr translated (const Point<int>& delta) = 0;
  68480. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68481. virtual const Rectangle<int> getClipBounds() const = 0;
  68482. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68483. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68484. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68485. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68486. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68487. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68488. protected:
  68489. template <class Iterator>
  68490. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68491. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68492. {
  68493. switch (destData.pixelFormat)
  68494. {
  68495. case Image::ARGB:
  68496. switch (srcData.pixelFormat)
  68497. {
  68498. case Image::ARGB:
  68499. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68500. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68501. break;
  68502. case Image::RGB:
  68503. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68504. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68505. break;
  68506. default:
  68507. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68508. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68509. break;
  68510. }
  68511. break;
  68512. case Image::RGB:
  68513. switch (srcData.pixelFormat)
  68514. {
  68515. case Image::ARGB:
  68516. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68517. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68518. break;
  68519. case Image::RGB:
  68520. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68521. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68522. break;
  68523. default:
  68524. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68525. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68526. break;
  68527. }
  68528. break;
  68529. default:
  68530. switch (srcData.pixelFormat)
  68531. {
  68532. case Image::ARGB:
  68533. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68534. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68535. break;
  68536. case Image::RGB:
  68537. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68538. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68539. break;
  68540. default:
  68541. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68542. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68543. break;
  68544. }
  68545. break;
  68546. }
  68547. }
  68548. template <class Iterator>
  68549. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68550. {
  68551. switch (destData.pixelFormat)
  68552. {
  68553. case Image::ARGB:
  68554. switch (srcData.pixelFormat)
  68555. {
  68556. case Image::ARGB:
  68557. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68558. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68559. break;
  68560. case Image::RGB:
  68561. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68562. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68563. break;
  68564. default:
  68565. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68566. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68567. break;
  68568. }
  68569. break;
  68570. case Image::RGB:
  68571. switch (srcData.pixelFormat)
  68572. {
  68573. case Image::ARGB:
  68574. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68575. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68576. break;
  68577. case Image::RGB:
  68578. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68579. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68580. break;
  68581. default:
  68582. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68583. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68584. break;
  68585. }
  68586. break;
  68587. default:
  68588. switch (srcData.pixelFormat)
  68589. {
  68590. case Image::ARGB:
  68591. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68592. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68593. break;
  68594. case Image::RGB:
  68595. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68596. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68597. break;
  68598. default:
  68599. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68600. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68601. break;
  68602. }
  68603. break;
  68604. }
  68605. }
  68606. template <class Iterator, class DestPixelType>
  68607. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68608. {
  68609. jassert (destData.pixelStride == sizeof (DestPixelType));
  68610. if (replaceContents)
  68611. {
  68612. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68613. iter.iterate (r);
  68614. }
  68615. else
  68616. {
  68617. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68618. iter.iterate (r);
  68619. }
  68620. }
  68621. template <class Iterator, class DestPixelType>
  68622. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68623. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68624. {
  68625. jassert (destData.pixelStride == sizeof (DestPixelType));
  68626. if (g.isRadial)
  68627. {
  68628. if (isIdentity)
  68629. {
  68630. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68631. iter.iterate (renderer);
  68632. }
  68633. else
  68634. {
  68635. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68636. iter.iterate (renderer);
  68637. }
  68638. }
  68639. else
  68640. {
  68641. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68642. iter.iterate (renderer);
  68643. }
  68644. }
  68645. };
  68646. class ClipRegion_EdgeTable : public ClipRegionBase
  68647. {
  68648. public:
  68649. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68650. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68651. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68652. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68653. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68654. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68655. ~ClipRegion_EdgeTable() {}
  68656. const Ptr clone() const
  68657. {
  68658. return new ClipRegion_EdgeTable (*this);
  68659. }
  68660. const Ptr applyClipTo (const Ptr& target) const
  68661. {
  68662. return target->clipToEdgeTable (edgeTable);
  68663. }
  68664. const Ptr clipToRectangle (const Rectangle<int>& r)
  68665. {
  68666. edgeTable.clipToRectangle (r);
  68667. return edgeTable.isEmpty() ? 0 : this;
  68668. }
  68669. const Ptr clipToRectangleList (const RectangleList& r)
  68670. {
  68671. RectangleList inverse (edgeTable.getMaximumBounds());
  68672. if (inverse.subtract (r))
  68673. for (RectangleList::Iterator iter (inverse); iter.next();)
  68674. edgeTable.excludeRectangle (*iter.getRectangle());
  68675. return edgeTable.isEmpty() ? 0 : this;
  68676. }
  68677. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68678. {
  68679. edgeTable.excludeRectangle (r);
  68680. return edgeTable.isEmpty() ? 0 : this;
  68681. }
  68682. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68683. {
  68684. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68685. edgeTable.clipToEdgeTable (et);
  68686. return edgeTable.isEmpty() ? 0 : this;
  68687. }
  68688. const Ptr clipToEdgeTable (const EdgeTable& et)
  68689. {
  68690. edgeTable.clipToEdgeTable (et);
  68691. return edgeTable.isEmpty() ? 0 : this;
  68692. }
  68693. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68694. {
  68695. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  68696. if (transform.isOnlyTranslation())
  68697. {
  68698. // If our translation doesn't involve any distortion, just use a simple blit..
  68699. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68700. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68701. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68702. {
  68703. const int imageX = ((tx + 128) >> 8);
  68704. const int imageY = ((ty + 128) >> 8);
  68705. if (image.getFormat() == Image::ARGB)
  68706. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68707. else
  68708. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68709. return edgeTable.isEmpty() ? 0 : this;
  68710. }
  68711. }
  68712. if (transform.isSingularity())
  68713. return 0;
  68714. {
  68715. Path p;
  68716. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68717. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68718. edgeTable.clipToEdgeTable (et2);
  68719. }
  68720. if (! edgeTable.isEmpty())
  68721. {
  68722. if (image.getFormat() == Image::ARGB)
  68723. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68724. else
  68725. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68726. }
  68727. return edgeTable.isEmpty() ? 0 : this;
  68728. }
  68729. const Ptr translated (const Point<int>& delta)
  68730. {
  68731. edgeTable.translate ((float) delta.getX(), delta.getY());
  68732. return edgeTable.isEmpty() ? 0 : this;
  68733. }
  68734. bool clipRegionIntersects (const Rectangle<int>& r) const
  68735. {
  68736. return edgeTable.getMaximumBounds().intersects (r);
  68737. }
  68738. const Rectangle<int> getClipBounds() const
  68739. {
  68740. return edgeTable.getMaximumBounds();
  68741. }
  68742. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68743. {
  68744. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68745. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68746. if (! clipped.isEmpty())
  68747. {
  68748. ClipRegion_EdgeTable et (clipped);
  68749. et.edgeTable.clipToEdgeTable (edgeTable);
  68750. et.fillAllWithColour (destData, colour, replaceContents);
  68751. }
  68752. }
  68753. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68754. {
  68755. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68756. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68757. if (! clipped.isEmpty())
  68758. {
  68759. ClipRegion_EdgeTable et (clipped);
  68760. et.edgeTable.clipToEdgeTable (edgeTable);
  68761. et.fillAllWithColour (destData, colour, false);
  68762. }
  68763. }
  68764. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68765. {
  68766. switch (destData.pixelFormat)
  68767. {
  68768. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68769. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68770. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68771. }
  68772. }
  68773. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68774. {
  68775. HeapBlock <PixelARGB> lookupTable;
  68776. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68777. jassert (numLookupEntries > 0);
  68778. switch (destData.pixelFormat)
  68779. {
  68780. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68781. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68782. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68783. }
  68784. }
  68785. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68786. {
  68787. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68788. }
  68789. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68790. {
  68791. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68792. }
  68793. EdgeTable edgeTable;
  68794. private:
  68795. template <class SrcPixelType>
  68796. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68797. {
  68798. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68799. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68800. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68801. edgeTable.getMaximumBounds().getWidth());
  68802. }
  68803. template <class SrcPixelType>
  68804. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68805. {
  68806. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68807. edgeTable.clipToRectangle (r);
  68808. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68809. for (int y = 0; y < r.getHeight(); ++y)
  68810. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68811. }
  68812. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68813. };
  68814. class ClipRegion_RectangleList : public ClipRegionBase
  68815. {
  68816. public:
  68817. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68818. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68819. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68820. ~ClipRegion_RectangleList() {}
  68821. const Ptr clone() const
  68822. {
  68823. return new ClipRegion_RectangleList (*this);
  68824. }
  68825. const Ptr applyClipTo (const Ptr& target) const
  68826. {
  68827. return target->clipToRectangleList (clip);
  68828. }
  68829. const Ptr clipToRectangle (const Rectangle<int>& r)
  68830. {
  68831. clip.clipTo (r);
  68832. return clip.isEmpty() ? 0 : this;
  68833. }
  68834. const Ptr clipToRectangleList (const RectangleList& r)
  68835. {
  68836. clip.clipTo (r);
  68837. return clip.isEmpty() ? 0 : this;
  68838. }
  68839. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68840. {
  68841. clip.subtract (r);
  68842. return clip.isEmpty() ? 0 : this;
  68843. }
  68844. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68845. {
  68846. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68847. }
  68848. const Ptr clipToEdgeTable (const EdgeTable& et)
  68849. {
  68850. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68851. }
  68852. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68853. {
  68854. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68855. }
  68856. const Ptr translated (const Point<int>& delta)
  68857. {
  68858. clip.offsetAll (delta.getX(), delta.getY());
  68859. return clip.isEmpty() ? 0 : this;
  68860. }
  68861. bool clipRegionIntersects (const Rectangle<int>& r) const
  68862. {
  68863. return clip.intersects (r);
  68864. }
  68865. const Rectangle<int> getClipBounds() const
  68866. {
  68867. return clip.getBounds();
  68868. }
  68869. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68870. {
  68871. SubRectangleIterator iter (clip, area);
  68872. switch (destData.pixelFormat)
  68873. {
  68874. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68875. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68876. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68877. }
  68878. }
  68879. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68880. {
  68881. SubRectangleIteratorFloat iter (clip, area);
  68882. switch (destData.pixelFormat)
  68883. {
  68884. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68885. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68886. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68887. }
  68888. }
  68889. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68890. {
  68891. switch (destData.pixelFormat)
  68892. {
  68893. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68894. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68895. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68896. }
  68897. }
  68898. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68899. {
  68900. HeapBlock <PixelARGB> lookupTable;
  68901. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68902. jassert (numLookupEntries > 0);
  68903. switch (destData.pixelFormat)
  68904. {
  68905. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68906. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68907. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68908. }
  68909. }
  68910. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68911. {
  68912. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68913. }
  68914. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68915. {
  68916. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68917. }
  68918. RectangleList clip;
  68919. template <class Renderer>
  68920. void iterate (Renderer& r) const throw()
  68921. {
  68922. RectangleList::Iterator iter (clip);
  68923. while (iter.next())
  68924. {
  68925. const Rectangle<int> rect (*iter.getRectangle());
  68926. const int x = rect.getX();
  68927. const int w = rect.getWidth();
  68928. jassert (w > 0);
  68929. const int bottom = rect.getBottom();
  68930. for (int y = rect.getY(); y < bottom; ++y)
  68931. {
  68932. r.setEdgeTableYPos (y);
  68933. r.handleEdgeTableLineFull (x, w);
  68934. }
  68935. }
  68936. }
  68937. private:
  68938. class SubRectangleIterator
  68939. {
  68940. public:
  68941. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68942. : clip (clip_), area (area_)
  68943. {
  68944. }
  68945. template <class Renderer>
  68946. void iterate (Renderer& r) const throw()
  68947. {
  68948. RectangleList::Iterator iter (clip);
  68949. while (iter.next())
  68950. {
  68951. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68952. if (! rect.isEmpty())
  68953. {
  68954. const int x = rect.getX();
  68955. const int w = rect.getWidth();
  68956. const int bottom = rect.getBottom();
  68957. for (int y = rect.getY(); y < bottom; ++y)
  68958. {
  68959. r.setEdgeTableYPos (y);
  68960. r.handleEdgeTableLineFull (x, w);
  68961. }
  68962. }
  68963. }
  68964. }
  68965. private:
  68966. const RectangleList& clip;
  68967. const Rectangle<int> area;
  68968. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68969. };
  68970. class SubRectangleIteratorFloat
  68971. {
  68972. public:
  68973. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68974. : clip (clip_), area (area_)
  68975. {
  68976. }
  68977. template <class Renderer>
  68978. void iterate (Renderer& r) const throw()
  68979. {
  68980. int left = roundToInt (area.getX() * 256.0f);
  68981. int top = roundToInt (area.getY() * 256.0f);
  68982. int right = roundToInt (area.getRight() * 256.0f);
  68983. int bottom = roundToInt (area.getBottom() * 256.0f);
  68984. int totalTop, totalLeft, totalBottom, totalRight;
  68985. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68986. if ((top >> 8) == (bottom >> 8))
  68987. {
  68988. topAlpha = bottom - top;
  68989. bottomAlpha = 0;
  68990. totalTop = top >> 8;
  68991. totalBottom = bottom = top = totalTop + 1;
  68992. }
  68993. else
  68994. {
  68995. if ((top & 255) == 0)
  68996. {
  68997. topAlpha = 0;
  68998. top = totalTop = (top >> 8);
  68999. }
  69000. else
  69001. {
  69002. topAlpha = 255 - (top & 255);
  69003. totalTop = (top >> 8);
  69004. top = totalTop + 1;
  69005. }
  69006. bottomAlpha = bottom & 255;
  69007. bottom >>= 8;
  69008. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  69009. }
  69010. if ((left >> 8) == (right >> 8))
  69011. {
  69012. leftAlpha = right - left;
  69013. rightAlpha = 0;
  69014. totalLeft = (left >> 8);
  69015. totalRight = right = left = totalLeft + 1;
  69016. }
  69017. else
  69018. {
  69019. if ((left & 255) == 0)
  69020. {
  69021. leftAlpha = 0;
  69022. left = totalLeft = (left >> 8);
  69023. }
  69024. else
  69025. {
  69026. leftAlpha = 255 - (left & 255);
  69027. totalLeft = (left >> 8);
  69028. left = totalLeft + 1;
  69029. }
  69030. rightAlpha = right & 255;
  69031. right >>= 8;
  69032. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  69033. }
  69034. RectangleList::Iterator iter (clip);
  69035. while (iter.next())
  69036. {
  69037. const int clipLeft = iter.getRectangle()->getX();
  69038. const int clipRight = iter.getRectangle()->getRight();
  69039. const int clipTop = iter.getRectangle()->getY();
  69040. const int clipBottom = iter.getRectangle()->getBottom();
  69041. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  69042. {
  69043. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  69044. {
  69045. if (topAlpha != 0 && totalTop >= clipTop)
  69046. {
  69047. r.setEdgeTableYPos (totalTop);
  69048. r.handleEdgeTablePixel (left, topAlpha);
  69049. }
  69050. const int endY = jmin (bottom, clipBottom);
  69051. for (int y = jmax (clipTop, top); y < endY; ++y)
  69052. {
  69053. r.setEdgeTableYPos (y);
  69054. r.handleEdgeTablePixelFull (left);
  69055. }
  69056. if (bottomAlpha != 0 && bottom < clipBottom)
  69057. {
  69058. r.setEdgeTableYPos (bottom);
  69059. r.handleEdgeTablePixel (left, bottomAlpha);
  69060. }
  69061. }
  69062. else
  69063. {
  69064. const int clippedLeft = jmax (left, clipLeft);
  69065. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  69066. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  69067. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  69068. if (topAlpha != 0 && totalTop >= clipTop)
  69069. {
  69070. r.setEdgeTableYPos (totalTop);
  69071. if (doLeftAlpha)
  69072. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  69073. if (clippedWidth > 0)
  69074. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  69075. if (doRightAlpha)
  69076. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  69077. }
  69078. const int endY = jmin (bottom, clipBottom);
  69079. for (int y = jmax (clipTop, top); y < endY; ++y)
  69080. {
  69081. r.setEdgeTableYPos (y);
  69082. if (doLeftAlpha)
  69083. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  69084. if (clippedWidth > 0)
  69085. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  69086. if (doRightAlpha)
  69087. r.handleEdgeTablePixel (right, rightAlpha);
  69088. }
  69089. if (bottomAlpha != 0 && bottom < clipBottom)
  69090. {
  69091. r.setEdgeTableYPos (bottom);
  69092. if (doLeftAlpha)
  69093. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  69094. if (clippedWidth > 0)
  69095. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  69096. if (doRightAlpha)
  69097. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  69098. }
  69099. }
  69100. }
  69101. }
  69102. }
  69103. private:
  69104. const RectangleList& clip;
  69105. const Rectangle<float>& area;
  69106. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  69107. };
  69108. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  69109. };
  69110. }
  69111. class LowLevelGraphicsSoftwareRenderer::SavedState
  69112. {
  69113. public:
  69114. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  69115. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69116. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  69117. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  69118. {
  69119. }
  69120. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  69121. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69122. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  69123. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  69124. {
  69125. }
  69126. SavedState (const SavedState& other)
  69127. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  69128. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  69129. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  69130. interpolationQuality (other.interpolationQuality)
  69131. {
  69132. }
  69133. void setOrigin (const int x, const int y) throw()
  69134. {
  69135. if (isOnlyTranslated)
  69136. {
  69137. xOffset += x;
  69138. yOffset += y;
  69139. }
  69140. else
  69141. {
  69142. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  69143. }
  69144. }
  69145. void addTransform (const AffineTransform& t)
  69146. {
  69147. if ((! isOnlyTranslated)
  69148. || (! t.isOnlyTranslation())
  69149. || (int) (t.getTranslationX() * 256.0f) != 0
  69150. || (int) (t.getTranslationY() * 256.0f) != 0)
  69151. {
  69152. complexTransform = getTransformWith (t);
  69153. isOnlyTranslated = false;
  69154. }
  69155. else
  69156. {
  69157. xOffset += (int) t.getTranslationX();
  69158. yOffset += (int) t.getTranslationY();
  69159. }
  69160. }
  69161. float getScaleFactor() const
  69162. {
  69163. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  69164. }
  69165. bool clipToRectangle (const Rectangle<int>& r)
  69166. {
  69167. if (clip != 0)
  69168. {
  69169. if (isOnlyTranslated)
  69170. {
  69171. cloneClipIfMultiplyReferenced();
  69172. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  69173. }
  69174. else
  69175. {
  69176. Path p;
  69177. p.addRectangle (r);
  69178. clipToPath (p, AffineTransform::identity);
  69179. }
  69180. }
  69181. return clip != 0;
  69182. }
  69183. bool clipToRectangleList (const RectangleList& r)
  69184. {
  69185. if (clip != 0)
  69186. {
  69187. if (isOnlyTranslated)
  69188. {
  69189. cloneClipIfMultiplyReferenced();
  69190. RectangleList offsetList (r);
  69191. offsetList.offsetAll (xOffset, yOffset);
  69192. clip = clip->clipToRectangleList (offsetList);
  69193. }
  69194. else
  69195. {
  69196. clipToPath (r.toPath(), AffineTransform::identity);
  69197. }
  69198. }
  69199. return clip != 0;
  69200. }
  69201. bool excludeClipRectangle (const Rectangle<int>& r)
  69202. {
  69203. if (clip != 0)
  69204. {
  69205. cloneClipIfMultiplyReferenced();
  69206. if (isOnlyTranslated)
  69207. {
  69208. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  69209. }
  69210. else
  69211. {
  69212. Path p;
  69213. p.addRectangle (r.toFloat());
  69214. p.applyTransform (complexTransform);
  69215. p.addRectangle (clip->getClipBounds().toFloat());
  69216. p.setUsingNonZeroWinding (false);
  69217. clip = clip->clipToPath (p, AffineTransform::identity);
  69218. }
  69219. }
  69220. return clip != 0;
  69221. }
  69222. void clipToPath (const Path& p, const AffineTransform& transform)
  69223. {
  69224. if (clip != 0)
  69225. {
  69226. cloneClipIfMultiplyReferenced();
  69227. clip = clip->clipToPath (p, getTransformWith (transform));
  69228. }
  69229. }
  69230. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  69231. {
  69232. if (clip != 0)
  69233. {
  69234. if (sourceImage.hasAlphaChannel())
  69235. {
  69236. cloneClipIfMultiplyReferenced();
  69237. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  69238. interpolationQuality != Graphics::lowResamplingQuality);
  69239. }
  69240. else
  69241. {
  69242. Path p;
  69243. p.addRectangle (sourceImage.getBounds());
  69244. clipToPath (p, t);
  69245. }
  69246. }
  69247. }
  69248. bool clipRegionIntersects (const Rectangle<int>& r) const
  69249. {
  69250. if (clip != 0)
  69251. {
  69252. if (isOnlyTranslated)
  69253. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  69254. else
  69255. return getClipBounds().intersects (r);
  69256. }
  69257. return false;
  69258. }
  69259. const Rectangle<int> getUntransformedClipBounds() const
  69260. {
  69261. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  69262. }
  69263. const Rectangle<int> getClipBounds() const
  69264. {
  69265. if (clip != 0)
  69266. {
  69267. if (isOnlyTranslated)
  69268. return clip->getClipBounds().translated (-xOffset, -yOffset);
  69269. else
  69270. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  69271. }
  69272. return Rectangle<int>();
  69273. }
  69274. SavedState* beginTransparencyLayer (float opacity)
  69275. {
  69276. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  69277. SavedState* s = new SavedState (*this);
  69278. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  69279. s->compositionAlpha = opacity;
  69280. if (s->isOnlyTranslated)
  69281. {
  69282. s->xOffset -= layerBounds.getX();
  69283. s->yOffset -= layerBounds.getY();
  69284. }
  69285. else
  69286. {
  69287. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  69288. (float) -layerBounds.getY()));
  69289. }
  69290. s->cloneClipIfMultiplyReferenced();
  69291. s->clip = s->clip->translated (-layerBounds.getPosition());
  69292. return s;
  69293. }
  69294. void endTransparencyLayer (SavedState& layerState)
  69295. {
  69296. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  69297. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  69298. g->setOpacity (layerState.compositionAlpha);
  69299. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  69300. (float) layerBounds.getY()), false);
  69301. }
  69302. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  69303. {
  69304. if (clip != 0)
  69305. {
  69306. if (isOnlyTranslated)
  69307. {
  69308. if (fillType.isColour())
  69309. {
  69310. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69311. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  69312. }
  69313. else
  69314. {
  69315. const Rectangle<int> totalClip (clip->getClipBounds());
  69316. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  69317. if (! clipped.isEmpty())
  69318. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  69319. }
  69320. }
  69321. else
  69322. {
  69323. Path p;
  69324. p.addRectangle (r);
  69325. fillPath (p, AffineTransform::identity);
  69326. }
  69327. }
  69328. }
  69329. void fillRect (const Rectangle<float>& r)
  69330. {
  69331. if (clip != 0)
  69332. {
  69333. if (isOnlyTranslated)
  69334. {
  69335. if (fillType.isColour())
  69336. {
  69337. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69338. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  69339. }
  69340. else
  69341. {
  69342. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69343. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69344. if (! clipped.isEmpty())
  69345. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69346. }
  69347. }
  69348. else
  69349. {
  69350. Path p;
  69351. p.addRectangle (r);
  69352. fillPath (p, AffineTransform::identity);
  69353. }
  69354. }
  69355. }
  69356. void fillPath (const Path& path, const AffineTransform& transform)
  69357. {
  69358. if (clip != 0)
  69359. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  69360. }
  69361. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  69362. {
  69363. jassert (isOnlyTranslated);
  69364. if (clip != 0)
  69365. {
  69366. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69367. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69368. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69369. fillShape (shapeToFill, false);
  69370. }
  69371. }
  69372. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69373. {
  69374. jassert (clip != 0);
  69375. shapeToFill = clip->applyClipTo (shapeToFill);
  69376. if (shapeToFill != 0)
  69377. {
  69378. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69379. if (fillType.isGradient())
  69380. {
  69381. jassert (! replaceContents); // that option is just for solid colours
  69382. ColourGradient g2 (*(fillType.gradient));
  69383. g2.multiplyOpacity (fillType.getOpacity());
  69384. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  69385. const bool isIdentity = transform.isOnlyTranslation();
  69386. if (isIdentity)
  69387. {
  69388. // If our translation doesn't involve any distortion, we can speed it up..
  69389. g2.point1.applyTransform (transform);
  69390. g2.point2.applyTransform (transform);
  69391. transform = AffineTransform::identity;
  69392. }
  69393. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69394. }
  69395. else if (fillType.isTiledImage())
  69396. {
  69397. renderImage (fillType.image, fillType.transform, shapeToFill);
  69398. }
  69399. else
  69400. {
  69401. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69402. }
  69403. }
  69404. }
  69405. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69406. {
  69407. const AffineTransform transform (getTransformWith (t));
  69408. const Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69409. const Image::BitmapData srcData (sourceImage, Image::BitmapData::readOnly);
  69410. const int alpha = fillType.colour.getAlpha();
  69411. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69412. if (transform.isOnlyTranslation())
  69413. {
  69414. // If our translation doesn't involve any distortion, just use a simple blit..
  69415. int tx = (int) (transform.getTranslationX() * 256.0f);
  69416. int ty = (int) (transform.getTranslationY() * 256.0f);
  69417. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69418. {
  69419. tx = ((tx + 128) >> 8);
  69420. ty = ((ty + 128) >> 8);
  69421. if (tiledFillClipRegion != 0)
  69422. {
  69423. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69424. }
  69425. else
  69426. {
  69427. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  69428. c = clip->applyClipTo (c);
  69429. if (c != 0)
  69430. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69431. }
  69432. return;
  69433. }
  69434. }
  69435. if (transform.isSingularity())
  69436. return;
  69437. if (tiledFillClipRegion != 0)
  69438. {
  69439. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69440. }
  69441. else
  69442. {
  69443. Path p;
  69444. p.addRectangle (sourceImage.getBounds());
  69445. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69446. c = c->clipToPath (p, transform);
  69447. if (c != 0)
  69448. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69449. }
  69450. }
  69451. Image image;
  69452. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69453. private:
  69454. AffineTransform complexTransform;
  69455. int xOffset, yOffset;
  69456. float compositionAlpha;
  69457. public:
  69458. bool isOnlyTranslated;
  69459. Font font;
  69460. FillType fillType;
  69461. Graphics::ResamplingQuality interpolationQuality;
  69462. private:
  69463. void cloneClipIfMultiplyReferenced()
  69464. {
  69465. if (clip->getReferenceCount() > 1)
  69466. clip = clip->clone();
  69467. }
  69468. const AffineTransform getTransform() const
  69469. {
  69470. if (isOnlyTranslated)
  69471. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69472. return complexTransform;
  69473. }
  69474. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69475. {
  69476. if (isOnlyTranslated)
  69477. return userTransform.translated ((float) xOffset, (float) yOffset);
  69478. return userTransform.followedBy (complexTransform);
  69479. }
  69480. SavedState& operator= (const SavedState&);
  69481. };
  69482. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69483. : image (image_),
  69484. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69485. {
  69486. }
  69487. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69488. const RectangleList& initialClip)
  69489. : image (image_),
  69490. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69491. {
  69492. }
  69493. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69494. {
  69495. }
  69496. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69497. {
  69498. return false;
  69499. }
  69500. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69501. {
  69502. currentState->setOrigin (x, y);
  69503. }
  69504. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69505. {
  69506. currentState->addTransform (transform);
  69507. }
  69508. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69509. {
  69510. return currentState->getScaleFactor();
  69511. }
  69512. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69513. {
  69514. return currentState->clipToRectangle (r);
  69515. }
  69516. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69517. {
  69518. return currentState->clipToRectangleList (clipRegion);
  69519. }
  69520. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69521. {
  69522. currentState->excludeClipRectangle (r);
  69523. }
  69524. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69525. {
  69526. currentState->clipToPath (path, transform);
  69527. }
  69528. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69529. {
  69530. currentState->clipToImageAlpha (sourceImage, transform);
  69531. }
  69532. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69533. {
  69534. return currentState->clipRegionIntersects (r);
  69535. }
  69536. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69537. {
  69538. return currentState->getClipBounds();
  69539. }
  69540. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69541. {
  69542. return currentState->clip == 0;
  69543. }
  69544. void LowLevelGraphicsSoftwareRenderer::saveState()
  69545. {
  69546. stateStack.add (new SavedState (*currentState));
  69547. }
  69548. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69549. {
  69550. SavedState* const top = stateStack.getLast();
  69551. if (top != 0)
  69552. {
  69553. currentState = top;
  69554. stateStack.removeLast (1, false);
  69555. }
  69556. else
  69557. {
  69558. jassertfalse; // trying to pop with an empty stack!
  69559. }
  69560. }
  69561. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69562. {
  69563. saveState();
  69564. currentState = currentState->beginTransparencyLayer (opacity);
  69565. }
  69566. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69567. {
  69568. const ScopedPointer<SavedState> layer (currentState);
  69569. restoreState();
  69570. currentState->endTransparencyLayer (*layer);
  69571. }
  69572. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69573. {
  69574. currentState->fillType = fillType;
  69575. }
  69576. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69577. {
  69578. currentState->fillType.setOpacity (newOpacity);
  69579. }
  69580. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69581. {
  69582. currentState->interpolationQuality = quality;
  69583. }
  69584. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69585. {
  69586. currentState->fillRect (r, replaceExistingContents);
  69587. }
  69588. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69589. {
  69590. currentState->fillPath (path, transform);
  69591. }
  69592. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69593. {
  69594. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69595. }
  69596. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69597. {
  69598. Path p;
  69599. p.addLineSegment (line, 1.0f);
  69600. fillPath (p, AffineTransform::identity);
  69601. }
  69602. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69603. {
  69604. if (bottom > top)
  69605. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69606. }
  69607. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69608. {
  69609. if (right > left)
  69610. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69611. }
  69612. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69613. {
  69614. public:
  69615. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69616. void draw (SavedState& state, float x, const float y) const
  69617. {
  69618. if (snapToIntegerCoordinate)
  69619. x = std::floor (x + 0.5f);
  69620. if (edgeTable != 0)
  69621. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69622. }
  69623. void generate (const Font& newFont, const int glyphNumber)
  69624. {
  69625. font = newFont;
  69626. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69627. glyph = glyphNumber;
  69628. edgeTable = 0;
  69629. Path glyphPath;
  69630. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69631. if (! glyphPath.isEmpty())
  69632. {
  69633. const float fontHeight = font.getHeight();
  69634. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69635. #if JUCE_MAC || JUCE_IOS
  69636. .translated (0.0f, -0.5f)
  69637. #endif
  69638. );
  69639. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69640. glyphPath, transform);
  69641. }
  69642. }
  69643. Font font;
  69644. int glyph, lastAccessCount;
  69645. bool snapToIntegerCoordinate;
  69646. private:
  69647. ScopedPointer <EdgeTable> edgeTable;
  69648. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69649. };
  69650. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69651. {
  69652. public:
  69653. GlyphCache()
  69654. : accessCounter (0), hits (0), misses (0)
  69655. {
  69656. addNewGlyphSlots (120);
  69657. }
  69658. ~GlyphCache()
  69659. {
  69660. clearSingletonInstance();
  69661. }
  69662. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69663. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69664. {
  69665. ++accessCounter;
  69666. int oldestCounter = std::numeric_limits<int>::max();
  69667. CachedGlyph* oldest = 0;
  69668. for (int i = glyphs.size(); --i >= 0;)
  69669. {
  69670. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69671. if (glyph->glyph == glyphNumber && glyph->font == font)
  69672. {
  69673. ++hits;
  69674. glyph->lastAccessCount = accessCounter;
  69675. glyph->draw (state, x, y);
  69676. return;
  69677. }
  69678. if (glyph->lastAccessCount <= oldestCounter)
  69679. {
  69680. oldestCounter = glyph->lastAccessCount;
  69681. oldest = glyph;
  69682. }
  69683. }
  69684. if (hits + ++misses > (glyphs.size() << 4))
  69685. {
  69686. if (misses * 2 > hits)
  69687. addNewGlyphSlots (32);
  69688. hits = misses = 0;
  69689. oldest = glyphs.getLast();
  69690. }
  69691. jassert (oldest != 0);
  69692. oldest->lastAccessCount = accessCounter;
  69693. oldest->generate (font, glyphNumber);
  69694. oldest->draw (state, x, y);
  69695. }
  69696. private:
  69697. friend class OwnedArray <CachedGlyph>;
  69698. OwnedArray <CachedGlyph> glyphs;
  69699. int accessCounter, hits, misses;
  69700. void addNewGlyphSlots (int num)
  69701. {
  69702. while (--num >= 0)
  69703. glyphs.add (new CachedGlyph());
  69704. }
  69705. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69706. };
  69707. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69708. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69709. {
  69710. currentState->font = newFont;
  69711. }
  69712. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69713. {
  69714. return currentState->font;
  69715. }
  69716. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69717. {
  69718. Font& f = currentState->font;
  69719. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69720. {
  69721. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69722. transform.getTranslationX(),
  69723. transform.getTranslationY());
  69724. }
  69725. else
  69726. {
  69727. Path p;
  69728. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69729. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69730. }
  69731. }
  69732. #if JUCE_MSVC
  69733. #pragma warning (pop)
  69734. #if JUCE_DEBUG
  69735. #pragma optimize ("", on) // resets optimisations to the project defaults
  69736. #endif
  69737. #endif
  69738. END_JUCE_NAMESPACE
  69739. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69740. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69741. BEGIN_JUCE_NAMESPACE
  69742. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69743. : flags (other.flags)
  69744. {
  69745. }
  69746. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69747. {
  69748. flags = other.flags;
  69749. return *this;
  69750. }
  69751. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69752. const double dx, const double dy, const double dw, const double dh) const throw()
  69753. {
  69754. if (w == 0 || h == 0)
  69755. return;
  69756. if ((flags & stretchToFit) != 0)
  69757. {
  69758. x = dx;
  69759. y = dy;
  69760. w = dw;
  69761. h = dh;
  69762. }
  69763. else
  69764. {
  69765. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69766. : jmin (dw / w, dh / h);
  69767. if ((flags & onlyReduceInSize) != 0)
  69768. scale = jmin (scale, 1.0);
  69769. if ((flags & onlyIncreaseInSize) != 0)
  69770. scale = jmax (scale, 1.0);
  69771. w *= scale;
  69772. h *= scale;
  69773. if ((flags & xLeft) != 0)
  69774. x = dx;
  69775. else if ((flags & xRight) != 0)
  69776. x = dx + dw - w;
  69777. else
  69778. x = dx + (dw - w) * 0.5;
  69779. if ((flags & yTop) != 0)
  69780. y = dy;
  69781. else if ((flags & yBottom) != 0)
  69782. y = dy + dh - h;
  69783. else
  69784. y = dy + (dh - h) * 0.5;
  69785. }
  69786. }
  69787. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69788. {
  69789. if (source.isEmpty())
  69790. return AffineTransform::identity;
  69791. float newX = destination.getX();
  69792. float newY = destination.getY();
  69793. float scaleX = destination.getWidth() / source.getWidth();
  69794. float scaleY = destination.getHeight() / source.getHeight();
  69795. if ((flags & stretchToFit) == 0)
  69796. {
  69797. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69798. : jmin (scaleX, scaleY);
  69799. if ((flags & onlyReduceInSize) != 0)
  69800. scaleX = jmin (scaleX, 1.0f);
  69801. if ((flags & onlyIncreaseInSize) != 0)
  69802. scaleX = jmax (scaleX, 1.0f);
  69803. scaleY = scaleX;
  69804. if ((flags & xRight) != 0)
  69805. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69806. else if ((flags & xLeft) == 0)
  69807. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69808. if ((flags & yBottom) != 0)
  69809. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69810. else if ((flags & yTop) == 0)
  69811. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69812. }
  69813. return AffineTransform::translation (-source.getX(), -source.getY())
  69814. .scaled (scaleX, scaleY)
  69815. .translated (newX, newY);
  69816. }
  69817. END_JUCE_NAMESPACE
  69818. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69819. /*** Start of inlined file: juce_Drawable.cpp ***/
  69820. BEGIN_JUCE_NAMESPACE
  69821. Drawable::Drawable()
  69822. {
  69823. setInterceptsMouseClicks (false, false);
  69824. setPaintingIsUnclipped (true);
  69825. }
  69826. Drawable::~Drawable()
  69827. {
  69828. }
  69829. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69830. {
  69831. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69832. }
  69833. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69834. {
  69835. Graphics::ScopedSaveState ss (g);
  69836. const float oldOpacity = getAlpha();
  69837. setAlpha (opacity);
  69838. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69839. (float) -originRelativeToComponent.getY())
  69840. .followedBy (getTransform())
  69841. .followedBy (transform));
  69842. if (! g.isClipEmpty())
  69843. paintEntireComponent (g, false);
  69844. setAlpha (oldOpacity);
  69845. }
  69846. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69847. {
  69848. draw (g, opacity, AffineTransform::translation (x, y));
  69849. }
  69850. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69851. {
  69852. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69853. }
  69854. DrawableComposite* Drawable::getParent() const
  69855. {
  69856. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69857. }
  69858. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69859. {
  69860. g.setOrigin (originRelativeToComponent.getX(),
  69861. originRelativeToComponent.getY());
  69862. }
  69863. void Drawable::parentHierarchyChanged()
  69864. {
  69865. setBoundsToEnclose (getDrawableBounds());
  69866. }
  69867. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69868. {
  69869. Drawable* const parent = getParent();
  69870. Point<int> parentOrigin;
  69871. if (parent != 0)
  69872. parentOrigin = parent->originRelativeToComponent;
  69873. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69874. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69875. setBounds (newBounds);
  69876. }
  69877. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69878. {
  69879. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69880. }
  69881. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69882. {
  69883. if (! area.isEmpty())
  69884. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69885. }
  69886. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69887. {
  69888. Drawable* result = 0;
  69889. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69890. if (image.isValid())
  69891. {
  69892. DrawableImage* const di = new DrawableImage();
  69893. di->setImage (image);
  69894. result = di;
  69895. }
  69896. else
  69897. {
  69898. const String asString (String::createStringFromData (data, (int) numBytes));
  69899. XmlDocument doc (asString);
  69900. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69901. if (outer != 0 && outer->hasTagName ("svg"))
  69902. {
  69903. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69904. if (svg != 0)
  69905. result = Drawable::createFromSVG (*svg);
  69906. }
  69907. }
  69908. return result;
  69909. }
  69910. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69911. {
  69912. MemoryOutputStream mo;
  69913. mo.writeFromInputStream (dataSource, -1);
  69914. return createFromImageData (mo.getData(), mo.getDataSize());
  69915. }
  69916. Drawable* Drawable::createFromImageFile (const File& file)
  69917. {
  69918. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69919. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69920. }
  69921. template <class DrawableClass>
  69922. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69923. {
  69924. public:
  69925. DrawableTypeHandler()
  69926. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69927. {
  69928. }
  69929. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69930. {
  69931. DrawableClass* const d = new DrawableClass();
  69932. if (parent != 0)
  69933. parent->addAndMakeVisible (d);
  69934. updateComponentFromState (d, state);
  69935. return d;
  69936. }
  69937. void updateComponentFromState (Component* component, const ValueTree& state)
  69938. {
  69939. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69940. jassert (d != 0);
  69941. d->refreshFromValueTree (state, *this->getBuilder());
  69942. }
  69943. };
  69944. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69945. {
  69946. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69947. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69948. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69949. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69950. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69951. }
  69952. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69953. {
  69954. ComponentBuilder builder (tree);
  69955. builder.setImageProvider (imageProvider);
  69956. registerDrawableTypeHandlers (builder);
  69957. ScopedPointer<Component> comp (builder.createComponent());
  69958. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69959. if (d != 0)
  69960. comp.release();
  69961. return d;
  69962. }
  69963. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69964. : state (state_)
  69965. {
  69966. }
  69967. const String Drawable::ValueTreeWrapperBase::getID() const
  69968. {
  69969. return state [ComponentBuilder::idProperty];
  69970. }
  69971. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69972. {
  69973. if (newID.isEmpty())
  69974. state.removeProperty (ComponentBuilder::idProperty, 0);
  69975. else
  69976. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69977. }
  69978. END_JUCE_NAMESPACE
  69979. /*** End of inlined file: juce_Drawable.cpp ***/
  69980. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69981. BEGIN_JUCE_NAMESPACE
  69982. DrawableShape::DrawableShape()
  69983. : strokeType (0.0f),
  69984. mainFill (Colours::black),
  69985. strokeFill (Colours::black)
  69986. {
  69987. }
  69988. DrawableShape::DrawableShape (const DrawableShape& other)
  69989. : strokeType (other.strokeType),
  69990. mainFill (other.mainFill),
  69991. strokeFill (other.strokeFill)
  69992. {
  69993. }
  69994. DrawableShape::~DrawableShape()
  69995. {
  69996. }
  69997. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69998. {
  69999. public:
  70000. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  70001. : RelativeCoordinatePositionerBase (component_),
  70002. owner (component_),
  70003. fill (fill_),
  70004. isMainFill (isMainFill_)
  70005. {
  70006. }
  70007. bool registerCoordinates()
  70008. {
  70009. bool ok = addPoint (fill.gradientPoint1);
  70010. ok = addPoint (fill.gradientPoint2) && ok;
  70011. return addPoint (fill.gradientPoint3) && ok;
  70012. }
  70013. void applyToComponentBounds()
  70014. {
  70015. ComponentScope scope (owner);
  70016. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  70017. : owner.strokeFill.recalculateCoords (&scope))
  70018. owner.repaint();
  70019. }
  70020. void applyNewBounds (const Rectangle<int>&)
  70021. {
  70022. jassertfalse; // drawables can't be resized directly!
  70023. }
  70024. private:
  70025. DrawableShape& owner;
  70026. const DrawableShape::RelativeFillType fill;
  70027. const bool isMainFill;
  70028. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70029. };
  70030. void DrawableShape::setFill (const FillType& newFill)
  70031. {
  70032. setFill (RelativeFillType (newFill));
  70033. }
  70034. void DrawableShape::setStrokeFill (const FillType& newFill)
  70035. {
  70036. setStrokeFill (RelativeFillType (newFill));
  70037. }
  70038. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  70039. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  70040. {
  70041. if (fill != newFill)
  70042. {
  70043. fill = newFill;
  70044. positioner = 0;
  70045. if (fill.isDynamic())
  70046. {
  70047. positioner = new RelativePositioner (*this, fill, true);
  70048. positioner->apply();
  70049. }
  70050. else
  70051. {
  70052. fill.recalculateCoords (0);
  70053. }
  70054. repaint();
  70055. }
  70056. }
  70057. void DrawableShape::setFill (const RelativeFillType& newFill)
  70058. {
  70059. setFillInternal (mainFill, newFill, mainFillPositioner);
  70060. }
  70061. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  70062. {
  70063. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  70064. }
  70065. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  70066. {
  70067. if (strokeType != newStrokeType)
  70068. {
  70069. strokeType = newStrokeType;
  70070. strokeChanged();
  70071. }
  70072. }
  70073. void DrawableShape::setStrokeThickness (const float newThickness)
  70074. {
  70075. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70076. }
  70077. bool DrawableShape::isStrokeVisible() const throw()
  70078. {
  70079. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  70080. }
  70081. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  70082. {
  70083. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  70084. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  70085. }
  70086. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  70087. {
  70088. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  70089. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  70090. state.setStrokeType (strokeType, undoManager);
  70091. }
  70092. void DrawableShape::paint (Graphics& g)
  70093. {
  70094. transformContextToCorrectOrigin (g);
  70095. g.setFillType (mainFill.fill);
  70096. g.fillPath (path);
  70097. if (isStrokeVisible())
  70098. {
  70099. g.setFillType (strokeFill.fill);
  70100. g.fillPath (strokePath);
  70101. }
  70102. }
  70103. void DrawableShape::pathChanged()
  70104. {
  70105. strokeChanged();
  70106. }
  70107. void DrawableShape::strokeChanged()
  70108. {
  70109. strokePath.clear();
  70110. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  70111. setBoundsToEnclose (getDrawableBounds());
  70112. repaint();
  70113. }
  70114. const Rectangle<float> DrawableShape::getDrawableBounds() const
  70115. {
  70116. if (isStrokeVisible())
  70117. return strokePath.getBounds();
  70118. else
  70119. return path.getBounds();
  70120. }
  70121. bool DrawableShape::hitTest (int x, int y)
  70122. {
  70123. bool allowsClicksOnThisComponent, allowsClicksOnChildComponents;
  70124. getInterceptsMouseClicks (allowsClicksOnThisComponent, allowsClicksOnChildComponents);
  70125. if (! allowsClicksOnThisComponent)
  70126. return false;
  70127. const float globalX = (float) (x - originRelativeToComponent.getX());
  70128. const float globalY = (float) (y - originRelativeToComponent.getY());
  70129. return path.contains (globalX, globalY)
  70130. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  70131. }
  70132. DrawableShape::RelativeFillType::RelativeFillType()
  70133. {
  70134. }
  70135. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  70136. : fill (fill_)
  70137. {
  70138. if (fill.isGradient())
  70139. {
  70140. const ColourGradient& g = *fill.gradient;
  70141. gradientPoint1 = g.point1.transformedBy (fill.transform);
  70142. gradientPoint2 = g.point2.transformedBy (fill.transform);
  70143. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  70144. g.point1.getY() + g.point1.getX() - g.point2.getX())
  70145. .transformedBy (fill.transform);
  70146. fill.transform = AffineTransform::identity;
  70147. }
  70148. }
  70149. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  70150. : fill (other.fill),
  70151. gradientPoint1 (other.gradientPoint1),
  70152. gradientPoint2 (other.gradientPoint2),
  70153. gradientPoint3 (other.gradientPoint3)
  70154. {
  70155. }
  70156. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  70157. {
  70158. fill = other.fill;
  70159. gradientPoint1 = other.gradientPoint1;
  70160. gradientPoint2 = other.gradientPoint2;
  70161. gradientPoint3 = other.gradientPoint3;
  70162. return *this;
  70163. }
  70164. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  70165. {
  70166. return fill == other.fill
  70167. && ((! fill.isGradient())
  70168. || (gradientPoint1 == other.gradientPoint1
  70169. && gradientPoint2 == other.gradientPoint2
  70170. && gradientPoint3 == other.gradientPoint3));
  70171. }
  70172. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  70173. {
  70174. return ! operator== (other);
  70175. }
  70176. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  70177. {
  70178. if (fill.isGradient())
  70179. {
  70180. const Point<float> g1 (gradientPoint1.resolve (scope));
  70181. const Point<float> g2 (gradientPoint2.resolve (scope));
  70182. AffineTransform t;
  70183. ColourGradient& g = *fill.gradient;
  70184. if (g.isRadial)
  70185. {
  70186. const Point<float> g3 (gradientPoint3.resolve (scope));
  70187. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  70188. g1.getY() + g1.getX() - g2.getX());
  70189. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  70190. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  70191. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  70192. }
  70193. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  70194. {
  70195. g.point1 = g1;
  70196. g.point2 = g2;
  70197. fill.transform = t;
  70198. return true;
  70199. }
  70200. }
  70201. return false;
  70202. }
  70203. bool DrawableShape::RelativeFillType::isDynamic() const
  70204. {
  70205. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  70206. }
  70207. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  70208. {
  70209. if (fill.isColour())
  70210. {
  70211. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  70212. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  70213. }
  70214. else if (fill.isGradient())
  70215. {
  70216. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  70217. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  70218. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  70219. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  70220. const ColourGradient& cg = *fill.gradient;
  70221. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  70222. String s;
  70223. for (int i = 0; i < cg.getNumColours(); ++i)
  70224. s << ' ' << cg.getColourPosition (i)
  70225. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  70226. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  70227. }
  70228. else if (fill.isTiledImage())
  70229. {
  70230. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  70231. if (imageProvider != 0)
  70232. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  70233. if (fill.getOpacity() < 1.0f)
  70234. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  70235. else
  70236. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  70237. }
  70238. else
  70239. {
  70240. jassertfalse;
  70241. }
  70242. }
  70243. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  70244. {
  70245. const String newType (v [FillAndStrokeState::type].toString());
  70246. if (newType == "solid")
  70247. {
  70248. const String colourString (v [FillAndStrokeState::colour].toString());
  70249. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  70250. : (uint32) colourString.getHexValue32()));
  70251. return true;
  70252. }
  70253. else if (newType == "gradient")
  70254. {
  70255. ColourGradient g;
  70256. g.isRadial = v [FillAndStrokeState::radial];
  70257. StringArray colourSteps;
  70258. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  70259. for (int i = 0; i < colourSteps.size() / 2; ++i)
  70260. g.addColour (colourSteps[i * 2].getDoubleValue(),
  70261. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  70262. fill.setGradient (g);
  70263. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  70264. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  70265. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  70266. return true;
  70267. }
  70268. else if (newType == "image")
  70269. {
  70270. Image im;
  70271. if (imageProvider != 0)
  70272. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  70273. fill.setTiledImage (im, AffineTransform::identity);
  70274. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  70275. return true;
  70276. }
  70277. jassertfalse;
  70278. return false;
  70279. }
  70280. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  70281. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  70282. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  70283. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  70284. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  70285. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  70286. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  70287. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  70288. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  70289. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  70290. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  70291. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  70292. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  70293. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  70294. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  70295. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  70296. : Drawable::ValueTreeWrapperBase (state_)
  70297. {
  70298. }
  70299. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  70300. {
  70301. DrawableShape::RelativeFillType f;
  70302. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  70303. return f;
  70304. }
  70305. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  70306. {
  70307. ValueTree v (state.getChildWithName (fillOrStrokeType));
  70308. if (v.isValid())
  70309. return v;
  70310. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  70311. return getFillState (fillOrStrokeType);
  70312. }
  70313. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  70314. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  70315. {
  70316. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  70317. newFill.writeTo (v, imageProvider, undoManager);
  70318. }
  70319. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  70320. {
  70321. const String jointStyleString (state [jointStyle].toString());
  70322. const String capStyleString (state [capStyle].toString());
  70323. return PathStrokeType (state [strokeWidth],
  70324. jointStyleString == "curved" ? PathStrokeType::curved
  70325. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70326. : PathStrokeType::mitered),
  70327. capStyleString == "square" ? PathStrokeType::square
  70328. : (capStyleString == "round" ? PathStrokeType::rounded
  70329. : PathStrokeType::butt));
  70330. }
  70331. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70332. {
  70333. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70334. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70335. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70336. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70337. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70338. }
  70339. END_JUCE_NAMESPACE
  70340. /*** End of inlined file: juce_DrawableShape.cpp ***/
  70341. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  70342. BEGIN_JUCE_NAMESPACE
  70343. DrawableComposite::DrawableComposite()
  70344. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  70345. updateBoundsReentrant (false)
  70346. {
  70347. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  70348. RelativeCoordinate (100.0),
  70349. RelativeCoordinate (0.0),
  70350. RelativeCoordinate (100.0)));
  70351. }
  70352. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  70353. : bounds (other.bounds),
  70354. markersX (other.markersX),
  70355. markersY (other.markersY),
  70356. updateBoundsReentrant (false)
  70357. {
  70358. for (int i = 0; i < other.getNumChildComponents(); ++i)
  70359. {
  70360. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  70361. if (d != 0)
  70362. addAndMakeVisible (d->createCopy());
  70363. }
  70364. }
  70365. DrawableComposite::~DrawableComposite()
  70366. {
  70367. deleteAllChildren();
  70368. }
  70369. Drawable* DrawableComposite::createCopy() const
  70370. {
  70371. return new DrawableComposite (*this);
  70372. }
  70373. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  70374. {
  70375. Rectangle<float> r;
  70376. for (int i = getNumChildComponents(); --i >= 0;)
  70377. {
  70378. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70379. if (d != 0)
  70380. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  70381. : d->getDrawableBounds());
  70382. }
  70383. return r;
  70384. }
  70385. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  70386. {
  70387. return xAxis ? &markersX : &markersY;
  70388. }
  70389. const RelativeRectangle DrawableComposite::getContentArea() const
  70390. {
  70391. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  70392. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  70393. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  70394. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  70395. }
  70396. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  70397. {
  70398. markersX.setMarker (contentLeftMarkerName, newArea.left);
  70399. markersX.setMarker (contentRightMarkerName, newArea.right);
  70400. markersY.setMarker (contentTopMarkerName, newArea.top);
  70401. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  70402. }
  70403. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  70404. {
  70405. if (bounds != newBounds)
  70406. {
  70407. bounds = newBounds;
  70408. if (bounds.isDynamic())
  70409. {
  70410. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  70411. setPositioner (p);
  70412. p->apply();
  70413. }
  70414. else
  70415. {
  70416. setPositioner (0);
  70417. recalculateCoordinates (0);
  70418. }
  70419. }
  70420. }
  70421. void DrawableComposite::resetBoundingBoxToContentArea()
  70422. {
  70423. const RelativeRectangle content (getContentArea());
  70424. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70425. RelativePoint (content.right, content.top),
  70426. RelativePoint (content.left, content.bottom)));
  70427. }
  70428. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  70429. {
  70430. const Rectangle<float> activeArea (getDrawableBounds());
  70431. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  70432. RelativeCoordinate (activeArea.getRight()),
  70433. RelativeCoordinate (activeArea.getY()),
  70434. RelativeCoordinate (activeArea.getBottom())));
  70435. resetBoundingBoxToContentArea();
  70436. }
  70437. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70438. {
  70439. bool ok = positioner.addPoint (bounds.topLeft);
  70440. ok = positioner.addPoint (bounds.topRight) && ok;
  70441. return positioner.addPoint (bounds.bottomLeft) && ok;
  70442. }
  70443. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  70444. {
  70445. Point<float> resolved[3];
  70446. bounds.resolveThreePoints (resolved, scope);
  70447. const Rectangle<float> content (getContentArea().resolve (scope));
  70448. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70449. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70450. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  70451. if (t.isSingularity())
  70452. t = AffineTransform::identity;
  70453. setTransform (t);
  70454. }
  70455. void DrawableComposite::parentHierarchyChanged()
  70456. {
  70457. DrawableComposite* parent = getParent();
  70458. if (parent != 0)
  70459. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  70460. }
  70461. void DrawableComposite::childBoundsChanged (Component*)
  70462. {
  70463. updateBoundsToFitChildren();
  70464. }
  70465. void DrawableComposite::childrenChanged()
  70466. {
  70467. updateBoundsToFitChildren();
  70468. }
  70469. void DrawableComposite::updateBoundsToFitChildren()
  70470. {
  70471. if (! updateBoundsReentrant)
  70472. {
  70473. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  70474. Rectangle<int> childArea;
  70475. for (int i = getNumChildComponents(); --i >= 0;)
  70476. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70477. const Point<int> delta (childArea.getPosition());
  70478. childArea += getPosition();
  70479. if (childArea != getBounds())
  70480. {
  70481. if (! delta.isOrigin())
  70482. {
  70483. originRelativeToComponent -= delta;
  70484. for (int i = getNumChildComponents(); --i >= 0;)
  70485. {
  70486. Component* const c = getChildComponent(i);
  70487. if (c != 0)
  70488. c->setBounds (c->getBounds() - delta);
  70489. }
  70490. }
  70491. setBounds (childArea);
  70492. }
  70493. }
  70494. }
  70495. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70496. const char* const DrawableComposite::contentRightMarkerName = "right";
  70497. const char* const DrawableComposite::contentTopMarkerName = "top";
  70498. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70499. const Identifier DrawableComposite::valueTreeType ("Group");
  70500. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70501. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70502. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70503. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70504. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70505. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70506. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70507. : ValueTreeWrapperBase (state_)
  70508. {
  70509. jassert (state.hasType (valueTreeType));
  70510. }
  70511. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70512. {
  70513. return state.getChildWithName (childGroupTag);
  70514. }
  70515. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70516. {
  70517. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70518. }
  70519. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70520. {
  70521. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70522. state.getProperty (topRight, "100, 0"),
  70523. state.getProperty (bottomLeft, "0, 100"));
  70524. }
  70525. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70526. {
  70527. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70528. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70529. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70530. }
  70531. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70532. {
  70533. const RelativeRectangle content (getContentArea());
  70534. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70535. RelativePoint (content.right, content.top),
  70536. RelativePoint (content.left, content.bottom)), undoManager);
  70537. }
  70538. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70539. {
  70540. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70541. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70542. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70543. markersX.getMarker (markersX.getMarkerState (1)).position,
  70544. markersY.getMarker (markersY.getMarkerState (0)).position,
  70545. markersY.getMarker (markersY.getMarkerState (1)).position);
  70546. }
  70547. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70548. {
  70549. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70550. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70551. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70552. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70553. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70554. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70555. }
  70556. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70557. {
  70558. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70559. }
  70560. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70561. {
  70562. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70563. }
  70564. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70565. {
  70566. const ValueTreeWrapper wrapper (tree);
  70567. setComponentID (wrapper.getID());
  70568. wrapper.getMarkerList (true).applyTo (markersX);
  70569. wrapper.getMarkerList (false).applyTo (markersY);
  70570. setBoundingBox (wrapper.getBoundingBox());
  70571. builder.updateChildComponents (*this, wrapper.getChildList());
  70572. }
  70573. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70574. {
  70575. ValueTree tree (valueTreeType);
  70576. ValueTreeWrapper v (tree);
  70577. v.setID (getComponentID());
  70578. v.setBoundingBox (bounds, 0);
  70579. ValueTree childList (v.getChildListCreating (0));
  70580. for (int i = 0; i < getNumChildComponents(); ++i)
  70581. {
  70582. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70583. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70584. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70585. }
  70586. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70587. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70588. return tree;
  70589. }
  70590. END_JUCE_NAMESPACE
  70591. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70592. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70593. BEGIN_JUCE_NAMESPACE
  70594. DrawableImage::DrawableImage()
  70595. : image (0),
  70596. opacity (1.0f),
  70597. overlayColour (0x00000000)
  70598. {
  70599. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70600. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70601. }
  70602. DrawableImage::DrawableImage (const DrawableImage& other)
  70603. : image (other.image),
  70604. opacity (other.opacity),
  70605. overlayColour (other.overlayColour),
  70606. bounds (other.bounds)
  70607. {
  70608. }
  70609. DrawableImage::~DrawableImage()
  70610. {
  70611. }
  70612. void DrawableImage::setImage (const Image& imageToUse)
  70613. {
  70614. image = imageToUse;
  70615. setBounds (imageToUse.getBounds());
  70616. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70617. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70618. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70619. recalculateCoordinates (0);
  70620. repaint();
  70621. }
  70622. void DrawableImage::setOpacity (const float newOpacity)
  70623. {
  70624. opacity = newOpacity;
  70625. }
  70626. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70627. {
  70628. overlayColour = newOverlayColour;
  70629. }
  70630. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70631. {
  70632. if (bounds != newBounds)
  70633. {
  70634. bounds = newBounds;
  70635. if (bounds.isDynamic())
  70636. {
  70637. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70638. setPositioner (p);
  70639. p->apply();
  70640. }
  70641. else
  70642. {
  70643. setPositioner (0);
  70644. recalculateCoordinates (0);
  70645. }
  70646. }
  70647. }
  70648. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70649. {
  70650. bool ok = positioner.addPoint (bounds.topLeft);
  70651. ok = positioner.addPoint (bounds.topRight) && ok;
  70652. return positioner.addPoint (bounds.bottomLeft) && ok;
  70653. }
  70654. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70655. {
  70656. if (image.isValid())
  70657. {
  70658. Point<float> resolved[3];
  70659. bounds.resolveThreePoints (resolved, scope);
  70660. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70661. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70662. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70663. tr.getX(), tr.getY(),
  70664. bl.getX(), bl.getY()));
  70665. if (t.isSingularity())
  70666. t = AffineTransform::identity;
  70667. setTransform (t);
  70668. }
  70669. }
  70670. void DrawableImage::paint (Graphics& g)
  70671. {
  70672. if (image.isValid())
  70673. {
  70674. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70675. {
  70676. g.setOpacity (opacity);
  70677. g.drawImageAt (image, 0, 0, false);
  70678. }
  70679. if (! overlayColour.isTransparent())
  70680. {
  70681. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70682. g.drawImageAt (image, 0, 0, true);
  70683. }
  70684. }
  70685. }
  70686. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70687. {
  70688. return image.getBounds().toFloat();
  70689. }
  70690. bool DrawableImage::hitTest (int x, int y) const
  70691. {
  70692. return (! image.isNull())
  70693. && image.getPixelAt (x, y).getAlpha() >= 127;
  70694. }
  70695. Drawable* DrawableImage::createCopy() const
  70696. {
  70697. return new DrawableImage (*this);
  70698. }
  70699. const Identifier DrawableImage::valueTreeType ("Image");
  70700. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70701. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70702. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70703. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70704. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70705. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70706. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70707. : ValueTreeWrapperBase (state_)
  70708. {
  70709. jassert (state.hasType (valueTreeType));
  70710. }
  70711. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70712. {
  70713. return state [image];
  70714. }
  70715. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70716. {
  70717. return state.getPropertyAsValue (image, undoManager);
  70718. }
  70719. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70720. {
  70721. state.setProperty (image, newIdentifier, undoManager);
  70722. }
  70723. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70724. {
  70725. return (float) state.getProperty (opacity, 1.0);
  70726. }
  70727. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70728. {
  70729. if (! state.hasProperty (opacity))
  70730. state.setProperty (opacity, 1.0, undoManager);
  70731. return state.getPropertyAsValue (opacity, undoManager);
  70732. }
  70733. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70734. {
  70735. state.setProperty (opacity, newOpacity, undoManager);
  70736. }
  70737. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70738. {
  70739. return Colour (state [overlay].toString().getHexValue32());
  70740. }
  70741. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70742. {
  70743. if (newColour.isTransparent())
  70744. state.removeProperty (overlay, undoManager);
  70745. else
  70746. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70747. }
  70748. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70749. {
  70750. return state.getPropertyAsValue (overlay, undoManager);
  70751. }
  70752. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70753. {
  70754. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70755. state.getProperty (topRight, "100, 0"),
  70756. state.getProperty (bottomLeft, "0, 100"));
  70757. }
  70758. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70759. {
  70760. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70761. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70762. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70763. }
  70764. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70765. {
  70766. const ValueTreeWrapper controller (tree);
  70767. setComponentID (controller.getID());
  70768. const float newOpacity = controller.getOpacity();
  70769. const Colour newOverlayColour (controller.getOverlayColour());
  70770. Image newImage;
  70771. const var imageIdentifier (controller.getImageIdentifier());
  70772. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70773. if (builder.getImageProvider() != 0)
  70774. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70775. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70776. if (bounds != newBounds || newOpacity != opacity
  70777. || overlayColour != newOverlayColour || image != newImage)
  70778. {
  70779. repaint();
  70780. opacity = newOpacity;
  70781. overlayColour = newOverlayColour;
  70782. if (image != newImage)
  70783. setImage (newImage);
  70784. setBoundingBox (newBounds);
  70785. }
  70786. }
  70787. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70788. {
  70789. ValueTree tree (valueTreeType);
  70790. ValueTreeWrapper v (tree);
  70791. v.setID (getComponentID());
  70792. v.setOpacity (opacity, 0);
  70793. v.setOverlayColour (overlayColour, 0);
  70794. v.setBoundingBox (bounds, 0);
  70795. if (image.isValid())
  70796. {
  70797. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70798. if (imageProvider != 0)
  70799. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70800. }
  70801. return tree;
  70802. }
  70803. END_JUCE_NAMESPACE
  70804. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70805. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70806. BEGIN_JUCE_NAMESPACE
  70807. DrawablePath::DrawablePath()
  70808. {
  70809. }
  70810. DrawablePath::DrawablePath (const DrawablePath& other)
  70811. : DrawableShape (other)
  70812. {
  70813. if (other.relativePath != 0)
  70814. setPath (*other.relativePath);
  70815. else
  70816. setPath (other.path);
  70817. }
  70818. DrawablePath::~DrawablePath()
  70819. {
  70820. }
  70821. Drawable* DrawablePath::createCopy() const
  70822. {
  70823. return new DrawablePath (*this);
  70824. }
  70825. void DrawablePath::setPath (const Path& newPath)
  70826. {
  70827. path = newPath;
  70828. pathChanged();
  70829. }
  70830. const Path& DrawablePath::getPath() const
  70831. {
  70832. return path;
  70833. }
  70834. const Path& DrawablePath::getStrokePath() const
  70835. {
  70836. return strokePath;
  70837. }
  70838. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70839. {
  70840. Path newPath;
  70841. newRelativePath.createPath (newPath, scope);
  70842. if (path != newPath)
  70843. {
  70844. path.swapWithPath (newPath);
  70845. pathChanged();
  70846. }
  70847. }
  70848. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70849. {
  70850. public:
  70851. RelativePositioner (DrawablePath& component_)
  70852. : RelativeCoordinatePositionerBase (component_),
  70853. owner (component_)
  70854. {
  70855. }
  70856. bool registerCoordinates()
  70857. {
  70858. bool ok = true;
  70859. jassert (owner.relativePath != 0);
  70860. const RelativePointPath& path = *owner.relativePath;
  70861. for (int i = 0; i < path.elements.size(); ++i)
  70862. {
  70863. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70864. int numPoints;
  70865. RelativePoint* const points = e->getControlPoints (numPoints);
  70866. for (int j = numPoints; --j >= 0;)
  70867. ok = addPoint (points[j]) && ok;
  70868. }
  70869. return ok;
  70870. }
  70871. void applyToComponentBounds()
  70872. {
  70873. jassert (owner.relativePath != 0);
  70874. ComponentScope scope (getComponent());
  70875. owner.applyRelativePath (*owner.relativePath, &scope);
  70876. }
  70877. void applyNewBounds (const Rectangle<int>&)
  70878. {
  70879. jassertfalse; // drawables can't be resized directly!
  70880. }
  70881. private:
  70882. DrawablePath& owner;
  70883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70884. };
  70885. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70886. {
  70887. if (newRelativePath.containsAnyDynamicPoints())
  70888. {
  70889. if (relativePath == 0 || newRelativePath != *relativePath)
  70890. {
  70891. relativePath = new RelativePointPath (newRelativePath);
  70892. RelativePositioner* const p = new RelativePositioner (*this);
  70893. setPositioner (p);
  70894. p->apply();
  70895. }
  70896. }
  70897. else
  70898. {
  70899. relativePath = 0;
  70900. applyRelativePath (newRelativePath, 0);
  70901. }
  70902. }
  70903. const Identifier DrawablePath::valueTreeType ("Path");
  70904. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70905. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70906. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70907. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70908. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70909. : FillAndStrokeState (state_)
  70910. {
  70911. jassert (state.hasType (valueTreeType));
  70912. }
  70913. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70914. {
  70915. return state.getOrCreateChildWithName (path, 0);
  70916. }
  70917. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70918. {
  70919. return state [nonZeroWinding];
  70920. }
  70921. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70922. {
  70923. state.setProperty (nonZeroWinding, b, undoManager);
  70924. }
  70925. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70926. {
  70927. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70928. ValueTree pathTree (getPathState());
  70929. pathTree.removeAllChildren (undoManager);
  70930. for (int i = 0; i < relativePath.elements.size(); ++i)
  70931. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70932. }
  70933. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70934. {
  70935. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70936. RelativePoint points[3];
  70937. const ValueTree pathTree (state.getChildWithName (path));
  70938. const int num = pathTree.getNumChildren();
  70939. for (int i = 0; i < num; ++i)
  70940. {
  70941. const Element e (pathTree.getChild(i));
  70942. const int numCps = e.getNumControlPoints();
  70943. for (int j = 0; j < numCps; ++j)
  70944. points[j] = e.getControlPoint (j);
  70945. const Identifier type (e.getType());
  70946. RelativePointPath::ElementBase* newElement = 0;
  70947. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70948. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70949. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70950. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70951. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70952. else jassertfalse;
  70953. relativePath.addElement (newElement);
  70954. }
  70955. }
  70956. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70957. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70958. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70959. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70960. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70961. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70962. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70963. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70964. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70965. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70966. : state (state_)
  70967. {
  70968. }
  70969. DrawablePath::ValueTreeWrapper::Element::~Element()
  70970. {
  70971. }
  70972. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70973. {
  70974. return ValueTreeWrapper (state.getParent().getParent());
  70975. }
  70976. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70977. {
  70978. return Element (state.getSibling (-1));
  70979. }
  70980. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70981. {
  70982. const Identifier i (state.getType());
  70983. if (i == startSubPathElement || i == lineToElement) return 1;
  70984. if (i == quadraticToElement) return 2;
  70985. if (i == cubicToElement) return 3;
  70986. return 0;
  70987. }
  70988. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70989. {
  70990. jassert (index >= 0 && index < getNumControlPoints());
  70991. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70992. }
  70993. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70994. {
  70995. jassert (index >= 0 && index < getNumControlPoints());
  70996. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70997. }
  70998. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70999. {
  71000. jassert (index >= 0 && index < getNumControlPoints());
  71001. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  71002. }
  71003. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  71004. {
  71005. const Identifier i (state.getType());
  71006. if (i == startSubPathElement)
  71007. return getControlPoint (0);
  71008. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  71009. return getPreviousElement().getEndPoint();
  71010. }
  71011. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  71012. {
  71013. const Identifier i (state.getType());
  71014. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  71015. if (i == quadraticToElement) return getControlPoint (1);
  71016. if (i == cubicToElement) return getControlPoint (2);
  71017. jassert (i == closeSubPathElement);
  71018. return RelativePoint();
  71019. }
  71020. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  71021. {
  71022. const Identifier i (state.getType());
  71023. if (i == lineToElement || i == closeSubPathElement)
  71024. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  71025. if (i == cubicToElement)
  71026. {
  71027. Path p;
  71028. p.startNewSubPath (getStartPoint().resolve (scope));
  71029. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  71030. return p.getLength();
  71031. }
  71032. if (i == quadraticToElement)
  71033. {
  71034. Path p;
  71035. p.startNewSubPath (getStartPoint().resolve (scope));
  71036. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  71037. return p.getLength();
  71038. }
  71039. jassert (i == startSubPathElement);
  71040. return 0;
  71041. }
  71042. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  71043. {
  71044. return state [mode].toString();
  71045. }
  71046. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  71047. {
  71048. if (state.hasType (cubicToElement))
  71049. state.setProperty (mode, newMode, undoManager);
  71050. }
  71051. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  71052. {
  71053. const Identifier i (state.getType());
  71054. if (i == quadraticToElement || i == cubicToElement)
  71055. {
  71056. ValueTree newState (lineToElement);
  71057. Element e (newState);
  71058. e.setControlPoint (0, getEndPoint(), undoManager);
  71059. state = newState;
  71060. }
  71061. }
  71062. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  71063. {
  71064. const Identifier i (state.getType());
  71065. if (i == lineToElement || i == quadraticToElement)
  71066. {
  71067. ValueTree newState (cubicToElement);
  71068. Element e (newState);
  71069. const RelativePoint start (getStartPoint());
  71070. const RelativePoint end (getEndPoint());
  71071. const Point<float> startResolved (start.resolve (scope));
  71072. const Point<float> endResolved (end.resolve (scope));
  71073. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  71074. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  71075. e.setControlPoint (2, end, undoManager);
  71076. state = newState;
  71077. }
  71078. }
  71079. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  71080. {
  71081. const Identifier i (state.getType());
  71082. if (i != startSubPathElement)
  71083. {
  71084. ValueTree newState (startSubPathElement);
  71085. Element e (newState);
  71086. e.setControlPoint (0, getEndPoint(), undoManager);
  71087. state = newState;
  71088. }
  71089. }
  71090. namespace DrawablePathHelpers
  71091. {
  71092. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  71093. {
  71094. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  71095. mid2 (points[1] + (points[2] - points[1]) * proportion),
  71096. mid3 (points[2] + (points[3] - points[2]) * proportion);
  71097. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  71098. newCp2 (mid2 + (mid3 - mid2) * proportion);
  71099. return newCp1 + (newCp2 - newCp1) * proportion;
  71100. }
  71101. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  71102. {
  71103. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  71104. mid2 (points[1] + (points[2] - points[1]) * proportion);
  71105. return mid1 + (mid2 - mid1) * proportion;
  71106. }
  71107. }
  71108. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  71109. {
  71110. using namespace DrawablePathHelpers;
  71111. const Identifier type (state.getType());
  71112. float bestProp = 0;
  71113. if (type == cubicToElement)
  71114. {
  71115. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71116. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  71117. float bestDistance = std::numeric_limits<float>::max();
  71118. for (int i = 110; --i >= 0;)
  71119. {
  71120. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71121. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  71122. const float distance = centre.getDistanceFrom (targetPoint);
  71123. if (distance < bestDistance)
  71124. {
  71125. bestProp = prop;
  71126. bestDistance = distance;
  71127. }
  71128. }
  71129. }
  71130. else if (type == quadraticToElement)
  71131. {
  71132. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71133. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  71134. float bestDistance = std::numeric_limits<float>::max();
  71135. for (int i = 110; --i >= 0;)
  71136. {
  71137. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71138. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  71139. const float distance = centre.getDistanceFrom (targetPoint);
  71140. if (distance < bestDistance)
  71141. {
  71142. bestProp = prop;
  71143. bestDistance = distance;
  71144. }
  71145. }
  71146. }
  71147. else if (type == lineToElement)
  71148. {
  71149. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71150. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  71151. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  71152. }
  71153. return bestProp;
  71154. }
  71155. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  71156. {
  71157. ValueTree newTree;
  71158. const Identifier type (state.getType());
  71159. if (type == cubicToElement)
  71160. {
  71161. float bestProp = findProportionAlongLine (targetPoint, scope);
  71162. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71163. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  71164. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71165. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  71166. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  71167. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  71168. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  71169. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  71170. setControlPoint (0, mid1, undoManager);
  71171. setControlPoint (1, newCp1, undoManager);
  71172. setControlPoint (2, newCentre, undoManager);
  71173. setModeOfEndPoint (roundedMode, undoManager);
  71174. Element newElement (newTree = ValueTree (cubicToElement));
  71175. newElement.setControlPoint (0, newCp2, 0);
  71176. newElement.setControlPoint (1, mid3, 0);
  71177. newElement.setControlPoint (2, rp4, 0);
  71178. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71179. }
  71180. else if (type == quadraticToElement)
  71181. {
  71182. float bestProp = findProportionAlongLine (targetPoint, scope);
  71183. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71184. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  71185. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71186. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  71187. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  71188. setControlPoint (0, mid1, undoManager);
  71189. setControlPoint (1, newCentre, undoManager);
  71190. setModeOfEndPoint (roundedMode, undoManager);
  71191. Element newElement (newTree = ValueTree (quadraticToElement));
  71192. newElement.setControlPoint (0, mid2, 0);
  71193. newElement.setControlPoint (1, rp3, 0);
  71194. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71195. }
  71196. else if (type == lineToElement)
  71197. {
  71198. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71199. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  71200. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  71201. setControlPoint (0, newPoint, undoManager);
  71202. Element newElement (newTree = ValueTree (lineToElement));
  71203. newElement.setControlPoint (0, rp2, 0);
  71204. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71205. }
  71206. else if (type == closeSubPathElement)
  71207. {
  71208. }
  71209. return newTree;
  71210. }
  71211. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  71212. {
  71213. state.getParent().removeChild (state, undoManager);
  71214. }
  71215. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71216. {
  71217. ValueTreeWrapper v (tree);
  71218. setComponentID (v.getID());
  71219. refreshFillTypes (v, builder.getImageProvider());
  71220. setStrokeType (v.getStrokeType());
  71221. RelativePointPath newRelativePath;
  71222. v.writeTo (newRelativePath);
  71223. setPath (newRelativePath);
  71224. }
  71225. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71226. {
  71227. ValueTree tree (valueTreeType);
  71228. ValueTreeWrapper v (tree);
  71229. v.setID (getComponentID());
  71230. writeTo (v, imageProvider, 0);
  71231. if (relativePath != 0)
  71232. v.readFrom (*relativePath, 0);
  71233. else
  71234. v.readFrom (RelativePointPath (path), 0);
  71235. return tree;
  71236. }
  71237. END_JUCE_NAMESPACE
  71238. /*** End of inlined file: juce_DrawablePath.cpp ***/
  71239. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  71240. BEGIN_JUCE_NAMESPACE
  71241. DrawableRectangle::DrawableRectangle()
  71242. {
  71243. }
  71244. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  71245. : DrawableShape (other),
  71246. bounds (other.bounds),
  71247. cornerSize (other.cornerSize)
  71248. {
  71249. }
  71250. DrawableRectangle::~DrawableRectangle()
  71251. {
  71252. }
  71253. Drawable* DrawableRectangle::createCopy() const
  71254. {
  71255. return new DrawableRectangle (*this);
  71256. }
  71257. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  71258. {
  71259. if (bounds != newBounds)
  71260. {
  71261. bounds = newBounds;
  71262. rebuildPath();
  71263. }
  71264. }
  71265. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  71266. {
  71267. if (cornerSize != newSize)
  71268. {
  71269. cornerSize = newSize;
  71270. rebuildPath();
  71271. }
  71272. }
  71273. void DrawableRectangle::rebuildPath()
  71274. {
  71275. if (bounds.isDynamic() || cornerSize.isDynamic())
  71276. {
  71277. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  71278. setPositioner (p);
  71279. p->apply();
  71280. }
  71281. else
  71282. {
  71283. setPositioner (0);
  71284. recalculateCoordinates (0);
  71285. }
  71286. }
  71287. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71288. {
  71289. bool ok = positioner.addPoint (bounds.topLeft);
  71290. ok = positioner.addPoint (bounds.topRight) && ok;
  71291. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71292. return positioner.addPoint (cornerSize) && ok;
  71293. }
  71294. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  71295. {
  71296. Point<float> points[3];
  71297. bounds.resolveThreePoints (points, scope);
  71298. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  71299. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  71300. const float w = Line<float> (points[0], points[1]).getLength();
  71301. const float h = Line<float> (points[0], points[2]).getLength();
  71302. Path newPath;
  71303. if (cornerSizeX > 0 && cornerSizeY > 0)
  71304. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  71305. else
  71306. newPath.addRectangle (0, 0, w, h);
  71307. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71308. w, 0, points[1].getX(), points[1].getY(),
  71309. 0, h, points[2].getX(), points[2].getY()));
  71310. if (path != newPath)
  71311. {
  71312. path.swapWithPath (newPath);
  71313. pathChanged();
  71314. }
  71315. }
  71316. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  71317. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  71318. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  71319. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71320. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  71321. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71322. : FillAndStrokeState (state_)
  71323. {
  71324. jassert (state.hasType (valueTreeType));
  71325. }
  71326. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  71327. {
  71328. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  71329. state.getProperty (topRight, "100, 0"),
  71330. state.getProperty (bottomLeft, "0, 100"));
  71331. }
  71332. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71333. {
  71334. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71335. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71336. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71337. }
  71338. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  71339. {
  71340. state.setProperty (cornerSize, newSize.toString(), undoManager);
  71341. }
  71342. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  71343. {
  71344. return RelativePoint (state [cornerSize]);
  71345. }
  71346. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  71347. {
  71348. return state.getPropertyAsValue (cornerSize, undoManager);
  71349. }
  71350. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71351. {
  71352. ValueTreeWrapper v (tree);
  71353. setComponentID (v.getID());
  71354. refreshFillTypes (v, builder.getImageProvider());
  71355. setStrokeType (v.getStrokeType());
  71356. setRectangle (v.getRectangle());
  71357. setCornerSize (v.getCornerSize());
  71358. }
  71359. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71360. {
  71361. ValueTree tree (valueTreeType);
  71362. ValueTreeWrapper v (tree);
  71363. v.setID (getComponentID());
  71364. writeTo (v, imageProvider, 0);
  71365. v.setRectangle (bounds, 0);
  71366. v.setCornerSize (cornerSize, 0);
  71367. return tree;
  71368. }
  71369. END_JUCE_NAMESPACE
  71370. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71371. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71372. BEGIN_JUCE_NAMESPACE
  71373. DrawableText::DrawableText()
  71374. : colour (Colours::black),
  71375. justification (Justification::centredLeft)
  71376. {
  71377. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71378. RelativePoint (50.0f, 0.0f),
  71379. RelativePoint (0.0f, 20.0f)));
  71380. setFont (Font (15.0f), true);
  71381. }
  71382. DrawableText::DrawableText (const DrawableText& other)
  71383. : bounds (other.bounds),
  71384. fontSizeControlPoint (other.fontSizeControlPoint),
  71385. font (other.font),
  71386. text (other.text),
  71387. colour (other.colour),
  71388. justification (other.justification)
  71389. {
  71390. }
  71391. DrawableText::~DrawableText()
  71392. {
  71393. }
  71394. void DrawableText::setText (const String& newText)
  71395. {
  71396. if (text != newText)
  71397. {
  71398. text = newText;
  71399. refreshBounds();
  71400. }
  71401. }
  71402. void DrawableText::setColour (const Colour& newColour)
  71403. {
  71404. if (colour != newColour)
  71405. {
  71406. colour = newColour;
  71407. repaint();
  71408. }
  71409. }
  71410. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71411. {
  71412. if (font != newFont)
  71413. {
  71414. font = newFont;
  71415. if (applySizeAndScale)
  71416. {
  71417. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  71418. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71419. }
  71420. refreshBounds();
  71421. }
  71422. }
  71423. void DrawableText::setJustification (const Justification& newJustification)
  71424. {
  71425. justification = newJustification;
  71426. repaint();
  71427. }
  71428. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71429. {
  71430. if (bounds != newBounds)
  71431. {
  71432. bounds = newBounds;
  71433. refreshBounds();
  71434. }
  71435. }
  71436. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71437. {
  71438. if (fontSizeControlPoint != newPoint)
  71439. {
  71440. fontSizeControlPoint = newPoint;
  71441. refreshBounds();
  71442. }
  71443. }
  71444. void DrawableText::refreshBounds()
  71445. {
  71446. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  71447. {
  71448. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  71449. setPositioner (p);
  71450. p->apply();
  71451. }
  71452. else
  71453. {
  71454. setPositioner (0);
  71455. recalculateCoordinates (0);
  71456. }
  71457. }
  71458. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71459. {
  71460. bool ok = positioner.addPoint (bounds.topLeft);
  71461. ok = positioner.addPoint (bounds.topRight) && ok;
  71462. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71463. return positioner.addPoint (fontSizeControlPoint) && ok;
  71464. }
  71465. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  71466. {
  71467. bounds.resolveThreePoints (resolvedPoints, scope);
  71468. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71469. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71470. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  71471. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71472. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71473. scaledFont = font;
  71474. scaledFont.setHeight (fontHeight);
  71475. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71476. setBoundsToEnclose (getDrawableBounds());
  71477. repaint();
  71478. }
  71479. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71480. {
  71481. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71482. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71483. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71484. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71485. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71486. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71487. }
  71488. void DrawableText::paint (Graphics& g)
  71489. {
  71490. transformContextToCorrectOrigin (g);
  71491. g.setColour (colour);
  71492. GlyphArrangement ga;
  71493. const AffineTransform transform (getArrangementAndTransform (ga));
  71494. ga.draw (g, transform);
  71495. }
  71496. const Rectangle<float> DrawableText::getDrawableBounds() const
  71497. {
  71498. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71499. }
  71500. Drawable* DrawableText::createCopy() const
  71501. {
  71502. return new DrawableText (*this);
  71503. }
  71504. const Identifier DrawableText::valueTreeType ("Text");
  71505. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71506. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71507. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71508. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71509. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71510. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71511. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71512. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71513. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71514. : ValueTreeWrapperBase (state_)
  71515. {
  71516. jassert (state.hasType (valueTreeType));
  71517. }
  71518. const String DrawableText::ValueTreeWrapper::getText() const
  71519. {
  71520. return state [text].toString();
  71521. }
  71522. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71523. {
  71524. state.setProperty (text, newText, undoManager);
  71525. }
  71526. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71527. {
  71528. return state.getPropertyAsValue (text, undoManager);
  71529. }
  71530. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71531. {
  71532. return Colour::fromString (state [colour].toString());
  71533. }
  71534. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71535. {
  71536. state.setProperty (colour, newColour.toString(), undoManager);
  71537. }
  71538. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71539. {
  71540. return Justification ((int) state [justification]);
  71541. }
  71542. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71543. {
  71544. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71545. }
  71546. const Font DrawableText::ValueTreeWrapper::getFont() const
  71547. {
  71548. return Font::fromString (state [font]);
  71549. }
  71550. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71551. {
  71552. state.setProperty (font, newFont.toString(), undoManager);
  71553. }
  71554. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71555. {
  71556. return state.getPropertyAsValue (font, undoManager);
  71557. }
  71558. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71559. {
  71560. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71561. }
  71562. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71563. {
  71564. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71565. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71566. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71567. }
  71568. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71569. {
  71570. return state [fontSizeAnchor].toString();
  71571. }
  71572. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71573. {
  71574. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71575. }
  71576. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71577. {
  71578. ValueTreeWrapper v (tree);
  71579. setComponentID (v.getID());
  71580. const RelativeParallelogram newBounds (v.getBoundingBox());
  71581. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71582. const Colour newColour (v.getColour());
  71583. const Justification newJustification (v.getJustification());
  71584. const String newText (v.getText());
  71585. const Font newFont (v.getFont());
  71586. if (text != newText || font != newFont || justification != newJustification
  71587. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71588. {
  71589. setBoundingBox (newBounds);
  71590. setFontSizeControlPoint (newFontPoint);
  71591. setColour (newColour);
  71592. setFont (newFont, false);
  71593. setJustification (newJustification);
  71594. setText (newText);
  71595. }
  71596. }
  71597. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71598. {
  71599. ValueTree tree (valueTreeType);
  71600. ValueTreeWrapper v (tree);
  71601. v.setID (getComponentID());
  71602. v.setText (text, 0);
  71603. v.setFont (font, 0);
  71604. v.setJustification (justification, 0);
  71605. v.setColour (colour, 0);
  71606. v.setBoundingBox (bounds, 0);
  71607. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71608. return tree;
  71609. }
  71610. END_JUCE_NAMESPACE
  71611. /*** End of inlined file: juce_DrawableText.cpp ***/
  71612. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71613. BEGIN_JUCE_NAMESPACE
  71614. class SVGState
  71615. {
  71616. public:
  71617. SVGState (const XmlElement* const topLevel)
  71618. : topLevelXml (topLevel),
  71619. elementX (0), elementY (0),
  71620. width (512), height (512),
  71621. viewBoxW (0), viewBoxH (0)
  71622. {
  71623. }
  71624. Drawable* parseSVGElement (const XmlElement& xml)
  71625. {
  71626. if (! xml.hasTagName ("svg"))
  71627. return 0;
  71628. DrawableComposite* const drawable = new DrawableComposite();
  71629. drawable->setName (xml.getStringAttribute ("id"));
  71630. SVGState newState (*this);
  71631. if (xml.hasAttribute ("transform"))
  71632. newState.addTransform (xml);
  71633. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71634. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71635. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71636. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71637. if (xml.hasAttribute ("viewBox"))
  71638. {
  71639. const String viewBoxAtt (xml.getStringAttribute ("viewBox"));
  71640. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  71641. float vx, vy, vw, vh;
  71642. if (parseCoords (viewParams, vx, vy, true)
  71643. && parseCoords (viewParams, vw, vh, true)
  71644. && vw > 0
  71645. && vh > 0)
  71646. {
  71647. newState.viewBoxW = vw;
  71648. newState.viewBoxH = vh;
  71649. int placementFlags = 0;
  71650. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71651. if (aspect.containsIgnoreCase ("none"))
  71652. {
  71653. placementFlags = RectanglePlacement::stretchToFit;
  71654. }
  71655. else
  71656. {
  71657. if (aspect.containsIgnoreCase ("slice"))
  71658. placementFlags |= RectanglePlacement::fillDestination;
  71659. if (aspect.containsIgnoreCase ("xMin"))
  71660. placementFlags |= RectanglePlacement::xLeft;
  71661. else if (aspect.containsIgnoreCase ("xMax"))
  71662. placementFlags |= RectanglePlacement::xRight;
  71663. else
  71664. placementFlags |= RectanglePlacement::xMid;
  71665. if (aspect.containsIgnoreCase ("yMin"))
  71666. placementFlags |= RectanglePlacement::yTop;
  71667. else if (aspect.containsIgnoreCase ("yMax"))
  71668. placementFlags |= RectanglePlacement::yBottom;
  71669. else
  71670. placementFlags |= RectanglePlacement::yMid;
  71671. }
  71672. const RectanglePlacement placement (placementFlags);
  71673. newState.transform
  71674. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71675. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71676. .followedBy (newState.transform);
  71677. }
  71678. }
  71679. else
  71680. {
  71681. if (viewBoxW == 0)
  71682. newState.viewBoxW = newState.width;
  71683. if (viewBoxH == 0)
  71684. newState.viewBoxH = newState.height;
  71685. }
  71686. newState.parseSubElements (xml, drawable);
  71687. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71688. return drawable;
  71689. }
  71690. private:
  71691. const XmlElement* const topLevelXml;
  71692. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71693. AffineTransform transform;
  71694. String cssStyleText;
  71695. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71696. {
  71697. forEachXmlChildElement (xml, e)
  71698. {
  71699. Drawable* d = 0;
  71700. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71701. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71702. else if (e->hasTagName ("path")) d = parsePath (*e);
  71703. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71704. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71705. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71706. else if (e->hasTagName ("line")) d = parseLine (*e);
  71707. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71708. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71709. else if (e->hasTagName ("text")) d = parseText (*e);
  71710. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71711. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71712. parentDrawable->addAndMakeVisible (d);
  71713. }
  71714. }
  71715. DrawableComposite* parseSwitch (const XmlElement& xml)
  71716. {
  71717. const XmlElement* const group = xml.getChildByName ("g");
  71718. if (group != 0)
  71719. return parseGroupElement (*group);
  71720. return 0;
  71721. }
  71722. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71723. {
  71724. DrawableComposite* const drawable = new DrawableComposite();
  71725. drawable->setName (xml.getStringAttribute ("id"));
  71726. if (xml.hasAttribute ("transform"))
  71727. {
  71728. SVGState newState (*this);
  71729. newState.addTransform (xml);
  71730. newState.parseSubElements (xml, drawable);
  71731. }
  71732. else
  71733. {
  71734. parseSubElements (xml, drawable);
  71735. }
  71736. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71737. return drawable;
  71738. }
  71739. Drawable* parsePath (const XmlElement& xml) const
  71740. {
  71741. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  71742. String::CharPointerType d (dAttribute.getCharPointer());
  71743. Path path;
  71744. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71745. path.setUsingNonZeroWinding (false);
  71746. float lastX = 0, lastY = 0;
  71747. float lastX2 = 0, lastY2 = 0;
  71748. juce_wchar lastCommandChar = 0;
  71749. bool isRelative = true;
  71750. bool carryOn = true;
  71751. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71752. while (! d.isEmpty())
  71753. {
  71754. float x, y, x2, y2, x3, y3;
  71755. if (validCommandChars.indexOf (*d) >= 0)
  71756. {
  71757. lastCommandChar = d.getAndAdvance();
  71758. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71759. }
  71760. switch (lastCommandChar)
  71761. {
  71762. case 'M':
  71763. case 'm':
  71764. case 'L':
  71765. case 'l':
  71766. if (parseCoords (d, x, y, false))
  71767. {
  71768. if (isRelative)
  71769. {
  71770. x += lastX;
  71771. y += lastY;
  71772. }
  71773. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71774. {
  71775. path.startNewSubPath (x, y);
  71776. lastCommandChar = 'l';
  71777. }
  71778. else
  71779. path.lineTo (x, y);
  71780. lastX2 = lastX;
  71781. lastY2 = lastY;
  71782. lastX = x;
  71783. lastY = y;
  71784. }
  71785. else
  71786. {
  71787. ++d;
  71788. }
  71789. break;
  71790. case 'H':
  71791. case 'h':
  71792. if (parseCoord (d, x, false, true))
  71793. {
  71794. if (isRelative)
  71795. x += lastX;
  71796. path.lineTo (x, lastY);
  71797. lastX2 = lastX;
  71798. lastX = x;
  71799. }
  71800. else
  71801. {
  71802. ++d;
  71803. }
  71804. break;
  71805. case 'V':
  71806. case 'v':
  71807. if (parseCoord (d, y, false, false))
  71808. {
  71809. if (isRelative)
  71810. y += lastY;
  71811. path.lineTo (lastX, y);
  71812. lastY2 = lastY;
  71813. lastY = y;
  71814. }
  71815. else
  71816. {
  71817. ++d;
  71818. }
  71819. break;
  71820. case 'C':
  71821. case 'c':
  71822. if (parseCoords (d, x, y, false)
  71823. && parseCoords (d, x2, y2, false)
  71824. && parseCoords (d, x3, y3, false))
  71825. {
  71826. if (isRelative)
  71827. {
  71828. x += lastX;
  71829. y += lastY;
  71830. x2 += lastX;
  71831. y2 += lastY;
  71832. x3 += lastX;
  71833. y3 += lastY;
  71834. }
  71835. path.cubicTo (x, y, x2, y2, x3, y3);
  71836. lastX2 = x2;
  71837. lastY2 = y2;
  71838. lastX = x3;
  71839. lastY = y3;
  71840. }
  71841. else
  71842. {
  71843. ++d;
  71844. }
  71845. break;
  71846. case 'S':
  71847. case 's':
  71848. if (parseCoords (d, x, y, false)
  71849. && parseCoords (d, x3, y3, false))
  71850. {
  71851. if (isRelative)
  71852. {
  71853. x += lastX;
  71854. y += lastY;
  71855. x3 += lastX;
  71856. y3 += lastY;
  71857. }
  71858. x2 = lastX + (lastX - lastX2);
  71859. y2 = lastY + (lastY - lastY2);
  71860. path.cubicTo (x2, y2, x, y, x3, y3);
  71861. lastX2 = x;
  71862. lastY2 = y;
  71863. lastX = x3;
  71864. lastY = y3;
  71865. }
  71866. else
  71867. {
  71868. ++d;
  71869. }
  71870. break;
  71871. case 'Q':
  71872. case 'q':
  71873. if (parseCoords (d, x, y, false)
  71874. && parseCoords (d, x2, y2, false))
  71875. {
  71876. if (isRelative)
  71877. {
  71878. x += lastX;
  71879. y += lastY;
  71880. x2 += lastX;
  71881. y2 += lastY;
  71882. }
  71883. path.quadraticTo (x, y, x2, y2);
  71884. lastX2 = x;
  71885. lastY2 = y;
  71886. lastX = x2;
  71887. lastY = y2;
  71888. }
  71889. else
  71890. {
  71891. ++d;
  71892. }
  71893. break;
  71894. case 'T':
  71895. case 't':
  71896. if (parseCoords (d, x, y, false))
  71897. {
  71898. if (isRelative)
  71899. {
  71900. x += lastX;
  71901. y += lastY;
  71902. }
  71903. x2 = lastX + (lastX - lastX2);
  71904. y2 = lastY + (lastY - lastY2);
  71905. path.quadraticTo (x2, y2, x, y);
  71906. lastX2 = x2;
  71907. lastY2 = y2;
  71908. lastX = x;
  71909. lastY = y;
  71910. }
  71911. else
  71912. {
  71913. ++d;
  71914. }
  71915. break;
  71916. case 'A':
  71917. case 'a':
  71918. if (parseCoords (d, x, y, false))
  71919. {
  71920. String num;
  71921. if (parseNextNumber (d, num, false))
  71922. {
  71923. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71924. if (parseNextNumber (d, num, false))
  71925. {
  71926. const bool largeArc = num.getIntValue() != 0;
  71927. if (parseNextNumber (d, num, false))
  71928. {
  71929. const bool sweep = num.getIntValue() != 0;
  71930. if (parseCoords (d, x2, y2, false))
  71931. {
  71932. if (isRelative)
  71933. {
  71934. x2 += lastX;
  71935. y2 += lastY;
  71936. }
  71937. if (lastX != x2 || lastY != y2)
  71938. {
  71939. double centreX, centreY, startAngle, deltaAngle;
  71940. double rx = x, ry = y;
  71941. endpointToCentreParameters (lastX, lastY, x2, y2,
  71942. angle, largeArc, sweep,
  71943. rx, ry, centreX, centreY,
  71944. startAngle, deltaAngle);
  71945. path.addCentredArc ((float) centreX, (float) centreY,
  71946. (float) rx, (float) ry,
  71947. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71948. false);
  71949. path.lineTo (x2, y2);
  71950. }
  71951. lastX2 = lastX;
  71952. lastY2 = lastY;
  71953. lastX = x2;
  71954. lastY = y2;
  71955. }
  71956. }
  71957. }
  71958. }
  71959. }
  71960. else
  71961. {
  71962. ++d;
  71963. }
  71964. break;
  71965. case 'Z':
  71966. case 'z':
  71967. path.closeSubPath();
  71968. d = d.findEndOfWhitespace();
  71969. break;
  71970. default:
  71971. carryOn = false;
  71972. break;
  71973. }
  71974. if (! carryOn)
  71975. break;
  71976. }
  71977. return parseShape (xml, path);
  71978. }
  71979. Drawable* parseRect (const XmlElement& xml) const
  71980. {
  71981. Path rect;
  71982. const bool hasRX = xml.hasAttribute ("rx");
  71983. const bool hasRY = xml.hasAttribute ("ry");
  71984. if (hasRX || hasRY)
  71985. {
  71986. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71987. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71988. if (! hasRX)
  71989. rx = ry;
  71990. else if (! hasRY)
  71991. ry = rx;
  71992. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71993. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71994. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71995. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71996. rx, ry);
  71997. }
  71998. else
  71999. {
  72000. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  72001. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  72002. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  72003. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  72004. }
  72005. return parseShape (xml, rect);
  72006. }
  72007. Drawable* parseCircle (const XmlElement& xml) const
  72008. {
  72009. Path circle;
  72010. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  72011. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  72012. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  72013. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  72014. return parseShape (xml, circle);
  72015. }
  72016. Drawable* parseEllipse (const XmlElement& xml) const
  72017. {
  72018. Path ellipse;
  72019. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  72020. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  72021. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  72022. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  72023. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  72024. return parseShape (xml, ellipse);
  72025. }
  72026. Drawable* parseLine (const XmlElement& xml) const
  72027. {
  72028. Path line;
  72029. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  72030. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  72031. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  72032. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  72033. line.startNewSubPath (x1, y1);
  72034. line.lineTo (x2, y2);
  72035. return parseShape (xml, line);
  72036. }
  72037. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  72038. {
  72039. const String pointsAtt (xml.getStringAttribute ("points"));
  72040. String::CharPointerType points (pointsAtt.getCharPointer());
  72041. Path path;
  72042. float x, y;
  72043. if (parseCoords (points, x, y, true))
  72044. {
  72045. float firstX = x;
  72046. float firstY = y;
  72047. float lastX = 0, lastY = 0;
  72048. path.startNewSubPath (x, y);
  72049. while (parseCoords (points, x, y, true))
  72050. {
  72051. lastX = x;
  72052. lastY = y;
  72053. path.lineTo (x, y);
  72054. }
  72055. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  72056. path.closeSubPath();
  72057. }
  72058. return parseShape (xml, path);
  72059. }
  72060. Drawable* parseShape (const XmlElement& xml, Path& path,
  72061. const bool shouldParseTransform = true) const
  72062. {
  72063. if (shouldParseTransform && xml.hasAttribute ("transform"))
  72064. {
  72065. SVGState newState (*this);
  72066. newState.addTransform (xml);
  72067. return newState.parseShape (xml, path, false);
  72068. }
  72069. DrawablePath* dp = new DrawablePath();
  72070. dp->setName (xml.getStringAttribute ("id"));
  72071. dp->setFill (Colours::transparentBlack);
  72072. path.applyTransform (transform);
  72073. dp->setPath (path);
  72074. Path::Iterator iter (path);
  72075. bool containsClosedSubPath = false;
  72076. while (iter.next())
  72077. {
  72078. if (iter.elementType == Path::Iterator::closePath)
  72079. {
  72080. containsClosedSubPath = true;
  72081. break;
  72082. }
  72083. }
  72084. dp->setFill (getPathFillType (path,
  72085. getStyleAttribute (&xml, "fill"),
  72086. getStyleAttribute (&xml, "fill-opacity"),
  72087. getStyleAttribute (&xml, "opacity"),
  72088. containsClosedSubPath ? Colours::black
  72089. : Colours::transparentBlack));
  72090. const String strokeType (getStyleAttribute (&xml, "stroke"));
  72091. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  72092. {
  72093. dp->setStrokeFill (getPathFillType (path, strokeType,
  72094. getStyleAttribute (&xml, "stroke-opacity"),
  72095. getStyleAttribute (&xml, "opacity"),
  72096. Colours::transparentBlack));
  72097. dp->setStrokeType (getStrokeFor (&xml));
  72098. }
  72099. return dp;
  72100. }
  72101. const XmlElement* findLinkedElement (const XmlElement* e) const
  72102. {
  72103. const String id (e->getStringAttribute ("xlink:href"));
  72104. if (! id.startsWithChar ('#'))
  72105. return 0;
  72106. return findElementForId (topLevelXml, id.substring (1));
  72107. }
  72108. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  72109. {
  72110. if (fillXml == 0)
  72111. return;
  72112. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  72113. {
  72114. int index = 0;
  72115. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  72116. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  72117. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  72118. double offset = e->getDoubleAttribute ("offset");
  72119. if (e->getStringAttribute ("offset").containsChar ('%'))
  72120. offset *= 0.01;
  72121. cg.addColour (jlimit (0.0, 1.0, offset), col);
  72122. }
  72123. }
  72124. const FillType getPathFillType (const Path& path,
  72125. const String& fill,
  72126. const String& fillOpacity,
  72127. const String& overallOpacity,
  72128. const Colour& defaultColour) const
  72129. {
  72130. float opacity = 1.0f;
  72131. if (overallOpacity.isNotEmpty())
  72132. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  72133. if (fillOpacity.isNotEmpty())
  72134. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  72135. if (fill.startsWithIgnoreCase ("url"))
  72136. {
  72137. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  72138. .upToLastOccurrenceOf (")", false, false).trim());
  72139. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  72140. if (fillXml != 0
  72141. && (fillXml->hasTagName ("linearGradient")
  72142. || fillXml->hasTagName ("radialGradient")))
  72143. {
  72144. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  72145. ColourGradient gradient;
  72146. addGradientStopsIn (gradient, inheritedFrom);
  72147. addGradientStopsIn (gradient, fillXml);
  72148. if (gradient.getNumColours() > 0)
  72149. {
  72150. gradient.addColour (0.0, gradient.getColour (0));
  72151. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  72152. }
  72153. else
  72154. {
  72155. gradient.addColour (0.0, Colours::black);
  72156. gradient.addColour (1.0, Colours::black);
  72157. }
  72158. if (overallOpacity.isNotEmpty())
  72159. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  72160. jassert (gradient.getNumColours() > 0);
  72161. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  72162. float gradientWidth = viewBoxW;
  72163. float gradientHeight = viewBoxH;
  72164. float dx = 0.0f;
  72165. float dy = 0.0f;
  72166. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  72167. if (! userSpace)
  72168. {
  72169. const Rectangle<float> bounds (path.getBounds());
  72170. dx = bounds.getX();
  72171. dy = bounds.getY();
  72172. gradientWidth = bounds.getWidth();
  72173. gradientHeight = bounds.getHeight();
  72174. }
  72175. if (gradient.isRadial)
  72176. {
  72177. if (userSpace)
  72178. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  72179. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  72180. else
  72181. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  72182. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  72183. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  72184. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  72185. //xxx (the fx, fy focal point isn't handled properly here..)
  72186. }
  72187. else
  72188. {
  72189. if (userSpace)
  72190. {
  72191. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  72192. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  72193. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  72194. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  72195. }
  72196. else
  72197. {
  72198. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  72199. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  72200. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  72201. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  72202. }
  72203. if (gradient.point1 == gradient.point2)
  72204. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  72205. }
  72206. FillType type (gradient);
  72207. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  72208. .followedBy (transform);
  72209. return type;
  72210. }
  72211. }
  72212. if (fill.equalsIgnoreCase ("none"))
  72213. return Colours::transparentBlack;
  72214. int i = 0;
  72215. const Colour colour (parseColour (fill, i, defaultColour));
  72216. return colour.withMultipliedAlpha (opacity);
  72217. }
  72218. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  72219. {
  72220. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  72221. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  72222. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  72223. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  72224. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  72225. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  72226. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  72227. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  72228. if (join.equalsIgnoreCase ("round"))
  72229. joinStyle = PathStrokeType::curved;
  72230. else if (join.equalsIgnoreCase ("bevel"))
  72231. joinStyle = PathStrokeType::beveled;
  72232. if (cap.equalsIgnoreCase ("round"))
  72233. capStyle = PathStrokeType::rounded;
  72234. else if (cap.equalsIgnoreCase ("square"))
  72235. capStyle = PathStrokeType::square;
  72236. float ox = 0.0f, oy = 0.0f;
  72237. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  72238. transform.transformPoints (ox, oy, x, y);
  72239. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  72240. joinStyle, capStyle);
  72241. }
  72242. Drawable* parseText (const XmlElement& xml)
  72243. {
  72244. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  72245. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  72246. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  72247. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  72248. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  72249. //xxx not done text yet!
  72250. forEachXmlChildElement (xml, e)
  72251. {
  72252. if (e->isTextElement())
  72253. {
  72254. const String text (e->getText());
  72255. Path path;
  72256. Drawable* s = parseShape (*e, path);
  72257. delete s; // xxx not finished!
  72258. }
  72259. else if (e->hasTagName ("tspan"))
  72260. {
  72261. Drawable* s = parseText (*e);
  72262. delete s; // xxx not finished!
  72263. }
  72264. }
  72265. return 0;
  72266. }
  72267. void addTransform (const XmlElement& xml)
  72268. {
  72269. transform = parseTransform (xml.getStringAttribute ("transform"))
  72270. .followedBy (transform);
  72271. }
  72272. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  72273. {
  72274. String number;
  72275. if (! parseNextNumber (s, number, allowUnits))
  72276. {
  72277. value = 0;
  72278. return false;
  72279. }
  72280. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  72281. return true;
  72282. }
  72283. bool parseCoords (String::CharPointerType& s, float& x, float& y, const bool allowUnits) const
  72284. {
  72285. return parseCoord (s, x, allowUnits, true)
  72286. && parseCoord (s, y, allowUnits, false);
  72287. }
  72288. float getCoordLength (const String& s, const float sizeForProportions) const
  72289. {
  72290. float n = s.getFloatValue();
  72291. const int len = s.length();
  72292. if (len > 2)
  72293. {
  72294. const float dpi = 96.0f;
  72295. const juce_wchar n1 = s [len - 2];
  72296. const juce_wchar n2 = s [len - 1];
  72297. if (n1 == 'i' && n2 == 'n')
  72298. n *= dpi;
  72299. else if (n1 == 'm' && n2 == 'm')
  72300. n *= dpi / 25.4f;
  72301. else if (n1 == 'c' && n2 == 'm')
  72302. n *= dpi / 2.54f;
  72303. else if (n1 == 'p' && n2 == 'c')
  72304. n *= 15.0f;
  72305. else if (n2 == '%')
  72306. n *= 0.01f * sizeForProportions;
  72307. }
  72308. return n;
  72309. }
  72310. void getCoordList (Array <float>& coords, const String& list,
  72311. const bool allowUnits, const bool isX) const
  72312. {
  72313. String::CharPointerType text (list.getCharPointer());
  72314. float value;
  72315. while (parseCoord (text, value, allowUnits, isX))
  72316. coords.add (value);
  72317. }
  72318. void parseCSSStyle (const XmlElement& xml)
  72319. {
  72320. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  72321. }
  72322. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  72323. const String& defaultValue = String::empty) const
  72324. {
  72325. if (xml->hasAttribute (attributeName))
  72326. return xml->getStringAttribute (attributeName, defaultValue);
  72327. const String styleAtt (xml->getStringAttribute ("style"));
  72328. if (styleAtt.isNotEmpty())
  72329. {
  72330. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  72331. if (value.isNotEmpty())
  72332. return value;
  72333. }
  72334. else if (xml->hasAttribute ("class"))
  72335. {
  72336. const String className ("." + xml->getStringAttribute ("class"));
  72337. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  72338. if (index < 0)
  72339. index = cssStyleText.indexOfIgnoreCase (className + "{");
  72340. if (index >= 0)
  72341. {
  72342. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72343. if (openBracket > index)
  72344. {
  72345. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72346. if (closeBracket > openBracket)
  72347. {
  72348. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72349. if (value.isNotEmpty())
  72350. return value;
  72351. }
  72352. }
  72353. }
  72354. }
  72355. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72356. if (xml != 0)
  72357. return getStyleAttribute (xml, attributeName, defaultValue);
  72358. return defaultValue;
  72359. }
  72360. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72361. {
  72362. if (xml->hasAttribute (attributeName))
  72363. return xml->getStringAttribute (attributeName);
  72364. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72365. if (xml != 0)
  72366. return getInheritedAttribute (xml, attributeName);
  72367. return String::empty;
  72368. }
  72369. static bool isIdentifierChar (const juce_wchar c)
  72370. {
  72371. return CharacterFunctions::isLetter (c) || c == '-';
  72372. }
  72373. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72374. {
  72375. int i = 0;
  72376. for (;;)
  72377. {
  72378. i = list.indexOf (i, attributeName);
  72379. if (i < 0)
  72380. break;
  72381. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72382. && ! isIdentifierChar (list [i + attributeName.length()]))
  72383. {
  72384. i = list.indexOfChar (i, ':');
  72385. if (i < 0)
  72386. break;
  72387. int end = list.indexOfChar (i, ';');
  72388. if (end < 0)
  72389. end = 0x7ffff;
  72390. return list.substring (i + 1, end).trim();
  72391. }
  72392. ++i;
  72393. }
  72394. return defaultValue;
  72395. }
  72396. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  72397. {
  72398. while (s.isWhitespace() || *s == ',')
  72399. ++s;
  72400. String::CharPointerType start (s);
  72401. int numChars = 0;
  72402. if (s.isDigit() || *s == '.' || *s == '-')
  72403. {
  72404. ++numChars;
  72405. ++s;
  72406. }
  72407. while (s.isDigit() || *s == '.')
  72408. {
  72409. ++numChars;
  72410. ++s;
  72411. }
  72412. if ((*s == 'e' || *s == 'E')
  72413. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  72414. {
  72415. s += 2;
  72416. numChars += 2;
  72417. while (s.isDigit())
  72418. {
  72419. ++numChars;
  72420. ++s;
  72421. }
  72422. }
  72423. if (allowUnits)
  72424. {
  72425. while (s.isLetter())
  72426. {
  72427. ++numChars;
  72428. ++s;
  72429. }
  72430. }
  72431. if (numChars == 0)
  72432. return false;
  72433. value = String (start, numChars);
  72434. while (s.isWhitespace() || *s == ',')
  72435. ++s;
  72436. return true;
  72437. }
  72438. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72439. {
  72440. if (s [index] == '#')
  72441. {
  72442. uint32 hex [6];
  72443. zeromem (hex, sizeof (hex));
  72444. int numChars = 0;
  72445. for (int i = 6; --i >= 0;)
  72446. {
  72447. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72448. if (hexValue >= 0)
  72449. hex [numChars++] = hexValue;
  72450. else
  72451. break;
  72452. }
  72453. if (numChars <= 3)
  72454. return Colour ((uint8) (hex [0] * 0x11),
  72455. (uint8) (hex [1] * 0x11),
  72456. (uint8) (hex [2] * 0x11));
  72457. else
  72458. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72459. (uint8) ((hex [2] << 4) + hex [3]),
  72460. (uint8) ((hex [4] << 4) + hex [5]));
  72461. }
  72462. else if (s [index] == 'r'
  72463. && s [index + 1] == 'g'
  72464. && s [index + 2] == 'b')
  72465. {
  72466. const int openBracket = s.indexOfChar (index, '(');
  72467. const int closeBracket = s.indexOfChar (openBracket, ')');
  72468. if (openBracket >= 3 && closeBracket > openBracket)
  72469. {
  72470. index = closeBracket;
  72471. StringArray tokens;
  72472. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72473. tokens.trim();
  72474. tokens.removeEmptyStrings();
  72475. if (tokens[0].containsChar ('%'))
  72476. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72477. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72478. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72479. else
  72480. return Colour ((uint8) tokens[0].getIntValue(),
  72481. (uint8) tokens[1].getIntValue(),
  72482. (uint8) tokens[2].getIntValue());
  72483. }
  72484. }
  72485. return Colours::findColourForName (s, defaultColour);
  72486. }
  72487. static const AffineTransform parseTransform (String t)
  72488. {
  72489. AffineTransform result;
  72490. while (t.isNotEmpty())
  72491. {
  72492. StringArray tokens;
  72493. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72494. .upToFirstOccurrenceOf (")", false, false),
  72495. ", ", String::empty);
  72496. tokens.removeEmptyStrings (true);
  72497. float numbers [6];
  72498. for (int i = 0; i < 6; ++i)
  72499. numbers[i] = tokens[i].getFloatValue();
  72500. AffineTransform trans;
  72501. if (t.startsWithIgnoreCase ("matrix"))
  72502. {
  72503. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72504. numbers[1], numbers[3], numbers[5]);
  72505. }
  72506. else if (t.startsWithIgnoreCase ("translate"))
  72507. {
  72508. jassert (tokens.size() == 2);
  72509. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72510. }
  72511. else if (t.startsWithIgnoreCase ("scale"))
  72512. {
  72513. if (tokens.size() == 1)
  72514. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72515. else
  72516. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72517. }
  72518. else if (t.startsWithIgnoreCase ("rotate"))
  72519. {
  72520. if (tokens.size() != 3)
  72521. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72522. else
  72523. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72524. numbers[1], numbers[2]);
  72525. }
  72526. else if (t.startsWithIgnoreCase ("skewX"))
  72527. {
  72528. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72529. 0.0f, 1.0f, 0.0f);
  72530. }
  72531. else if (t.startsWithIgnoreCase ("skewY"))
  72532. {
  72533. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72534. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72535. }
  72536. result = trans.followedBy (result);
  72537. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72538. }
  72539. return result;
  72540. }
  72541. static void endpointToCentreParameters (const double x1, const double y1,
  72542. const double x2, const double y2,
  72543. const double angle,
  72544. const bool largeArc, const bool sweep,
  72545. double& rx, double& ry,
  72546. double& centreX, double& centreY,
  72547. double& startAngle, double& deltaAngle)
  72548. {
  72549. const double midX = (x1 - x2) * 0.5;
  72550. const double midY = (y1 - y2) * 0.5;
  72551. const double cosAngle = cos (angle);
  72552. const double sinAngle = sin (angle);
  72553. const double xp = cosAngle * midX + sinAngle * midY;
  72554. const double yp = cosAngle * midY - sinAngle * midX;
  72555. const double xp2 = xp * xp;
  72556. const double yp2 = yp * yp;
  72557. double rx2 = rx * rx;
  72558. double ry2 = ry * ry;
  72559. const double s = (xp2 / rx2) + (yp2 / ry2);
  72560. double c;
  72561. if (s <= 1.0)
  72562. {
  72563. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72564. / (( rx2 * yp2) + (ry2 * xp2))));
  72565. if (largeArc == sweep)
  72566. c = -c;
  72567. }
  72568. else
  72569. {
  72570. const double s2 = std::sqrt (s);
  72571. rx *= s2;
  72572. ry *= s2;
  72573. rx2 = rx * rx;
  72574. ry2 = ry * ry;
  72575. c = 0;
  72576. }
  72577. const double cpx = ((rx * yp) / ry) * c;
  72578. const double cpy = ((-ry * xp) / rx) * c;
  72579. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72580. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72581. const double ux = (xp - cpx) / rx;
  72582. const double uy = (yp - cpy) / ry;
  72583. const double vx = (-xp - cpx) / rx;
  72584. const double vy = (-yp - cpy) / ry;
  72585. const double length = juce_hypot (ux, uy);
  72586. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72587. if (uy < 0)
  72588. startAngle = -startAngle;
  72589. startAngle += double_Pi * 0.5;
  72590. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72591. / (length * juce_hypot (vx, vy))));
  72592. if ((ux * vy) - (uy * vx) < 0)
  72593. deltaAngle = -deltaAngle;
  72594. if (sweep)
  72595. {
  72596. if (deltaAngle < 0)
  72597. deltaAngle += double_Pi * 2.0;
  72598. }
  72599. else
  72600. {
  72601. if (deltaAngle > 0)
  72602. deltaAngle -= double_Pi * 2.0;
  72603. }
  72604. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72605. }
  72606. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72607. {
  72608. forEachXmlChildElement (*parent, e)
  72609. {
  72610. if (e->compareAttribute ("id", id))
  72611. return e;
  72612. const XmlElement* const found = findElementForId (e, id);
  72613. if (found != 0)
  72614. return found;
  72615. }
  72616. return 0;
  72617. }
  72618. SVGState& operator= (const SVGState&);
  72619. };
  72620. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72621. {
  72622. SVGState state (&svgDocument);
  72623. return state.parseSVGElement (svgDocument);
  72624. }
  72625. END_JUCE_NAMESPACE
  72626. /*** End of inlined file: juce_SVGParser.cpp ***/
  72627. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72628. BEGIN_JUCE_NAMESPACE
  72629. #if JUCE_MSVC && JUCE_DEBUG
  72630. #pragma optimize ("t", on)
  72631. #endif
  72632. DropShadowEffect::DropShadowEffect()
  72633. : offsetX (0),
  72634. offsetY (0),
  72635. radius (4),
  72636. opacity (0.6f)
  72637. {
  72638. }
  72639. DropShadowEffect::~DropShadowEffect()
  72640. {
  72641. }
  72642. void DropShadowEffect::setShadowProperties (const float newRadius,
  72643. const float newOpacity,
  72644. const int newShadowOffsetX,
  72645. const int newShadowOffsetY)
  72646. {
  72647. radius = jmax (1.1f, newRadius);
  72648. offsetX = newShadowOffsetX;
  72649. offsetY = newShadowOffsetY;
  72650. opacity = newOpacity;
  72651. }
  72652. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72653. {
  72654. const int w = image.getWidth();
  72655. const int h = image.getHeight();
  72656. Image shadowImage (Image::SingleChannel, w, h, false);
  72657. {
  72658. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  72659. const Image::BitmapData destData (shadowImage, Image::BitmapData::readWrite);
  72660. const int filter = roundToInt (63.0f / radius);
  72661. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72662. for (int x = w; --x >= 0;)
  72663. {
  72664. int shadowAlpha = 0;
  72665. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72666. uint8* shadowPix = destData.data + x;
  72667. for (int y = h; --y >= 0;)
  72668. {
  72669. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72670. *shadowPix = (uint8) shadowAlpha;
  72671. src = addBytesToPointer (src, srcData.lineStride);
  72672. shadowPix += destData.lineStride;
  72673. }
  72674. }
  72675. for (int y = h; --y >= 0;)
  72676. {
  72677. int shadowAlpha = 0;
  72678. uint8* shadowPix = destData.getLinePointer (y);
  72679. for (int x = w; --x >= 0;)
  72680. {
  72681. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72682. *shadowPix++ = (uint8) shadowAlpha;
  72683. }
  72684. }
  72685. }
  72686. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72687. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72688. g.setOpacity (alpha);
  72689. g.drawImageAt (image, 0, 0);
  72690. }
  72691. #if JUCE_MSVC && JUCE_DEBUG
  72692. #pragma optimize ("", on) // resets optimisations to the project defaults
  72693. #endif
  72694. END_JUCE_NAMESPACE
  72695. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72696. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72697. BEGIN_JUCE_NAMESPACE
  72698. GlowEffect::GlowEffect()
  72699. : radius (2.0f),
  72700. colour (Colours::white)
  72701. {
  72702. }
  72703. GlowEffect::~GlowEffect()
  72704. {
  72705. }
  72706. void GlowEffect::setGlowProperties (const float newRadius,
  72707. const Colour& newColour)
  72708. {
  72709. radius = newRadius;
  72710. colour = newColour;
  72711. }
  72712. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72713. {
  72714. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72715. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72716. blurKernel.createGaussianBlur (radius);
  72717. blurKernel.rescaleAllValues (radius);
  72718. blurKernel.applyToImage (temp, image, image.getBounds());
  72719. g.setColour (colour.withMultipliedAlpha (alpha));
  72720. g.drawImageAt (temp, 0, 0, true);
  72721. g.setOpacity (alpha);
  72722. g.drawImageAt (image, 0, 0, false);
  72723. }
  72724. END_JUCE_NAMESPACE
  72725. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72726. /*** Start of inlined file: juce_Font.cpp ***/
  72727. BEGIN_JUCE_NAMESPACE
  72728. namespace FontValues
  72729. {
  72730. float limitFontHeight (const float height) throw()
  72731. {
  72732. return jlimit (0.1f, 10000.0f, height);
  72733. }
  72734. const float defaultFontHeight = 14.0f;
  72735. String fallbackFont;
  72736. }
  72737. class TypefaceCache : public DeletedAtShutdown
  72738. {
  72739. public:
  72740. TypefaceCache()
  72741. : counter (0)
  72742. {
  72743. setSize (10);
  72744. }
  72745. ~TypefaceCache()
  72746. {
  72747. clearSingletonInstance();
  72748. }
  72749. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72750. void setSize (const int numToCache)
  72751. {
  72752. faces.clear();
  72753. faces.insertMultiple (-1, CachedFace(), numToCache);
  72754. }
  72755. const Typeface::Ptr findTypefaceFor (const Font& font)
  72756. {
  72757. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72758. const String faceName (font.getTypefaceName());
  72759. int i;
  72760. for (i = faces.size(); --i >= 0;)
  72761. {
  72762. CachedFace& face = faces.getReference(i);
  72763. if (face.flags == flags
  72764. && face.typefaceName == faceName
  72765. && face.typeface->isSuitableForFont (font))
  72766. {
  72767. face.lastUsageCount = ++counter;
  72768. return face.typeface;
  72769. }
  72770. }
  72771. int replaceIndex = 0;
  72772. int bestLastUsageCount = std::numeric_limits<int>::max();
  72773. for (i = faces.size(); --i >= 0;)
  72774. {
  72775. const int lu = faces.getReference(i).lastUsageCount;
  72776. if (bestLastUsageCount > lu)
  72777. {
  72778. bestLastUsageCount = lu;
  72779. replaceIndex = i;
  72780. }
  72781. }
  72782. CachedFace& face = faces.getReference (replaceIndex);
  72783. face.typefaceName = faceName;
  72784. face.flags = flags;
  72785. face.lastUsageCount = ++counter;
  72786. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72787. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72788. if (defaultFace == 0 && font == Font())
  72789. defaultFace = face.typeface;
  72790. return face.typeface;
  72791. }
  72792. const Typeface::Ptr getDefaultTypeface() const throw()
  72793. {
  72794. return defaultFace;
  72795. }
  72796. private:
  72797. struct CachedFace
  72798. {
  72799. CachedFace() throw()
  72800. : lastUsageCount (0), flags (-1)
  72801. {
  72802. }
  72803. // Although it seems a bit wacky to store the name here, it's because it may be a
  72804. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72805. // Since the typeface itself doesn't know that it may have this alias, the name under
  72806. // which it was fetched needs to be stored separately.
  72807. String typefaceName;
  72808. int lastUsageCount, flags;
  72809. Typeface::Ptr typeface;
  72810. };
  72811. Array <CachedFace> faces;
  72812. Typeface::Ptr defaultFace;
  72813. int counter;
  72814. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72815. };
  72816. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72817. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72818. {
  72819. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72820. }
  72821. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72822. : typefaceName (Font::getDefaultSansSerifFontName()),
  72823. height (height_),
  72824. horizontalScale (1.0f),
  72825. kerning (0),
  72826. ascent (0),
  72827. styleFlags (styleFlags_),
  72828. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72829. {
  72830. }
  72831. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72832. : typefaceName (typefaceName_),
  72833. height (height_),
  72834. horizontalScale (1.0f),
  72835. kerning (0),
  72836. ascent (0),
  72837. styleFlags (styleFlags_),
  72838. typeface (0)
  72839. {
  72840. }
  72841. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72842. : typefaceName (typeface_->getName()),
  72843. height (FontValues::defaultFontHeight),
  72844. horizontalScale (1.0f),
  72845. kerning (0),
  72846. ascent (0),
  72847. styleFlags (Font::plain),
  72848. typeface (typeface_)
  72849. {
  72850. }
  72851. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72852. : typefaceName (other.typefaceName),
  72853. height (other.height),
  72854. horizontalScale (other.horizontalScale),
  72855. kerning (other.kerning),
  72856. ascent (other.ascent),
  72857. styleFlags (other.styleFlags),
  72858. typeface (other.typeface)
  72859. {
  72860. }
  72861. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72862. {
  72863. return height == other.height
  72864. && styleFlags == other.styleFlags
  72865. && horizontalScale == other.horizontalScale
  72866. && kerning == other.kerning
  72867. && typefaceName == other.typefaceName;
  72868. }
  72869. Font::Font()
  72870. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72871. {
  72872. }
  72873. Font::Font (const float fontHeight, const int styleFlags_)
  72874. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72875. {
  72876. }
  72877. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72878. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72879. {
  72880. }
  72881. Font::Font (const Typeface::Ptr& typeface)
  72882. : font (new SharedFontInternal (typeface))
  72883. {
  72884. }
  72885. Font::Font (const Font& other) throw()
  72886. : font (other.font)
  72887. {
  72888. }
  72889. Font& Font::operator= (const Font& other) throw()
  72890. {
  72891. font = other.font;
  72892. return *this;
  72893. }
  72894. Font::~Font() throw()
  72895. {
  72896. }
  72897. bool Font::operator== (const Font& other) const throw()
  72898. {
  72899. return font == other.font
  72900. || *font == *other.font;
  72901. }
  72902. bool Font::operator!= (const Font& other) const throw()
  72903. {
  72904. return ! operator== (other);
  72905. }
  72906. void Font::dupeInternalIfShared()
  72907. {
  72908. if (font->getReferenceCount() > 1)
  72909. font = new SharedFontInternal (*font);
  72910. }
  72911. const String Font::getDefaultSansSerifFontName()
  72912. {
  72913. static const String name ("<Sans-Serif>");
  72914. return name;
  72915. }
  72916. const String Font::getDefaultSerifFontName()
  72917. {
  72918. static const String name ("<Serif>");
  72919. return name;
  72920. }
  72921. const String Font::getDefaultMonospacedFontName()
  72922. {
  72923. static const String name ("<Monospaced>");
  72924. return name;
  72925. }
  72926. void Font::setTypefaceName (const String& faceName)
  72927. {
  72928. if (faceName != font->typefaceName)
  72929. {
  72930. dupeInternalIfShared();
  72931. font->typefaceName = faceName;
  72932. font->typeface = 0;
  72933. font->ascent = 0;
  72934. }
  72935. }
  72936. const String Font::getFallbackFontName()
  72937. {
  72938. return FontValues::fallbackFont;
  72939. }
  72940. void Font::setFallbackFontName (const String& name)
  72941. {
  72942. FontValues::fallbackFont = name;
  72943. }
  72944. void Font::setHeight (float newHeight)
  72945. {
  72946. newHeight = FontValues::limitFontHeight (newHeight);
  72947. if (font->height != newHeight)
  72948. {
  72949. dupeInternalIfShared();
  72950. font->height = newHeight;
  72951. }
  72952. }
  72953. void Font::setHeightWithoutChangingWidth (float newHeight)
  72954. {
  72955. newHeight = FontValues::limitFontHeight (newHeight);
  72956. if (font->height != newHeight)
  72957. {
  72958. dupeInternalIfShared();
  72959. font->horizontalScale *= (font->height / newHeight);
  72960. font->height = newHeight;
  72961. }
  72962. }
  72963. void Font::setStyleFlags (const int newFlags)
  72964. {
  72965. if (font->styleFlags != newFlags)
  72966. {
  72967. dupeInternalIfShared();
  72968. font->styleFlags = newFlags;
  72969. font->typeface = 0;
  72970. font->ascent = 0;
  72971. }
  72972. }
  72973. void Font::setSizeAndStyle (float newHeight,
  72974. const int newStyleFlags,
  72975. const float newHorizontalScale,
  72976. const float newKerningAmount)
  72977. {
  72978. newHeight = FontValues::limitFontHeight (newHeight);
  72979. if (font->height != newHeight
  72980. || font->horizontalScale != newHorizontalScale
  72981. || font->kerning != newKerningAmount)
  72982. {
  72983. dupeInternalIfShared();
  72984. font->height = newHeight;
  72985. font->horizontalScale = newHorizontalScale;
  72986. font->kerning = newKerningAmount;
  72987. }
  72988. setStyleFlags (newStyleFlags);
  72989. }
  72990. void Font::setHorizontalScale (const float scaleFactor)
  72991. {
  72992. dupeInternalIfShared();
  72993. font->horizontalScale = scaleFactor;
  72994. }
  72995. void Font::setExtraKerningFactor (const float extraKerning)
  72996. {
  72997. dupeInternalIfShared();
  72998. font->kerning = extraKerning;
  72999. }
  73000. void Font::setBold (const bool shouldBeBold)
  73001. {
  73002. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  73003. : (font->styleFlags & ~bold));
  73004. }
  73005. const Font Font::boldened() const
  73006. {
  73007. Font f (*this);
  73008. f.setBold (true);
  73009. return f;
  73010. }
  73011. bool Font::isBold() const throw()
  73012. {
  73013. return (font->styleFlags & bold) != 0;
  73014. }
  73015. void Font::setItalic (const bool shouldBeItalic)
  73016. {
  73017. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  73018. : (font->styleFlags & ~italic));
  73019. }
  73020. const Font Font::italicised() const
  73021. {
  73022. Font f (*this);
  73023. f.setItalic (true);
  73024. return f;
  73025. }
  73026. bool Font::isItalic() const throw()
  73027. {
  73028. return (font->styleFlags & italic) != 0;
  73029. }
  73030. void Font::setUnderline (const bool shouldBeUnderlined)
  73031. {
  73032. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  73033. : (font->styleFlags & ~underlined));
  73034. }
  73035. bool Font::isUnderlined() const throw()
  73036. {
  73037. return (font->styleFlags & underlined) != 0;
  73038. }
  73039. float Font::getAscent() const
  73040. {
  73041. if (font->ascent == 0)
  73042. font->ascent = getTypeface()->getAscent();
  73043. return font->height * font->ascent;
  73044. }
  73045. float Font::getDescent() const
  73046. {
  73047. return font->height - getAscent();
  73048. }
  73049. int Font::getStringWidth (const String& text) const
  73050. {
  73051. return roundToInt (getStringWidthFloat (text));
  73052. }
  73053. float Font::getStringWidthFloat (const String& text) const
  73054. {
  73055. float w = getTypeface()->getStringWidth (text);
  73056. if (font->kerning != 0)
  73057. w += font->kerning * text.length();
  73058. return w * font->height * font->horizontalScale;
  73059. }
  73060. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  73061. {
  73062. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  73063. const float scale = font->height * font->horizontalScale;
  73064. const int num = xOffsets.size();
  73065. if (num > 0)
  73066. {
  73067. float* const x = &(xOffsets.getReference(0));
  73068. if (font->kerning != 0)
  73069. {
  73070. for (int i = 0; i < num; ++i)
  73071. x[i] = (x[i] + i * font->kerning) * scale;
  73072. }
  73073. else
  73074. {
  73075. for (int i = 0; i < num; ++i)
  73076. x[i] *= scale;
  73077. }
  73078. }
  73079. }
  73080. void Font::findFonts (Array<Font>& destArray)
  73081. {
  73082. const StringArray names (findAllTypefaceNames());
  73083. for (int i = 0; i < names.size(); ++i)
  73084. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  73085. }
  73086. const String Font::toString() const
  73087. {
  73088. String s (getTypefaceName());
  73089. if (s == getDefaultSansSerifFontName())
  73090. s = String::empty;
  73091. else
  73092. s += "; ";
  73093. s += String (getHeight(), 1);
  73094. if (isBold())
  73095. s += " bold";
  73096. if (isItalic())
  73097. s += " italic";
  73098. return s;
  73099. }
  73100. const Font Font::fromString (const String& fontDescription)
  73101. {
  73102. String name;
  73103. const int separator = fontDescription.indexOfChar (';');
  73104. if (separator > 0)
  73105. name = fontDescription.substring (0, separator).trim();
  73106. if (name.isEmpty())
  73107. name = getDefaultSansSerifFontName();
  73108. String sizeAndStyle (fontDescription.substring (separator + 1));
  73109. float height = sizeAndStyle.getFloatValue();
  73110. if (height <= 0)
  73111. height = 10.0f;
  73112. int flags = Font::plain;
  73113. if (sizeAndStyle.containsIgnoreCase ("bold"))
  73114. flags |= Font::bold;
  73115. if (sizeAndStyle.containsIgnoreCase ("italic"))
  73116. flags |= Font::italic;
  73117. return Font (name, height, flags);
  73118. }
  73119. Typeface* Font::getTypeface() const
  73120. {
  73121. if (font->typeface == 0)
  73122. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  73123. return font->typeface;
  73124. }
  73125. END_JUCE_NAMESPACE
  73126. /*** End of inlined file: juce_Font.cpp ***/
  73127. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  73128. BEGIN_JUCE_NAMESPACE
  73129. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  73130. const juce_wchar character_, const int glyph_)
  73131. : x (x_),
  73132. y (y_),
  73133. w (w_),
  73134. font (font_),
  73135. character (character_),
  73136. glyph (glyph_)
  73137. {
  73138. }
  73139. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  73140. : x (other.x),
  73141. y (other.y),
  73142. w (other.w),
  73143. font (other.font),
  73144. character (other.character),
  73145. glyph (other.glyph)
  73146. {
  73147. }
  73148. void PositionedGlyph::draw (const Graphics& g) const
  73149. {
  73150. if (! isWhitespace())
  73151. {
  73152. g.getInternalContext()->setFont (font);
  73153. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  73154. }
  73155. }
  73156. void PositionedGlyph::draw (const Graphics& g,
  73157. const AffineTransform& transform) const
  73158. {
  73159. if (! isWhitespace())
  73160. {
  73161. g.getInternalContext()->setFont (font);
  73162. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  73163. .followedBy (transform));
  73164. }
  73165. }
  73166. void PositionedGlyph::createPath (Path& path) const
  73167. {
  73168. if (! isWhitespace())
  73169. {
  73170. Typeface* const t = font.getTypeface();
  73171. if (t != 0)
  73172. {
  73173. Path p;
  73174. t->getOutlineForGlyph (glyph, p);
  73175. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  73176. .translated (x, y));
  73177. }
  73178. }
  73179. }
  73180. bool PositionedGlyph::hitTest (float px, float py) const
  73181. {
  73182. if (getBounds().contains (px, py) && ! isWhitespace())
  73183. {
  73184. Typeface* const t = font.getTypeface();
  73185. if (t != 0)
  73186. {
  73187. Path p;
  73188. t->getOutlineForGlyph (glyph, p);
  73189. AffineTransform::translation (-x, -y)
  73190. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  73191. .transformPoint (px, py);
  73192. return p.contains (px, py);
  73193. }
  73194. }
  73195. return false;
  73196. }
  73197. void PositionedGlyph::moveBy (const float deltaX,
  73198. const float deltaY)
  73199. {
  73200. x += deltaX;
  73201. y += deltaY;
  73202. }
  73203. GlyphArrangement::GlyphArrangement()
  73204. {
  73205. glyphs.ensureStorageAllocated (128);
  73206. }
  73207. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  73208. {
  73209. addGlyphArrangement (other);
  73210. }
  73211. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  73212. {
  73213. if (this != &other)
  73214. {
  73215. clear();
  73216. addGlyphArrangement (other);
  73217. }
  73218. return *this;
  73219. }
  73220. GlyphArrangement::~GlyphArrangement()
  73221. {
  73222. }
  73223. void GlyphArrangement::clear()
  73224. {
  73225. glyphs.clear();
  73226. }
  73227. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  73228. {
  73229. jassert (isPositiveAndBelow (index, glyphs.size()));
  73230. return *glyphs [index];
  73231. }
  73232. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  73233. {
  73234. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  73235. glyphs.addCopiesOf (other.glyphs);
  73236. }
  73237. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  73238. {
  73239. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  73240. }
  73241. void GlyphArrangement::addLineOfText (const Font& font,
  73242. const String& text,
  73243. const float xOffset,
  73244. const float yOffset)
  73245. {
  73246. addCurtailedLineOfText (font, text,
  73247. xOffset, yOffset,
  73248. 1.0e10f, false);
  73249. }
  73250. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  73251. const String& text,
  73252. float xOffset,
  73253. const float yOffset,
  73254. const float maxWidthPixels,
  73255. const bool useEllipsis)
  73256. {
  73257. if (text.isNotEmpty())
  73258. {
  73259. Array <int> newGlyphs;
  73260. Array <float> xOffsets;
  73261. font.getGlyphPositions (text, newGlyphs, xOffsets);
  73262. const int textLen = newGlyphs.size();
  73263. String::CharPointerType t (text.getCharPointer());
  73264. for (int i = 0; i < textLen; ++i)
  73265. {
  73266. const float thisX = xOffsets.getUnchecked (i);
  73267. const float nextX = xOffsets.getUnchecked (i + 1);
  73268. if (nextX > maxWidthPixels + 1.0f)
  73269. {
  73270. // curtail the string if it's too wide..
  73271. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  73272. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  73273. break;
  73274. }
  73275. else
  73276. {
  73277. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  73278. font, t.getAndAdvance(), newGlyphs.getUnchecked(i)));
  73279. }
  73280. }
  73281. }
  73282. }
  73283. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  73284. const int startIndex, int endIndex)
  73285. {
  73286. int numDeleted = 0;
  73287. if (glyphs.size() > 0)
  73288. {
  73289. Array<int> dotGlyphs;
  73290. Array<float> dotXs;
  73291. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  73292. const float dx = dotXs[1];
  73293. float xOffset = 0.0f, yOffset = 0.0f;
  73294. while (endIndex > startIndex)
  73295. {
  73296. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  73297. xOffset = pg->x;
  73298. yOffset = pg->y;
  73299. glyphs.remove (endIndex);
  73300. ++numDeleted;
  73301. if (xOffset + dx * 3 <= maxXPos)
  73302. break;
  73303. }
  73304. for (int i = 3; --i >= 0;)
  73305. {
  73306. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  73307. font, '.', dotGlyphs.getFirst()));
  73308. --numDeleted;
  73309. xOffset += dx;
  73310. if (xOffset > maxXPos)
  73311. break;
  73312. }
  73313. }
  73314. return numDeleted;
  73315. }
  73316. void GlyphArrangement::addJustifiedText (const Font& font,
  73317. const String& text,
  73318. float x, float y,
  73319. const float maxLineWidth,
  73320. const Justification& horizontalLayout)
  73321. {
  73322. int lineStartIndex = glyphs.size();
  73323. addLineOfText (font, text, x, y);
  73324. const float originalY = y;
  73325. while (lineStartIndex < glyphs.size())
  73326. {
  73327. int i = lineStartIndex;
  73328. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  73329. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  73330. ++i;
  73331. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  73332. int lastWordBreakIndex = -1;
  73333. while (i < glyphs.size())
  73334. {
  73335. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  73336. const juce_wchar c = pg->getCharacter();
  73337. if (c == '\r' || c == '\n')
  73338. {
  73339. ++i;
  73340. if (c == '\r' && i < glyphs.size()
  73341. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  73342. ++i;
  73343. break;
  73344. }
  73345. else if (pg->isWhitespace())
  73346. {
  73347. lastWordBreakIndex = i + 1;
  73348. }
  73349. else if (pg->getRight() - 0.0001f >= lineMaxX)
  73350. {
  73351. if (lastWordBreakIndex >= 0)
  73352. i = lastWordBreakIndex;
  73353. break;
  73354. }
  73355. ++i;
  73356. }
  73357. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73358. float currentLineEndX = currentLineStartX;
  73359. for (int j = i; --j >= lineStartIndex;)
  73360. {
  73361. if (! glyphs.getUnchecked (j)->isWhitespace())
  73362. {
  73363. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73364. break;
  73365. }
  73366. }
  73367. float deltaX = 0.0f;
  73368. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73369. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73370. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73371. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73372. else if (horizontalLayout.testFlags (Justification::right))
  73373. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73374. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73375. x + deltaX - currentLineStartX, y - originalY);
  73376. lineStartIndex = i;
  73377. y += font.getHeight();
  73378. }
  73379. }
  73380. void GlyphArrangement::addFittedText (const Font& f,
  73381. const String& text,
  73382. const float x, const float y,
  73383. const float width, const float height,
  73384. const Justification& layout,
  73385. int maximumLines,
  73386. const float minimumHorizontalScale)
  73387. {
  73388. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73389. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73390. if (text.containsAnyOf ("\r\n"))
  73391. {
  73392. GlyphArrangement ga;
  73393. ga.addJustifiedText (f, text, x, y, width, layout);
  73394. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73395. float dy = y - bb.getY();
  73396. if (layout.testFlags (Justification::verticallyCentred))
  73397. dy += (height - bb.getHeight()) * 0.5f;
  73398. else if (layout.testFlags (Justification::bottom))
  73399. dy += height - bb.getHeight();
  73400. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73401. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73402. for (int i = 0; i < ga.glyphs.size(); ++i)
  73403. glyphs.add (ga.glyphs.getUnchecked (i));
  73404. ga.glyphs.clear (false);
  73405. return;
  73406. }
  73407. int startIndex = glyphs.size();
  73408. addLineOfText (f, text.trim(), x, y);
  73409. if (glyphs.size() > startIndex)
  73410. {
  73411. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73412. - glyphs.getUnchecked (startIndex)->getLeft();
  73413. if (lineWidth <= 0)
  73414. return;
  73415. if (lineWidth * minimumHorizontalScale < width)
  73416. {
  73417. if (lineWidth > width)
  73418. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73419. width / lineWidth);
  73420. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73421. x, y, width, height, layout);
  73422. }
  73423. else if (maximumLines <= 1)
  73424. {
  73425. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73426. x, y, width, height, f, layout, minimumHorizontalScale);
  73427. }
  73428. else
  73429. {
  73430. Font font (f);
  73431. String txt (text.trim());
  73432. const int length = txt.length();
  73433. const int originalStartIndex = startIndex;
  73434. int numLines = 1;
  73435. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73436. maximumLines = 1;
  73437. maximumLines = jmin (maximumLines, length);
  73438. while (numLines < maximumLines)
  73439. {
  73440. ++numLines;
  73441. const float newFontHeight = height / (float) numLines;
  73442. if (newFontHeight < font.getHeight())
  73443. {
  73444. font.setHeight (jmax (8.0f, newFontHeight));
  73445. removeRangeOfGlyphs (startIndex, -1);
  73446. addLineOfText (font, txt, x, y);
  73447. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73448. - glyphs.getUnchecked (startIndex)->getLeft();
  73449. }
  73450. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73451. break;
  73452. }
  73453. if (numLines < 1)
  73454. numLines = 1;
  73455. float lineY = y;
  73456. float widthPerLine = lineWidth / numLines;
  73457. int lastLineStartIndex = 0;
  73458. for (int line = 0; line < numLines; ++line)
  73459. {
  73460. int i = startIndex;
  73461. lastLineStartIndex = i;
  73462. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73463. if (line == numLines - 1)
  73464. {
  73465. widthPerLine = width;
  73466. i = glyphs.size();
  73467. }
  73468. else
  73469. {
  73470. while (i < glyphs.size())
  73471. {
  73472. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73473. if (lineWidth > widthPerLine)
  73474. {
  73475. // got to a point where the line's too long, so skip forward to find a
  73476. // good place to break it..
  73477. const int searchStartIndex = i;
  73478. while (i < glyphs.size())
  73479. {
  73480. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73481. {
  73482. if (glyphs.getUnchecked (i)->isWhitespace()
  73483. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73484. {
  73485. ++i;
  73486. break;
  73487. }
  73488. }
  73489. else
  73490. {
  73491. // can't find a suitable break, so try looking backwards..
  73492. i = searchStartIndex;
  73493. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73494. {
  73495. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73496. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73497. {
  73498. i -= back - 1;
  73499. break;
  73500. }
  73501. }
  73502. break;
  73503. }
  73504. ++i;
  73505. }
  73506. break;
  73507. }
  73508. ++i;
  73509. }
  73510. int wsStart = i;
  73511. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73512. --wsStart;
  73513. int wsEnd = i;
  73514. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73515. ++wsEnd;
  73516. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73517. i = jmax (wsStart, startIndex + 1);
  73518. }
  73519. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73520. x, lineY, width, font.getHeight(), font,
  73521. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73522. minimumHorizontalScale);
  73523. startIndex = i;
  73524. lineY += font.getHeight();
  73525. if (startIndex >= glyphs.size())
  73526. break;
  73527. }
  73528. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73529. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73530. }
  73531. }
  73532. }
  73533. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73534. const float dx, const float dy)
  73535. {
  73536. jassert (startIndex >= 0);
  73537. if (dx != 0.0f || dy != 0.0f)
  73538. {
  73539. if (num < 0 || startIndex + num > glyphs.size())
  73540. num = glyphs.size() - startIndex;
  73541. while (--num >= 0)
  73542. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73543. }
  73544. }
  73545. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73546. const Justification& justification, float minimumHorizontalScale)
  73547. {
  73548. int numDeleted = 0;
  73549. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73550. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73551. if (lineWidth > w)
  73552. {
  73553. if (minimumHorizontalScale < 1.0f)
  73554. {
  73555. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73556. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73557. }
  73558. if (lineWidth > w)
  73559. {
  73560. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73561. numGlyphs -= numDeleted;
  73562. }
  73563. }
  73564. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73565. return numDeleted;
  73566. }
  73567. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73568. const float horizontalScaleFactor)
  73569. {
  73570. jassert (startIndex >= 0);
  73571. if (num < 0 || startIndex + num > glyphs.size())
  73572. num = glyphs.size() - startIndex;
  73573. if (num > 0)
  73574. {
  73575. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73576. while (--num >= 0)
  73577. {
  73578. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73579. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73580. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73581. pg->w *= horizontalScaleFactor;
  73582. }
  73583. }
  73584. }
  73585. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73586. {
  73587. jassert (startIndex >= 0);
  73588. if (num < 0 || startIndex + num > glyphs.size())
  73589. num = glyphs.size() - startIndex;
  73590. Rectangle<float> result;
  73591. while (--num >= 0)
  73592. {
  73593. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73594. if (includeWhitespace || ! pg->isWhitespace())
  73595. result = result.getUnion (pg->getBounds());
  73596. }
  73597. return result;
  73598. }
  73599. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73600. const float x, const float y, const float width, const float height,
  73601. const Justification& justification)
  73602. {
  73603. jassert (num >= 0 && startIndex >= 0);
  73604. if (glyphs.size() > 0 && num > 0)
  73605. {
  73606. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73607. | Justification::horizontallyCentred)));
  73608. float deltaX = 0.0f;
  73609. if (justification.testFlags (Justification::horizontallyJustified))
  73610. deltaX = x - bb.getX();
  73611. else if (justification.testFlags (Justification::horizontallyCentred))
  73612. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73613. else if (justification.testFlags (Justification::right))
  73614. deltaX = (x + width) - bb.getRight();
  73615. else
  73616. deltaX = x - bb.getX();
  73617. float deltaY = 0.0f;
  73618. if (justification.testFlags (Justification::top))
  73619. deltaY = y - bb.getY();
  73620. else if (justification.testFlags (Justification::bottom))
  73621. deltaY = (y + height) - bb.getBottom();
  73622. else
  73623. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73624. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73625. if (justification.testFlags (Justification::horizontallyJustified))
  73626. {
  73627. int lineStart = 0;
  73628. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73629. int i;
  73630. for (i = 0; i < num; ++i)
  73631. {
  73632. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73633. if (glyphY != baseY)
  73634. {
  73635. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73636. lineStart = i;
  73637. baseY = glyphY;
  73638. }
  73639. }
  73640. if (i > lineStart)
  73641. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73642. }
  73643. }
  73644. }
  73645. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73646. {
  73647. if (start + num < glyphs.size()
  73648. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73649. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73650. {
  73651. int numSpaces = 0;
  73652. int spacesAtEnd = 0;
  73653. for (int i = 0; i < num; ++i)
  73654. {
  73655. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73656. {
  73657. ++spacesAtEnd;
  73658. ++numSpaces;
  73659. }
  73660. else
  73661. {
  73662. spacesAtEnd = 0;
  73663. }
  73664. }
  73665. numSpaces -= spacesAtEnd;
  73666. if (numSpaces > 0)
  73667. {
  73668. const float startX = glyphs.getUnchecked (start)->getLeft();
  73669. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73670. const float extraPaddingBetweenWords
  73671. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73672. float deltaX = 0.0f;
  73673. for (int i = 0; i < num; ++i)
  73674. {
  73675. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73676. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73677. deltaX += extraPaddingBetweenWords;
  73678. }
  73679. }
  73680. }
  73681. }
  73682. void GlyphArrangement::draw (const Graphics& g) const
  73683. {
  73684. for (int i = 0; i < glyphs.size(); ++i)
  73685. {
  73686. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73687. if (pg->font.isUnderlined())
  73688. {
  73689. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73690. float nextX = pg->x + pg->w;
  73691. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73692. nextX = glyphs.getUnchecked (i + 1)->x;
  73693. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73694. nextX - pg->x, lineThickness);
  73695. }
  73696. pg->draw (g);
  73697. }
  73698. }
  73699. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73700. {
  73701. for (int i = 0; i < glyphs.size(); ++i)
  73702. {
  73703. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73704. if (pg->font.isUnderlined())
  73705. {
  73706. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73707. float nextX = pg->x + pg->w;
  73708. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73709. nextX = glyphs.getUnchecked (i + 1)->x;
  73710. Path p;
  73711. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73712. nextX, pg->y + lineThickness * 2.0f),
  73713. lineThickness);
  73714. g.fillPath (p, transform);
  73715. }
  73716. pg->draw (g, transform);
  73717. }
  73718. }
  73719. void GlyphArrangement::createPath (Path& path) const
  73720. {
  73721. for (int i = 0; i < glyphs.size(); ++i)
  73722. glyphs.getUnchecked (i)->createPath (path);
  73723. }
  73724. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73725. {
  73726. for (int i = 0; i < glyphs.size(); ++i)
  73727. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73728. return i;
  73729. return -1;
  73730. }
  73731. END_JUCE_NAMESPACE
  73732. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73733. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73734. BEGIN_JUCE_NAMESPACE
  73735. class TextLayout::Token
  73736. {
  73737. public:
  73738. Token (const String& t,
  73739. const Font& f,
  73740. const bool isWhitespace_)
  73741. : text (t),
  73742. font (f),
  73743. x(0),
  73744. y(0),
  73745. isWhitespace (isWhitespace_)
  73746. {
  73747. w = font.getStringWidth (t);
  73748. h = roundToInt (f.getHeight());
  73749. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73750. }
  73751. Token (const Token& other)
  73752. : text (other.text),
  73753. font (other.font),
  73754. x (other.x),
  73755. y (other.y),
  73756. w (other.w),
  73757. h (other.h),
  73758. line (other.line),
  73759. lineHeight (other.lineHeight),
  73760. isWhitespace (other.isWhitespace),
  73761. isNewLine (other.isNewLine)
  73762. {
  73763. }
  73764. void draw (Graphics& g,
  73765. const int xOffset,
  73766. const int yOffset)
  73767. {
  73768. if (! isWhitespace)
  73769. {
  73770. g.setFont (font);
  73771. g.drawSingleLineText (text.trimEnd(),
  73772. xOffset + x,
  73773. yOffset + y + (lineHeight - h)
  73774. + roundToInt (font.getAscent()));
  73775. }
  73776. }
  73777. String text;
  73778. Font font;
  73779. int x, y, w, h;
  73780. int line, lineHeight;
  73781. bool isWhitespace, isNewLine;
  73782. private:
  73783. JUCE_LEAK_DETECTOR (Token);
  73784. };
  73785. TextLayout::TextLayout()
  73786. : totalLines (0)
  73787. {
  73788. tokens.ensureStorageAllocated (64);
  73789. }
  73790. TextLayout::TextLayout (const String& text, const Font& font)
  73791. : totalLines (0)
  73792. {
  73793. tokens.ensureStorageAllocated (64);
  73794. appendText (text, font);
  73795. }
  73796. TextLayout::TextLayout (const TextLayout& other)
  73797. : totalLines (0)
  73798. {
  73799. *this = other;
  73800. }
  73801. TextLayout& TextLayout::operator= (const TextLayout& other)
  73802. {
  73803. if (this != &other)
  73804. {
  73805. clear();
  73806. totalLines = other.totalLines;
  73807. tokens.addCopiesOf (other.tokens);
  73808. }
  73809. return *this;
  73810. }
  73811. TextLayout::~TextLayout()
  73812. {
  73813. clear();
  73814. }
  73815. void TextLayout::clear()
  73816. {
  73817. tokens.clear();
  73818. totalLines = 0;
  73819. }
  73820. bool TextLayout::isEmpty() const
  73821. {
  73822. return tokens.size() == 0;
  73823. }
  73824. void TextLayout::appendText (const String& text, const Font& font)
  73825. {
  73826. String::CharPointerType t (text.getCharPointer());
  73827. String currentString;
  73828. int lastCharType = 0;
  73829. for (;;)
  73830. {
  73831. const juce_wchar c = t.getAndAdvance();
  73832. if (c == 0)
  73833. break;
  73834. int charType;
  73835. if (c == '\r' || c == '\n')
  73836. {
  73837. charType = 0;
  73838. }
  73839. else if (CharacterFunctions::isWhitespace (c))
  73840. {
  73841. charType = 2;
  73842. }
  73843. else
  73844. {
  73845. charType = 1;
  73846. }
  73847. if (charType == 0 || charType != lastCharType)
  73848. {
  73849. if (currentString.isNotEmpty())
  73850. {
  73851. tokens.add (new Token (currentString, font,
  73852. lastCharType == 2 || lastCharType == 0));
  73853. }
  73854. currentString = String::charToString (c);
  73855. if (c == '\r' && *t == '\n')
  73856. currentString += t.getAndAdvance();
  73857. }
  73858. else
  73859. {
  73860. currentString += c;
  73861. }
  73862. lastCharType = charType;
  73863. }
  73864. if (currentString.isNotEmpty())
  73865. tokens.add (new Token (currentString, font, lastCharType == 2));
  73866. }
  73867. void TextLayout::setText (const String& text, const Font& font)
  73868. {
  73869. clear();
  73870. appendText (text, font);
  73871. }
  73872. void TextLayout::layout (int maxWidth,
  73873. const Justification& justification,
  73874. const bool attemptToBalanceLineLengths)
  73875. {
  73876. if (attemptToBalanceLineLengths)
  73877. {
  73878. const int originalW = maxWidth;
  73879. int bestWidth = maxWidth;
  73880. float bestLineProportion = 0.0f;
  73881. while (maxWidth > originalW / 2)
  73882. {
  73883. layout (maxWidth, justification, false);
  73884. if (getNumLines() <= 1)
  73885. return;
  73886. const int lastLineW = getLineWidth (getNumLines() - 1);
  73887. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73888. const float prop = lastLineW / (float) lastButOneLineW;
  73889. if (prop > 0.9f)
  73890. return;
  73891. if (prop > bestLineProportion)
  73892. {
  73893. bestLineProportion = prop;
  73894. bestWidth = maxWidth;
  73895. }
  73896. maxWidth -= 10;
  73897. }
  73898. layout (bestWidth, justification, false);
  73899. }
  73900. else
  73901. {
  73902. int x = 0;
  73903. int y = 0;
  73904. int h = 0;
  73905. totalLines = 0;
  73906. int i;
  73907. for (i = 0; i < tokens.size(); ++i)
  73908. {
  73909. Token* const t = tokens.getUnchecked(i);
  73910. t->x = x;
  73911. t->y = y;
  73912. t->line = totalLines;
  73913. x += t->w;
  73914. h = jmax (h, t->h);
  73915. const Token* nextTok = tokens [i + 1];
  73916. if (nextTok == 0)
  73917. break;
  73918. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73919. {
  73920. // finished a line, so go back and update the heights of the things on it
  73921. for (int j = i; j >= 0; --j)
  73922. {
  73923. Token* const tok = tokens.getUnchecked(j);
  73924. if (tok->line == totalLines)
  73925. tok->lineHeight = h;
  73926. else
  73927. break;
  73928. }
  73929. x = 0;
  73930. y += h;
  73931. h = 0;
  73932. ++totalLines;
  73933. }
  73934. }
  73935. // finished a line, so go back and update the heights of the things on it
  73936. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73937. {
  73938. Token* const t = tokens.getUnchecked(j);
  73939. if (t->line == totalLines)
  73940. t->lineHeight = h;
  73941. else
  73942. break;
  73943. }
  73944. ++totalLines;
  73945. if (! justification.testFlags (Justification::left))
  73946. {
  73947. int totalW = getWidth();
  73948. for (i = totalLines; --i >= 0;)
  73949. {
  73950. const int lineW = getLineWidth (i);
  73951. int dx = 0;
  73952. if (justification.testFlags (Justification::horizontallyCentred))
  73953. dx = (totalW - lineW) / 2;
  73954. else if (justification.testFlags (Justification::right))
  73955. dx = totalW - lineW;
  73956. for (int j = tokens.size(); --j >= 0;)
  73957. {
  73958. Token* const t = tokens.getUnchecked(j);
  73959. if (t->line == i)
  73960. t->x += dx;
  73961. }
  73962. }
  73963. }
  73964. }
  73965. }
  73966. int TextLayout::getLineWidth (const int lineNumber) const
  73967. {
  73968. int maxW = 0;
  73969. for (int i = tokens.size(); --i >= 0;)
  73970. {
  73971. const Token* const t = tokens.getUnchecked(i);
  73972. if (t->line == lineNumber && ! t->isWhitespace)
  73973. maxW = jmax (maxW, t->x + t->w);
  73974. }
  73975. return maxW;
  73976. }
  73977. int TextLayout::getWidth() const
  73978. {
  73979. int maxW = 0;
  73980. for (int i = tokens.size(); --i >= 0;)
  73981. {
  73982. const Token* const t = tokens.getUnchecked(i);
  73983. if (! t->isWhitespace)
  73984. maxW = jmax (maxW, t->x + t->w);
  73985. }
  73986. return maxW;
  73987. }
  73988. int TextLayout::getHeight() const
  73989. {
  73990. int maxH = 0;
  73991. for (int i = tokens.size(); --i >= 0;)
  73992. {
  73993. const Token* const t = tokens.getUnchecked(i);
  73994. if (! t->isWhitespace)
  73995. maxH = jmax (maxH, t->y + t->h);
  73996. }
  73997. return maxH;
  73998. }
  73999. void TextLayout::draw (Graphics& g,
  74000. const int xOffset,
  74001. const int yOffset) const
  74002. {
  74003. for (int i = tokens.size(); --i >= 0;)
  74004. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  74005. }
  74006. void TextLayout::drawWithin (Graphics& g,
  74007. int x, int y, int w, int h,
  74008. const Justification& justification) const
  74009. {
  74010. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  74011. x, y, w, h);
  74012. draw (g, x, y);
  74013. }
  74014. END_JUCE_NAMESPACE
  74015. /*** End of inlined file: juce_TextLayout.cpp ***/
  74016. /*** Start of inlined file: juce_Typeface.cpp ***/
  74017. BEGIN_JUCE_NAMESPACE
  74018. Typeface::Typeface (const String& name_) throw()
  74019. : name (name_), isFallbackFont (false)
  74020. {
  74021. }
  74022. Typeface::~Typeface()
  74023. {
  74024. }
  74025. const Typeface::Ptr Typeface::getFallbackTypeface()
  74026. {
  74027. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  74028. Typeface* t = fallbackFont.getTypeface();
  74029. t->isFallbackFont = true;
  74030. return t;
  74031. }
  74032. class CustomTypeface::GlyphInfo
  74033. {
  74034. public:
  74035. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  74036. : character (character_), path (path_), width (width_)
  74037. {
  74038. }
  74039. struct KerningPair
  74040. {
  74041. juce_wchar character2;
  74042. float kerningAmount;
  74043. };
  74044. void addKerningPair (const juce_wchar subsequentCharacter,
  74045. const float extraKerningAmount) throw()
  74046. {
  74047. KerningPair kp;
  74048. kp.character2 = subsequentCharacter;
  74049. kp.kerningAmount = extraKerningAmount;
  74050. kerningPairs.add (kp);
  74051. }
  74052. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  74053. {
  74054. if (subsequentCharacter != 0)
  74055. {
  74056. for (int i = kerningPairs.size(); --i >= 0;)
  74057. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  74058. return width + kerningPairs.getReference(i).kerningAmount;
  74059. }
  74060. return width;
  74061. }
  74062. const juce_wchar character;
  74063. const Path path;
  74064. float width;
  74065. Array <KerningPair> kerningPairs;
  74066. private:
  74067. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  74068. };
  74069. CustomTypeface::CustomTypeface()
  74070. : Typeface (String::empty)
  74071. {
  74072. clear();
  74073. }
  74074. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  74075. : Typeface (String::empty)
  74076. {
  74077. clear();
  74078. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  74079. BufferedInputStream in (gzin, 32768);
  74080. name = in.readString();
  74081. isBold = in.readBool();
  74082. isItalic = in.readBool();
  74083. ascent = in.readFloat();
  74084. defaultCharacter = (juce_wchar) in.readShort();
  74085. int i, numChars = in.readInt();
  74086. for (i = 0; i < numChars; ++i)
  74087. {
  74088. const juce_wchar c = (juce_wchar) in.readShort();
  74089. const float width = in.readFloat();
  74090. Path p;
  74091. p.loadPathFromStream (in);
  74092. addGlyph (c, p, width);
  74093. }
  74094. const int numKerningPairs = in.readInt();
  74095. for (i = 0; i < numKerningPairs; ++i)
  74096. {
  74097. const juce_wchar char1 = (juce_wchar) in.readShort();
  74098. const juce_wchar char2 = (juce_wchar) in.readShort();
  74099. addKerningPair (char1, char2, in.readFloat());
  74100. }
  74101. }
  74102. CustomTypeface::~CustomTypeface()
  74103. {
  74104. }
  74105. void CustomTypeface::clear()
  74106. {
  74107. defaultCharacter = 0;
  74108. ascent = 1.0f;
  74109. isBold = isItalic = false;
  74110. zeromem (lookupTable, sizeof (lookupTable));
  74111. glyphs.clear();
  74112. }
  74113. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  74114. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  74115. {
  74116. name = name_;
  74117. defaultCharacter = defaultCharacter_;
  74118. ascent = ascent_;
  74119. isBold = isBold_;
  74120. isItalic = isItalic_;
  74121. }
  74122. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  74123. {
  74124. // Check that you're not trying to add the same character twice..
  74125. jassert (findGlyph (character, false) == 0);
  74126. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  74127. lookupTable [character] = (short) glyphs.size();
  74128. glyphs.add (new GlyphInfo (character, path, width));
  74129. }
  74130. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  74131. {
  74132. if (extraAmount != 0)
  74133. {
  74134. GlyphInfo* const g = findGlyph (char1, true);
  74135. jassert (g != 0); // can only add kerning pairs for characters that exist!
  74136. if (g != 0)
  74137. g->addKerningPair (char2, extraAmount);
  74138. }
  74139. }
  74140. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  74141. {
  74142. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  74143. return glyphs [(int) lookupTable [(int) character]];
  74144. for (int i = 0; i < glyphs.size(); ++i)
  74145. {
  74146. GlyphInfo* const g = glyphs.getUnchecked(i);
  74147. if (g->character == character)
  74148. return g;
  74149. }
  74150. if (loadIfNeeded && loadGlyphIfPossible (character))
  74151. return findGlyph (character, false);
  74152. return 0;
  74153. }
  74154. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  74155. {
  74156. GlyphInfo* glyph = findGlyph (character, true);
  74157. if (glyph == 0)
  74158. {
  74159. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  74160. glyph = findGlyph (L' ', true);
  74161. if (glyph == 0)
  74162. {
  74163. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  74164. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  74165. if (fallbackTypeface != 0 && fallbackTypeface != this)
  74166. {
  74167. Path path;
  74168. fallbackTypeface->getOutlineForGlyph (character, path);
  74169. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  74170. }
  74171. if (glyph == 0)
  74172. glyph = findGlyph (defaultCharacter, true);
  74173. }
  74174. }
  74175. return glyph;
  74176. }
  74177. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  74178. {
  74179. return false;
  74180. }
  74181. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  74182. {
  74183. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  74184. for (int i = 0; i < numCharacters; ++i)
  74185. {
  74186. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  74187. Array <int> glyphIndexes;
  74188. Array <float> offsets;
  74189. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  74190. const int glyphIndex = glyphIndexes.getFirst();
  74191. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  74192. {
  74193. const float glyphWidth = offsets[1];
  74194. Path p;
  74195. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  74196. addGlyph (c, p, glyphWidth);
  74197. for (int j = glyphs.size() - 1; --j >= 0;)
  74198. {
  74199. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  74200. glyphIndexes.clearQuick();
  74201. offsets.clearQuick();
  74202. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  74203. if (offsets.size() > 1)
  74204. addKerningPair (c, char2, offsets[1] - glyphWidth);
  74205. }
  74206. }
  74207. }
  74208. }
  74209. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  74210. {
  74211. GZIPCompressorOutputStream out (&outputStream);
  74212. out.writeString (name);
  74213. out.writeBool (isBold);
  74214. out.writeBool (isItalic);
  74215. out.writeFloat (ascent);
  74216. out.writeShort ((short) (unsigned short) defaultCharacter);
  74217. out.writeInt (glyphs.size());
  74218. int i, numKerningPairs = 0;
  74219. for (i = 0; i < glyphs.size(); ++i)
  74220. {
  74221. const GlyphInfo* const g = glyphs.getUnchecked (i);
  74222. out.writeShort ((short) (unsigned short) g->character);
  74223. out.writeFloat (g->width);
  74224. g->path.writePathToStream (out);
  74225. numKerningPairs += g->kerningPairs.size();
  74226. }
  74227. out.writeInt (numKerningPairs);
  74228. for (i = 0; i < glyphs.size(); ++i)
  74229. {
  74230. const GlyphInfo* const g = glyphs.getUnchecked (i);
  74231. for (int j = 0; j < g->kerningPairs.size(); ++j)
  74232. {
  74233. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  74234. out.writeShort ((short) (unsigned short) g->character);
  74235. out.writeShort ((short) (unsigned short) p.character2);
  74236. out.writeFloat (p.kerningAmount);
  74237. }
  74238. }
  74239. return true;
  74240. }
  74241. float CustomTypeface::getAscent() const
  74242. {
  74243. return ascent;
  74244. }
  74245. float CustomTypeface::getDescent() const
  74246. {
  74247. return 1.0f - ascent;
  74248. }
  74249. float CustomTypeface::getStringWidth (const String& text)
  74250. {
  74251. float x = 0;
  74252. String::CharPointerType t (text.getCharPointer());
  74253. while (! t.isEmpty())
  74254. {
  74255. const GlyphInfo* const glyph = findGlyphSubstituting (t.getAndAdvance());
  74256. if (glyph == 0 && ! isFallbackFont)
  74257. {
  74258. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74259. if (fallbackTypeface != 0)
  74260. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  74261. }
  74262. if (glyph != 0)
  74263. x += glyph->getHorizontalSpacing (*t);
  74264. }
  74265. return x;
  74266. }
  74267. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  74268. {
  74269. xOffsets.add (0);
  74270. float x = 0;
  74271. String::CharPointerType t (text.getCharPointer());
  74272. while (! t.isEmpty())
  74273. {
  74274. const juce_wchar c = t.getAndAdvance();
  74275. const GlyphInfo* const glyph = findGlyph (c, true);
  74276. if (glyph == 0 && ! isFallbackFont)
  74277. {
  74278. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74279. if (fallbackTypeface != 0)
  74280. {
  74281. Array <int> subGlyphs;
  74282. Array <float> subOffsets;
  74283. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  74284. if (subGlyphs.size() > 0)
  74285. {
  74286. resultGlyphs.add (subGlyphs.getFirst());
  74287. x += subOffsets[1];
  74288. xOffsets.add (x);
  74289. }
  74290. }
  74291. }
  74292. if (glyph != 0)
  74293. {
  74294. x += glyph->getHorizontalSpacing (*t);
  74295. resultGlyphs.add ((int) glyph->character);
  74296. xOffsets.add (x);
  74297. }
  74298. }
  74299. }
  74300. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  74301. {
  74302. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  74303. if (glyph == 0 && ! isFallbackFont)
  74304. {
  74305. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74306. if (fallbackTypeface != 0)
  74307. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  74308. }
  74309. if (glyph != 0)
  74310. {
  74311. path = glyph->path;
  74312. return true;
  74313. }
  74314. return false;
  74315. }
  74316. END_JUCE_NAMESPACE
  74317. /*** End of inlined file: juce_Typeface.cpp ***/
  74318. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  74319. BEGIN_JUCE_NAMESPACE
  74320. AffineTransform::AffineTransform() throw()
  74321. : mat00 (1.0f), mat01 (0), mat02 (0),
  74322. mat10 (0), mat11 (1.0f), mat12 (0)
  74323. {
  74324. }
  74325. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  74326. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  74327. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  74328. {
  74329. }
  74330. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  74331. const float mat10_, const float mat11_, const float mat12_) throw()
  74332. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  74333. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  74334. {
  74335. }
  74336. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  74337. {
  74338. mat00 = other.mat00;
  74339. mat01 = other.mat01;
  74340. mat02 = other.mat02;
  74341. mat10 = other.mat10;
  74342. mat11 = other.mat11;
  74343. mat12 = other.mat12;
  74344. return *this;
  74345. }
  74346. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  74347. {
  74348. return mat00 == other.mat00
  74349. && mat01 == other.mat01
  74350. && mat02 == other.mat02
  74351. && mat10 == other.mat10
  74352. && mat11 == other.mat11
  74353. && mat12 == other.mat12;
  74354. }
  74355. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74356. {
  74357. return ! operator== (other);
  74358. }
  74359. bool AffineTransform::isIdentity() const throw()
  74360. {
  74361. return (mat01 == 0)
  74362. && (mat02 == 0)
  74363. && (mat10 == 0)
  74364. && (mat12 == 0)
  74365. && (mat00 == 1.0f)
  74366. && (mat11 == 1.0f);
  74367. }
  74368. const AffineTransform AffineTransform::identity;
  74369. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74370. {
  74371. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74372. other.mat00 * mat01 + other.mat01 * mat11,
  74373. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74374. other.mat10 * mat00 + other.mat11 * mat10,
  74375. other.mat10 * mat01 + other.mat11 * mat11,
  74376. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74377. }
  74378. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  74379. {
  74380. return AffineTransform (mat00, mat01, mat02 + dx,
  74381. mat10, mat11, mat12 + dy);
  74382. }
  74383. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  74384. {
  74385. return AffineTransform (1.0f, 0, dx,
  74386. 0, 1.0f, dy);
  74387. }
  74388. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74389. {
  74390. const float cosRad = std::cos (rad);
  74391. const float sinRad = std::sin (rad);
  74392. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  74393. cosRad * mat01 + -sinRad * mat11,
  74394. cosRad * mat02 + -sinRad * mat12,
  74395. sinRad * mat00 + cosRad * mat10,
  74396. sinRad * mat01 + cosRad * mat11,
  74397. sinRad * mat02 + cosRad * mat12);
  74398. }
  74399. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74400. {
  74401. const float cosRad = std::cos (rad);
  74402. const float sinRad = std::sin (rad);
  74403. return AffineTransform (cosRad, -sinRad, 0,
  74404. sinRad, cosRad, 0);
  74405. }
  74406. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  74407. {
  74408. const float cosRad = std::cos (rad);
  74409. const float sinRad = std::sin (rad);
  74410. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  74411. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  74412. }
  74413. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  74414. {
  74415. return followedBy (rotation (angle, pivotX, pivotY));
  74416. }
  74417. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  74418. {
  74419. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74420. factorY * mat10, factorY * mat11, factorY * mat12);
  74421. }
  74422. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  74423. {
  74424. return AffineTransform (factorX, 0, 0,
  74425. 0, factorY, 0);
  74426. }
  74427. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  74428. const float pivotX, const float pivotY) const throw()
  74429. {
  74430. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  74431. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  74432. }
  74433. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  74434. const float pivotX, const float pivotY) throw()
  74435. {
  74436. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  74437. 0, factorY, pivotY * (1.0f - factorY));
  74438. }
  74439. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  74440. {
  74441. return AffineTransform (1.0f, shearX, 0,
  74442. shearY, 1.0f, 0);
  74443. }
  74444. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  74445. {
  74446. return AffineTransform (mat00 + shearX * mat10,
  74447. mat01 + shearX * mat11,
  74448. mat02 + shearX * mat12,
  74449. shearY * mat00 + mat10,
  74450. shearY * mat01 + mat11,
  74451. shearY * mat02 + mat12);
  74452. }
  74453. const AffineTransform AffineTransform::inverted() const throw()
  74454. {
  74455. double determinant = (mat00 * mat11 - mat10 * mat01);
  74456. if (determinant != 0.0)
  74457. {
  74458. determinant = 1.0 / determinant;
  74459. const float dst00 = (float) (mat11 * determinant);
  74460. const float dst10 = (float) (-mat10 * determinant);
  74461. const float dst01 = (float) (-mat01 * determinant);
  74462. const float dst11 = (float) (mat00 * determinant);
  74463. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74464. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74465. }
  74466. else
  74467. {
  74468. // singularity..
  74469. return *this;
  74470. }
  74471. }
  74472. bool AffineTransform::isSingularity() const throw()
  74473. {
  74474. return (mat00 * mat11 - mat10 * mat01) == 0;
  74475. }
  74476. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74477. const float x10, const float y10,
  74478. const float x01, const float y01) throw()
  74479. {
  74480. return AffineTransform (x10 - x00, x01 - x00, x00,
  74481. y10 - y00, y01 - y00, y00);
  74482. }
  74483. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74484. const float sx2, const float sy2, const float tx2, const float ty2,
  74485. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74486. {
  74487. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74488. .inverted()
  74489. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74490. }
  74491. bool AffineTransform::isOnlyTranslation() const throw()
  74492. {
  74493. return (mat01 == 0)
  74494. && (mat10 == 0)
  74495. && (mat00 == 1.0f)
  74496. && (mat11 == 1.0f);
  74497. }
  74498. float AffineTransform::getScaleFactor() const throw()
  74499. {
  74500. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74501. }
  74502. END_JUCE_NAMESPACE
  74503. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74504. /*** Start of inlined file: juce_Path.cpp ***/
  74505. BEGIN_JUCE_NAMESPACE
  74506. // tests that some co-ords aren't NaNs
  74507. #define CHECK_COORDS_ARE_VALID(x, y) \
  74508. jassert (x == x && y == y);
  74509. namespace PathHelpers
  74510. {
  74511. const float ellipseAngularIncrement = 0.05f;
  74512. const String nextToken (String::CharPointerType& t)
  74513. {
  74514. t = t.findEndOfWhitespace();
  74515. String::CharPointerType start (t);
  74516. int numChars = 0;
  74517. while (! (t.isEmpty() || t.isWhitespace()))
  74518. {
  74519. ++t;
  74520. ++numChars;
  74521. }
  74522. return String (start, numChars);
  74523. }
  74524. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74525. {
  74526. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74527. }
  74528. }
  74529. const float Path::lineMarker = 100001.0f;
  74530. const float Path::moveMarker = 100002.0f;
  74531. const float Path::quadMarker = 100003.0f;
  74532. const float Path::cubicMarker = 100004.0f;
  74533. const float Path::closeSubPathMarker = 100005.0f;
  74534. Path::Path()
  74535. : numElements (0),
  74536. pathXMin (0),
  74537. pathXMax (0),
  74538. pathYMin (0),
  74539. pathYMax (0),
  74540. useNonZeroWinding (true)
  74541. {
  74542. }
  74543. Path::~Path()
  74544. {
  74545. }
  74546. Path::Path (const Path& other)
  74547. : numElements (other.numElements),
  74548. pathXMin (other.pathXMin),
  74549. pathXMax (other.pathXMax),
  74550. pathYMin (other.pathYMin),
  74551. pathYMax (other.pathYMax),
  74552. useNonZeroWinding (other.useNonZeroWinding)
  74553. {
  74554. if (numElements > 0)
  74555. {
  74556. data.setAllocatedSize ((int) numElements);
  74557. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74558. }
  74559. }
  74560. Path& Path::operator= (const Path& other)
  74561. {
  74562. if (this != &other)
  74563. {
  74564. data.ensureAllocatedSize ((int) other.numElements);
  74565. numElements = other.numElements;
  74566. pathXMin = other.pathXMin;
  74567. pathXMax = other.pathXMax;
  74568. pathYMin = other.pathYMin;
  74569. pathYMax = other.pathYMax;
  74570. useNonZeroWinding = other.useNonZeroWinding;
  74571. if (numElements > 0)
  74572. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74573. }
  74574. return *this;
  74575. }
  74576. bool Path::operator== (const Path& other) const throw()
  74577. {
  74578. return ! operator!= (other);
  74579. }
  74580. bool Path::operator!= (const Path& other) const throw()
  74581. {
  74582. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74583. return true;
  74584. for (size_t i = 0; i < numElements; ++i)
  74585. if (data.elements[i] != other.data.elements[i])
  74586. return true;
  74587. return false;
  74588. }
  74589. void Path::clear() throw()
  74590. {
  74591. numElements = 0;
  74592. pathXMin = 0;
  74593. pathYMin = 0;
  74594. pathYMax = 0;
  74595. pathXMax = 0;
  74596. }
  74597. void Path::swapWithPath (Path& other) throw()
  74598. {
  74599. data.swapWith (other.data);
  74600. swapVariables <size_t> (numElements, other.numElements);
  74601. swapVariables <float> (pathXMin, other.pathXMin);
  74602. swapVariables <float> (pathXMax, other.pathXMax);
  74603. swapVariables <float> (pathYMin, other.pathYMin);
  74604. swapVariables <float> (pathYMax, other.pathYMax);
  74605. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74606. }
  74607. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74608. {
  74609. useNonZeroWinding = isNonZero;
  74610. }
  74611. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74612. const bool preserveProportions) throw()
  74613. {
  74614. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74615. }
  74616. bool Path::isEmpty() const throw()
  74617. {
  74618. size_t i = 0;
  74619. while (i < numElements)
  74620. {
  74621. const float type = data.elements [i++];
  74622. if (type == moveMarker)
  74623. {
  74624. i += 2;
  74625. }
  74626. else if (type == lineMarker
  74627. || type == quadMarker
  74628. || type == cubicMarker)
  74629. {
  74630. return false;
  74631. }
  74632. }
  74633. return true;
  74634. }
  74635. const Rectangle<float> Path::getBounds() const throw()
  74636. {
  74637. return Rectangle<float> (pathXMin, pathYMin,
  74638. pathXMax - pathXMin,
  74639. pathYMax - pathYMin);
  74640. }
  74641. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74642. {
  74643. return getBounds().transformed (transform);
  74644. }
  74645. void Path::startNewSubPath (const float x, const float y)
  74646. {
  74647. CHECK_COORDS_ARE_VALID (x, y);
  74648. if (numElements == 0)
  74649. {
  74650. pathXMin = pathXMax = x;
  74651. pathYMin = pathYMax = y;
  74652. }
  74653. else
  74654. {
  74655. pathXMin = jmin (pathXMin, x);
  74656. pathXMax = jmax (pathXMax, x);
  74657. pathYMin = jmin (pathYMin, y);
  74658. pathYMax = jmax (pathYMax, y);
  74659. }
  74660. data.ensureAllocatedSize ((int) numElements + 3);
  74661. data.elements [numElements++] = moveMarker;
  74662. data.elements [numElements++] = x;
  74663. data.elements [numElements++] = y;
  74664. }
  74665. void Path::startNewSubPath (const Point<float>& start)
  74666. {
  74667. startNewSubPath (start.getX(), start.getY());
  74668. }
  74669. void Path::lineTo (const float x, const float y)
  74670. {
  74671. CHECK_COORDS_ARE_VALID (x, y);
  74672. if (numElements == 0)
  74673. startNewSubPath (0, 0);
  74674. data.ensureAllocatedSize ((int) numElements + 3);
  74675. data.elements [numElements++] = lineMarker;
  74676. data.elements [numElements++] = x;
  74677. data.elements [numElements++] = y;
  74678. pathXMin = jmin (pathXMin, x);
  74679. pathXMax = jmax (pathXMax, x);
  74680. pathYMin = jmin (pathYMin, y);
  74681. pathYMax = jmax (pathYMax, y);
  74682. }
  74683. void Path::lineTo (const Point<float>& end)
  74684. {
  74685. lineTo (end.getX(), end.getY());
  74686. }
  74687. void Path::quadraticTo (const float x1, const float y1,
  74688. const float x2, const float y2)
  74689. {
  74690. CHECK_COORDS_ARE_VALID (x1, y1);
  74691. CHECK_COORDS_ARE_VALID (x2, y2);
  74692. if (numElements == 0)
  74693. startNewSubPath (0, 0);
  74694. data.ensureAllocatedSize ((int) numElements + 5);
  74695. data.elements [numElements++] = quadMarker;
  74696. data.elements [numElements++] = x1;
  74697. data.elements [numElements++] = y1;
  74698. data.elements [numElements++] = x2;
  74699. data.elements [numElements++] = y2;
  74700. pathXMin = jmin (pathXMin, x1, x2);
  74701. pathXMax = jmax (pathXMax, x1, x2);
  74702. pathYMin = jmin (pathYMin, y1, y2);
  74703. pathYMax = jmax (pathYMax, y1, y2);
  74704. }
  74705. void Path::quadraticTo (const Point<float>& controlPoint,
  74706. const Point<float>& endPoint)
  74707. {
  74708. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74709. endPoint.getX(), endPoint.getY());
  74710. }
  74711. void Path::cubicTo (const float x1, const float y1,
  74712. const float x2, const float y2,
  74713. const float x3, const float y3)
  74714. {
  74715. CHECK_COORDS_ARE_VALID (x1, y1);
  74716. CHECK_COORDS_ARE_VALID (x2, y2);
  74717. CHECK_COORDS_ARE_VALID (x3, y3);
  74718. if (numElements == 0)
  74719. startNewSubPath (0, 0);
  74720. data.ensureAllocatedSize ((int) numElements + 7);
  74721. data.elements [numElements++] = cubicMarker;
  74722. data.elements [numElements++] = x1;
  74723. data.elements [numElements++] = y1;
  74724. data.elements [numElements++] = x2;
  74725. data.elements [numElements++] = y2;
  74726. data.elements [numElements++] = x3;
  74727. data.elements [numElements++] = y3;
  74728. pathXMin = jmin (pathXMin, x1, x2, x3);
  74729. pathXMax = jmax (pathXMax, x1, x2, x3);
  74730. pathYMin = jmin (pathYMin, y1, y2, y3);
  74731. pathYMax = jmax (pathYMax, y1, y2, y3);
  74732. }
  74733. void Path::cubicTo (const Point<float>& controlPoint1,
  74734. const Point<float>& controlPoint2,
  74735. const Point<float>& endPoint)
  74736. {
  74737. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74738. controlPoint2.getX(), controlPoint2.getY(),
  74739. endPoint.getX(), endPoint.getY());
  74740. }
  74741. void Path::closeSubPath()
  74742. {
  74743. if (numElements > 0
  74744. && data.elements [numElements - 1] != closeSubPathMarker)
  74745. {
  74746. data.ensureAllocatedSize ((int) numElements + 1);
  74747. data.elements [numElements++] = closeSubPathMarker;
  74748. }
  74749. }
  74750. const Point<float> Path::getCurrentPosition() const
  74751. {
  74752. int i = (int) numElements - 1;
  74753. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74754. {
  74755. while (i >= 0)
  74756. {
  74757. if (data.elements[i] == moveMarker)
  74758. {
  74759. i += 2;
  74760. break;
  74761. }
  74762. --i;
  74763. }
  74764. }
  74765. if (i > 0)
  74766. return Point<float> (data.elements [i - 1], data.elements [i]);
  74767. return Point<float>();
  74768. }
  74769. void Path::addRectangle (const float x, const float y,
  74770. const float w, const float h)
  74771. {
  74772. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74773. if (w < 0)
  74774. swapVariables (x1, x2);
  74775. if (h < 0)
  74776. swapVariables (y1, y2);
  74777. data.ensureAllocatedSize ((int) numElements + 13);
  74778. if (numElements == 0)
  74779. {
  74780. pathXMin = x1;
  74781. pathXMax = x2;
  74782. pathYMin = y1;
  74783. pathYMax = y2;
  74784. }
  74785. else
  74786. {
  74787. pathXMin = jmin (pathXMin, x1);
  74788. pathXMax = jmax (pathXMax, x2);
  74789. pathYMin = jmin (pathYMin, y1);
  74790. pathYMax = jmax (pathYMax, y2);
  74791. }
  74792. data.elements [numElements++] = moveMarker;
  74793. data.elements [numElements++] = x1;
  74794. data.elements [numElements++] = y2;
  74795. data.elements [numElements++] = lineMarker;
  74796. data.elements [numElements++] = x1;
  74797. data.elements [numElements++] = y1;
  74798. data.elements [numElements++] = lineMarker;
  74799. data.elements [numElements++] = x2;
  74800. data.elements [numElements++] = y1;
  74801. data.elements [numElements++] = lineMarker;
  74802. data.elements [numElements++] = x2;
  74803. data.elements [numElements++] = y2;
  74804. data.elements [numElements++] = closeSubPathMarker;
  74805. }
  74806. void Path::addRoundedRectangle (const float x, const float y,
  74807. const float w, const float h,
  74808. float csx,
  74809. float csy)
  74810. {
  74811. csx = jmin (csx, w * 0.5f);
  74812. csy = jmin (csy, h * 0.5f);
  74813. const float cs45x = csx * 0.45f;
  74814. const float cs45y = csy * 0.45f;
  74815. const float x2 = x + w;
  74816. const float y2 = y + h;
  74817. startNewSubPath (x + csx, y);
  74818. lineTo (x2 - csx, y);
  74819. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74820. lineTo (x2, y2 - csy);
  74821. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74822. lineTo (x + csx, y2);
  74823. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74824. lineTo (x, y + csy);
  74825. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74826. closeSubPath();
  74827. }
  74828. void Path::addRoundedRectangle (const float x, const float y,
  74829. const float w, const float h,
  74830. float cs)
  74831. {
  74832. addRoundedRectangle (x, y, w, h, cs, cs);
  74833. }
  74834. void Path::addTriangle (const float x1, const float y1,
  74835. const float x2, const float y2,
  74836. const float x3, const float y3)
  74837. {
  74838. startNewSubPath (x1, y1);
  74839. lineTo (x2, y2);
  74840. lineTo (x3, y3);
  74841. closeSubPath();
  74842. }
  74843. void Path::addQuadrilateral (const float x1, const float y1,
  74844. const float x2, const float y2,
  74845. const float x3, const float y3,
  74846. const float x4, const float y4)
  74847. {
  74848. startNewSubPath (x1, y1);
  74849. lineTo (x2, y2);
  74850. lineTo (x3, y3);
  74851. lineTo (x4, y4);
  74852. closeSubPath();
  74853. }
  74854. void Path::addEllipse (const float x, const float y,
  74855. const float w, const float h)
  74856. {
  74857. const float hw = w * 0.5f;
  74858. const float hw55 = hw * 0.55f;
  74859. const float hh = h * 0.5f;
  74860. const float hh55 = hh * 0.55f;
  74861. const float cx = x + hw;
  74862. const float cy = y + hh;
  74863. startNewSubPath (cx, cy - hh);
  74864. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74865. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74866. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74867. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74868. closeSubPath();
  74869. }
  74870. void Path::addArc (const float x, const float y,
  74871. const float w, const float h,
  74872. const float fromRadians,
  74873. const float toRadians,
  74874. const bool startAsNewSubPath)
  74875. {
  74876. const float radiusX = w / 2.0f;
  74877. const float radiusY = h / 2.0f;
  74878. addCentredArc (x + radiusX,
  74879. y + radiusY,
  74880. radiusX, radiusY,
  74881. 0.0f,
  74882. fromRadians, toRadians,
  74883. startAsNewSubPath);
  74884. }
  74885. void Path::addCentredArc (const float centreX, const float centreY,
  74886. const float radiusX, const float radiusY,
  74887. const float rotationOfEllipse,
  74888. const float fromRadians,
  74889. const float toRadians,
  74890. const bool startAsNewSubPath)
  74891. {
  74892. if (radiusX > 0.0f && radiusY > 0.0f)
  74893. {
  74894. const Point<float> centre (centreX, centreY);
  74895. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74896. float angle = fromRadians;
  74897. if (startAsNewSubPath)
  74898. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74899. if (fromRadians < toRadians)
  74900. {
  74901. if (startAsNewSubPath)
  74902. angle += PathHelpers::ellipseAngularIncrement;
  74903. while (angle < toRadians)
  74904. {
  74905. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74906. angle += PathHelpers::ellipseAngularIncrement;
  74907. }
  74908. }
  74909. else
  74910. {
  74911. if (startAsNewSubPath)
  74912. angle -= PathHelpers::ellipseAngularIncrement;
  74913. while (angle > toRadians)
  74914. {
  74915. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74916. angle -= PathHelpers::ellipseAngularIncrement;
  74917. }
  74918. }
  74919. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74920. }
  74921. }
  74922. void Path::addPieSegment (const float x, const float y,
  74923. const float width, const float height,
  74924. const float fromRadians,
  74925. const float toRadians,
  74926. const float innerCircleProportionalSize)
  74927. {
  74928. float radiusX = width * 0.5f;
  74929. float radiusY = height * 0.5f;
  74930. const Point<float> centre (x + radiusX, y + radiusY);
  74931. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74932. addArc (x, y, width, height, fromRadians, toRadians);
  74933. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74934. {
  74935. closeSubPath();
  74936. if (innerCircleProportionalSize > 0)
  74937. {
  74938. radiusX *= innerCircleProportionalSize;
  74939. radiusY *= innerCircleProportionalSize;
  74940. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74941. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74942. }
  74943. }
  74944. else
  74945. {
  74946. if (innerCircleProportionalSize > 0)
  74947. {
  74948. radiusX *= innerCircleProportionalSize;
  74949. radiusY *= innerCircleProportionalSize;
  74950. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74951. }
  74952. else
  74953. {
  74954. lineTo (centre);
  74955. }
  74956. }
  74957. closeSubPath();
  74958. }
  74959. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74960. {
  74961. const Line<float> reversed (line.reversed());
  74962. lineThickness *= 0.5f;
  74963. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74964. lineTo (line.getPointAlongLine (0, -lineThickness));
  74965. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74966. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74967. closeSubPath();
  74968. }
  74969. void Path::addArrow (const Line<float>& line, float lineThickness,
  74970. float arrowheadWidth, float arrowheadLength)
  74971. {
  74972. const Line<float> reversed (line.reversed());
  74973. lineThickness *= 0.5f;
  74974. arrowheadWidth *= 0.5f;
  74975. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74976. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74977. lineTo (line.getPointAlongLine (0, -lineThickness));
  74978. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74979. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74980. lineTo (line.getEnd());
  74981. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74982. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74983. closeSubPath();
  74984. }
  74985. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74986. const float radius, const float startAngle)
  74987. {
  74988. jassert (numberOfSides > 1); // this would be silly.
  74989. if (numberOfSides > 1)
  74990. {
  74991. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74992. for (int i = 0; i < numberOfSides; ++i)
  74993. {
  74994. const float angle = startAngle + i * angleBetweenPoints;
  74995. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74996. if (i == 0)
  74997. startNewSubPath (p);
  74998. else
  74999. lineTo (p);
  75000. }
  75001. closeSubPath();
  75002. }
  75003. }
  75004. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  75005. const float innerRadius, const float outerRadius, const float startAngle)
  75006. {
  75007. jassert (numberOfPoints > 1); // this would be silly.
  75008. if (numberOfPoints > 1)
  75009. {
  75010. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  75011. for (int i = 0; i < numberOfPoints; ++i)
  75012. {
  75013. const float angle = startAngle + i * angleBetweenPoints;
  75014. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  75015. if (i == 0)
  75016. startNewSubPath (p);
  75017. else
  75018. lineTo (p);
  75019. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  75020. }
  75021. closeSubPath();
  75022. }
  75023. }
  75024. void Path::addBubble (float x, float y,
  75025. float w, float h,
  75026. float cs,
  75027. float tipX,
  75028. float tipY,
  75029. int whichSide,
  75030. float arrowPos,
  75031. float arrowWidth)
  75032. {
  75033. if (w > 1.0f && h > 1.0f)
  75034. {
  75035. cs = jmin (cs, w * 0.5f, h * 0.5f);
  75036. const float cs2 = 2.0f * cs;
  75037. startNewSubPath (x + cs, y);
  75038. if (whichSide == 0)
  75039. {
  75040. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  75041. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  75042. lineTo (arrowX1, y);
  75043. lineTo (tipX, tipY);
  75044. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  75045. }
  75046. lineTo (x + w - cs, y);
  75047. if (cs > 0.0f)
  75048. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  75049. if (whichSide == 3)
  75050. {
  75051. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  75052. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  75053. lineTo (x + w, arrowY1);
  75054. lineTo (tipX, tipY);
  75055. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  75056. }
  75057. lineTo (x + w, y + h - cs);
  75058. if (cs > 0.0f)
  75059. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  75060. if (whichSide == 2)
  75061. {
  75062. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  75063. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  75064. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  75065. lineTo (tipX, tipY);
  75066. lineTo (arrowX1, y + h);
  75067. }
  75068. lineTo (x + cs, y + h);
  75069. if (cs > 0.0f)
  75070. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  75071. if (whichSide == 1)
  75072. {
  75073. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  75074. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  75075. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  75076. lineTo (tipX, tipY);
  75077. lineTo (x, arrowY1);
  75078. }
  75079. lineTo (x, y + cs);
  75080. if (cs > 0.0f)
  75081. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  75082. closeSubPath();
  75083. }
  75084. }
  75085. void Path::addPath (const Path& other)
  75086. {
  75087. size_t i = 0;
  75088. while (i < other.numElements)
  75089. {
  75090. const float type = other.data.elements [i++];
  75091. if (type == moveMarker)
  75092. {
  75093. startNewSubPath (other.data.elements [i],
  75094. other.data.elements [i + 1]);
  75095. i += 2;
  75096. }
  75097. else if (type == lineMarker)
  75098. {
  75099. lineTo (other.data.elements [i],
  75100. other.data.elements [i + 1]);
  75101. i += 2;
  75102. }
  75103. else if (type == quadMarker)
  75104. {
  75105. quadraticTo (other.data.elements [i],
  75106. other.data.elements [i + 1],
  75107. other.data.elements [i + 2],
  75108. other.data.elements [i + 3]);
  75109. i += 4;
  75110. }
  75111. else if (type == cubicMarker)
  75112. {
  75113. cubicTo (other.data.elements [i],
  75114. other.data.elements [i + 1],
  75115. other.data.elements [i + 2],
  75116. other.data.elements [i + 3],
  75117. other.data.elements [i + 4],
  75118. other.data.elements [i + 5]);
  75119. i += 6;
  75120. }
  75121. else if (type == closeSubPathMarker)
  75122. {
  75123. closeSubPath();
  75124. }
  75125. else
  75126. {
  75127. // something's gone wrong with the element list!
  75128. jassertfalse;
  75129. }
  75130. }
  75131. }
  75132. void Path::addPath (const Path& other,
  75133. const AffineTransform& transformToApply)
  75134. {
  75135. size_t i = 0;
  75136. while (i < other.numElements)
  75137. {
  75138. const float type = other.data.elements [i++];
  75139. if (type == closeSubPathMarker)
  75140. {
  75141. closeSubPath();
  75142. }
  75143. else
  75144. {
  75145. float x = other.data.elements [i++];
  75146. float y = other.data.elements [i++];
  75147. transformToApply.transformPoint (x, y);
  75148. if (type == moveMarker)
  75149. {
  75150. startNewSubPath (x, y);
  75151. }
  75152. else if (type == lineMarker)
  75153. {
  75154. lineTo (x, y);
  75155. }
  75156. else if (type == quadMarker)
  75157. {
  75158. float x2 = other.data.elements [i++];
  75159. float y2 = other.data.elements [i++];
  75160. transformToApply.transformPoint (x2, y2);
  75161. quadraticTo (x, y, x2, y2);
  75162. }
  75163. else if (type == cubicMarker)
  75164. {
  75165. float x2 = other.data.elements [i++];
  75166. float y2 = other.data.elements [i++];
  75167. float x3 = other.data.elements [i++];
  75168. float y3 = other.data.elements [i++];
  75169. transformToApply.transformPoints (x2, y2, x3, y3);
  75170. cubicTo (x, y, x2, y2, x3, y3);
  75171. }
  75172. else
  75173. {
  75174. // something's gone wrong with the element list!
  75175. jassertfalse;
  75176. }
  75177. }
  75178. }
  75179. }
  75180. void Path::applyTransform (const AffineTransform& transform) throw()
  75181. {
  75182. size_t i = 0;
  75183. pathYMin = pathXMin = 0;
  75184. pathYMax = pathXMax = 0;
  75185. bool setMaxMin = false;
  75186. while (i < numElements)
  75187. {
  75188. const float type = data.elements [i++];
  75189. if (type == moveMarker)
  75190. {
  75191. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  75192. if (setMaxMin)
  75193. {
  75194. pathXMin = jmin (pathXMin, data.elements [i]);
  75195. pathXMax = jmax (pathXMax, data.elements [i]);
  75196. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  75197. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  75198. }
  75199. else
  75200. {
  75201. pathXMin = pathXMax = data.elements [i];
  75202. pathYMin = pathYMax = data.elements [i + 1];
  75203. setMaxMin = true;
  75204. }
  75205. i += 2;
  75206. }
  75207. else if (type == lineMarker)
  75208. {
  75209. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  75210. pathXMin = jmin (pathXMin, data.elements [i]);
  75211. pathXMax = jmax (pathXMax, data.elements [i]);
  75212. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  75213. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  75214. i += 2;
  75215. }
  75216. else if (type == quadMarker)
  75217. {
  75218. transform.transformPoints (data.elements [i], data.elements [i + 1],
  75219. data.elements [i + 2], data.elements [i + 3]);
  75220. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  75221. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  75222. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  75223. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  75224. i += 4;
  75225. }
  75226. else if (type == cubicMarker)
  75227. {
  75228. transform.transformPoints (data.elements [i], data.elements [i + 1],
  75229. data.elements [i + 2], data.elements [i + 3],
  75230. data.elements [i + 4], data.elements [i + 5]);
  75231. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75232. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75233. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75234. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75235. i += 6;
  75236. }
  75237. }
  75238. }
  75239. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  75240. const float w, const float h,
  75241. const bool preserveProportions,
  75242. const Justification& justification) const
  75243. {
  75244. Rectangle<float> bounds (getBounds());
  75245. if (preserveProportions)
  75246. {
  75247. if (w <= 0 || h <= 0 || bounds.isEmpty())
  75248. return AffineTransform::identity;
  75249. float newW, newH;
  75250. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  75251. if (srcRatio > h / w)
  75252. {
  75253. newW = h / srcRatio;
  75254. newH = h;
  75255. }
  75256. else
  75257. {
  75258. newW = w;
  75259. newH = w * srcRatio;
  75260. }
  75261. float newXCentre = x;
  75262. float newYCentre = y;
  75263. if (justification.testFlags (Justification::left))
  75264. newXCentre += newW * 0.5f;
  75265. else if (justification.testFlags (Justification::right))
  75266. newXCentre += w - newW * 0.5f;
  75267. else
  75268. newXCentre += w * 0.5f;
  75269. if (justification.testFlags (Justification::top))
  75270. newYCentre += newH * 0.5f;
  75271. else if (justification.testFlags (Justification::bottom))
  75272. newYCentre += h - newH * 0.5f;
  75273. else
  75274. newYCentre += h * 0.5f;
  75275. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75276. bounds.getHeight() * -0.5f - bounds.getY())
  75277. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75278. .translated (newXCentre, newYCentre);
  75279. }
  75280. else
  75281. {
  75282. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75283. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75284. .translated (x, y);
  75285. }
  75286. }
  75287. bool Path::contains (const float x, const float y, const float tolerance) const
  75288. {
  75289. if (x <= pathXMin || x >= pathXMax
  75290. || y <= pathYMin || y >= pathYMax)
  75291. return false;
  75292. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75293. int positiveCrossings = 0;
  75294. int negativeCrossings = 0;
  75295. while (i.next())
  75296. {
  75297. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75298. {
  75299. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75300. if (intersectX <= x)
  75301. {
  75302. if (i.y1 < i.y2)
  75303. ++positiveCrossings;
  75304. else
  75305. ++negativeCrossings;
  75306. }
  75307. }
  75308. }
  75309. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75310. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75311. }
  75312. bool Path::contains (const Point<float>& point, const float tolerance) const
  75313. {
  75314. return contains (point.getX(), point.getY(), tolerance);
  75315. }
  75316. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  75317. {
  75318. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75319. Point<float> intersection;
  75320. while (i.next())
  75321. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75322. return true;
  75323. return false;
  75324. }
  75325. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75326. {
  75327. Line<float> result (line);
  75328. const bool startInside = contains (line.getStart());
  75329. const bool endInside = contains (line.getEnd());
  75330. if (startInside == endInside)
  75331. {
  75332. if (keepSectionOutsidePath == startInside)
  75333. result = Line<float>();
  75334. }
  75335. else
  75336. {
  75337. PathFlatteningIterator i (*this, AffineTransform::identity);
  75338. Point<float> intersection;
  75339. while (i.next())
  75340. {
  75341. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75342. {
  75343. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75344. result.setStart (intersection);
  75345. else
  75346. result.setEnd (intersection);
  75347. }
  75348. }
  75349. }
  75350. return result;
  75351. }
  75352. float Path::getLength (const AffineTransform& transform) const
  75353. {
  75354. float length = 0;
  75355. PathFlatteningIterator i (*this, transform);
  75356. while (i.next())
  75357. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75358. return length;
  75359. }
  75360. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75361. {
  75362. PathFlatteningIterator i (*this, transform);
  75363. while (i.next())
  75364. {
  75365. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75366. const float lineLength = line.getLength();
  75367. if (distanceFromStart <= lineLength)
  75368. return line.getPointAlongLine (distanceFromStart);
  75369. distanceFromStart -= lineLength;
  75370. }
  75371. return Point<float> (i.x2, i.y2);
  75372. }
  75373. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75374. const AffineTransform& transform) const
  75375. {
  75376. PathFlatteningIterator i (*this, transform);
  75377. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75378. float length = 0;
  75379. Point<float> pointOnLine;
  75380. while (i.next())
  75381. {
  75382. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75383. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75384. if (distance < bestDistance)
  75385. {
  75386. bestDistance = distance;
  75387. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75388. pointOnPath = pointOnLine;
  75389. }
  75390. length += line.getLength();
  75391. }
  75392. return bestPosition;
  75393. }
  75394. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75395. {
  75396. if (cornerRadius <= 0.01f)
  75397. return *this;
  75398. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75399. size_t n = 0;
  75400. bool lastWasLine = false, firstWasLine = false;
  75401. Path p;
  75402. while (n < numElements)
  75403. {
  75404. const float type = data.elements [n++];
  75405. if (type == moveMarker)
  75406. {
  75407. indexOfPathStart = p.numElements;
  75408. indexOfPathStartThis = n - 1;
  75409. const float x = data.elements [n++];
  75410. const float y = data.elements [n++];
  75411. p.startNewSubPath (x, y);
  75412. lastWasLine = false;
  75413. firstWasLine = (data.elements [n] == lineMarker);
  75414. }
  75415. else if (type == lineMarker || type == closeSubPathMarker)
  75416. {
  75417. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75418. if (type == lineMarker)
  75419. {
  75420. endX = data.elements [n++];
  75421. endY = data.elements [n++];
  75422. if (n > 8)
  75423. {
  75424. startX = data.elements [n - 8];
  75425. startY = data.elements [n - 7];
  75426. joinX = data.elements [n - 5];
  75427. joinY = data.elements [n - 4];
  75428. }
  75429. }
  75430. else
  75431. {
  75432. endX = data.elements [indexOfPathStartThis + 1];
  75433. endY = data.elements [indexOfPathStartThis + 2];
  75434. if (n > 6)
  75435. {
  75436. startX = data.elements [n - 6];
  75437. startY = data.elements [n - 5];
  75438. joinX = data.elements [n - 3];
  75439. joinY = data.elements [n - 2];
  75440. }
  75441. }
  75442. if (lastWasLine)
  75443. {
  75444. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75445. if (len1 > 0)
  75446. {
  75447. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75448. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75449. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75450. }
  75451. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75452. if (len2 > 0)
  75453. {
  75454. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75455. p.quadraticTo (joinX, joinY,
  75456. (float) (joinX + (endX - joinX) * propNeeded),
  75457. (float) (joinY + (endY - joinY) * propNeeded));
  75458. }
  75459. p.lineTo (endX, endY);
  75460. }
  75461. else if (type == lineMarker)
  75462. {
  75463. p.lineTo (endX, endY);
  75464. lastWasLine = true;
  75465. }
  75466. if (type == closeSubPathMarker)
  75467. {
  75468. if (firstWasLine)
  75469. {
  75470. startX = data.elements [n - 3];
  75471. startY = data.elements [n - 2];
  75472. joinX = endX;
  75473. joinY = endY;
  75474. endX = data.elements [indexOfPathStartThis + 4];
  75475. endY = data.elements [indexOfPathStartThis + 5];
  75476. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75477. if (len1 > 0)
  75478. {
  75479. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75480. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75481. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75482. }
  75483. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75484. if (len2 > 0)
  75485. {
  75486. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75487. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75488. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75489. p.quadraticTo (joinX, joinY, endX, endY);
  75490. p.data.elements [indexOfPathStart + 1] = endX;
  75491. p.data.elements [indexOfPathStart + 2] = endY;
  75492. }
  75493. }
  75494. p.closeSubPath();
  75495. }
  75496. }
  75497. else if (type == quadMarker)
  75498. {
  75499. lastWasLine = false;
  75500. const float x1 = data.elements [n++];
  75501. const float y1 = data.elements [n++];
  75502. const float x2 = data.elements [n++];
  75503. const float y2 = data.elements [n++];
  75504. p.quadraticTo (x1, y1, x2, y2);
  75505. }
  75506. else if (type == cubicMarker)
  75507. {
  75508. lastWasLine = false;
  75509. const float x1 = data.elements [n++];
  75510. const float y1 = data.elements [n++];
  75511. const float x2 = data.elements [n++];
  75512. const float y2 = data.elements [n++];
  75513. const float x3 = data.elements [n++];
  75514. const float y3 = data.elements [n++];
  75515. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75516. }
  75517. }
  75518. return p;
  75519. }
  75520. void Path::loadPathFromStream (InputStream& source)
  75521. {
  75522. while (! source.isExhausted())
  75523. {
  75524. switch (source.readByte())
  75525. {
  75526. case 'm':
  75527. {
  75528. const float x = source.readFloat();
  75529. const float y = source.readFloat();
  75530. startNewSubPath (x, y);
  75531. break;
  75532. }
  75533. case 'l':
  75534. {
  75535. const float x = source.readFloat();
  75536. const float y = source.readFloat();
  75537. lineTo (x, y);
  75538. break;
  75539. }
  75540. case 'q':
  75541. {
  75542. const float x1 = source.readFloat();
  75543. const float y1 = source.readFloat();
  75544. const float x2 = source.readFloat();
  75545. const float y2 = source.readFloat();
  75546. quadraticTo (x1, y1, x2, y2);
  75547. break;
  75548. }
  75549. case 'b':
  75550. {
  75551. const float x1 = source.readFloat();
  75552. const float y1 = source.readFloat();
  75553. const float x2 = source.readFloat();
  75554. const float y2 = source.readFloat();
  75555. const float x3 = source.readFloat();
  75556. const float y3 = source.readFloat();
  75557. cubicTo (x1, y1, x2, y2, x3, y3);
  75558. break;
  75559. }
  75560. case 'c':
  75561. closeSubPath();
  75562. break;
  75563. case 'n':
  75564. useNonZeroWinding = true;
  75565. break;
  75566. case 'z':
  75567. useNonZeroWinding = false;
  75568. break;
  75569. case 'e':
  75570. return; // end of path marker
  75571. default:
  75572. jassertfalse; // illegal char in the stream
  75573. break;
  75574. }
  75575. }
  75576. }
  75577. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75578. {
  75579. MemoryInputStream in (pathData, numberOfBytes, false);
  75580. loadPathFromStream (in);
  75581. }
  75582. void Path::writePathToStream (OutputStream& dest) const
  75583. {
  75584. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75585. size_t i = 0;
  75586. while (i < numElements)
  75587. {
  75588. const float type = data.elements [i++];
  75589. if (type == moveMarker)
  75590. {
  75591. dest.writeByte ('m');
  75592. dest.writeFloat (data.elements [i++]);
  75593. dest.writeFloat (data.elements [i++]);
  75594. }
  75595. else if (type == lineMarker)
  75596. {
  75597. dest.writeByte ('l');
  75598. dest.writeFloat (data.elements [i++]);
  75599. dest.writeFloat (data.elements [i++]);
  75600. }
  75601. else if (type == quadMarker)
  75602. {
  75603. dest.writeByte ('q');
  75604. dest.writeFloat (data.elements [i++]);
  75605. dest.writeFloat (data.elements [i++]);
  75606. dest.writeFloat (data.elements [i++]);
  75607. dest.writeFloat (data.elements [i++]);
  75608. }
  75609. else if (type == cubicMarker)
  75610. {
  75611. dest.writeByte ('b');
  75612. dest.writeFloat (data.elements [i++]);
  75613. dest.writeFloat (data.elements [i++]);
  75614. dest.writeFloat (data.elements [i++]);
  75615. dest.writeFloat (data.elements [i++]);
  75616. dest.writeFloat (data.elements [i++]);
  75617. dest.writeFloat (data.elements [i++]);
  75618. }
  75619. else if (type == closeSubPathMarker)
  75620. {
  75621. dest.writeByte ('c');
  75622. }
  75623. }
  75624. dest.writeByte ('e'); // marks the end-of-path
  75625. }
  75626. const String Path::toString() const
  75627. {
  75628. MemoryOutputStream s (2048);
  75629. if (! useNonZeroWinding)
  75630. s << 'a';
  75631. size_t i = 0;
  75632. float lastMarker = 0.0f;
  75633. while (i < numElements)
  75634. {
  75635. const float marker = data.elements [i++];
  75636. char markerChar = 0;
  75637. int numCoords = 0;
  75638. if (marker == moveMarker)
  75639. {
  75640. markerChar = 'm';
  75641. numCoords = 2;
  75642. }
  75643. else if (marker == lineMarker)
  75644. {
  75645. markerChar = 'l';
  75646. numCoords = 2;
  75647. }
  75648. else if (marker == quadMarker)
  75649. {
  75650. markerChar = 'q';
  75651. numCoords = 4;
  75652. }
  75653. else if (marker == cubicMarker)
  75654. {
  75655. markerChar = 'c';
  75656. numCoords = 6;
  75657. }
  75658. else
  75659. {
  75660. jassert (marker == closeSubPathMarker);
  75661. markerChar = 'z';
  75662. }
  75663. if (marker != lastMarker)
  75664. {
  75665. if (s.getDataSize() != 0)
  75666. s << ' ';
  75667. s << markerChar;
  75668. lastMarker = marker;
  75669. }
  75670. while (--numCoords >= 0 && i < numElements)
  75671. {
  75672. String coord (data.elements [i++], 3);
  75673. while (coord.endsWithChar ('0') && coord != "0")
  75674. coord = coord.dropLastCharacters (1);
  75675. if (coord.endsWithChar ('.'))
  75676. coord = coord.dropLastCharacters (1);
  75677. if (s.getDataSize() != 0)
  75678. s << ' ';
  75679. s << coord;
  75680. }
  75681. }
  75682. return s.toUTF8();
  75683. }
  75684. void Path::restoreFromString (const String& stringVersion)
  75685. {
  75686. clear();
  75687. setUsingNonZeroWinding (true);
  75688. String::CharPointerType t (stringVersion.getCharPointer());
  75689. juce_wchar marker = 'm';
  75690. int numValues = 2;
  75691. float values [6];
  75692. for (;;)
  75693. {
  75694. const String token (PathHelpers::nextToken (t));
  75695. const juce_wchar firstChar = token[0];
  75696. int startNum = 0;
  75697. if (firstChar == 0)
  75698. break;
  75699. if (firstChar == 'm' || firstChar == 'l')
  75700. {
  75701. marker = firstChar;
  75702. numValues = 2;
  75703. }
  75704. else if (firstChar == 'q')
  75705. {
  75706. marker = firstChar;
  75707. numValues = 4;
  75708. }
  75709. else if (firstChar == 'c')
  75710. {
  75711. marker = firstChar;
  75712. numValues = 6;
  75713. }
  75714. else if (firstChar == 'z')
  75715. {
  75716. marker = firstChar;
  75717. numValues = 0;
  75718. }
  75719. else if (firstChar == 'a')
  75720. {
  75721. setUsingNonZeroWinding (false);
  75722. continue;
  75723. }
  75724. else
  75725. {
  75726. ++startNum;
  75727. values [0] = token.getFloatValue();
  75728. }
  75729. for (int i = startNum; i < numValues; ++i)
  75730. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75731. switch (marker)
  75732. {
  75733. case 'm': startNewSubPath (values[0], values[1]); break;
  75734. case 'l': lineTo (values[0], values[1]); break;
  75735. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75736. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75737. case 'z': closeSubPath(); break;
  75738. default: jassertfalse; break; // illegal string format?
  75739. }
  75740. }
  75741. }
  75742. Path::Iterator::Iterator (const Path& path_)
  75743. : path (path_),
  75744. index (0)
  75745. {
  75746. }
  75747. Path::Iterator::~Iterator()
  75748. {
  75749. }
  75750. bool Path::Iterator::next()
  75751. {
  75752. const float* const elements = path.data.elements;
  75753. if (index < path.numElements)
  75754. {
  75755. const float type = elements [index++];
  75756. if (type == moveMarker)
  75757. {
  75758. elementType = startNewSubPath;
  75759. x1 = elements [index++];
  75760. y1 = elements [index++];
  75761. }
  75762. else if (type == lineMarker)
  75763. {
  75764. elementType = lineTo;
  75765. x1 = elements [index++];
  75766. y1 = elements [index++];
  75767. }
  75768. else if (type == quadMarker)
  75769. {
  75770. elementType = quadraticTo;
  75771. x1 = elements [index++];
  75772. y1 = elements [index++];
  75773. x2 = elements [index++];
  75774. y2 = elements [index++];
  75775. }
  75776. else if (type == cubicMarker)
  75777. {
  75778. elementType = cubicTo;
  75779. x1 = elements [index++];
  75780. y1 = elements [index++];
  75781. x2 = elements [index++];
  75782. y2 = elements [index++];
  75783. x3 = elements [index++];
  75784. y3 = elements [index++];
  75785. }
  75786. else if (type == closeSubPathMarker)
  75787. {
  75788. elementType = closePath;
  75789. }
  75790. return true;
  75791. }
  75792. return false;
  75793. }
  75794. END_JUCE_NAMESPACE
  75795. /*** End of inlined file: juce_Path.cpp ***/
  75796. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75797. BEGIN_JUCE_NAMESPACE
  75798. #if JUCE_MSVC && JUCE_DEBUG
  75799. #pragma optimize ("t", on)
  75800. #endif
  75801. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75802. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75803. const AffineTransform& transform_,
  75804. const float tolerance)
  75805. : x2 (0),
  75806. y2 (0),
  75807. closesSubPath (false),
  75808. subPathIndex (-1),
  75809. path (path_),
  75810. transform (transform_),
  75811. points (path_.data.elements),
  75812. toleranceSquared (tolerance * tolerance),
  75813. subPathCloseX (0),
  75814. subPathCloseY (0),
  75815. isIdentityTransform (transform_.isIdentity()),
  75816. stackBase (32),
  75817. index (0),
  75818. stackSize (32)
  75819. {
  75820. stackPos = stackBase;
  75821. }
  75822. PathFlatteningIterator::~PathFlatteningIterator()
  75823. {
  75824. }
  75825. bool PathFlatteningIterator::isLastInSubpath() const throw()
  75826. {
  75827. return stackPos == stackBase.getData()
  75828. && (index >= path.numElements || points [index] == Path::moveMarker);
  75829. }
  75830. bool PathFlatteningIterator::next()
  75831. {
  75832. x1 = x2;
  75833. y1 = y2;
  75834. float x3 = 0;
  75835. float y3 = 0;
  75836. float x4 = 0;
  75837. float y4 = 0;
  75838. float type;
  75839. for (;;)
  75840. {
  75841. if (stackPos == stackBase)
  75842. {
  75843. if (index >= path.numElements)
  75844. {
  75845. return false;
  75846. }
  75847. else
  75848. {
  75849. type = points [index++];
  75850. if (type != Path::closeSubPathMarker)
  75851. {
  75852. x2 = points [index++];
  75853. y2 = points [index++];
  75854. if (type == Path::quadMarker)
  75855. {
  75856. x3 = points [index++];
  75857. y3 = points [index++];
  75858. if (! isIdentityTransform)
  75859. transform.transformPoints (x2, y2, x3, y3);
  75860. }
  75861. else if (type == Path::cubicMarker)
  75862. {
  75863. x3 = points [index++];
  75864. y3 = points [index++];
  75865. x4 = points [index++];
  75866. y4 = points [index++];
  75867. if (! isIdentityTransform)
  75868. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75869. }
  75870. else
  75871. {
  75872. if (! isIdentityTransform)
  75873. transform.transformPoint (x2, y2);
  75874. }
  75875. }
  75876. }
  75877. }
  75878. else
  75879. {
  75880. type = *--stackPos;
  75881. if (type != Path::closeSubPathMarker)
  75882. {
  75883. x2 = *--stackPos;
  75884. y2 = *--stackPos;
  75885. if (type == Path::quadMarker)
  75886. {
  75887. x3 = *--stackPos;
  75888. y3 = *--stackPos;
  75889. }
  75890. else if (type == Path::cubicMarker)
  75891. {
  75892. x3 = *--stackPos;
  75893. y3 = *--stackPos;
  75894. x4 = *--stackPos;
  75895. y4 = *--stackPos;
  75896. }
  75897. }
  75898. }
  75899. if (type == Path::lineMarker)
  75900. {
  75901. ++subPathIndex;
  75902. closesSubPath = (stackPos == stackBase)
  75903. && (index < path.numElements)
  75904. && (points [index] == Path::closeSubPathMarker)
  75905. && x2 == subPathCloseX
  75906. && y2 == subPathCloseY;
  75907. return true;
  75908. }
  75909. else if (type == Path::quadMarker)
  75910. {
  75911. const size_t offset = (size_t) (stackPos - stackBase);
  75912. if (offset >= stackSize - 10)
  75913. {
  75914. stackSize <<= 1;
  75915. stackBase.realloc (stackSize);
  75916. stackPos = stackBase + offset;
  75917. }
  75918. const float m1x = (x1 + x2) * 0.5f;
  75919. const float m1y = (y1 + y2) * 0.5f;
  75920. const float m2x = (x2 + x3) * 0.5f;
  75921. const float m2y = (y2 + y3) * 0.5f;
  75922. const float m3x = (m1x + m2x) * 0.5f;
  75923. const float m3y = (m1y + m2y) * 0.5f;
  75924. const float errorX = m3x - x2;
  75925. const float errorY = m3y - y2;
  75926. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75927. {
  75928. *stackPos++ = y3;
  75929. *stackPos++ = x3;
  75930. *stackPos++ = m2y;
  75931. *stackPos++ = m2x;
  75932. *stackPos++ = Path::quadMarker;
  75933. *stackPos++ = m3y;
  75934. *stackPos++ = m3x;
  75935. *stackPos++ = m1y;
  75936. *stackPos++ = m1x;
  75937. *stackPos++ = Path::quadMarker;
  75938. }
  75939. else
  75940. {
  75941. *stackPos++ = y3;
  75942. *stackPos++ = x3;
  75943. *stackPos++ = Path::lineMarker;
  75944. *stackPos++ = m3y;
  75945. *stackPos++ = m3x;
  75946. *stackPos++ = Path::lineMarker;
  75947. }
  75948. jassert (stackPos < stackBase + stackSize);
  75949. }
  75950. else if (type == Path::cubicMarker)
  75951. {
  75952. const size_t offset = (size_t) (stackPos - stackBase);
  75953. if (offset >= stackSize - 16)
  75954. {
  75955. stackSize <<= 1;
  75956. stackBase.realloc (stackSize);
  75957. stackPos = stackBase + offset;
  75958. }
  75959. const float m1x = (x1 + x2) * 0.5f;
  75960. const float m1y = (y1 + y2) * 0.5f;
  75961. const float m2x = (x3 + x2) * 0.5f;
  75962. const float m2y = (y3 + y2) * 0.5f;
  75963. const float m3x = (x3 + x4) * 0.5f;
  75964. const float m3y = (y3 + y4) * 0.5f;
  75965. const float m4x = (m1x + m2x) * 0.5f;
  75966. const float m4y = (m1y + m2y) * 0.5f;
  75967. const float m5x = (m3x + m2x) * 0.5f;
  75968. const float m5y = (m3y + m2y) * 0.5f;
  75969. const float error1X = m4x - x2;
  75970. const float error1Y = m4y - y2;
  75971. const float error2X = m5x - x3;
  75972. const float error2Y = m5y - y3;
  75973. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75974. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75975. {
  75976. *stackPos++ = y4;
  75977. *stackPos++ = x4;
  75978. *stackPos++ = m3y;
  75979. *stackPos++ = m3x;
  75980. *stackPos++ = m5y;
  75981. *stackPos++ = m5x;
  75982. *stackPos++ = Path::cubicMarker;
  75983. *stackPos++ = (m4y + m5y) * 0.5f;
  75984. *stackPos++ = (m4x + m5x) * 0.5f;
  75985. *stackPos++ = m4y;
  75986. *stackPos++ = m4x;
  75987. *stackPos++ = m1y;
  75988. *stackPos++ = m1x;
  75989. *stackPos++ = Path::cubicMarker;
  75990. }
  75991. else
  75992. {
  75993. *stackPos++ = y4;
  75994. *stackPos++ = x4;
  75995. *stackPos++ = Path::lineMarker;
  75996. *stackPos++ = m5y;
  75997. *stackPos++ = m5x;
  75998. *stackPos++ = Path::lineMarker;
  75999. *stackPos++ = m4y;
  76000. *stackPos++ = m4x;
  76001. *stackPos++ = Path::lineMarker;
  76002. }
  76003. }
  76004. else if (type == Path::closeSubPathMarker)
  76005. {
  76006. if (x2 != subPathCloseX || y2 != subPathCloseY)
  76007. {
  76008. x1 = x2;
  76009. y1 = y2;
  76010. x2 = subPathCloseX;
  76011. y2 = subPathCloseY;
  76012. closesSubPath = true;
  76013. return true;
  76014. }
  76015. }
  76016. else
  76017. {
  76018. jassert (type == Path::moveMarker);
  76019. subPathIndex = -1;
  76020. subPathCloseX = x1 = x2;
  76021. subPathCloseY = y1 = y2;
  76022. }
  76023. }
  76024. }
  76025. #if JUCE_MSVC && JUCE_DEBUG
  76026. #pragma optimize ("", on) // resets optimisations to the project defaults
  76027. #endif
  76028. END_JUCE_NAMESPACE
  76029. /*** End of inlined file: juce_PathIterator.cpp ***/
  76030. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  76031. BEGIN_JUCE_NAMESPACE
  76032. PathStrokeType::PathStrokeType (const float strokeThickness,
  76033. const JointStyle jointStyle_,
  76034. const EndCapStyle endStyle_) throw()
  76035. : thickness (strokeThickness),
  76036. jointStyle (jointStyle_),
  76037. endStyle (endStyle_)
  76038. {
  76039. }
  76040. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  76041. : thickness (other.thickness),
  76042. jointStyle (other.jointStyle),
  76043. endStyle (other.endStyle)
  76044. {
  76045. }
  76046. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  76047. {
  76048. thickness = other.thickness;
  76049. jointStyle = other.jointStyle;
  76050. endStyle = other.endStyle;
  76051. return *this;
  76052. }
  76053. PathStrokeType::~PathStrokeType() throw()
  76054. {
  76055. }
  76056. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  76057. {
  76058. return thickness == other.thickness
  76059. && jointStyle == other.jointStyle
  76060. && endStyle == other.endStyle;
  76061. }
  76062. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  76063. {
  76064. return ! operator== (other);
  76065. }
  76066. namespace PathStrokeHelpers
  76067. {
  76068. bool lineIntersection (const float x1, const float y1,
  76069. const float x2, const float y2,
  76070. const float x3, const float y3,
  76071. const float x4, const float y4,
  76072. float& intersectionX,
  76073. float& intersectionY,
  76074. float& distanceBeyondLine1EndSquared) throw()
  76075. {
  76076. if (x2 != x3 || y2 != y3)
  76077. {
  76078. const float dx1 = x2 - x1;
  76079. const float dy1 = y2 - y1;
  76080. const float dx2 = x4 - x3;
  76081. const float dy2 = y4 - y3;
  76082. const float divisor = dx1 * dy2 - dx2 * dy1;
  76083. if (divisor == 0)
  76084. {
  76085. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  76086. {
  76087. if (dy1 == 0 && dy2 != 0)
  76088. {
  76089. const float along = (y1 - y3) / dy2;
  76090. intersectionX = x3 + along * dx2;
  76091. intersectionY = y1;
  76092. distanceBeyondLine1EndSquared = intersectionX - x2;
  76093. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76094. if ((x2 > x1) == (intersectionX < x2))
  76095. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76096. return along >= 0 && along <= 1.0f;
  76097. }
  76098. else if (dy2 == 0 && dy1 != 0)
  76099. {
  76100. const float along = (y3 - y1) / dy1;
  76101. intersectionX = x1 + along * dx1;
  76102. intersectionY = y3;
  76103. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  76104. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76105. if (along < 1.0f)
  76106. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76107. return along >= 0 && along <= 1.0f;
  76108. }
  76109. else if (dx1 == 0 && dx2 != 0)
  76110. {
  76111. const float along = (x1 - x3) / dx2;
  76112. intersectionX = x1;
  76113. intersectionY = y3 + along * dy2;
  76114. distanceBeyondLine1EndSquared = intersectionY - y2;
  76115. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76116. if ((y2 > y1) == (intersectionY < y2))
  76117. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76118. return along >= 0 && along <= 1.0f;
  76119. }
  76120. else if (dx2 == 0 && dx1 != 0)
  76121. {
  76122. const float along = (x3 - x1) / dx1;
  76123. intersectionX = x3;
  76124. intersectionY = y1 + along * dy1;
  76125. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  76126. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76127. if (along < 1.0f)
  76128. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76129. return along >= 0 && along <= 1.0f;
  76130. }
  76131. }
  76132. intersectionX = 0.5f * (x2 + x3);
  76133. intersectionY = 0.5f * (y2 + y3);
  76134. distanceBeyondLine1EndSquared = 0.0f;
  76135. return false;
  76136. }
  76137. else
  76138. {
  76139. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  76140. intersectionX = x1 + along1 * dx1;
  76141. intersectionY = y1 + along1 * dy1;
  76142. if (along1 >= 0 && along1 <= 1.0f)
  76143. {
  76144. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  76145. if (along2 >= 0 && along2 <= divisor)
  76146. {
  76147. distanceBeyondLine1EndSquared = 0.0f;
  76148. return true;
  76149. }
  76150. }
  76151. distanceBeyondLine1EndSquared = along1 - 1.0f;
  76152. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76153. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  76154. if (along1 < 1.0f)
  76155. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76156. return false;
  76157. }
  76158. }
  76159. intersectionX = x2;
  76160. intersectionY = y2;
  76161. distanceBeyondLine1EndSquared = 0.0f;
  76162. return true;
  76163. }
  76164. void addEdgeAndJoint (Path& destPath,
  76165. const PathStrokeType::JointStyle style,
  76166. const float maxMiterExtensionSquared, const float width,
  76167. const float x1, const float y1,
  76168. const float x2, const float y2,
  76169. const float x3, const float y3,
  76170. const float x4, const float y4,
  76171. const float midX, const float midY)
  76172. {
  76173. if (style == PathStrokeType::beveled
  76174. || (x3 == x4 && y3 == y4)
  76175. || (x1 == x2 && y1 == y2))
  76176. {
  76177. destPath.lineTo (x2, y2);
  76178. destPath.lineTo (x3, y3);
  76179. }
  76180. else
  76181. {
  76182. float jx, jy, distanceBeyondLine1EndSquared;
  76183. // if they intersect, use this point..
  76184. if (lineIntersection (x1, y1, x2, y2,
  76185. x3, y3, x4, y4,
  76186. jx, jy, distanceBeyondLine1EndSquared))
  76187. {
  76188. destPath.lineTo (jx, jy);
  76189. }
  76190. else
  76191. {
  76192. if (style == PathStrokeType::mitered)
  76193. {
  76194. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  76195. && distanceBeyondLine1EndSquared > 0.0f)
  76196. {
  76197. destPath.lineTo (jx, jy);
  76198. }
  76199. else
  76200. {
  76201. // the end sticks out too far, so just use a blunt joint
  76202. destPath.lineTo (x2, y2);
  76203. destPath.lineTo (x3, y3);
  76204. }
  76205. }
  76206. else
  76207. {
  76208. // curved joints
  76209. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  76210. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  76211. const float angleIncrement = 0.1f;
  76212. destPath.lineTo (x2, y2);
  76213. if (std::abs (angle1 - angle2) > angleIncrement)
  76214. {
  76215. if (angle2 > angle1 + float_Pi
  76216. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  76217. {
  76218. if (angle2 > angle1)
  76219. angle2 -= float_Pi * 2.0f;
  76220. jassert (angle1 <= angle2 + float_Pi);
  76221. angle1 -= angleIncrement;
  76222. while (angle1 > angle2)
  76223. {
  76224. destPath.lineTo (midX + width * std::sin (angle1),
  76225. midY + width * std::cos (angle1));
  76226. angle1 -= angleIncrement;
  76227. }
  76228. }
  76229. else
  76230. {
  76231. if (angle1 > angle2)
  76232. angle1 -= float_Pi * 2.0f;
  76233. jassert (angle1 >= angle2 - float_Pi);
  76234. angle1 += angleIncrement;
  76235. while (angle1 < angle2)
  76236. {
  76237. destPath.lineTo (midX + width * std::sin (angle1),
  76238. midY + width * std::cos (angle1));
  76239. angle1 += angleIncrement;
  76240. }
  76241. }
  76242. }
  76243. destPath.lineTo (x3, y3);
  76244. }
  76245. }
  76246. }
  76247. }
  76248. void addLineEnd (Path& destPath,
  76249. const PathStrokeType::EndCapStyle style,
  76250. const float x1, const float y1,
  76251. const float x2, const float y2,
  76252. const float width)
  76253. {
  76254. if (style == PathStrokeType::butt)
  76255. {
  76256. destPath.lineTo (x2, y2);
  76257. }
  76258. else
  76259. {
  76260. float offx1, offy1, offx2, offy2;
  76261. float dx = x2 - x1;
  76262. float dy = y2 - y1;
  76263. const float len = juce_hypot (dx, dy);
  76264. if (len == 0)
  76265. {
  76266. offx1 = offx2 = x1;
  76267. offy1 = offy2 = y1;
  76268. }
  76269. else
  76270. {
  76271. const float offset = width / len;
  76272. dx *= offset;
  76273. dy *= offset;
  76274. offx1 = x1 + dy;
  76275. offy1 = y1 - dx;
  76276. offx2 = x2 + dy;
  76277. offy2 = y2 - dx;
  76278. }
  76279. if (style == PathStrokeType::square)
  76280. {
  76281. // sqaure ends
  76282. destPath.lineTo (offx1, offy1);
  76283. destPath.lineTo (offx2, offy2);
  76284. destPath.lineTo (x2, y2);
  76285. }
  76286. else
  76287. {
  76288. // rounded ends
  76289. const float midx = (offx1 + offx2) * 0.5f;
  76290. const float midy = (offy1 + offy2) * 0.5f;
  76291. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76292. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76293. midx, midy);
  76294. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76295. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76296. x2, y2);
  76297. }
  76298. }
  76299. }
  76300. struct Arrowhead
  76301. {
  76302. float startWidth, startLength;
  76303. float endWidth, endLength;
  76304. };
  76305. void addArrowhead (Path& destPath,
  76306. const float x1, const float y1,
  76307. const float x2, const float y2,
  76308. const float tipX, const float tipY,
  76309. const float width,
  76310. const float arrowheadWidth)
  76311. {
  76312. Line<float> line (x1, y1, x2, y2);
  76313. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76314. destPath.lineTo (tipX, tipY);
  76315. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76316. destPath.lineTo (x2, y2);
  76317. }
  76318. struct LineSection
  76319. {
  76320. float x1, y1, x2, y2; // original line
  76321. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76322. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76323. };
  76324. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76325. {
  76326. while (amountAtEnd > 0 && subPath.size() > 0)
  76327. {
  76328. LineSection& l = subPath.getReference (subPath.size() - 1);
  76329. float dx = l.rx2 - l.rx1;
  76330. float dy = l.ry2 - l.ry1;
  76331. const float len = juce_hypot (dx, dy);
  76332. if (len <= amountAtEnd && subPath.size() > 1)
  76333. {
  76334. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76335. prev.x2 = l.x2;
  76336. prev.y2 = l.y2;
  76337. subPath.removeLast();
  76338. amountAtEnd -= len;
  76339. }
  76340. else
  76341. {
  76342. const float prop = jmin (0.9999f, amountAtEnd / len);
  76343. dx *= prop;
  76344. dy *= prop;
  76345. l.rx1 += dx;
  76346. l.ry1 += dy;
  76347. l.lx2 += dx;
  76348. l.ly2 += dy;
  76349. break;
  76350. }
  76351. }
  76352. while (amountAtStart > 0 && subPath.size() > 0)
  76353. {
  76354. LineSection& l = subPath.getReference (0);
  76355. float dx = l.rx2 - l.rx1;
  76356. float dy = l.ry2 - l.ry1;
  76357. const float len = juce_hypot (dx, dy);
  76358. if (len <= amountAtStart && subPath.size() > 1)
  76359. {
  76360. LineSection& next = subPath.getReference (1);
  76361. next.x1 = l.x1;
  76362. next.y1 = l.y1;
  76363. subPath.remove (0);
  76364. amountAtStart -= len;
  76365. }
  76366. else
  76367. {
  76368. const float prop = jmin (0.9999f, amountAtStart / len);
  76369. dx *= prop;
  76370. dy *= prop;
  76371. l.rx2 -= dx;
  76372. l.ry2 -= dy;
  76373. l.lx1 -= dx;
  76374. l.ly1 -= dy;
  76375. break;
  76376. }
  76377. }
  76378. }
  76379. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76380. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76381. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76382. const Arrowhead* const arrowhead)
  76383. {
  76384. jassert (subPath.size() > 0);
  76385. if (arrowhead != 0)
  76386. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76387. const LineSection& firstLine = subPath.getReference (0);
  76388. float lastX1 = firstLine.lx1;
  76389. float lastY1 = firstLine.ly1;
  76390. float lastX2 = firstLine.lx2;
  76391. float lastY2 = firstLine.ly2;
  76392. if (isClosed)
  76393. {
  76394. destPath.startNewSubPath (lastX1, lastY1);
  76395. }
  76396. else
  76397. {
  76398. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76399. if (arrowhead != 0)
  76400. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76401. width, arrowhead->startWidth);
  76402. else
  76403. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76404. }
  76405. int i;
  76406. for (i = 1; i < subPath.size(); ++i)
  76407. {
  76408. const LineSection& l = subPath.getReference (i);
  76409. addEdgeAndJoint (destPath, jointStyle,
  76410. maxMiterExtensionSquared, width,
  76411. lastX1, lastY1, lastX2, lastY2,
  76412. l.lx1, l.ly1, l.lx2, l.ly2,
  76413. l.x1, l.y1);
  76414. lastX1 = l.lx1;
  76415. lastY1 = l.ly1;
  76416. lastX2 = l.lx2;
  76417. lastY2 = l.ly2;
  76418. }
  76419. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76420. if (isClosed)
  76421. {
  76422. const LineSection& l = subPath.getReference (0);
  76423. addEdgeAndJoint (destPath, jointStyle,
  76424. maxMiterExtensionSquared, width,
  76425. lastX1, lastY1, lastX2, lastY2,
  76426. l.lx1, l.ly1, l.lx2, l.ly2,
  76427. l.x1, l.y1);
  76428. destPath.closeSubPath();
  76429. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76430. }
  76431. else
  76432. {
  76433. destPath.lineTo (lastX2, lastY2);
  76434. if (arrowhead != 0)
  76435. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76436. width, arrowhead->endWidth);
  76437. else
  76438. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76439. }
  76440. lastX1 = lastLine.rx1;
  76441. lastY1 = lastLine.ry1;
  76442. lastX2 = lastLine.rx2;
  76443. lastY2 = lastLine.ry2;
  76444. for (i = subPath.size() - 1; --i >= 0;)
  76445. {
  76446. const LineSection& l = subPath.getReference (i);
  76447. addEdgeAndJoint (destPath, jointStyle,
  76448. maxMiterExtensionSquared, width,
  76449. lastX1, lastY1, lastX2, lastY2,
  76450. l.rx1, l.ry1, l.rx2, l.ry2,
  76451. l.x2, l.y2);
  76452. lastX1 = l.rx1;
  76453. lastY1 = l.ry1;
  76454. lastX2 = l.rx2;
  76455. lastY2 = l.ry2;
  76456. }
  76457. if (isClosed)
  76458. {
  76459. addEdgeAndJoint (destPath, jointStyle,
  76460. maxMiterExtensionSquared, width,
  76461. lastX1, lastY1, lastX2, lastY2,
  76462. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76463. lastLine.x2, lastLine.y2);
  76464. }
  76465. else
  76466. {
  76467. // do the last line
  76468. destPath.lineTo (lastX2, lastY2);
  76469. }
  76470. destPath.closeSubPath();
  76471. }
  76472. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76473. const PathStrokeType::EndCapStyle endStyle,
  76474. Path& destPath, const Path& source,
  76475. const AffineTransform& transform,
  76476. const float extraAccuracy, const Arrowhead* const arrowhead)
  76477. {
  76478. jassert (extraAccuracy > 0);
  76479. if (thickness <= 0)
  76480. {
  76481. destPath.clear();
  76482. return;
  76483. }
  76484. const Path* sourcePath = &source;
  76485. Path temp;
  76486. if (sourcePath == &destPath)
  76487. {
  76488. destPath.swapWithPath (temp);
  76489. sourcePath = &temp;
  76490. }
  76491. else
  76492. {
  76493. destPath.clear();
  76494. }
  76495. destPath.setUsingNonZeroWinding (true);
  76496. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76497. const float width = 0.5f * thickness;
  76498. // Iterate the path, creating a list of the
  76499. // left/right-hand lines along either side of it...
  76500. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76501. Array <LineSection> subPath;
  76502. subPath.ensureStorageAllocated (512);
  76503. LineSection l;
  76504. l.x1 = 0;
  76505. l.y1 = 0;
  76506. const float minSegmentLength = 0.0001f;
  76507. while (it.next())
  76508. {
  76509. if (it.subPathIndex == 0)
  76510. {
  76511. if (subPath.size() > 0)
  76512. {
  76513. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76514. subPath.clearQuick();
  76515. }
  76516. l.x1 = it.x1;
  76517. l.y1 = it.y1;
  76518. }
  76519. l.x2 = it.x2;
  76520. l.y2 = it.y2;
  76521. float dx = l.x2 - l.x1;
  76522. float dy = l.y2 - l.y1;
  76523. const float hypotSquared = dx*dx + dy*dy;
  76524. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76525. {
  76526. const float len = std::sqrt (hypotSquared);
  76527. if (len == 0)
  76528. {
  76529. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76530. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76531. }
  76532. else
  76533. {
  76534. const float offset = width / len;
  76535. dx *= offset;
  76536. dy *= offset;
  76537. l.rx2 = l.x1 - dy;
  76538. l.ry2 = l.y1 + dx;
  76539. l.lx1 = l.x1 + dy;
  76540. l.ly1 = l.y1 - dx;
  76541. l.lx2 = l.x2 + dy;
  76542. l.ly2 = l.y2 - dx;
  76543. l.rx1 = l.x2 - dy;
  76544. l.ry1 = l.y2 + dx;
  76545. }
  76546. subPath.add (l);
  76547. if (it.closesSubPath)
  76548. {
  76549. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76550. subPath.clearQuick();
  76551. }
  76552. else
  76553. {
  76554. l.x1 = it.x2;
  76555. l.y1 = it.y2;
  76556. }
  76557. }
  76558. }
  76559. if (subPath.size() > 0)
  76560. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76561. }
  76562. }
  76563. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76564. const AffineTransform& transform, const float extraAccuracy) const
  76565. {
  76566. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76567. transform, extraAccuracy, 0);
  76568. }
  76569. void PathStrokeType::createDashedStroke (Path& destPath,
  76570. const Path& sourcePath,
  76571. const float* dashLengths,
  76572. int numDashLengths,
  76573. const AffineTransform& transform,
  76574. const float extraAccuracy) const
  76575. {
  76576. jassert (extraAccuracy > 0);
  76577. if (thickness <= 0)
  76578. return;
  76579. // this should really be an even number..
  76580. jassert ((numDashLengths & 1) == 0);
  76581. Path newDestPath;
  76582. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76583. bool first = true;
  76584. int dashNum = 0;
  76585. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76586. float dx = 0.0f, dy = 0.0f;
  76587. for (;;)
  76588. {
  76589. const bool isSolid = ((dashNum & 1) == 0);
  76590. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76591. jassert (dashLen > 0); // must be a positive increment!
  76592. if (dashLen <= 0)
  76593. break;
  76594. pos += dashLen;
  76595. while (pos > lineEndPos)
  76596. {
  76597. if (! it.next())
  76598. {
  76599. if (isSolid && ! first)
  76600. newDestPath.lineTo (it.x2, it.y2);
  76601. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76602. return;
  76603. }
  76604. if (isSolid && ! first)
  76605. newDestPath.lineTo (it.x1, it.y1);
  76606. else
  76607. newDestPath.startNewSubPath (it.x1, it.y1);
  76608. dx = it.x2 - it.x1;
  76609. dy = it.y2 - it.y1;
  76610. lineLen = juce_hypot (dx, dy);
  76611. lineEndPos += lineLen;
  76612. first = it.closesSubPath;
  76613. }
  76614. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76615. if (isSolid)
  76616. newDestPath.lineTo (it.x1 + dx * alpha,
  76617. it.y1 + dy * alpha);
  76618. else
  76619. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76620. it.y1 + dy * alpha);
  76621. }
  76622. }
  76623. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76624. const Path& sourcePath,
  76625. const float arrowheadStartWidth, const float arrowheadStartLength,
  76626. const float arrowheadEndWidth, const float arrowheadEndLength,
  76627. const AffineTransform& transform,
  76628. const float extraAccuracy) const
  76629. {
  76630. PathStrokeHelpers::Arrowhead head;
  76631. head.startWidth = arrowheadStartWidth;
  76632. head.startLength = arrowheadStartLength;
  76633. head.endWidth = arrowheadEndWidth;
  76634. head.endLength = arrowheadEndLength;
  76635. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76636. destPath, sourcePath, transform, extraAccuracy, &head);
  76637. }
  76638. END_JUCE_NAMESPACE
  76639. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76640. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76641. BEGIN_JUCE_NAMESPACE
  76642. RectangleList::RectangleList() throw()
  76643. {
  76644. }
  76645. RectangleList::RectangleList (const Rectangle<int>& rect)
  76646. {
  76647. if (! rect.isEmpty())
  76648. rects.add (rect);
  76649. }
  76650. RectangleList::RectangleList (const RectangleList& other)
  76651. : rects (other.rects)
  76652. {
  76653. }
  76654. RectangleList& RectangleList::operator= (const RectangleList& other)
  76655. {
  76656. rects = other.rects;
  76657. return *this;
  76658. }
  76659. RectangleList::~RectangleList()
  76660. {
  76661. }
  76662. void RectangleList::clear()
  76663. {
  76664. rects.clearQuick();
  76665. }
  76666. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76667. {
  76668. if (isPositiveAndBelow (index, rects.size()))
  76669. return rects.getReference (index);
  76670. return Rectangle<int>();
  76671. }
  76672. bool RectangleList::isEmpty() const throw()
  76673. {
  76674. return rects.size() == 0;
  76675. }
  76676. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76677. : current (0),
  76678. owner (list),
  76679. index (list.rects.size())
  76680. {
  76681. }
  76682. RectangleList::Iterator::~Iterator()
  76683. {
  76684. }
  76685. bool RectangleList::Iterator::next() throw()
  76686. {
  76687. if (--index >= 0)
  76688. {
  76689. current = & (owner.rects.getReference (index));
  76690. return true;
  76691. }
  76692. return false;
  76693. }
  76694. void RectangleList::add (const Rectangle<int>& rect)
  76695. {
  76696. if (! rect.isEmpty())
  76697. {
  76698. if (rects.size() == 0)
  76699. {
  76700. rects.add (rect);
  76701. }
  76702. else
  76703. {
  76704. bool anyOverlaps = false;
  76705. int i;
  76706. for (i = rects.size(); --i >= 0;)
  76707. {
  76708. Rectangle<int>& ourRect = rects.getReference (i);
  76709. if (rect.intersects (ourRect))
  76710. {
  76711. if (rect.contains (ourRect))
  76712. rects.remove (i);
  76713. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76714. anyOverlaps = true;
  76715. }
  76716. }
  76717. if (anyOverlaps && rects.size() > 0)
  76718. {
  76719. RectangleList r (rect);
  76720. for (i = rects.size(); --i >= 0;)
  76721. {
  76722. const Rectangle<int>& ourRect = rects.getReference (i);
  76723. if (rect.intersects (ourRect))
  76724. {
  76725. r.subtract (ourRect);
  76726. if (r.rects.size() == 0)
  76727. return;
  76728. }
  76729. }
  76730. for (i = r.getNumRectangles(); --i >= 0;)
  76731. rects.add (r.rects.getReference (i));
  76732. }
  76733. else
  76734. {
  76735. rects.add (rect);
  76736. }
  76737. }
  76738. }
  76739. }
  76740. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76741. {
  76742. if (! rect.isEmpty())
  76743. rects.add (rect);
  76744. }
  76745. void RectangleList::add (const int x, const int y, const int w, const int h)
  76746. {
  76747. if (rects.size() == 0)
  76748. {
  76749. if (w > 0 && h > 0)
  76750. rects.add (Rectangle<int> (x, y, w, h));
  76751. }
  76752. else
  76753. {
  76754. add (Rectangle<int> (x, y, w, h));
  76755. }
  76756. }
  76757. void RectangleList::add (const RectangleList& other)
  76758. {
  76759. for (int i = 0; i < other.rects.size(); ++i)
  76760. add (other.rects.getReference (i));
  76761. }
  76762. void RectangleList::subtract (const Rectangle<int>& rect)
  76763. {
  76764. const int originalNumRects = rects.size();
  76765. if (originalNumRects > 0)
  76766. {
  76767. const int x1 = rect.x;
  76768. const int y1 = rect.y;
  76769. const int x2 = x1 + rect.w;
  76770. const int y2 = y1 + rect.h;
  76771. for (int i = getNumRectangles(); --i >= 0;)
  76772. {
  76773. Rectangle<int>& r = rects.getReference (i);
  76774. const int rx1 = r.x;
  76775. const int ry1 = r.y;
  76776. const int rx2 = rx1 + r.w;
  76777. const int ry2 = ry1 + r.h;
  76778. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76779. {
  76780. if (x1 > rx1 && x1 < rx2)
  76781. {
  76782. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76783. {
  76784. r.w = x1 - rx1;
  76785. }
  76786. else
  76787. {
  76788. r.x = x1;
  76789. r.w = rx2 - x1;
  76790. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76791. i += 2;
  76792. }
  76793. }
  76794. else if (x2 > rx1 && x2 < rx2)
  76795. {
  76796. r.x = x2;
  76797. r.w = rx2 - x2;
  76798. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76799. {
  76800. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76801. i += 2;
  76802. }
  76803. }
  76804. else if (y1 > ry1 && y1 < ry2)
  76805. {
  76806. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76807. {
  76808. r.h = y1 - ry1;
  76809. }
  76810. else
  76811. {
  76812. r.y = y1;
  76813. r.h = ry2 - y1;
  76814. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76815. i += 2;
  76816. }
  76817. }
  76818. else if (y2 > ry1 && y2 < ry2)
  76819. {
  76820. r.y = y2;
  76821. r.h = ry2 - y2;
  76822. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76823. {
  76824. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76825. i += 2;
  76826. }
  76827. }
  76828. else
  76829. {
  76830. rects.remove (i);
  76831. }
  76832. }
  76833. }
  76834. }
  76835. }
  76836. bool RectangleList::subtract (const RectangleList& otherList)
  76837. {
  76838. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76839. subtract (otherList.rects.getReference (i));
  76840. return rects.size() > 0;
  76841. }
  76842. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76843. {
  76844. bool notEmpty = false;
  76845. if (rect.isEmpty())
  76846. {
  76847. clear();
  76848. }
  76849. else
  76850. {
  76851. for (int i = rects.size(); --i >= 0;)
  76852. {
  76853. Rectangle<int>& r = rects.getReference (i);
  76854. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76855. rects.remove (i);
  76856. else
  76857. notEmpty = true;
  76858. }
  76859. }
  76860. return notEmpty;
  76861. }
  76862. bool RectangleList::clipTo (const RectangleList& other)
  76863. {
  76864. if (rects.size() == 0)
  76865. return false;
  76866. RectangleList result;
  76867. for (int j = 0; j < rects.size(); ++j)
  76868. {
  76869. const Rectangle<int>& rect = rects.getReference (j);
  76870. for (int i = other.rects.size(); --i >= 0;)
  76871. {
  76872. Rectangle<int> r (other.rects.getReference (i));
  76873. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76874. result.rects.add (r);
  76875. }
  76876. }
  76877. swapWith (result);
  76878. return ! isEmpty();
  76879. }
  76880. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76881. {
  76882. destRegion.clear();
  76883. if (! rect.isEmpty())
  76884. {
  76885. for (int i = rects.size(); --i >= 0;)
  76886. {
  76887. Rectangle<int> r (rects.getReference (i));
  76888. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76889. destRegion.rects.add (r);
  76890. }
  76891. }
  76892. return destRegion.rects.size() > 0;
  76893. }
  76894. void RectangleList::swapWith (RectangleList& otherList) throw()
  76895. {
  76896. rects.swapWithArray (otherList.rects);
  76897. }
  76898. void RectangleList::consolidate()
  76899. {
  76900. int i;
  76901. for (i = 0; i < getNumRectangles() - 1; ++i)
  76902. {
  76903. Rectangle<int>& r = rects.getReference (i);
  76904. const int rx1 = r.x;
  76905. const int ry1 = r.y;
  76906. const int rx2 = rx1 + r.w;
  76907. const int ry2 = ry1 + r.h;
  76908. for (int j = rects.size(); --j > i;)
  76909. {
  76910. Rectangle<int>& r2 = rects.getReference (j);
  76911. const int jrx1 = r2.x;
  76912. const int jry1 = r2.y;
  76913. const int jrx2 = jrx1 + r2.w;
  76914. const int jry2 = jry1 + r2.h;
  76915. // if the vertical edges of any blocks are touching and their horizontals don't
  76916. // line up, split them horizontally..
  76917. if (jrx1 == rx2 || jrx2 == rx1)
  76918. {
  76919. if (jry1 > ry1 && jry1 < ry2)
  76920. {
  76921. r.h = jry1 - ry1;
  76922. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76923. i = -1;
  76924. break;
  76925. }
  76926. if (jry2 > ry1 && jry2 < ry2)
  76927. {
  76928. r.h = jry2 - ry1;
  76929. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76930. i = -1;
  76931. break;
  76932. }
  76933. else if (ry1 > jry1 && ry1 < jry2)
  76934. {
  76935. r2.h = ry1 - jry1;
  76936. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76937. i = -1;
  76938. break;
  76939. }
  76940. else if (ry2 > jry1 && ry2 < jry2)
  76941. {
  76942. r2.h = ry2 - jry1;
  76943. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76944. i = -1;
  76945. break;
  76946. }
  76947. }
  76948. }
  76949. }
  76950. for (i = 0; i < rects.size() - 1; ++i)
  76951. {
  76952. Rectangle<int>& r = rects.getReference (i);
  76953. for (int j = rects.size(); --j > i;)
  76954. {
  76955. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76956. {
  76957. rects.remove (j);
  76958. i = -1;
  76959. break;
  76960. }
  76961. }
  76962. }
  76963. }
  76964. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76965. {
  76966. for (int i = getNumRectangles(); --i >= 0;)
  76967. if (rects.getReference (i).contains (x, y))
  76968. return true;
  76969. return false;
  76970. }
  76971. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76972. {
  76973. if (rects.size() > 1)
  76974. {
  76975. RectangleList r (rectangleToCheck);
  76976. for (int i = rects.size(); --i >= 0;)
  76977. {
  76978. r.subtract (rects.getReference (i));
  76979. if (r.rects.size() == 0)
  76980. return true;
  76981. }
  76982. }
  76983. else if (rects.size() > 0)
  76984. {
  76985. return rects.getReference (0).contains (rectangleToCheck);
  76986. }
  76987. return false;
  76988. }
  76989. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76990. {
  76991. for (int i = rects.size(); --i >= 0;)
  76992. if (rects.getReference (i).intersects (rectangleToCheck))
  76993. return true;
  76994. return false;
  76995. }
  76996. bool RectangleList::intersects (const RectangleList& other) const throw()
  76997. {
  76998. for (int i = rects.size(); --i >= 0;)
  76999. if (other.intersectsRectangle (rects.getReference (i)))
  77000. return true;
  77001. return false;
  77002. }
  77003. const Rectangle<int> RectangleList::getBounds() const throw()
  77004. {
  77005. if (rects.size() <= 1)
  77006. {
  77007. if (rects.size() == 0)
  77008. return Rectangle<int>();
  77009. else
  77010. return rects.getReference (0);
  77011. }
  77012. else
  77013. {
  77014. const Rectangle<int>& r = rects.getReference (0);
  77015. int minX = r.x;
  77016. int minY = r.y;
  77017. int maxX = minX + r.w;
  77018. int maxY = minY + r.h;
  77019. for (int i = rects.size(); --i > 0;)
  77020. {
  77021. const Rectangle<int>& r2 = rects.getReference (i);
  77022. minX = jmin (minX, r2.x);
  77023. minY = jmin (minY, r2.y);
  77024. maxX = jmax (maxX, r2.getRight());
  77025. maxY = jmax (maxY, r2.getBottom());
  77026. }
  77027. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77028. }
  77029. }
  77030. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77031. {
  77032. for (int i = rects.size(); --i >= 0;)
  77033. {
  77034. Rectangle<int>& r = rects.getReference (i);
  77035. r.x += dx;
  77036. r.y += dy;
  77037. }
  77038. }
  77039. const Path RectangleList::toPath() const
  77040. {
  77041. Path p;
  77042. for (int i = rects.size(); --i >= 0;)
  77043. {
  77044. const Rectangle<int>& r = rects.getReference (i);
  77045. p.addRectangle ((float) r.x,
  77046. (float) r.y,
  77047. (float) r.w,
  77048. (float) r.h);
  77049. }
  77050. return p;
  77051. }
  77052. END_JUCE_NAMESPACE
  77053. /*** End of inlined file: juce_RectangleList.cpp ***/
  77054. /*** Start of inlined file: juce_Image.cpp ***/
  77055. BEGIN_JUCE_NAMESPACE
  77056. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77057. : format (format_), width (width_), height (height_)
  77058. {
  77059. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77060. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77061. }
  77062. Image::SharedImage::~SharedImage()
  77063. {
  77064. }
  77065. class SoftwareSharedImage : public Image::SharedImage
  77066. {
  77067. public:
  77068. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77069. : Image::SharedImage (format_, width_, height_),
  77070. pixelStride (format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1)),
  77071. lineStride ((pixelStride * jmax (1, width_) + 3) & ~3)
  77072. {
  77073. imageData.allocate (lineStride * jmax (1, height_), clearImage);
  77074. }
  77075. Image::ImageType getType() const
  77076. {
  77077. return Image::SoftwareImage;
  77078. }
  77079. LowLevelGraphicsContext* createLowLevelContext()
  77080. {
  77081. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77082. }
  77083. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  77084. {
  77085. bitmap.data = imageData + x * pixelStride + y * lineStride;
  77086. bitmap.pixelFormat = format;
  77087. bitmap.lineStride = lineStride;
  77088. bitmap.pixelStride = pixelStride;
  77089. }
  77090. Image::SharedImage* clone()
  77091. {
  77092. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77093. memcpy (s->imageData, imageData, lineStride * height);
  77094. return s;
  77095. }
  77096. private:
  77097. HeapBlock<uint8> imageData;
  77098. const int pixelStride, lineStride;
  77099. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  77100. };
  77101. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77102. {
  77103. return new SoftwareSharedImage (format, width, height, clearImage);
  77104. }
  77105. class SubsectionSharedImage : public Image::SharedImage
  77106. {
  77107. public:
  77108. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77109. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77110. image (image_), area (area_)
  77111. {
  77112. }
  77113. Image::ImageType getType() const
  77114. {
  77115. return Image::SoftwareImage;
  77116. }
  77117. LowLevelGraphicsContext* createLowLevelContext()
  77118. {
  77119. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77120. g->clipToRectangle (area);
  77121. g->setOrigin (area.getX(), area.getY());
  77122. return g;
  77123. }
  77124. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode)
  77125. {
  77126. image->initialiseBitmapData (bitmap, x + area.getX(), y + area.getY(), mode);
  77127. }
  77128. Image::SharedImage* clone()
  77129. {
  77130. return new SubsectionSharedImage (image->clone(), area);
  77131. }
  77132. private:
  77133. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77134. const Rectangle<int> area;
  77135. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  77136. };
  77137. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77138. {
  77139. if (area.contains (getBounds()))
  77140. return *this;
  77141. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77142. if (validArea.isEmpty())
  77143. return Image::null;
  77144. return Image (new SubsectionSharedImage (image, validArea));
  77145. }
  77146. Image::Image()
  77147. {
  77148. }
  77149. Image::Image (SharedImage* const instance)
  77150. : image (instance)
  77151. {
  77152. }
  77153. Image::Image (const PixelFormat format,
  77154. const int width, const int height,
  77155. const bool clearImage, const ImageType type)
  77156. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77157. : new SoftwareSharedImage (format, width, height, clearImage))
  77158. {
  77159. }
  77160. Image::Image (const Image& other)
  77161. : image (other.image)
  77162. {
  77163. }
  77164. Image& Image::operator= (const Image& other)
  77165. {
  77166. image = other.image;
  77167. return *this;
  77168. }
  77169. Image::~Image()
  77170. {
  77171. }
  77172. const Image Image::null;
  77173. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77174. {
  77175. return image == 0 ? 0 : image->createLowLevelContext();
  77176. }
  77177. void Image::duplicateIfShared()
  77178. {
  77179. if (image != 0 && image->getReferenceCount() > 1)
  77180. image = image->clone();
  77181. }
  77182. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77183. {
  77184. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77185. return *this;
  77186. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77187. Graphics g (newImage);
  77188. g.setImageResamplingQuality (quality);
  77189. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77190. return newImage;
  77191. }
  77192. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77193. {
  77194. if (image == 0 || newFormat == image->format)
  77195. return *this;
  77196. const int w = image->width, h = image->height;
  77197. Image newImage (newFormat, w, h, false, image->getType());
  77198. if (newFormat == SingleChannel)
  77199. {
  77200. if (! hasAlphaChannel())
  77201. {
  77202. newImage.clear (getBounds(), Colours::black);
  77203. }
  77204. else
  77205. {
  77206. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  77207. const BitmapData srcData (*this, 0, 0, w, h);
  77208. for (int y = 0; y < h; ++y)
  77209. {
  77210. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77211. uint8* dst = destData.getLinePointer (y);
  77212. for (int x = w; --x >= 0;)
  77213. {
  77214. *dst++ = src->getAlpha();
  77215. ++src;
  77216. }
  77217. }
  77218. }
  77219. }
  77220. else
  77221. {
  77222. if (hasAlphaChannel())
  77223. newImage.clear (getBounds());
  77224. Graphics g (newImage);
  77225. g.drawImageAt (*this, 0, 0);
  77226. }
  77227. return newImage;
  77228. }
  77229. NamedValueSet* Image::getProperties() const
  77230. {
  77231. return image == 0 ? 0 : &(image->userData);
  77232. }
  77233. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, BitmapData::ReadWriteMode mode)
  77234. : width (w),
  77235. height (h)
  77236. {
  77237. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  77238. jassert (image.image != 0);
  77239. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77240. image.image->initialiseBitmapData (*this, x, y, mode);
  77241. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77242. }
  77243. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77244. : width (w),
  77245. height (h)
  77246. {
  77247. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  77248. jassert (image.image != 0);
  77249. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77250. image.image->initialiseBitmapData (*this, x, y, readOnly);
  77251. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77252. }
  77253. Image::BitmapData::BitmapData (const Image& image, BitmapData::ReadWriteMode mode)
  77254. : width (image.getWidth()),
  77255. height (image.getHeight())
  77256. {
  77257. // The BitmapData class must be given a valid image!
  77258. jassert (image.image != 0);
  77259. image.image->initialiseBitmapData (*this, 0, 0, mode);
  77260. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77261. }
  77262. Image::BitmapData::~BitmapData()
  77263. {
  77264. }
  77265. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77266. {
  77267. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77268. const uint8* const pixel = getPixelPointer (x, y);
  77269. switch (pixelFormat)
  77270. {
  77271. case Image::ARGB: return Colour (((const PixelARGB*) pixel)->getUnpremultipliedARGB());
  77272. case Image::RGB: return Colour (((const PixelRGB*) pixel)->getUnpremultipliedARGB());
  77273. case Image::SingleChannel: return Colour (((const PixelAlpha*) pixel)->getUnpremultipliedARGB());
  77274. default: jassertfalse; break;
  77275. }
  77276. return Colour();
  77277. }
  77278. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77279. {
  77280. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77281. uint8* const pixel = getPixelPointer (x, y);
  77282. const PixelARGB col (colour.getPixelARGB());
  77283. switch (pixelFormat)
  77284. {
  77285. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77286. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77287. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77288. default: jassertfalse; break;
  77289. }
  77290. }
  77291. void Image::setPixelData (int x, int y, int w, int h,
  77292. const uint8* const sourcePixelData, const int sourceLineStride)
  77293. {
  77294. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77295. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77296. {
  77297. const BitmapData dest (*this, x, y, w, h, BitmapData::writeOnly);
  77298. for (int i = 0; i < h; ++i)
  77299. {
  77300. memcpy (dest.getLinePointer(i),
  77301. sourcePixelData + sourceLineStride * i,
  77302. w * dest.pixelStride);
  77303. }
  77304. }
  77305. }
  77306. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77307. {
  77308. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77309. if (! clipped.isEmpty())
  77310. {
  77311. const PixelARGB col (colourToClearTo.getPixelARGB());
  77312. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), BitmapData::writeOnly);
  77313. uint8* dest = destData.data;
  77314. int dh = clipped.getHeight();
  77315. while (--dh >= 0)
  77316. {
  77317. uint8* line = dest;
  77318. dest += destData.lineStride;
  77319. if (isARGB())
  77320. {
  77321. for (int x = clipped.getWidth(); --x >= 0;)
  77322. {
  77323. ((PixelARGB*) line)->set (col);
  77324. line += destData.pixelStride;
  77325. }
  77326. }
  77327. else if (isRGB())
  77328. {
  77329. for (int x = clipped.getWidth(); --x >= 0;)
  77330. {
  77331. ((PixelRGB*) line)->set (col);
  77332. line += destData.pixelStride;
  77333. }
  77334. }
  77335. else
  77336. {
  77337. for (int x = clipped.getWidth(); --x >= 0;)
  77338. {
  77339. *line = col.getAlpha();
  77340. line += destData.pixelStride;
  77341. }
  77342. }
  77343. }
  77344. }
  77345. }
  77346. const Colour Image::getPixelAt (const int x, const int y) const
  77347. {
  77348. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77349. {
  77350. const BitmapData srcData (*this, x, y, 1, 1);
  77351. return srcData.getPixelColour (0, 0);
  77352. }
  77353. return Colour();
  77354. }
  77355. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77356. {
  77357. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77358. {
  77359. const BitmapData destData (*this, x, y, 1, 1, BitmapData::writeOnly);
  77360. destData.setPixelColour (0, 0, colour);
  77361. }
  77362. }
  77363. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77364. {
  77365. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77366. && hasAlphaChannel())
  77367. {
  77368. const BitmapData destData (*this, x, y, 1, 1, BitmapData::readWrite);
  77369. if (isARGB())
  77370. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77371. else
  77372. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77373. }
  77374. }
  77375. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77376. {
  77377. if (hasAlphaChannel())
  77378. {
  77379. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  77380. if (isARGB())
  77381. {
  77382. for (int y = 0; y < destData.height; ++y)
  77383. {
  77384. uint8* p = destData.getLinePointer (y);
  77385. for (int x = 0; x < destData.width; ++x)
  77386. {
  77387. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77388. p += destData.pixelStride;
  77389. }
  77390. }
  77391. }
  77392. else
  77393. {
  77394. for (int y = 0; y < destData.height; ++y)
  77395. {
  77396. uint8* p = destData.getLinePointer (y);
  77397. for (int x = 0; x < destData.width; ++x)
  77398. {
  77399. *p = (uint8) (*p * amountToMultiplyBy);
  77400. p += destData.pixelStride;
  77401. }
  77402. }
  77403. }
  77404. }
  77405. else
  77406. {
  77407. jassertfalse; // can't do this without an alpha-channel!
  77408. }
  77409. }
  77410. void Image::desaturate()
  77411. {
  77412. if (isARGB() || isRGB())
  77413. {
  77414. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  77415. if (isARGB())
  77416. {
  77417. for (int y = 0; y < destData.height; ++y)
  77418. {
  77419. uint8* p = destData.getLinePointer (y);
  77420. for (int x = 0; x < destData.width; ++x)
  77421. {
  77422. ((PixelARGB*) p)->desaturate();
  77423. p += destData.pixelStride;
  77424. }
  77425. }
  77426. }
  77427. else
  77428. {
  77429. for (int y = 0; y < destData.height; ++y)
  77430. {
  77431. uint8* p = destData.getLinePointer (y);
  77432. for (int x = 0; x < destData.width; ++x)
  77433. {
  77434. ((PixelRGB*) p)->desaturate();
  77435. p += destData.pixelStride;
  77436. }
  77437. }
  77438. }
  77439. }
  77440. }
  77441. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77442. {
  77443. if (hasAlphaChannel())
  77444. {
  77445. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77446. SparseSet<int> pixelsOnRow;
  77447. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77448. for (int y = 0; y < srcData.height; ++y)
  77449. {
  77450. pixelsOnRow.clear();
  77451. const uint8* lineData = srcData.getLinePointer (y);
  77452. if (isARGB())
  77453. {
  77454. for (int x = 0; x < srcData.width; ++x)
  77455. {
  77456. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77457. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77458. lineData += srcData.pixelStride;
  77459. }
  77460. }
  77461. else
  77462. {
  77463. for (int x = 0; x < srcData.width; ++x)
  77464. {
  77465. if (*lineData >= threshold)
  77466. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77467. lineData += srcData.pixelStride;
  77468. }
  77469. }
  77470. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77471. {
  77472. const Range<int> range (pixelsOnRow.getRange (i));
  77473. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77474. }
  77475. result.consolidate();
  77476. }
  77477. }
  77478. else
  77479. {
  77480. result.add (0, 0, getWidth(), getHeight());
  77481. }
  77482. }
  77483. void Image::moveImageSection (int dx, int dy,
  77484. int sx, int sy,
  77485. int w, int h)
  77486. {
  77487. if (dx < 0)
  77488. {
  77489. w += dx;
  77490. sx -= dx;
  77491. dx = 0;
  77492. }
  77493. if (dy < 0)
  77494. {
  77495. h += dy;
  77496. sy -= dy;
  77497. dy = 0;
  77498. }
  77499. if (sx < 0)
  77500. {
  77501. w += sx;
  77502. dx -= sx;
  77503. sx = 0;
  77504. }
  77505. if (sy < 0)
  77506. {
  77507. h += sy;
  77508. dy -= sy;
  77509. sy = 0;
  77510. }
  77511. const int minX = jmin (dx, sx);
  77512. const int minY = jmin (dy, sy);
  77513. w = jmin (w, getWidth() - jmax (sx, dx));
  77514. h = jmin (h, getHeight() - jmax (sy, dy));
  77515. if (w > 0 && h > 0)
  77516. {
  77517. const int maxX = jmax (dx, sx) + w;
  77518. const int maxY = jmax (dy, sy) + h;
  77519. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, BitmapData::readWrite);
  77520. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77521. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77522. const int lineSize = destData.pixelStride * w;
  77523. if (dy > sy)
  77524. {
  77525. while (--h >= 0)
  77526. {
  77527. const int offset = h * destData.lineStride;
  77528. memmove (dst + offset, src + offset, lineSize);
  77529. }
  77530. }
  77531. else if (dst != src)
  77532. {
  77533. while (--h >= 0)
  77534. {
  77535. memmove (dst, src, lineSize);
  77536. dst += destData.lineStride;
  77537. src += destData.lineStride;
  77538. }
  77539. }
  77540. }
  77541. }
  77542. END_JUCE_NAMESPACE
  77543. /*** End of inlined file: juce_Image.cpp ***/
  77544. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77545. BEGIN_JUCE_NAMESPACE
  77546. class ImageCache::Pimpl : public Timer,
  77547. public DeletedAtShutdown
  77548. {
  77549. public:
  77550. Pimpl()
  77551. : cacheTimeout (5000)
  77552. {
  77553. }
  77554. ~Pimpl()
  77555. {
  77556. clearSingletonInstance();
  77557. }
  77558. const Image getFromHashCode (const int64 hashCode)
  77559. {
  77560. const ScopedLock sl (lock);
  77561. for (int i = images.size(); --i >= 0;)
  77562. {
  77563. Item* const item = images.getUnchecked(i);
  77564. if (item->hashCode == hashCode)
  77565. return item->image;
  77566. }
  77567. return Image::null;
  77568. }
  77569. void addImageToCache (const Image& image, const int64 hashCode)
  77570. {
  77571. if (image.isValid())
  77572. {
  77573. if (! isTimerRunning())
  77574. startTimer (2000);
  77575. Item* const item = new Item();
  77576. item->hashCode = hashCode;
  77577. item->image = image;
  77578. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77579. const ScopedLock sl (lock);
  77580. images.add (item);
  77581. }
  77582. }
  77583. void timerCallback()
  77584. {
  77585. const uint32 now = Time::getApproximateMillisecondCounter();
  77586. const ScopedLock sl (lock);
  77587. for (int i = images.size(); --i >= 0;)
  77588. {
  77589. Item* const item = images.getUnchecked(i);
  77590. if (item->image.getReferenceCount() <= 1)
  77591. {
  77592. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77593. images.remove (i);
  77594. }
  77595. else
  77596. {
  77597. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77598. }
  77599. }
  77600. if (images.size() == 0)
  77601. stopTimer();
  77602. }
  77603. struct Item
  77604. {
  77605. Image image;
  77606. int64 hashCode;
  77607. uint32 lastUseTime;
  77608. };
  77609. int cacheTimeout;
  77610. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77611. private:
  77612. OwnedArray<Item> images;
  77613. CriticalSection lock;
  77614. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77615. };
  77616. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77617. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77618. {
  77619. if (Pimpl::getInstanceWithoutCreating() != 0)
  77620. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77621. return Image::null;
  77622. }
  77623. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77624. {
  77625. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77626. }
  77627. const Image ImageCache::getFromFile (const File& file)
  77628. {
  77629. const int64 hashCode = file.hashCode64();
  77630. Image image (getFromHashCode (hashCode));
  77631. if (image.isNull())
  77632. {
  77633. image = ImageFileFormat::loadFrom (file);
  77634. addImageToCache (image, hashCode);
  77635. }
  77636. return image;
  77637. }
  77638. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77639. {
  77640. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77641. Image image (getFromHashCode (hashCode));
  77642. if (image.isNull())
  77643. {
  77644. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77645. addImageToCache (image, hashCode);
  77646. }
  77647. return image;
  77648. }
  77649. void ImageCache::setCacheTimeout (const int millisecs)
  77650. {
  77651. Pimpl::getInstance()->cacheTimeout = millisecs;
  77652. }
  77653. END_JUCE_NAMESPACE
  77654. /*** End of inlined file: juce_ImageCache.cpp ***/
  77655. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77656. BEGIN_JUCE_NAMESPACE
  77657. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77658. : values (size_ * size_),
  77659. size (size_)
  77660. {
  77661. clear();
  77662. }
  77663. ImageConvolutionKernel::~ImageConvolutionKernel()
  77664. {
  77665. }
  77666. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77667. {
  77668. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77669. return values [x + y * size];
  77670. jassertfalse;
  77671. return 0;
  77672. }
  77673. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77674. {
  77675. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77676. {
  77677. values [x + y * size] = value;
  77678. }
  77679. else
  77680. {
  77681. jassertfalse;
  77682. }
  77683. }
  77684. void ImageConvolutionKernel::clear()
  77685. {
  77686. for (int i = size * size; --i >= 0;)
  77687. values[i] = 0;
  77688. }
  77689. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77690. {
  77691. double currentTotal = 0.0;
  77692. for (int i = size * size; --i >= 0;)
  77693. currentTotal += values[i];
  77694. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77695. }
  77696. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77697. {
  77698. for (int i = size * size; --i >= 0;)
  77699. values[i] *= multiplier;
  77700. }
  77701. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77702. {
  77703. const double radiusFactor = -1.0 / (radius * radius * 2);
  77704. const int centre = size >> 1;
  77705. for (int y = size; --y >= 0;)
  77706. {
  77707. for (int x = size; --x >= 0;)
  77708. {
  77709. const int cx = x - centre;
  77710. const int cy = y - centre;
  77711. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77712. }
  77713. }
  77714. setOverallSum (1.0f);
  77715. }
  77716. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77717. const Image& sourceImage,
  77718. const Rectangle<int>& destinationArea) const
  77719. {
  77720. if (sourceImage == destImage)
  77721. {
  77722. destImage.duplicateIfShared();
  77723. }
  77724. else
  77725. {
  77726. if (sourceImage.getWidth() != destImage.getWidth()
  77727. || sourceImage.getHeight() != destImage.getHeight()
  77728. || sourceImage.getFormat() != destImage.getFormat())
  77729. {
  77730. jassertfalse;
  77731. return;
  77732. }
  77733. }
  77734. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77735. if (area.isEmpty())
  77736. return;
  77737. const int right = area.getRight();
  77738. const int bottom = area.getBottom();
  77739. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(),
  77740. Image::BitmapData::writeOnly);
  77741. uint8* line = destData.data;
  77742. const Image::BitmapData srcData (sourceImage, Image::BitmapData::readOnly);
  77743. if (destData.pixelStride == 4)
  77744. {
  77745. for (int y = area.getY(); y < bottom; ++y)
  77746. {
  77747. uint8* dest = line;
  77748. line += destData.lineStride;
  77749. for (int x = area.getX(); x < right; ++x)
  77750. {
  77751. float c1 = 0;
  77752. float c2 = 0;
  77753. float c3 = 0;
  77754. float c4 = 0;
  77755. for (int yy = 0; yy < size; ++yy)
  77756. {
  77757. const int sy = y + yy - (size >> 1);
  77758. if (sy >= srcData.height)
  77759. break;
  77760. if (sy >= 0)
  77761. {
  77762. int sx = x - (size >> 1);
  77763. const uint8* src = srcData.getPixelPointer (sx, sy);
  77764. for (int xx = 0; xx < size; ++xx)
  77765. {
  77766. if (sx >= srcData.width)
  77767. break;
  77768. if (sx >= 0)
  77769. {
  77770. const float kernelMult = values [xx + yy * size];
  77771. c1 += kernelMult * *src++;
  77772. c2 += kernelMult * *src++;
  77773. c3 += kernelMult * *src++;
  77774. c4 += kernelMult * *src++;
  77775. }
  77776. else
  77777. {
  77778. src += 4;
  77779. }
  77780. ++sx;
  77781. }
  77782. }
  77783. }
  77784. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77785. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77786. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77787. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77788. }
  77789. }
  77790. }
  77791. else if (destData.pixelStride == 3)
  77792. {
  77793. for (int y = area.getY(); y < bottom; ++y)
  77794. {
  77795. uint8* dest = line;
  77796. line += destData.lineStride;
  77797. for (int x = area.getX(); x < right; ++x)
  77798. {
  77799. float c1 = 0;
  77800. float c2 = 0;
  77801. float c3 = 0;
  77802. for (int yy = 0; yy < size; ++yy)
  77803. {
  77804. const int sy = y + yy - (size >> 1);
  77805. if (sy >= srcData.height)
  77806. break;
  77807. if (sy >= 0)
  77808. {
  77809. int sx = x - (size >> 1);
  77810. const uint8* src = srcData.getPixelPointer (sx, sy);
  77811. for (int xx = 0; xx < size; ++xx)
  77812. {
  77813. if (sx >= srcData.width)
  77814. break;
  77815. if (sx >= 0)
  77816. {
  77817. const float kernelMult = values [xx + yy * size];
  77818. c1 += kernelMult * *src++;
  77819. c2 += kernelMult * *src++;
  77820. c3 += kernelMult * *src++;
  77821. }
  77822. else
  77823. {
  77824. src += 3;
  77825. }
  77826. ++sx;
  77827. }
  77828. }
  77829. }
  77830. *dest++ = (uint8) roundToInt (c1);
  77831. *dest++ = (uint8) roundToInt (c2);
  77832. *dest++ = (uint8) roundToInt (c3);
  77833. }
  77834. }
  77835. }
  77836. }
  77837. END_JUCE_NAMESPACE
  77838. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77839. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77840. BEGIN_JUCE_NAMESPACE
  77841. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77842. {
  77843. static PNGImageFormat png;
  77844. static JPEGImageFormat jpg;
  77845. static GIFImageFormat gif;
  77846. ImageFileFormat* formats[4];
  77847. int numFormats = 0;
  77848. formats [numFormats++] = &png;
  77849. formats [numFormats++] = &jpg;
  77850. formats [numFormats++] = &gif;
  77851. const int64 streamPos = input.getPosition();
  77852. for (int i = 0; i < numFormats; ++i)
  77853. {
  77854. const bool found = formats[i]->canUnderstand (input);
  77855. input.setPosition (streamPos);
  77856. if (found)
  77857. return formats[i];
  77858. }
  77859. return 0;
  77860. }
  77861. const Image ImageFileFormat::loadFrom (InputStream& input)
  77862. {
  77863. ImageFileFormat* const format = findImageFormatForStream (input);
  77864. if (format != 0)
  77865. return format->decodeImage (input);
  77866. return Image::null;
  77867. }
  77868. const Image ImageFileFormat::loadFrom (const File& file)
  77869. {
  77870. InputStream* const in = file.createInputStream();
  77871. if (in != 0)
  77872. {
  77873. BufferedInputStream b (in, 8192, true);
  77874. return loadFrom (b);
  77875. }
  77876. return Image::null;
  77877. }
  77878. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77879. {
  77880. if (rawData != 0 && numBytes > 4)
  77881. {
  77882. MemoryInputStream stream (rawData, numBytes, false);
  77883. return loadFrom (stream);
  77884. }
  77885. return Image::null;
  77886. }
  77887. END_JUCE_NAMESPACE
  77888. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77889. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77890. BEGIN_JUCE_NAMESPACE
  77891. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77892. const Image juce_loadWithCoreImage (InputStream& input);
  77893. #else
  77894. class GIFLoader
  77895. {
  77896. public:
  77897. GIFLoader (InputStream& in)
  77898. : input (in),
  77899. dataBlockIsZero (false),
  77900. fresh (false),
  77901. finished (false)
  77902. {
  77903. currentBit = lastBit = lastByteIndex = 0;
  77904. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77905. firstcode = oldcode = 0;
  77906. clearCode = end_code = 0;
  77907. int imageWidth, imageHeight;
  77908. int transparent = -1;
  77909. if (! getSizeFromHeader (imageWidth, imageHeight))
  77910. return;
  77911. if ((imageWidth <= 0) || (imageHeight <= 0))
  77912. return;
  77913. unsigned char buf [16];
  77914. if (in.read (buf, 3) != 3)
  77915. return;
  77916. int numColours = 2 << (buf[0] & 7);
  77917. if ((buf[0] & 0x80) != 0)
  77918. readPalette (numColours);
  77919. for (;;)
  77920. {
  77921. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77922. break;
  77923. if (buf[0] == '!')
  77924. {
  77925. if (input.read (buf, 1) != 1)
  77926. break;
  77927. if (processExtension (buf[0], transparent) < 0)
  77928. break;
  77929. continue;
  77930. }
  77931. if (buf[0] != ',')
  77932. continue;
  77933. if (input.read (buf, 9) != 9)
  77934. break;
  77935. imageWidth = makeWord (buf[4], buf[5]);
  77936. imageHeight = makeWord (buf[6], buf[7]);
  77937. numColours = 2 << (buf[8] & 7);
  77938. if ((buf[8] & 0x80) != 0)
  77939. if (! readPalette (numColours))
  77940. break;
  77941. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77942. imageWidth, imageHeight, (transparent >= 0));
  77943. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77944. readImage ((buf[8] & 0x40) != 0, transparent);
  77945. break;
  77946. }
  77947. }
  77948. ~GIFLoader() {}
  77949. Image image;
  77950. private:
  77951. InputStream& input;
  77952. uint8 buffer [300];
  77953. uint8 palette [256][4];
  77954. bool dataBlockIsZero, fresh, finished;
  77955. int currentBit, lastBit, lastByteIndex;
  77956. int codeSize, setCodeSize;
  77957. int maxCode, maxCodeSize;
  77958. int firstcode, oldcode;
  77959. int clearCode, end_code;
  77960. enum { maxGifCode = 1 << 12 };
  77961. int table [2] [maxGifCode];
  77962. int stack [2 * maxGifCode];
  77963. int *sp;
  77964. bool getSizeFromHeader (int& w, int& h)
  77965. {
  77966. char b[8];
  77967. if (input.read (b, 6) == 6)
  77968. {
  77969. if ((strncmp ("GIF87a", b, 6) == 0)
  77970. || (strncmp ("GIF89a", b, 6) == 0))
  77971. {
  77972. if (input.read (b, 4) == 4)
  77973. {
  77974. w = makeWord (b[0], b[1]);
  77975. h = makeWord (b[2], b[3]);
  77976. return true;
  77977. }
  77978. }
  77979. }
  77980. return false;
  77981. }
  77982. bool readPalette (const int numCols)
  77983. {
  77984. unsigned char rgb[4];
  77985. for (int i = 0; i < numCols; ++i)
  77986. {
  77987. input.read (rgb, 3);
  77988. palette [i][0] = rgb[0];
  77989. palette [i][1] = rgb[1];
  77990. palette [i][2] = rgb[2];
  77991. palette [i][3] = 0xff;
  77992. }
  77993. return true;
  77994. }
  77995. int readDataBlock (unsigned char* dest)
  77996. {
  77997. unsigned char n;
  77998. if (input.read (&n, 1) == 1)
  77999. {
  78000. dataBlockIsZero = (n == 0);
  78001. if (dataBlockIsZero || (input.read (dest, n) == n))
  78002. return n;
  78003. }
  78004. return -1;
  78005. }
  78006. int processExtension (const int type, int& transparent)
  78007. {
  78008. unsigned char b [300];
  78009. int n = 0;
  78010. if (type == 0xf9)
  78011. {
  78012. n = readDataBlock (b);
  78013. if (n < 0)
  78014. return 1;
  78015. if ((b[0] & 0x1) != 0)
  78016. transparent = b[3];
  78017. }
  78018. do
  78019. {
  78020. n = readDataBlock (b);
  78021. }
  78022. while (n > 0);
  78023. return n;
  78024. }
  78025. int readLZWByte (const bool initialise, const int inputCodeSize)
  78026. {
  78027. int code, incode, i;
  78028. if (initialise)
  78029. {
  78030. setCodeSize = inputCodeSize;
  78031. codeSize = setCodeSize + 1;
  78032. clearCode = 1 << setCodeSize;
  78033. end_code = clearCode + 1;
  78034. maxCodeSize = 2 * clearCode;
  78035. maxCode = clearCode + 2;
  78036. getCode (0, true);
  78037. fresh = true;
  78038. for (i = 0; i < clearCode; ++i)
  78039. {
  78040. table[0][i] = 0;
  78041. table[1][i] = i;
  78042. }
  78043. for (; i < maxGifCode; ++i)
  78044. {
  78045. table[0][i] = 0;
  78046. table[1][i] = 0;
  78047. }
  78048. sp = stack;
  78049. return 0;
  78050. }
  78051. else if (fresh)
  78052. {
  78053. fresh = false;
  78054. do
  78055. {
  78056. firstcode = oldcode
  78057. = getCode (codeSize, false);
  78058. }
  78059. while (firstcode == clearCode);
  78060. return firstcode;
  78061. }
  78062. if (sp > stack)
  78063. return *--sp;
  78064. while ((code = getCode (codeSize, false)) >= 0)
  78065. {
  78066. if (code == clearCode)
  78067. {
  78068. for (i = 0; i < clearCode; ++i)
  78069. {
  78070. table[0][i] = 0;
  78071. table[1][i] = i;
  78072. }
  78073. for (; i < maxGifCode; ++i)
  78074. {
  78075. table[0][i] = 0;
  78076. table[1][i] = 0;
  78077. }
  78078. codeSize = setCodeSize + 1;
  78079. maxCodeSize = 2 * clearCode;
  78080. maxCode = clearCode + 2;
  78081. sp = stack;
  78082. firstcode = oldcode = getCode (codeSize, false);
  78083. return firstcode;
  78084. }
  78085. else if (code == end_code)
  78086. {
  78087. if (dataBlockIsZero)
  78088. return -2;
  78089. unsigned char buf [260];
  78090. int n;
  78091. while ((n = readDataBlock (buf)) > 0)
  78092. {}
  78093. if (n != 0)
  78094. return -2;
  78095. }
  78096. incode = code;
  78097. if (code >= maxCode)
  78098. {
  78099. *sp++ = firstcode;
  78100. code = oldcode;
  78101. }
  78102. while (code >= clearCode)
  78103. {
  78104. *sp++ = table[1][code];
  78105. if (code == table[0][code])
  78106. return -2;
  78107. code = table[0][code];
  78108. }
  78109. *sp++ = firstcode = table[1][code];
  78110. if ((code = maxCode) < maxGifCode)
  78111. {
  78112. table[0][code] = oldcode;
  78113. table[1][code] = firstcode;
  78114. ++maxCode;
  78115. if ((maxCode >= maxCodeSize)
  78116. && (maxCodeSize < maxGifCode))
  78117. {
  78118. maxCodeSize <<= 1;
  78119. ++codeSize;
  78120. }
  78121. }
  78122. oldcode = incode;
  78123. if (sp > stack)
  78124. return *--sp;
  78125. }
  78126. return code;
  78127. }
  78128. int getCode (const int codeSize_, const bool initialise)
  78129. {
  78130. if (initialise)
  78131. {
  78132. currentBit = 0;
  78133. lastBit = 0;
  78134. finished = false;
  78135. return 0;
  78136. }
  78137. if ((currentBit + codeSize_) >= lastBit)
  78138. {
  78139. if (finished)
  78140. return -1;
  78141. buffer[0] = buffer [lastByteIndex - 2];
  78142. buffer[1] = buffer [lastByteIndex - 1];
  78143. const int n = readDataBlock (&buffer[2]);
  78144. if (n == 0)
  78145. finished = true;
  78146. lastByteIndex = 2 + n;
  78147. currentBit = (currentBit - lastBit) + 16;
  78148. lastBit = (2 + n) * 8 ;
  78149. }
  78150. int result = 0;
  78151. int i = currentBit;
  78152. for (int j = 0; j < codeSize_; ++j)
  78153. {
  78154. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78155. ++i;
  78156. }
  78157. currentBit += codeSize_;
  78158. return result;
  78159. }
  78160. bool readImage (const int interlace, const int transparent)
  78161. {
  78162. unsigned char c;
  78163. if (input.read (&c, 1) != 1
  78164. || readLZWByte (true, c) < 0)
  78165. return false;
  78166. if (transparent >= 0)
  78167. {
  78168. palette [transparent][0] = 0;
  78169. palette [transparent][1] = 0;
  78170. palette [transparent][2] = 0;
  78171. palette [transparent][3] = 0;
  78172. }
  78173. int index;
  78174. int xpos = 0, ypos = 0, pass = 0;
  78175. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  78176. uint8* p = destData.data;
  78177. const bool hasAlpha = image.hasAlphaChannel();
  78178. while ((index = readLZWByte (false, c)) >= 0)
  78179. {
  78180. const uint8* const paletteEntry = palette [index];
  78181. if (hasAlpha)
  78182. {
  78183. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78184. paletteEntry[0],
  78185. paletteEntry[1],
  78186. paletteEntry[2]);
  78187. ((PixelARGB*) p)->premultiply();
  78188. }
  78189. else
  78190. {
  78191. ((PixelRGB*) p)->setARGB (0,
  78192. paletteEntry[0],
  78193. paletteEntry[1],
  78194. paletteEntry[2]);
  78195. }
  78196. p += destData.pixelStride;
  78197. ++xpos;
  78198. if (xpos == destData.width)
  78199. {
  78200. xpos = 0;
  78201. if (interlace)
  78202. {
  78203. switch (pass)
  78204. {
  78205. case 0:
  78206. case 1: ypos += 8; break;
  78207. case 2: ypos += 4; break;
  78208. case 3: ypos += 2; break;
  78209. }
  78210. while (ypos >= destData.height)
  78211. {
  78212. ++pass;
  78213. switch (pass)
  78214. {
  78215. case 1: ypos = 4; break;
  78216. case 2: ypos = 2; break;
  78217. case 3: ypos = 1; break;
  78218. default: return true;
  78219. }
  78220. }
  78221. }
  78222. else
  78223. {
  78224. ++ypos;
  78225. }
  78226. p = destData.getPixelPointer (xpos, ypos);
  78227. }
  78228. if (ypos >= destData.height)
  78229. break;
  78230. }
  78231. return true;
  78232. }
  78233. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78234. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  78235. };
  78236. #endif
  78237. GIFImageFormat::GIFImageFormat() {}
  78238. GIFImageFormat::~GIFImageFormat() {}
  78239. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78240. bool GIFImageFormat::canUnderstand (InputStream& in)
  78241. {
  78242. char header [4];
  78243. return (in.read (header, sizeof (header)) == sizeof (header))
  78244. && header[0] == 'G'
  78245. && header[1] == 'I'
  78246. && header[2] == 'F';
  78247. }
  78248. const Image GIFImageFormat::decodeImage (InputStream& in)
  78249. {
  78250. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78251. return juce_loadWithCoreImage (in);
  78252. #else
  78253. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78254. return loader->image;
  78255. #endif
  78256. }
  78257. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78258. {
  78259. jassertfalse; // writing isn't implemented for GIFs!
  78260. return false;
  78261. }
  78262. END_JUCE_NAMESPACE
  78263. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78264. #endif
  78265. //==============================================================================
  78266. // some files include lots of library code, so leave them to the end to avoid cluttering
  78267. // up the build for the clean files.
  78268. #if JUCE_BUILD_CORE
  78269. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78270. namespace zlibNamespace
  78271. {
  78272. #if JUCE_INCLUDE_ZLIB_CODE
  78273. #undef OS_CODE
  78274. #undef fdopen
  78275. /*** Start of inlined file: zlib.h ***/
  78276. #ifndef ZLIB_H
  78277. #define ZLIB_H
  78278. /*** Start of inlined file: zconf.h ***/
  78279. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78280. #ifndef ZCONF_H
  78281. #define ZCONF_H
  78282. // *** Just a few hacks here to make it compile nicely with Juce..
  78283. #define Z_PREFIX 1
  78284. #undef __MACTYPES__
  78285. #ifdef _MSC_VER
  78286. #pragma warning (disable : 4131 4127 4244 4267)
  78287. #endif
  78288. /*
  78289. * If you *really* need a unique prefix for all types and library functions,
  78290. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78291. */
  78292. #ifdef Z_PREFIX
  78293. # define deflateInit_ z_deflateInit_
  78294. # define deflate z_deflate
  78295. # define deflateEnd z_deflateEnd
  78296. # define inflateInit_ z_inflateInit_
  78297. # define inflate z_inflate
  78298. # define inflateEnd z_inflateEnd
  78299. # define inflatePrime z_inflatePrime
  78300. # define inflateGetHeader z_inflateGetHeader
  78301. # define adler32_combine z_adler32_combine
  78302. # define crc32_combine z_crc32_combine
  78303. # define deflateInit2_ z_deflateInit2_
  78304. # define deflateSetDictionary z_deflateSetDictionary
  78305. # define deflateCopy z_deflateCopy
  78306. # define deflateReset z_deflateReset
  78307. # define deflateParams z_deflateParams
  78308. # define deflateBound z_deflateBound
  78309. # define deflatePrime z_deflatePrime
  78310. # define inflateInit2_ z_inflateInit2_
  78311. # define inflateSetDictionary z_inflateSetDictionary
  78312. # define inflateSync z_inflateSync
  78313. # define inflateSyncPoint z_inflateSyncPoint
  78314. # define inflateCopy z_inflateCopy
  78315. # define inflateReset z_inflateReset
  78316. # define inflateBack z_inflateBack
  78317. # define inflateBackEnd z_inflateBackEnd
  78318. # define compress z_compress
  78319. # define compress2 z_compress2
  78320. # define compressBound z_compressBound
  78321. # define uncompress z_uncompress
  78322. # define adler32 z_adler32
  78323. # define crc32 z_crc32
  78324. # define get_crc_table z_get_crc_table
  78325. # define zError z_zError
  78326. # define alloc_func z_alloc_func
  78327. # define free_func z_free_func
  78328. # define in_func z_in_func
  78329. # define out_func z_out_func
  78330. # define Byte z_Byte
  78331. # define uInt z_uInt
  78332. # define uLong z_uLong
  78333. # define Bytef z_Bytef
  78334. # define charf z_charf
  78335. # define intf z_intf
  78336. # define uIntf z_uIntf
  78337. # define uLongf z_uLongf
  78338. # define voidpf z_voidpf
  78339. # define voidp z_voidp
  78340. #endif
  78341. #if defined(__MSDOS__) && !defined(MSDOS)
  78342. # define MSDOS
  78343. #endif
  78344. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78345. # define OS2
  78346. #endif
  78347. #if defined(_WINDOWS) && !defined(WINDOWS)
  78348. # define WINDOWS
  78349. #endif
  78350. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78351. # ifndef WIN32
  78352. # define WIN32
  78353. # endif
  78354. #endif
  78355. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78356. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78357. # ifndef SYS16BIT
  78358. # define SYS16BIT
  78359. # endif
  78360. # endif
  78361. #endif
  78362. /*
  78363. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78364. * than 64k bytes at a time (needed on systems with 16-bit int).
  78365. */
  78366. #ifdef SYS16BIT
  78367. # define MAXSEG_64K
  78368. #endif
  78369. #ifdef MSDOS
  78370. # define UNALIGNED_OK
  78371. #endif
  78372. #ifdef __STDC_VERSION__
  78373. # ifndef STDC
  78374. # define STDC
  78375. # endif
  78376. # if __STDC_VERSION__ >= 199901L
  78377. # ifndef STDC99
  78378. # define STDC99
  78379. # endif
  78380. # endif
  78381. #endif
  78382. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78383. # define STDC
  78384. #endif
  78385. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78386. # define STDC
  78387. #endif
  78388. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78389. # define STDC
  78390. #endif
  78391. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78392. # define STDC
  78393. #endif
  78394. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78395. # define STDC
  78396. #endif
  78397. #ifndef STDC
  78398. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78399. # define const /* note: need a more gentle solution here */
  78400. # endif
  78401. #endif
  78402. /* Some Mac compilers merge all .h files incorrectly: */
  78403. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78404. # define NO_DUMMY_DECL
  78405. #endif
  78406. /* Maximum value for memLevel in deflateInit2 */
  78407. #ifndef MAX_MEM_LEVEL
  78408. # ifdef MAXSEG_64K
  78409. # define MAX_MEM_LEVEL 8
  78410. # else
  78411. # define MAX_MEM_LEVEL 9
  78412. # endif
  78413. #endif
  78414. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78415. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78416. * created by gzip. (Files created by minigzip can still be extracted by
  78417. * gzip.)
  78418. */
  78419. #ifndef MAX_WBITS
  78420. # define MAX_WBITS 15 /* 32K LZ77 window */
  78421. #endif
  78422. /* The memory requirements for deflate are (in bytes):
  78423. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78424. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78425. plus a few kilobytes for small objects. For example, if you want to reduce
  78426. the default memory requirements from 256K to 128K, compile with
  78427. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78428. Of course this will generally degrade compression (there's no free lunch).
  78429. The memory requirements for inflate are (in bytes) 1 << windowBits
  78430. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78431. for small objects.
  78432. */
  78433. /* Type declarations */
  78434. #ifndef OF /* function prototypes */
  78435. # ifdef STDC
  78436. # define OF(args) args
  78437. # else
  78438. # define OF(args) ()
  78439. # endif
  78440. #endif
  78441. /* The following definitions for FAR are needed only for MSDOS mixed
  78442. * model programming (small or medium model with some far allocations).
  78443. * This was tested only with MSC; for other MSDOS compilers you may have
  78444. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78445. * just define FAR to be empty.
  78446. */
  78447. #ifdef SYS16BIT
  78448. # if defined(M_I86SM) || defined(M_I86MM)
  78449. /* MSC small or medium model */
  78450. # define SMALL_MEDIUM
  78451. # ifdef _MSC_VER
  78452. # define FAR _far
  78453. # else
  78454. # define FAR far
  78455. # endif
  78456. # endif
  78457. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78458. /* Turbo C small or medium model */
  78459. # define SMALL_MEDIUM
  78460. # ifdef __BORLANDC__
  78461. # define FAR _far
  78462. # else
  78463. # define FAR far
  78464. # endif
  78465. # endif
  78466. #endif
  78467. #if defined(WINDOWS) || defined(WIN32)
  78468. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78469. * This is not mandatory, but it offers a little performance increase.
  78470. */
  78471. # ifdef ZLIB_DLL
  78472. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78473. # ifdef ZLIB_INTERNAL
  78474. # define ZEXTERN extern __declspec(dllexport)
  78475. # else
  78476. # define ZEXTERN extern __declspec(dllimport)
  78477. # endif
  78478. # endif
  78479. # endif /* ZLIB_DLL */
  78480. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78481. * define ZLIB_WINAPI.
  78482. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78483. */
  78484. # ifdef ZLIB_WINAPI
  78485. # ifdef FAR
  78486. # undef FAR
  78487. # endif
  78488. # include <windows.h>
  78489. /* No need for _export, use ZLIB.DEF instead. */
  78490. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78491. # define ZEXPORT WINAPI
  78492. # ifdef WIN32
  78493. # define ZEXPORTVA WINAPIV
  78494. # else
  78495. # define ZEXPORTVA FAR CDECL
  78496. # endif
  78497. # endif
  78498. #endif
  78499. #if defined (__BEOS__)
  78500. # ifdef ZLIB_DLL
  78501. # ifdef ZLIB_INTERNAL
  78502. # define ZEXPORT __declspec(dllexport)
  78503. # define ZEXPORTVA __declspec(dllexport)
  78504. # else
  78505. # define ZEXPORT __declspec(dllimport)
  78506. # define ZEXPORTVA __declspec(dllimport)
  78507. # endif
  78508. # endif
  78509. #endif
  78510. #ifndef ZEXTERN
  78511. # define ZEXTERN extern
  78512. #endif
  78513. #ifndef ZEXPORT
  78514. # define ZEXPORT
  78515. #endif
  78516. #ifndef ZEXPORTVA
  78517. # define ZEXPORTVA
  78518. #endif
  78519. #ifndef FAR
  78520. # define FAR
  78521. #endif
  78522. #if !defined(__MACTYPES__)
  78523. typedef unsigned char Byte; /* 8 bits */
  78524. #endif
  78525. typedef unsigned int uInt; /* 16 bits or more */
  78526. typedef unsigned long uLong; /* 32 bits or more */
  78527. #ifdef SMALL_MEDIUM
  78528. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78529. # define Bytef Byte FAR
  78530. #else
  78531. typedef Byte FAR Bytef;
  78532. #endif
  78533. typedef char FAR charf;
  78534. typedef int FAR intf;
  78535. typedef uInt FAR uIntf;
  78536. typedef uLong FAR uLongf;
  78537. #ifdef STDC
  78538. typedef void const *voidpc;
  78539. typedef void FAR *voidpf;
  78540. typedef void *voidp;
  78541. #else
  78542. typedef Byte const *voidpc;
  78543. typedef Byte FAR *voidpf;
  78544. typedef Byte *voidp;
  78545. #endif
  78546. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78547. # include <sys/types.h> /* for off_t */
  78548. # include <unistd.h> /* for SEEK_* and off_t */
  78549. # ifdef VMS
  78550. # include <unixio.h> /* for off_t */
  78551. # endif
  78552. # define z_off_t off_t
  78553. #endif
  78554. #ifndef SEEK_SET
  78555. # define SEEK_SET 0 /* Seek from beginning of file. */
  78556. # define SEEK_CUR 1 /* Seek from current position. */
  78557. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78558. #endif
  78559. #ifndef z_off_t
  78560. # define z_off_t long
  78561. #endif
  78562. #if defined(__OS400__)
  78563. # define NO_vsnprintf
  78564. #endif
  78565. #if defined(__MVS__)
  78566. # define NO_vsnprintf
  78567. # ifdef FAR
  78568. # undef FAR
  78569. # endif
  78570. #endif
  78571. /* MVS linker does not support external names larger than 8 bytes */
  78572. #if defined(__MVS__)
  78573. # pragma map(deflateInit_,"DEIN")
  78574. # pragma map(deflateInit2_,"DEIN2")
  78575. # pragma map(deflateEnd,"DEEND")
  78576. # pragma map(deflateBound,"DEBND")
  78577. # pragma map(inflateInit_,"ININ")
  78578. # pragma map(inflateInit2_,"ININ2")
  78579. # pragma map(inflateEnd,"INEND")
  78580. # pragma map(inflateSync,"INSY")
  78581. # pragma map(inflateSetDictionary,"INSEDI")
  78582. # pragma map(compressBound,"CMBND")
  78583. # pragma map(inflate_table,"INTABL")
  78584. # pragma map(inflate_fast,"INFA")
  78585. # pragma map(inflate_copyright,"INCOPY")
  78586. #endif
  78587. #endif /* ZCONF_H */
  78588. /*** End of inlined file: zconf.h ***/
  78589. #ifdef __cplusplus
  78590. //extern "C" {
  78591. #endif
  78592. #define ZLIB_VERSION "1.2.3"
  78593. #define ZLIB_VERNUM 0x1230
  78594. /*
  78595. The 'zlib' compression library provides in-memory compression and
  78596. decompression functions, including integrity checks of the uncompressed
  78597. data. This version of the library supports only one compression method
  78598. (deflation) but other algorithms will be added later and will have the same
  78599. stream interface.
  78600. Compression can be done in a single step if the buffers are large
  78601. enough (for example if an input file is mmap'ed), or can be done by
  78602. repeated calls of the compression function. In the latter case, the
  78603. application must provide more input and/or consume the output
  78604. (providing more output space) before each call.
  78605. The compressed data format used by default by the in-memory functions is
  78606. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78607. around a deflate stream, which is itself documented in RFC 1951.
  78608. The library also supports reading and writing files in gzip (.gz) format
  78609. with an interface similar to that of stdio using the functions that start
  78610. with "gz". The gzip format is different from the zlib format. gzip is a
  78611. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78612. This library can optionally read and write gzip streams in memory as well.
  78613. The zlib format was designed to be compact and fast for use in memory
  78614. and on communications channels. The gzip format was designed for single-
  78615. file compression on file systems, has a larger header than zlib to maintain
  78616. directory information, and uses a different, slower check method than zlib.
  78617. The library does not install any signal handler. The decoder checks
  78618. the consistency of the compressed data, so the library should never
  78619. crash even in case of corrupted input.
  78620. */
  78621. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78622. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78623. struct internal_state;
  78624. typedef struct z_stream_s {
  78625. Bytef *next_in; /* next input byte */
  78626. uInt avail_in; /* number of bytes available at next_in */
  78627. uLong total_in; /* total nb of input bytes read so far */
  78628. Bytef *next_out; /* next output byte should be put there */
  78629. uInt avail_out; /* remaining free space at next_out */
  78630. uLong total_out; /* total nb of bytes output so far */
  78631. char *msg; /* last error message, NULL if no error */
  78632. struct internal_state FAR *state; /* not visible by applications */
  78633. alloc_func zalloc; /* used to allocate the internal state */
  78634. free_func zfree; /* used to free the internal state */
  78635. voidpf opaque; /* private data object passed to zalloc and zfree */
  78636. int data_type; /* best guess about the data type: binary or text */
  78637. uLong adler; /* adler32 value of the uncompressed data */
  78638. uLong reserved; /* reserved for future use */
  78639. } z_stream;
  78640. typedef z_stream FAR *z_streamp;
  78641. /*
  78642. gzip header information passed to and from zlib routines. See RFC 1952
  78643. for more details on the meanings of these fields.
  78644. */
  78645. typedef struct gz_header_s {
  78646. int text; /* true if compressed data believed to be text */
  78647. uLong time; /* modification time */
  78648. int xflags; /* extra flags (not used when writing a gzip file) */
  78649. int os; /* operating system */
  78650. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78651. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78652. uInt extra_max; /* space at extra (only when reading header) */
  78653. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78654. uInt name_max; /* space at name (only when reading header) */
  78655. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78656. uInt comm_max; /* space at comment (only when reading header) */
  78657. int hcrc; /* true if there was or will be a header crc */
  78658. int done; /* true when done reading gzip header (not used
  78659. when writing a gzip file) */
  78660. } gz_header;
  78661. typedef gz_header FAR *gz_headerp;
  78662. /*
  78663. The application must update next_in and avail_in when avail_in has
  78664. dropped to zero. It must update next_out and avail_out when avail_out
  78665. has dropped to zero. The application must initialize zalloc, zfree and
  78666. opaque before calling the init function. All other fields are set by the
  78667. compression library and must not be updated by the application.
  78668. The opaque value provided by the application will be passed as the first
  78669. parameter for calls of zalloc and zfree. This can be useful for custom
  78670. memory management. The compression library attaches no meaning to the
  78671. opaque value.
  78672. zalloc must return Z_NULL if there is not enough memory for the object.
  78673. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78674. thread safe.
  78675. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78676. exactly 65536 bytes, but will not be required to allocate more than this
  78677. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78678. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78679. have their offset normalized to zero. The default allocation function
  78680. provided by this library ensures this (see zutil.c). To reduce memory
  78681. requirements and avoid any allocation of 64K objects, at the expense of
  78682. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78683. The fields total_in and total_out can be used for statistics or
  78684. progress reports. After compression, total_in holds the total size of
  78685. the uncompressed data and may be saved for use in the decompressor
  78686. (particularly if the decompressor wants to decompress everything in
  78687. a single step).
  78688. */
  78689. /* constants */
  78690. #define Z_NO_FLUSH 0
  78691. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78692. #define Z_SYNC_FLUSH 2
  78693. #define Z_FULL_FLUSH 3
  78694. #define Z_FINISH 4
  78695. #define Z_BLOCK 5
  78696. /* Allowed flush values; see deflate() and inflate() below for details */
  78697. #define Z_OK 0
  78698. #define Z_STREAM_END 1
  78699. #define Z_NEED_DICT 2
  78700. #define Z_ERRNO (-1)
  78701. #define Z_STREAM_ERROR (-2)
  78702. #define Z_DATA_ERROR (-3)
  78703. #define Z_MEM_ERROR (-4)
  78704. #define Z_BUF_ERROR (-5)
  78705. #define Z_VERSION_ERROR (-6)
  78706. /* Return codes for the compression/decompression functions. Negative
  78707. * values are errors, positive values are used for special but normal events.
  78708. */
  78709. #define Z_NO_COMPRESSION 0
  78710. #define Z_BEST_SPEED 1
  78711. #define Z_BEST_COMPRESSION 9
  78712. #define Z_DEFAULT_COMPRESSION (-1)
  78713. /* compression levels */
  78714. #define Z_FILTERED 1
  78715. #define Z_HUFFMAN_ONLY 2
  78716. #define Z_RLE 3
  78717. #define Z_FIXED 4
  78718. #define Z_DEFAULT_STRATEGY 0
  78719. /* compression strategy; see deflateInit2() below for details */
  78720. #define Z_BINARY 0
  78721. #define Z_TEXT 1
  78722. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78723. #define Z_UNKNOWN 2
  78724. /* Possible values of the data_type field (though see inflate()) */
  78725. #define Z_DEFLATED 8
  78726. /* The deflate compression method (the only one supported in this version) */
  78727. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78728. #define zlib_version zlibVersion()
  78729. /* for compatibility with versions < 1.0.2 */
  78730. /* basic functions */
  78731. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78732. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78733. If the first character differs, the library code actually used is
  78734. not compatible with the zlib.h header file used by the application.
  78735. This check is automatically made by deflateInit and inflateInit.
  78736. */
  78737. /*
  78738. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78739. Initializes the internal stream state for compression. The fields
  78740. zalloc, zfree and opaque must be initialized before by the caller.
  78741. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78742. use default allocation functions.
  78743. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78744. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78745. all (the input data is simply copied a block at a time).
  78746. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78747. compression (currently equivalent to level 6).
  78748. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78749. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78750. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78751. with the version assumed by the caller (ZLIB_VERSION).
  78752. msg is set to null if there is no error message. deflateInit does not
  78753. perform any compression: this will be done by deflate().
  78754. */
  78755. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78756. /*
  78757. deflate compresses as much data as possible, and stops when the input
  78758. buffer becomes empty or the output buffer becomes full. It may introduce some
  78759. output latency (reading input without producing any output) except when
  78760. forced to flush.
  78761. The detailed semantics are as follows. deflate performs one or both of the
  78762. following actions:
  78763. - Compress more input starting at next_in and update next_in and avail_in
  78764. accordingly. If not all input can be processed (because there is not
  78765. enough room in the output buffer), next_in and avail_in are updated and
  78766. processing will resume at this point for the next call of deflate().
  78767. - Provide more output starting at next_out and update next_out and avail_out
  78768. accordingly. This action is forced if the parameter flush is non zero.
  78769. Forcing flush frequently degrades the compression ratio, so this parameter
  78770. should be set only when necessary (in interactive applications).
  78771. Some output may be provided even if flush is not set.
  78772. Before the call of deflate(), the application should ensure that at least
  78773. one of the actions is possible, by providing more input and/or consuming
  78774. more output, and updating avail_in or avail_out accordingly; avail_out
  78775. should never be zero before the call. The application can consume the
  78776. compressed output when it wants, for example when the output buffer is full
  78777. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78778. and with zero avail_out, it must be called again after making room in the
  78779. output buffer because there might be more output pending.
  78780. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78781. decide how much data to accumualte before producing output, in order to
  78782. maximize compression.
  78783. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78784. flushed to the output buffer and the output is aligned on a byte boundary, so
  78785. that the decompressor can get all input data available so far. (In particular
  78786. avail_in is zero after the call if enough output space has been provided
  78787. before the call.) Flushing may degrade compression for some compression
  78788. algorithms and so it should be used only when necessary.
  78789. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78790. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78791. restart from this point if previous compressed data has been damaged or if
  78792. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78793. compression.
  78794. If deflate returns with avail_out == 0, this function must be called again
  78795. with the same value of the flush parameter and more output space (updated
  78796. avail_out), until the flush is complete (deflate returns with non-zero
  78797. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78798. avail_out is greater than six to avoid repeated flush markers due to
  78799. avail_out == 0 on return.
  78800. If the parameter flush is set to Z_FINISH, pending input is processed,
  78801. pending output is flushed and deflate returns with Z_STREAM_END if there
  78802. was enough output space; if deflate returns with Z_OK, this function must be
  78803. called again with Z_FINISH and more output space (updated avail_out) but no
  78804. more input data, until it returns with Z_STREAM_END or an error. After
  78805. deflate has returned Z_STREAM_END, the only possible operations on the
  78806. stream are deflateReset or deflateEnd.
  78807. Z_FINISH can be used immediately after deflateInit if all the compression
  78808. is to be done in a single step. In this case, avail_out must be at least
  78809. the value returned by deflateBound (see below). If deflate does not return
  78810. Z_STREAM_END, then it must be called again as described above.
  78811. deflate() sets strm->adler to the adler32 checksum of all input read
  78812. so far (that is, total_in bytes).
  78813. deflate() may update strm->data_type if it can make a good guess about
  78814. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78815. binary. This field is only for information purposes and does not affect
  78816. the compression algorithm in any manner.
  78817. deflate() returns Z_OK if some progress has been made (more input
  78818. processed or more output produced), Z_STREAM_END if all input has been
  78819. consumed and all output has been produced (only when flush is set to
  78820. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78821. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78822. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78823. fatal, and deflate() can be called again with more input and more output
  78824. space to continue compressing.
  78825. */
  78826. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78827. /*
  78828. All dynamically allocated data structures for this stream are freed.
  78829. This function discards any unprocessed input and does not flush any
  78830. pending output.
  78831. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78832. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78833. prematurely (some input or output was discarded). In the error case,
  78834. msg may be set but then points to a static string (which must not be
  78835. deallocated).
  78836. */
  78837. /*
  78838. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78839. Initializes the internal stream state for decompression. The fields
  78840. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78841. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78842. value depends on the compression method), inflateInit determines the
  78843. compression method from the zlib header and allocates all data structures
  78844. accordingly; otherwise the allocation will be deferred to the first call of
  78845. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78846. use default allocation functions.
  78847. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78848. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78849. version assumed by the caller. msg is set to null if there is no error
  78850. message. inflateInit does not perform any decompression apart from reading
  78851. the zlib header if present: this will be done by inflate(). (So next_in and
  78852. avail_in may be modified, but next_out and avail_out are unchanged.)
  78853. */
  78854. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78855. /*
  78856. inflate decompresses as much data as possible, and stops when the input
  78857. buffer becomes empty or the output buffer becomes full. It may introduce
  78858. some output latency (reading input without producing any output) except when
  78859. forced to flush.
  78860. The detailed semantics are as follows. inflate performs one or both of the
  78861. following actions:
  78862. - Decompress more input starting at next_in and update next_in and avail_in
  78863. accordingly. If not all input can be processed (because there is not
  78864. enough room in the output buffer), next_in is updated and processing
  78865. will resume at this point for the next call of inflate().
  78866. - Provide more output starting at next_out and update next_out and avail_out
  78867. accordingly. inflate() provides as much output as possible, until there
  78868. is no more input data or no more space in the output buffer (see below
  78869. about the flush parameter).
  78870. Before the call of inflate(), the application should ensure that at least
  78871. one of the actions is possible, by providing more input and/or consuming
  78872. more output, and updating the next_* and avail_* values accordingly.
  78873. The application can consume the uncompressed output when it wants, for
  78874. example when the output buffer is full (avail_out == 0), or after each
  78875. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78876. must be called again after making room in the output buffer because there
  78877. might be more output pending.
  78878. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78879. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78880. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78881. if and when it gets to the next deflate block boundary. When decoding the
  78882. zlib or gzip format, this will cause inflate() to return immediately after
  78883. the header and before the first block. When doing a raw inflate, inflate()
  78884. will go ahead and process the first block, and will return when it gets to
  78885. the end of that block, or when it runs out of data.
  78886. The Z_BLOCK option assists in appending to or combining deflate streams.
  78887. Also to assist in this, on return inflate() will set strm->data_type to the
  78888. number of unused bits in the last byte taken from strm->next_in, plus 64
  78889. if inflate() is currently decoding the last block in the deflate stream,
  78890. plus 128 if inflate() returned immediately after decoding an end-of-block
  78891. code or decoding the complete header up to just before the first byte of the
  78892. deflate stream. The end-of-block will not be indicated until all of the
  78893. uncompressed data from that block has been written to strm->next_out. The
  78894. number of unused bits may in general be greater than seven, except when
  78895. bit 7 of data_type is set, in which case the number of unused bits will be
  78896. less than eight.
  78897. inflate() should normally be called until it returns Z_STREAM_END or an
  78898. error. However if all decompression is to be performed in a single step
  78899. (a single call of inflate), the parameter flush should be set to
  78900. Z_FINISH. In this case all pending input is processed and all pending
  78901. output is flushed; avail_out must be large enough to hold all the
  78902. uncompressed data. (The size of the uncompressed data may have been saved
  78903. by the compressor for this purpose.) The next operation on this stream must
  78904. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78905. is never required, but can be used to inform inflate that a faster approach
  78906. may be used for the single inflate() call.
  78907. In this implementation, inflate() always flushes as much output as
  78908. possible to the output buffer, and always uses the faster approach on the
  78909. first call. So the only effect of the flush parameter in this implementation
  78910. is on the return value of inflate(), as noted below, or when it returns early
  78911. because Z_BLOCK is used.
  78912. If a preset dictionary is needed after this call (see inflateSetDictionary
  78913. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78914. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78915. strm->adler to the adler32 checksum of all output produced so far (that is,
  78916. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78917. below. At the end of the stream, inflate() checks that its computed adler32
  78918. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78919. only if the checksum is correct.
  78920. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78921. deflate data. The header type is detected automatically. Any information
  78922. contained in the gzip header is not retained, so applications that need that
  78923. information should instead use raw inflate, see inflateInit2() below, or
  78924. inflateBack() and perform their own processing of the gzip header and
  78925. trailer.
  78926. inflate() returns Z_OK if some progress has been made (more input processed
  78927. or more output produced), Z_STREAM_END if the end of the compressed data has
  78928. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78929. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78930. corrupted (input stream not conforming to the zlib format or incorrect check
  78931. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78932. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78933. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78934. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78935. inflate() can be called again with more input and more output space to
  78936. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78937. call inflateSync() to look for a good compression block if a partial recovery
  78938. of the data is desired.
  78939. */
  78940. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78941. /*
  78942. All dynamically allocated data structures for this stream are freed.
  78943. This function discards any unprocessed input and does not flush any
  78944. pending output.
  78945. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78946. was inconsistent. In the error case, msg may be set but then points to a
  78947. static string (which must not be deallocated).
  78948. */
  78949. /* Advanced functions */
  78950. /*
  78951. The following functions are needed only in some special applications.
  78952. */
  78953. /*
  78954. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78955. int level,
  78956. int method,
  78957. int windowBits,
  78958. int memLevel,
  78959. int strategy));
  78960. This is another version of deflateInit with more compression options. The
  78961. fields next_in, zalloc, zfree and opaque must be initialized before by
  78962. the caller.
  78963. The method parameter is the compression method. It must be Z_DEFLATED in
  78964. this version of the library.
  78965. The windowBits parameter is the base two logarithm of the window size
  78966. (the size of the history buffer). It should be in the range 8..15 for this
  78967. version of the library. Larger values of this parameter result in better
  78968. compression at the expense of memory usage. The default value is 15 if
  78969. deflateInit is used instead.
  78970. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78971. determines the window size. deflate() will then generate raw deflate data
  78972. with no zlib header or trailer, and will not compute an adler32 check value.
  78973. windowBits can also be greater than 15 for optional gzip encoding. Add
  78974. 16 to windowBits to write a simple gzip header and trailer around the
  78975. compressed data instead of a zlib wrapper. The gzip header will have no
  78976. file name, no extra data, no comment, no modification time (set to zero),
  78977. no header crc, and the operating system will be set to 255 (unknown). If a
  78978. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78979. The memLevel parameter specifies how much memory should be allocated
  78980. for the internal compression state. memLevel=1 uses minimum memory but
  78981. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78982. for optimal speed. The default value is 8. See zconf.h for total memory
  78983. usage as a function of windowBits and memLevel.
  78984. The strategy parameter is used to tune the compression algorithm. Use the
  78985. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78986. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78987. string match), or Z_RLE to limit match distances to one (run-length
  78988. encoding). Filtered data consists mostly of small values with a somewhat
  78989. random distribution. In this case, the compression algorithm is tuned to
  78990. compress them better. The effect of Z_FILTERED is to force more Huffman
  78991. coding and less string matching; it is somewhat intermediate between
  78992. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78993. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78994. parameter only affects the compression ratio but not the correctness of the
  78995. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78996. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78997. applications.
  78998. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78999. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79000. method). msg is set to null if there is no error message. deflateInit2 does
  79001. not perform any compression: this will be done by deflate().
  79002. */
  79003. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79004. const Bytef *dictionary,
  79005. uInt dictLength));
  79006. /*
  79007. Initializes the compression dictionary from the given byte sequence
  79008. without producing any compressed output. This function must be called
  79009. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79010. call of deflate. The compressor and decompressor must use exactly the same
  79011. dictionary (see inflateSetDictionary).
  79012. The dictionary should consist of strings (byte sequences) that are likely
  79013. to be encountered later in the data to be compressed, with the most commonly
  79014. used strings preferably put towards the end of the dictionary. Using a
  79015. dictionary is most useful when the data to be compressed is short and can be
  79016. predicted with good accuracy; the data can then be compressed better than
  79017. with the default empty dictionary.
  79018. Depending on the size of the compression data structures selected by
  79019. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79020. discarded, for example if the dictionary is larger than the window size in
  79021. deflate or deflate2. Thus the strings most likely to be useful should be
  79022. put at the end of the dictionary, not at the front. In addition, the
  79023. current implementation of deflate will use at most the window size minus
  79024. 262 bytes of the provided dictionary.
  79025. Upon return of this function, strm->adler is set to the adler32 value
  79026. of the dictionary; the decompressor may later use this value to determine
  79027. which dictionary has been used by the compressor. (The adler32 value
  79028. applies to the whole dictionary even if only a subset of the dictionary is
  79029. actually used by the compressor.) If a raw deflate was requested, then the
  79030. adler32 value is not computed and strm->adler is not set.
  79031. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79032. parameter is invalid (such as NULL dictionary) or the stream state is
  79033. inconsistent (for example if deflate has already been called for this stream
  79034. or if the compression method is bsort). deflateSetDictionary does not
  79035. perform any compression: this will be done by deflate().
  79036. */
  79037. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79038. z_streamp source));
  79039. /*
  79040. Sets the destination stream as a complete copy of the source stream.
  79041. This function can be useful when several compression strategies will be
  79042. tried, for example when there are several ways of pre-processing the input
  79043. data with a filter. The streams that will be discarded should then be freed
  79044. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79045. compression state which can be quite large, so this strategy is slow and
  79046. can consume lots of memory.
  79047. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79048. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79049. (such as zalloc being NULL). msg is left unchanged in both source and
  79050. destination.
  79051. */
  79052. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79053. /*
  79054. This function is equivalent to deflateEnd followed by deflateInit,
  79055. but does not free and reallocate all the internal compression state.
  79056. The stream will keep the same compression level and any other attributes
  79057. that may have been set by deflateInit2.
  79058. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79059. stream state was inconsistent (such as zalloc or state being NULL).
  79060. */
  79061. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79062. int level,
  79063. int strategy));
  79064. /*
  79065. Dynamically update the compression level and compression strategy. The
  79066. interpretation of level and strategy is as in deflateInit2. This can be
  79067. used to switch between compression and straight copy of the input data, or
  79068. to switch to a different kind of input data requiring a different
  79069. strategy. If the compression level is changed, the input available so far
  79070. is compressed with the old level (and may be flushed); the new level will
  79071. take effect only at the next call of deflate().
  79072. Before the call of deflateParams, the stream state must be set as for
  79073. a call of deflate(), since the currently available input may have to
  79074. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79075. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79076. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79077. if strm->avail_out was zero.
  79078. */
  79079. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79080. int good_length,
  79081. int max_lazy,
  79082. int nice_length,
  79083. int max_chain));
  79084. /*
  79085. Fine tune deflate's internal compression parameters. This should only be
  79086. used by someone who understands the algorithm used by zlib's deflate for
  79087. searching for the best matching string, and even then only by the most
  79088. fanatic optimizer trying to squeeze out the last compressed bit for their
  79089. specific input data. Read the deflate.c source code for the meaning of the
  79090. max_lazy, good_length, nice_length, and max_chain parameters.
  79091. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79092. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79093. */
  79094. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79095. uLong sourceLen));
  79096. /*
  79097. deflateBound() returns an upper bound on the compressed size after
  79098. deflation of sourceLen bytes. It must be called after deflateInit()
  79099. or deflateInit2(). This would be used to allocate an output buffer
  79100. for deflation in a single pass, and so would be called before deflate().
  79101. */
  79102. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79103. int bits,
  79104. int value));
  79105. /*
  79106. deflatePrime() inserts bits in the deflate output stream. The intent
  79107. is that this function is used to start off the deflate output with the
  79108. bits leftover from a previous deflate stream when appending to it. As such,
  79109. this function can only be used for raw deflate, and must be used before the
  79110. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79111. less than or equal to 16, and that many of the least significant bits of
  79112. value will be inserted in the output.
  79113. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79114. stream state was inconsistent.
  79115. */
  79116. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79117. gz_headerp head));
  79118. /*
  79119. deflateSetHeader() provides gzip header information for when a gzip
  79120. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79121. after deflateInit2() or deflateReset() and before the first call of
  79122. deflate(). The text, time, os, extra field, name, and comment information
  79123. in the provided gz_header structure are written to the gzip header (xflag is
  79124. ignored -- the extra flags are set according to the compression level). The
  79125. caller must assure that, if not Z_NULL, name and comment are terminated with
  79126. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79127. available there. If hcrc is true, a gzip header crc is included. Note that
  79128. the current versions of the command-line version of gzip (up through version
  79129. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79130. gzip file" and give up.
  79131. If deflateSetHeader is not used, the default gzip header has text false,
  79132. the time set to zero, and os set to 255, with no extra, name, or comment
  79133. fields. The gzip header is returned to the default state by deflateReset().
  79134. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79135. stream state was inconsistent.
  79136. */
  79137. /*
  79138. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79139. int windowBits));
  79140. This is another version of inflateInit with an extra parameter. The
  79141. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79142. before by the caller.
  79143. The windowBits parameter is the base two logarithm of the maximum window
  79144. size (the size of the history buffer). It should be in the range 8..15 for
  79145. this version of the library. The default value is 15 if inflateInit is used
  79146. instead. windowBits must be greater than or equal to the windowBits value
  79147. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79148. deflateInit2() was not used. If a compressed stream with a larger window
  79149. size is given as input, inflate() will return with the error code
  79150. Z_DATA_ERROR instead of trying to allocate a larger window.
  79151. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79152. determines the window size. inflate() will then process raw deflate data,
  79153. not looking for a zlib or gzip header, not generating a check value, and not
  79154. looking for any check values for comparison at the end of the stream. This
  79155. is for use with other formats that use the deflate compressed data format
  79156. such as zip. Those formats provide their own check values. If a custom
  79157. format is developed using the raw deflate format for compressed data, it is
  79158. recommended that a check value such as an adler32 or a crc32 be applied to
  79159. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79160. most applications, the zlib format should be used as is. Note that comments
  79161. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79162. windowBits can also be greater than 15 for optional gzip decoding. Add
  79163. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79164. detection, or add 16 to decode only the gzip format (the zlib format will
  79165. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79166. a crc32 instead of an adler32.
  79167. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79168. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79169. is set to null if there is no error message. inflateInit2 does not perform
  79170. any decompression apart from reading the zlib header if present: this will
  79171. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79172. and avail_out are unchanged.)
  79173. */
  79174. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79175. const Bytef *dictionary,
  79176. uInt dictLength));
  79177. /*
  79178. Initializes the decompression dictionary from the given uncompressed byte
  79179. sequence. This function must be called immediately after a call of inflate,
  79180. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79181. can be determined from the adler32 value returned by that call of inflate.
  79182. The compressor and decompressor must use exactly the same dictionary (see
  79183. deflateSetDictionary). For raw inflate, this function can be called
  79184. immediately after inflateInit2() or inflateReset() and before any call of
  79185. inflate() to set the dictionary. The application must insure that the
  79186. dictionary that was used for compression is provided.
  79187. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79188. parameter is invalid (such as NULL dictionary) or the stream state is
  79189. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79190. expected one (incorrect adler32 value). inflateSetDictionary does not
  79191. perform any decompression: this will be done by subsequent calls of
  79192. inflate().
  79193. */
  79194. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79195. /*
  79196. Skips invalid compressed data until a full flush point (see above the
  79197. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79198. available input is skipped. No output is provided.
  79199. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79200. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79201. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79202. case, the application may save the current current value of total_in which
  79203. indicates where valid compressed data was found. In the error case, the
  79204. application may repeatedly call inflateSync, providing more input each time,
  79205. until success or end of the input data.
  79206. */
  79207. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79208. z_streamp source));
  79209. /*
  79210. Sets the destination stream as a complete copy of the source stream.
  79211. This function can be useful when randomly accessing a large stream. The
  79212. first pass through the stream can periodically record the inflate state,
  79213. allowing restarting inflate at those points when randomly accessing the
  79214. stream.
  79215. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79216. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79217. (such as zalloc being NULL). msg is left unchanged in both source and
  79218. destination.
  79219. */
  79220. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79221. /*
  79222. This function is equivalent to inflateEnd followed by inflateInit,
  79223. but does not free and reallocate all the internal decompression state.
  79224. The stream will keep attributes that may have been set by inflateInit2.
  79225. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79226. stream state was inconsistent (such as zalloc or state being NULL).
  79227. */
  79228. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79229. int bits,
  79230. int value));
  79231. /*
  79232. This function inserts bits in the inflate input stream. The intent is
  79233. that this function is used to start inflating at a bit position in the
  79234. middle of a byte. The provided bits will be used before any bytes are used
  79235. from next_in. This function should only be used with raw inflate, and
  79236. should be used before the first inflate() call after inflateInit2() or
  79237. inflateReset(). bits must be less than or equal to 16, and that many of the
  79238. least significant bits of value will be inserted in the input.
  79239. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79240. stream state was inconsistent.
  79241. */
  79242. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79243. gz_headerp head));
  79244. /*
  79245. inflateGetHeader() requests that gzip header information be stored in the
  79246. provided gz_header structure. inflateGetHeader() may be called after
  79247. inflateInit2() or inflateReset(), and before the first call of inflate().
  79248. As inflate() processes the gzip stream, head->done is zero until the header
  79249. is completed, at which time head->done is set to one. If a zlib stream is
  79250. being decoded, then head->done is set to -1 to indicate that there will be
  79251. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79252. force inflate() to return immediately after header processing is complete
  79253. and before any actual data is decompressed.
  79254. The text, time, xflags, and os fields are filled in with the gzip header
  79255. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79256. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79257. contains the maximum number of bytes to write to extra. Once done is true,
  79258. extra_len contains the actual extra field length, and extra contains the
  79259. extra field, or that field truncated if extra_max is less than extra_len.
  79260. If name is not Z_NULL, then up to name_max characters are written there,
  79261. terminated with a zero unless the length is greater than name_max. If
  79262. comment is not Z_NULL, then up to comm_max characters are written there,
  79263. terminated with a zero unless the length is greater than comm_max. When
  79264. any of extra, name, or comment are not Z_NULL and the respective field is
  79265. not present in the header, then that field is set to Z_NULL to signal its
  79266. absence. This allows the use of deflateSetHeader() with the returned
  79267. structure to duplicate the header. However if those fields are set to
  79268. allocated memory, then the application will need to save those pointers
  79269. elsewhere so that they can be eventually freed.
  79270. If inflateGetHeader is not used, then the header information is simply
  79271. discarded. The header is always checked for validity, including the header
  79272. CRC if present. inflateReset() will reset the process to discard the header
  79273. information. The application would need to call inflateGetHeader() again to
  79274. retrieve the header from the next gzip stream.
  79275. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79276. stream state was inconsistent.
  79277. */
  79278. /*
  79279. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79280. unsigned char FAR *window));
  79281. Initialize the internal stream state for decompression using inflateBack()
  79282. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79283. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79284. derived memory allocation routines are used. windowBits is the base two
  79285. logarithm of the window size, in the range 8..15. window is a caller
  79286. supplied buffer of that size. Except for special applications where it is
  79287. assured that deflate was used with small window sizes, windowBits must be 15
  79288. and a 32K byte window must be supplied to be able to decompress general
  79289. deflate streams.
  79290. See inflateBack() for the usage of these routines.
  79291. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79292. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79293. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79294. match the version of the header file.
  79295. */
  79296. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79297. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79298. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79299. in_func in, void FAR *in_desc,
  79300. out_func out, void FAR *out_desc));
  79301. /*
  79302. inflateBack() does a raw inflate with a single call using a call-back
  79303. interface for input and output. This is more efficient than inflate() for
  79304. file i/o applications in that it avoids copying between the output and the
  79305. sliding window by simply making the window itself the output buffer. This
  79306. function trusts the application to not change the output buffer passed by
  79307. the output function, at least until inflateBack() returns.
  79308. inflateBackInit() must be called first to allocate the internal state
  79309. and to initialize the state with the user-provided window buffer.
  79310. inflateBack() may then be used multiple times to inflate a complete, raw
  79311. deflate stream with each call. inflateBackEnd() is then called to free
  79312. the allocated state.
  79313. A raw deflate stream is one with no zlib or gzip header or trailer.
  79314. This routine would normally be used in a utility that reads zip or gzip
  79315. files and writes out uncompressed files. The utility would decode the
  79316. header and process the trailer on its own, hence this routine expects
  79317. only the raw deflate stream to decompress. This is different from the
  79318. normal behavior of inflate(), which expects either a zlib or gzip header and
  79319. trailer around the deflate stream.
  79320. inflateBack() uses two subroutines supplied by the caller that are then
  79321. called by inflateBack() for input and output. inflateBack() calls those
  79322. routines until it reads a complete deflate stream and writes out all of the
  79323. uncompressed data, or until it encounters an error. The function's
  79324. parameters and return types are defined above in the in_func and out_func
  79325. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79326. number of bytes of provided input, and a pointer to that input in buf. If
  79327. there is no input available, in() must return zero--buf is ignored in that
  79328. case--and inflateBack() will return a buffer error. inflateBack() will call
  79329. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79330. should return zero on success, or non-zero on failure. If out() returns
  79331. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79332. are permitted to change the contents of the window provided to
  79333. inflateBackInit(), which is also the buffer that out() uses to write from.
  79334. The length written by out() will be at most the window size. Any non-zero
  79335. amount of input may be provided by in().
  79336. For convenience, inflateBack() can be provided input on the first call by
  79337. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79338. in() will be called. Therefore strm->next_in must be initialized before
  79339. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79340. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79341. must also be initialized, and then if strm->avail_in is not zero, input will
  79342. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79343. The in_desc and out_desc parameters of inflateBack() is passed as the
  79344. first parameter of in() and out() respectively when they are called. These
  79345. descriptors can be optionally used to pass any information that the caller-
  79346. supplied in() and out() functions need to do their job.
  79347. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79348. pass back any unused input that was provided by the last in() call. The
  79349. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79350. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79351. error in the deflate stream (in which case strm->msg is set to indicate the
  79352. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79353. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79354. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79355. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79356. out() returning non-zero. (in() will always be called before out(), so
  79357. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79358. that inflateBack() cannot return Z_OK.
  79359. */
  79360. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79361. /*
  79362. All memory allocated by inflateBackInit() is freed.
  79363. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79364. state was inconsistent.
  79365. */
  79366. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79367. /* Return flags indicating compile-time options.
  79368. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79369. 1.0: size of uInt
  79370. 3.2: size of uLong
  79371. 5.4: size of voidpf (pointer)
  79372. 7.6: size of z_off_t
  79373. Compiler, assembler, and debug options:
  79374. 8: DEBUG
  79375. 9: ASMV or ASMINF -- use ASM code
  79376. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79377. 11: 0 (reserved)
  79378. One-time table building (smaller code, but not thread-safe if true):
  79379. 12: BUILDFIXED -- build static block decoding tables when needed
  79380. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79381. 14,15: 0 (reserved)
  79382. Library content (indicates missing functionality):
  79383. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79384. deflate code when not needed)
  79385. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79386. and decode gzip streams (to avoid linking crc code)
  79387. 18-19: 0 (reserved)
  79388. Operation variations (changes in library functionality):
  79389. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79390. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79391. 22,23: 0 (reserved)
  79392. The sprintf variant used by gzprintf (zero is best):
  79393. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79394. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79395. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79396. Remainder:
  79397. 27-31: 0 (reserved)
  79398. */
  79399. /* utility functions */
  79400. /*
  79401. The following utility functions are implemented on top of the
  79402. basic stream-oriented functions. To simplify the interface, some
  79403. default options are assumed (compression level and memory usage,
  79404. standard memory allocation functions). The source code of these
  79405. utility functions can easily be modified if you need special options.
  79406. */
  79407. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79408. const Bytef *source, uLong sourceLen));
  79409. /*
  79410. Compresses the source buffer into the destination buffer. sourceLen is
  79411. the byte length of the source buffer. Upon entry, destLen is the total
  79412. size of the destination buffer, which must be at least the value returned
  79413. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79414. compressed buffer.
  79415. This function can be used to compress a whole file at once if the
  79416. input file is mmap'ed.
  79417. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79418. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79419. buffer.
  79420. */
  79421. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79422. const Bytef *source, uLong sourceLen,
  79423. int level));
  79424. /*
  79425. Compresses the source buffer into the destination buffer. The level
  79426. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79427. length of the source buffer. Upon entry, destLen is the total size of the
  79428. destination buffer, which must be at least the value returned by
  79429. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79430. compressed buffer.
  79431. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79432. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79433. Z_STREAM_ERROR if the level parameter is invalid.
  79434. */
  79435. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79436. /*
  79437. compressBound() returns an upper bound on the compressed size after
  79438. compress() or compress2() on sourceLen bytes. It would be used before
  79439. a compress() or compress2() call to allocate the destination buffer.
  79440. */
  79441. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79442. const Bytef *source, uLong sourceLen));
  79443. /*
  79444. Decompresses the source buffer into the destination buffer. sourceLen is
  79445. the byte length of the source buffer. Upon entry, destLen is the total
  79446. size of the destination buffer, which must be large enough to hold the
  79447. entire uncompressed data. (The size of the uncompressed data must have
  79448. been saved previously by the compressor and transmitted to the decompressor
  79449. by some mechanism outside the scope of this compression library.)
  79450. Upon exit, destLen is the actual size of the compressed buffer.
  79451. This function can be used to decompress a whole file at once if the
  79452. input file is mmap'ed.
  79453. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79454. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79455. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79456. */
  79457. typedef voidp gzFile;
  79458. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79459. /*
  79460. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79461. is as in fopen ("rb" or "wb") but can also include a compression level
  79462. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79463. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79464. as in "wb1R". (See the description of deflateInit2 for more information
  79465. about the strategy parameter.)
  79466. gzopen can be used to read a file which is not in gzip format; in this
  79467. case gzread will directly read from the file without decompression.
  79468. gzopen returns NULL if the file could not be opened or if there was
  79469. insufficient memory to allocate the (de)compression state; errno
  79470. can be checked to distinguish the two cases (if errno is zero, the
  79471. zlib error is Z_MEM_ERROR). */
  79472. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79473. /*
  79474. gzdopen() associates a gzFile with the file descriptor fd. File
  79475. descriptors are obtained from calls like open, dup, creat, pipe or
  79476. fileno (in the file has been previously opened with fopen).
  79477. The mode parameter is as in gzopen.
  79478. The next call of gzclose on the returned gzFile will also close the
  79479. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79480. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79481. gzdopen returns NULL if there was insufficient memory to allocate
  79482. the (de)compression state.
  79483. */
  79484. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79485. /*
  79486. Dynamically update the compression level or strategy. See the description
  79487. of deflateInit2 for the meaning of these parameters.
  79488. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79489. opened for writing.
  79490. */
  79491. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79492. /*
  79493. Reads the given number of uncompressed bytes from the compressed file.
  79494. If the input file was not in gzip format, gzread copies the given number
  79495. of bytes into the buffer.
  79496. gzread returns the number of uncompressed bytes actually read (0 for
  79497. end of file, -1 for error). */
  79498. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79499. voidpc buf, unsigned len));
  79500. /*
  79501. Writes the given number of uncompressed bytes into the compressed file.
  79502. gzwrite returns the number of uncompressed bytes actually written
  79503. (0 in case of error).
  79504. */
  79505. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79506. /*
  79507. Converts, formats, and writes the args to the compressed file under
  79508. control of the format string, as in fprintf. gzprintf returns the number of
  79509. uncompressed bytes actually written (0 in case of error). The number of
  79510. uncompressed bytes written is limited to 4095. The caller should assure that
  79511. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79512. return an error (0) with nothing written. In this case, there may also be a
  79513. buffer overflow with unpredictable consequences, which is possible only if
  79514. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79515. because the secure snprintf() or vsnprintf() functions were not available.
  79516. */
  79517. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79518. /*
  79519. Writes the given null-terminated string to the compressed file, excluding
  79520. the terminating null character.
  79521. gzputs returns the number of characters written, or -1 in case of error.
  79522. */
  79523. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79524. /*
  79525. Reads bytes from the compressed file until len-1 characters are read, or
  79526. a newline character is read and transferred to buf, or an end-of-file
  79527. condition is encountered. The string is then terminated with a null
  79528. character.
  79529. gzgets returns buf, or Z_NULL in case of error.
  79530. */
  79531. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79532. /*
  79533. Writes c, converted to an unsigned char, into the compressed file.
  79534. gzputc returns the value that was written, or -1 in case of error.
  79535. */
  79536. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79537. /*
  79538. Reads one byte from the compressed file. gzgetc returns this byte
  79539. or -1 in case of end of file or error.
  79540. */
  79541. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79542. /*
  79543. Push one character back onto the stream to be read again later.
  79544. Only one character of push-back is allowed. gzungetc() returns the
  79545. character pushed, or -1 on failure. gzungetc() will fail if a
  79546. character has been pushed but not read yet, or if c is -1. The pushed
  79547. character will be discarded if the stream is repositioned with gzseek()
  79548. or gzrewind().
  79549. */
  79550. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79551. /*
  79552. Flushes all pending output into the compressed file. The parameter
  79553. flush is as in the deflate() function. The return value is the zlib
  79554. error number (see function gzerror below). gzflush returns Z_OK if
  79555. the flush parameter is Z_FINISH and all output could be flushed.
  79556. gzflush should be called only when strictly necessary because it can
  79557. degrade compression.
  79558. */
  79559. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79560. z_off_t offset, int whence));
  79561. /*
  79562. Sets the starting position for the next gzread or gzwrite on the
  79563. given compressed file. The offset represents a number of bytes in the
  79564. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79565. the value SEEK_END is not supported.
  79566. If the file is opened for reading, this function is emulated but can be
  79567. extremely slow. If the file is opened for writing, only forward seeks are
  79568. supported; gzseek then compresses a sequence of zeroes up to the new
  79569. starting position.
  79570. gzseek returns the resulting offset location as measured in bytes from
  79571. the beginning of the uncompressed stream, or -1 in case of error, in
  79572. particular if the file is opened for writing and the new starting position
  79573. would be before the current position.
  79574. */
  79575. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79576. /*
  79577. Rewinds the given file. This function is supported only for reading.
  79578. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79579. */
  79580. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79581. /*
  79582. Returns the starting position for the next gzread or gzwrite on the
  79583. given compressed file. This position represents a number of bytes in the
  79584. uncompressed data stream.
  79585. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79586. */
  79587. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79588. /*
  79589. Returns 1 when EOF has previously been detected reading the given
  79590. input stream, otherwise zero.
  79591. */
  79592. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79593. /*
  79594. Returns 1 if file is being read directly without decompression, otherwise
  79595. zero.
  79596. */
  79597. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79598. /*
  79599. Flushes all pending output if necessary, closes the compressed file
  79600. and deallocates all the (de)compression state. The return value is the zlib
  79601. error number (see function gzerror below).
  79602. */
  79603. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79604. /*
  79605. Returns the error message for the last error which occurred on the
  79606. given compressed file. errnum is set to zlib error number. If an
  79607. error occurred in the file system and not in the compression library,
  79608. errnum is set to Z_ERRNO and the application may consult errno
  79609. to get the exact error code.
  79610. */
  79611. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79612. /*
  79613. Clears the error and end-of-file flags for file. This is analogous to the
  79614. clearerr() function in stdio. This is useful for continuing to read a gzip
  79615. file that is being written concurrently.
  79616. */
  79617. /* checksum functions */
  79618. /*
  79619. These functions are not related to compression but are exported
  79620. anyway because they might be useful in applications using the
  79621. compression library.
  79622. */
  79623. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79624. /*
  79625. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79626. return the updated checksum. If buf is NULL, this function returns
  79627. the required initial value for the checksum.
  79628. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79629. much faster. Usage example:
  79630. uLong adler = adler32(0L, Z_NULL, 0);
  79631. while (read_buffer(buffer, length) != EOF) {
  79632. adler = adler32(adler, buffer, length);
  79633. }
  79634. if (adler != original_adler) error();
  79635. */
  79636. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79637. z_off_t len2));
  79638. /*
  79639. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79640. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79641. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79642. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79643. */
  79644. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79645. /*
  79646. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79647. updated CRC-32. If buf is NULL, this function returns the required initial
  79648. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79649. performed within this function so it shouldn't be done by the application.
  79650. Usage example:
  79651. uLong crc = crc32(0L, Z_NULL, 0);
  79652. while (read_buffer(buffer, length) != EOF) {
  79653. crc = crc32(crc, buffer, length);
  79654. }
  79655. if (crc != original_crc) error();
  79656. */
  79657. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79658. /*
  79659. Combine two CRC-32 check values into one. For two sequences of bytes,
  79660. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79661. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79662. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79663. len2.
  79664. */
  79665. /* various hacks, don't look :) */
  79666. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79667. * and the compiler's view of z_stream:
  79668. */
  79669. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79670. const char *version, int stream_size));
  79671. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79672. const char *version, int stream_size));
  79673. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79674. int windowBits, int memLevel,
  79675. int strategy, const char *version,
  79676. int stream_size));
  79677. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79678. const char *version, int stream_size));
  79679. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79680. unsigned char FAR *window,
  79681. const char *version,
  79682. int stream_size));
  79683. #define deflateInit(strm, level) \
  79684. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79685. #define inflateInit(strm) \
  79686. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79687. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79688. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79689. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79690. #define inflateInit2(strm, windowBits) \
  79691. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79692. #define inflateBackInit(strm, windowBits, window) \
  79693. inflateBackInit_((strm), (windowBits), (window), \
  79694. ZLIB_VERSION, sizeof(z_stream))
  79695. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79696. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79697. #endif
  79698. ZEXTERN const char * ZEXPORT zError OF((int));
  79699. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79700. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79701. #ifdef __cplusplus
  79702. //}
  79703. #endif
  79704. #endif /* ZLIB_H */
  79705. /*** End of inlined file: zlib.h ***/
  79706. #undef OS_CODE
  79707. #else
  79708. #include <zlib.h>
  79709. #endif
  79710. }
  79711. BEGIN_JUCE_NAMESPACE
  79712. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79713. {
  79714. public:
  79715. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79716. : data (0),
  79717. dataSize (0),
  79718. compLevel (compressionLevel),
  79719. strategy (0),
  79720. setParams (true),
  79721. streamIsValid (false),
  79722. finished (false),
  79723. shouldFinish (false)
  79724. {
  79725. using namespace zlibNamespace;
  79726. zerostruct (stream);
  79727. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79728. windowBits != 0 ? windowBits : MAX_WBITS,
  79729. 8, strategy) == Z_OK);
  79730. }
  79731. ~GZIPCompressorHelper()
  79732. {
  79733. using namespace zlibNamespace;
  79734. if (streamIsValid)
  79735. deflateEnd (&stream);
  79736. }
  79737. bool needsInput() const throw()
  79738. {
  79739. return dataSize <= 0;
  79740. }
  79741. void setInput (const uint8* const newData, const int size) throw()
  79742. {
  79743. data = newData;
  79744. dataSize = size;
  79745. }
  79746. int doNextBlock (uint8* const dest, const int destSize) throw()
  79747. {
  79748. using namespace zlibNamespace;
  79749. if (streamIsValid)
  79750. {
  79751. stream.next_in = const_cast <uint8*> (data);
  79752. stream.next_out = dest;
  79753. stream.avail_in = dataSize;
  79754. stream.avail_out = destSize;
  79755. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79756. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79757. setParams = false;
  79758. switch (result)
  79759. {
  79760. case Z_STREAM_END:
  79761. finished = true;
  79762. // Deliberate fall-through..
  79763. case Z_OK:
  79764. data += dataSize - stream.avail_in;
  79765. dataSize = stream.avail_in;
  79766. return destSize - stream.avail_out;
  79767. default:
  79768. break;
  79769. }
  79770. }
  79771. return 0;
  79772. }
  79773. enum { gzipCompBufferSize = 32768 };
  79774. private:
  79775. zlibNamespace::z_stream stream;
  79776. const uint8* data;
  79777. int dataSize, compLevel, strategy;
  79778. bool setParams, streamIsValid;
  79779. public:
  79780. bool finished, shouldFinish;
  79781. };
  79782. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79783. int compressionLevel,
  79784. const bool deleteDestStream,
  79785. const int windowBits)
  79786. : destStream (destStream_, deleteDestStream),
  79787. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79788. {
  79789. if (compressionLevel < 1 || compressionLevel > 9)
  79790. compressionLevel = -1;
  79791. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79792. }
  79793. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79794. {
  79795. flush();
  79796. }
  79797. void GZIPCompressorOutputStream::flush()
  79798. {
  79799. if (! helper->finished)
  79800. {
  79801. helper->shouldFinish = true;
  79802. while (! helper->finished)
  79803. doNextBlock();
  79804. }
  79805. destStream->flush();
  79806. }
  79807. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79808. {
  79809. if (! helper->finished)
  79810. {
  79811. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79812. while (! helper->needsInput())
  79813. {
  79814. if (! doNextBlock())
  79815. return false;
  79816. }
  79817. }
  79818. return true;
  79819. }
  79820. bool GZIPCompressorOutputStream::doNextBlock()
  79821. {
  79822. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79823. return len <= 0 || destStream->write (buffer, len);
  79824. }
  79825. int64 GZIPCompressorOutputStream::getPosition()
  79826. {
  79827. return destStream->getPosition();
  79828. }
  79829. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79830. {
  79831. jassertfalse; // can't do it!
  79832. return false;
  79833. }
  79834. END_JUCE_NAMESPACE
  79835. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79836. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79837. #if JUCE_MSVC
  79838. #pragma warning (push)
  79839. #pragma warning (disable: 4309 4305)
  79840. #endif
  79841. namespace zlibNamespace
  79842. {
  79843. #if JUCE_INCLUDE_ZLIB_CODE
  79844. #undef OS_CODE
  79845. #undef fdopen
  79846. #define ZLIB_INTERNAL
  79847. #define NO_DUMMY_DECL
  79848. /*** Start of inlined file: adler32.c ***/
  79849. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79850. #define ZLIB_INTERNAL
  79851. #define BASE 65521UL /* largest prime smaller than 65536 */
  79852. #define NMAX 5552
  79853. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79854. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79855. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79856. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79857. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79858. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79859. /* use NO_DIVIDE if your processor does not do division in hardware */
  79860. #ifdef NO_DIVIDE
  79861. # define MOD(a) \
  79862. do { \
  79863. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79864. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79865. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79866. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79867. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79868. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79869. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79870. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79871. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79872. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79873. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79874. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79875. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79876. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79877. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79878. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79879. if (a >= BASE) a -= BASE; \
  79880. } while (0)
  79881. # define MOD4(a) \
  79882. do { \
  79883. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79884. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79885. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79886. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79887. if (a >= BASE) a -= BASE; \
  79888. } while (0)
  79889. #else
  79890. # define MOD(a) a %= BASE
  79891. # define MOD4(a) a %= BASE
  79892. #endif
  79893. /* ========================================================================= */
  79894. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79895. {
  79896. unsigned long sum2;
  79897. unsigned n;
  79898. /* split Adler-32 into component sums */
  79899. sum2 = (adler >> 16) & 0xffff;
  79900. adler &= 0xffff;
  79901. /* in case user likes doing a byte at a time, keep it fast */
  79902. if (len == 1) {
  79903. adler += buf[0];
  79904. if (adler >= BASE)
  79905. adler -= BASE;
  79906. sum2 += adler;
  79907. if (sum2 >= BASE)
  79908. sum2 -= BASE;
  79909. return adler | (sum2 << 16);
  79910. }
  79911. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79912. if (buf == Z_NULL)
  79913. return 1L;
  79914. /* in case short lengths are provided, keep it somewhat fast */
  79915. if (len < 16) {
  79916. while (len--) {
  79917. adler += *buf++;
  79918. sum2 += adler;
  79919. }
  79920. if (adler >= BASE)
  79921. adler -= BASE;
  79922. MOD4(sum2); /* only added so many BASE's */
  79923. return adler | (sum2 << 16);
  79924. }
  79925. /* do length NMAX blocks -- requires just one modulo operation */
  79926. while (len >= NMAX) {
  79927. len -= NMAX;
  79928. n = NMAX / 16; /* NMAX is divisible by 16 */
  79929. do {
  79930. DO16(buf); /* 16 sums unrolled */
  79931. buf += 16;
  79932. } while (--n);
  79933. MOD(adler);
  79934. MOD(sum2);
  79935. }
  79936. /* do remaining bytes (less than NMAX, still just one modulo) */
  79937. if (len) { /* avoid modulos if none remaining */
  79938. while (len >= 16) {
  79939. len -= 16;
  79940. DO16(buf);
  79941. buf += 16;
  79942. }
  79943. while (len--) {
  79944. adler += *buf++;
  79945. sum2 += adler;
  79946. }
  79947. MOD(adler);
  79948. MOD(sum2);
  79949. }
  79950. /* return recombined sums */
  79951. return adler | (sum2 << 16);
  79952. }
  79953. /* ========================================================================= */
  79954. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79955. {
  79956. unsigned long sum1;
  79957. unsigned long sum2;
  79958. unsigned rem;
  79959. /* the derivation of this formula is left as an exercise for the reader */
  79960. rem = (unsigned)(len2 % BASE);
  79961. sum1 = adler1 & 0xffff;
  79962. sum2 = rem * sum1;
  79963. MOD(sum2);
  79964. sum1 += (adler2 & 0xffff) + BASE - 1;
  79965. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79966. if (sum1 > BASE) sum1 -= BASE;
  79967. if (sum1 > BASE) sum1 -= BASE;
  79968. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79969. if (sum2 > BASE) sum2 -= BASE;
  79970. return sum1 | (sum2 << 16);
  79971. }
  79972. /*** End of inlined file: adler32.c ***/
  79973. /*** Start of inlined file: compress.c ***/
  79974. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79975. #define ZLIB_INTERNAL
  79976. /* ===========================================================================
  79977. Compresses the source buffer into the destination buffer. The level
  79978. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79979. length of the source buffer. Upon entry, destLen is the total size of the
  79980. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79981. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79982. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79983. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79984. Z_STREAM_ERROR if the level parameter is invalid.
  79985. */
  79986. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79987. uLong sourceLen, int level)
  79988. {
  79989. z_stream stream;
  79990. int err;
  79991. stream.next_in = (Bytef*)source;
  79992. stream.avail_in = (uInt)sourceLen;
  79993. #ifdef MAXSEG_64K
  79994. /* Check for source > 64K on 16-bit machine: */
  79995. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79996. #endif
  79997. stream.next_out = dest;
  79998. stream.avail_out = (uInt)*destLen;
  79999. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80000. stream.zalloc = (alloc_func)0;
  80001. stream.zfree = (free_func)0;
  80002. stream.opaque = (voidpf)0;
  80003. err = deflateInit(&stream, level);
  80004. if (err != Z_OK) return err;
  80005. err = deflate(&stream, Z_FINISH);
  80006. if (err != Z_STREAM_END) {
  80007. deflateEnd(&stream);
  80008. return err == Z_OK ? Z_BUF_ERROR : err;
  80009. }
  80010. *destLen = stream.total_out;
  80011. err = deflateEnd(&stream);
  80012. return err;
  80013. }
  80014. /* ===========================================================================
  80015. */
  80016. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80017. {
  80018. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80019. }
  80020. /* ===========================================================================
  80021. If the default memLevel or windowBits for deflateInit() is changed, then
  80022. this function needs to be updated.
  80023. */
  80024. uLong ZEXPORT compressBound (uLong sourceLen)
  80025. {
  80026. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80027. }
  80028. /*** End of inlined file: compress.c ***/
  80029. #undef DO1
  80030. #undef DO8
  80031. /*** Start of inlined file: crc32.c ***/
  80032. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80033. /*
  80034. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80035. protection on the static variables used to control the first-use generation
  80036. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80037. first call get_crc_table() to initialize the tables before allowing more than
  80038. one thread to use crc32().
  80039. */
  80040. #ifdef MAKECRCH
  80041. # include <stdio.h>
  80042. # ifndef DYNAMIC_CRC_TABLE
  80043. # define DYNAMIC_CRC_TABLE
  80044. # endif /* !DYNAMIC_CRC_TABLE */
  80045. #endif /* MAKECRCH */
  80046. /*** Start of inlined file: zutil.h ***/
  80047. /* WARNING: this file should *not* be used by applications. It is
  80048. part of the implementation of the compression library and is
  80049. subject to change. Applications should only use zlib.h.
  80050. */
  80051. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80052. #ifndef ZUTIL_H
  80053. #define ZUTIL_H
  80054. #define ZLIB_INTERNAL
  80055. #ifdef STDC
  80056. # ifndef _WIN32_WCE
  80057. # include <stddef.h>
  80058. # endif
  80059. # include <string.h>
  80060. # include <stdlib.h>
  80061. #endif
  80062. #ifdef NO_ERRNO_H
  80063. # ifdef _WIN32_WCE
  80064. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80065. * errno. We define it as a global variable to simplify porting.
  80066. * Its value is always 0 and should not be used. We rename it to
  80067. * avoid conflict with other libraries that use the same workaround.
  80068. */
  80069. # define errno z_errno
  80070. # endif
  80071. extern int errno;
  80072. #else
  80073. # ifndef _WIN32_WCE
  80074. # include <errno.h>
  80075. # endif
  80076. #endif
  80077. #ifndef local
  80078. # define local static
  80079. #endif
  80080. /* compile with -Dlocal if your debugger can't find static symbols */
  80081. typedef unsigned char uch;
  80082. typedef uch FAR uchf;
  80083. typedef unsigned short ush;
  80084. typedef ush FAR ushf;
  80085. typedef unsigned long ulg;
  80086. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80087. /* (size given to avoid silly warnings with Visual C++) */
  80088. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80089. #define ERR_RETURN(strm,err) \
  80090. return (strm->msg = (char*)ERR_MSG(err), (err))
  80091. /* To be used only when the state is known to be valid */
  80092. /* common constants */
  80093. #ifndef DEF_WBITS
  80094. # define DEF_WBITS MAX_WBITS
  80095. #endif
  80096. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80097. #if MAX_MEM_LEVEL >= 8
  80098. # define DEF_MEM_LEVEL 8
  80099. #else
  80100. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80101. #endif
  80102. /* default memLevel */
  80103. #define STORED_BLOCK 0
  80104. #define STATIC_TREES 1
  80105. #define DYN_TREES 2
  80106. /* The three kinds of block type */
  80107. #define MIN_MATCH 3
  80108. #define MAX_MATCH 258
  80109. /* The minimum and maximum match lengths */
  80110. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80111. /* target dependencies */
  80112. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80113. # define OS_CODE 0x00
  80114. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80115. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80116. /* Allow compilation with ANSI keywords only enabled */
  80117. void _Cdecl farfree( void *block );
  80118. void *_Cdecl farmalloc( unsigned long nbytes );
  80119. # else
  80120. # include <alloc.h>
  80121. # endif
  80122. # else /* MSC or DJGPP */
  80123. # include <malloc.h>
  80124. # endif
  80125. #endif
  80126. #ifdef AMIGA
  80127. # define OS_CODE 0x01
  80128. #endif
  80129. #if defined(VAXC) || defined(VMS)
  80130. # define OS_CODE 0x02
  80131. # define F_OPEN(name, mode) \
  80132. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80133. #endif
  80134. #if defined(ATARI) || defined(atarist)
  80135. # define OS_CODE 0x05
  80136. #endif
  80137. #ifdef OS2
  80138. # define OS_CODE 0x06
  80139. # ifdef M_I86
  80140. #include <malloc.h>
  80141. # endif
  80142. #endif
  80143. #if defined(MACOS) || TARGET_OS_MAC
  80144. # define OS_CODE 0x07
  80145. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80146. # include <unix.h> /* for fdopen */
  80147. # else
  80148. # ifndef fdopen
  80149. # define fdopen(fd,mode) NULL /* No fdopen() */
  80150. # endif
  80151. # endif
  80152. #endif
  80153. #ifdef TOPS20
  80154. # define OS_CODE 0x0a
  80155. #endif
  80156. #ifdef WIN32
  80157. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80158. # define OS_CODE 0x0b
  80159. # endif
  80160. #endif
  80161. #ifdef __50SERIES /* Prime/PRIMOS */
  80162. # define OS_CODE 0x0f
  80163. #endif
  80164. #if defined(_BEOS_) || defined(RISCOS)
  80165. # define fdopen(fd,mode) NULL /* No fdopen() */
  80166. #endif
  80167. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80168. # if defined(_WIN32_WCE)
  80169. # define fdopen(fd,mode) NULL /* No fdopen() */
  80170. # ifndef _PTRDIFF_T_DEFINED
  80171. typedef int ptrdiff_t;
  80172. # define _PTRDIFF_T_DEFINED
  80173. # endif
  80174. # else
  80175. # define fdopen(fd,type) _fdopen(fd,type)
  80176. # endif
  80177. #endif
  80178. /* common defaults */
  80179. #ifndef OS_CODE
  80180. # define OS_CODE 0x03 /* assume Unix */
  80181. #endif
  80182. #ifndef F_OPEN
  80183. # define F_OPEN(name, mode) fopen((name), (mode))
  80184. #endif
  80185. /* functions */
  80186. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80187. # ifndef HAVE_VSNPRINTF
  80188. # define HAVE_VSNPRINTF
  80189. # endif
  80190. #endif
  80191. #if defined(__CYGWIN__)
  80192. # ifndef HAVE_VSNPRINTF
  80193. # define HAVE_VSNPRINTF
  80194. # endif
  80195. #endif
  80196. #ifndef HAVE_VSNPRINTF
  80197. # ifdef MSDOS
  80198. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80199. but for now we just assume it doesn't. */
  80200. # define NO_vsnprintf
  80201. # endif
  80202. # ifdef __TURBOC__
  80203. # define NO_vsnprintf
  80204. # endif
  80205. # ifdef WIN32
  80206. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80207. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80208. # define vsnprintf _vsnprintf
  80209. # endif
  80210. # endif
  80211. # ifdef __SASC
  80212. # define NO_vsnprintf
  80213. # endif
  80214. #endif
  80215. #ifdef VMS
  80216. # define NO_vsnprintf
  80217. #endif
  80218. #if defined(pyr)
  80219. # define NO_MEMCPY
  80220. #endif
  80221. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80222. /* Use our own functions for small and medium model with MSC <= 5.0.
  80223. * You may have to use the same strategy for Borland C (untested).
  80224. * The __SC__ check is for Symantec.
  80225. */
  80226. # define NO_MEMCPY
  80227. #endif
  80228. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80229. # define HAVE_MEMCPY
  80230. #endif
  80231. #ifdef HAVE_MEMCPY
  80232. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80233. # define zmemcpy _fmemcpy
  80234. # define zmemcmp _fmemcmp
  80235. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80236. # else
  80237. # define zmemcpy memcpy
  80238. # define zmemcmp memcmp
  80239. # define zmemzero(dest, len) memset(dest, 0, len)
  80240. # endif
  80241. #else
  80242. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80243. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80244. extern void zmemzero OF((Bytef* dest, uInt len));
  80245. #endif
  80246. /* Diagnostic functions */
  80247. #ifdef DEBUG
  80248. # include <stdio.h>
  80249. extern int z_verbose;
  80250. extern void z_error OF((const char *m));
  80251. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80252. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80253. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80254. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80255. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80256. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80257. #else
  80258. # define Assert(cond,msg)
  80259. # define Trace(x)
  80260. # define Tracev(x)
  80261. # define Tracevv(x)
  80262. # define Tracec(c,x)
  80263. # define Tracecv(c,x)
  80264. #endif
  80265. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80266. void zcfree OF((voidpf opaque, voidpf ptr));
  80267. #define ZALLOC(strm, items, size) \
  80268. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80269. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80270. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80271. #endif /* ZUTIL_H */
  80272. /*** End of inlined file: zutil.h ***/
  80273. /* for STDC and FAR definitions */
  80274. #define local static
  80275. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80276. #ifndef NOBYFOUR
  80277. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80278. # include <limits.h>
  80279. # define BYFOUR
  80280. # if (UINT_MAX == 0xffffffffUL)
  80281. typedef unsigned int u4;
  80282. # else
  80283. # if (ULONG_MAX == 0xffffffffUL)
  80284. typedef unsigned long u4;
  80285. # else
  80286. # if (USHRT_MAX == 0xffffffffUL)
  80287. typedef unsigned short u4;
  80288. # else
  80289. # undef BYFOUR /* can't find a four-byte integer type! */
  80290. # endif
  80291. # endif
  80292. # endif
  80293. # endif /* STDC */
  80294. #endif /* !NOBYFOUR */
  80295. /* Definitions for doing the crc four data bytes at a time. */
  80296. #ifdef BYFOUR
  80297. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80298. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80299. local unsigned long crc32_little OF((unsigned long,
  80300. const unsigned char FAR *, unsigned));
  80301. local unsigned long crc32_big OF((unsigned long,
  80302. const unsigned char FAR *, unsigned));
  80303. # define TBLS 8
  80304. #else
  80305. # define TBLS 1
  80306. #endif /* BYFOUR */
  80307. /* Local functions for crc concatenation */
  80308. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80309. unsigned long vec));
  80310. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80311. #ifdef DYNAMIC_CRC_TABLE
  80312. local volatile int crc_table_empty = 1;
  80313. local unsigned long FAR crc_table[TBLS][256];
  80314. local void make_crc_table OF((void));
  80315. #ifdef MAKECRCH
  80316. local void write_table OF((FILE *, const unsigned long FAR *));
  80317. #endif /* MAKECRCH */
  80318. /*
  80319. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80320. 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.
  80321. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80322. with the lowest powers in the most significant bit. Then adding polynomials
  80323. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80324. one. If we call the above polynomial p, and represent a byte as the
  80325. polynomial q, also with the lowest power in the most significant bit (so the
  80326. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80327. where a mod b means the remainder after dividing a by b.
  80328. This calculation is done using the shift-register method of multiplying and
  80329. taking the remainder. The register is initialized to zero, and for each
  80330. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80331. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80332. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80333. out is a one). We start with the highest power (least significant bit) of
  80334. q and repeat for all eight bits of q.
  80335. The first table is simply the CRC of all possible eight bit values. This is
  80336. all the information needed to generate CRCs on data a byte at a time for all
  80337. combinations of CRC register values and incoming bytes. The remaining tables
  80338. allow for word-at-a-time CRC calculation for both big-endian and little-
  80339. endian machines, where a word is four bytes.
  80340. */
  80341. local void make_crc_table()
  80342. {
  80343. unsigned long c;
  80344. int n, k;
  80345. unsigned long poly; /* polynomial exclusive-or pattern */
  80346. /* terms of polynomial defining this crc (except x^32): */
  80347. static volatile int first = 1; /* flag to limit concurrent making */
  80348. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80349. /* See if another task is already doing this (not thread-safe, but better
  80350. than nothing -- significantly reduces duration of vulnerability in
  80351. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80352. if (first) {
  80353. first = 0;
  80354. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80355. poly = 0UL;
  80356. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80357. poly |= 1UL << (31 - p[n]);
  80358. /* generate a crc for every 8-bit value */
  80359. for (n = 0; n < 256; n++) {
  80360. c = (unsigned long)n;
  80361. for (k = 0; k < 8; k++)
  80362. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80363. crc_table[0][n] = c;
  80364. }
  80365. #ifdef BYFOUR
  80366. /* generate crc for each value followed by one, two, and three zeros,
  80367. and then the byte reversal of those as well as the first table */
  80368. for (n = 0; n < 256; n++) {
  80369. c = crc_table[0][n];
  80370. crc_table[4][n] = REV(c);
  80371. for (k = 1; k < 4; k++) {
  80372. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80373. crc_table[k][n] = c;
  80374. crc_table[k + 4][n] = REV(c);
  80375. }
  80376. }
  80377. #endif /* BYFOUR */
  80378. crc_table_empty = 0;
  80379. }
  80380. else { /* not first */
  80381. /* wait for the other guy to finish (not efficient, but rare) */
  80382. while (crc_table_empty)
  80383. ;
  80384. }
  80385. #ifdef MAKECRCH
  80386. /* write out CRC tables to crc32.h */
  80387. {
  80388. FILE *out;
  80389. out = fopen("crc32.h", "w");
  80390. if (out == NULL) return;
  80391. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80392. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80393. fprintf(out, "local const unsigned long FAR ");
  80394. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80395. write_table(out, crc_table[0]);
  80396. # ifdef BYFOUR
  80397. fprintf(out, "#ifdef BYFOUR\n");
  80398. for (k = 1; k < 8; k++) {
  80399. fprintf(out, " },\n {\n");
  80400. write_table(out, crc_table[k]);
  80401. }
  80402. fprintf(out, "#endif\n");
  80403. # endif /* BYFOUR */
  80404. fprintf(out, " }\n};\n");
  80405. fclose(out);
  80406. }
  80407. #endif /* MAKECRCH */
  80408. }
  80409. #ifdef MAKECRCH
  80410. local void write_table(out, table)
  80411. FILE *out;
  80412. const unsigned long FAR *table;
  80413. {
  80414. int n;
  80415. for (n = 0; n < 256; n++)
  80416. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80417. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80418. }
  80419. #endif /* MAKECRCH */
  80420. #else /* !DYNAMIC_CRC_TABLE */
  80421. /* ========================================================================
  80422. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80423. */
  80424. /*** Start of inlined file: crc32.h ***/
  80425. local const unsigned long FAR crc_table[TBLS][256] =
  80426. {
  80427. {
  80428. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80429. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80430. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80431. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80432. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80433. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80434. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80435. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80436. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80437. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80438. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80439. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80440. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80441. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80442. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80443. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80444. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80445. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80446. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80447. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80448. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80449. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80450. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80451. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80452. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80453. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80454. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80455. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80456. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80457. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80458. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80459. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80460. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80461. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80462. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80463. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80464. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80465. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80466. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80467. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80468. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80469. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80470. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80471. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80472. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80473. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80474. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80475. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80476. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80477. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80478. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80479. 0x2d02ef8dUL
  80480. #ifdef BYFOUR
  80481. },
  80482. {
  80483. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80484. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80485. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80486. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80487. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80488. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80489. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80490. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80491. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80492. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80493. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80494. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80495. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80496. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80497. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80498. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80499. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80500. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80501. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80502. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80503. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80504. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80505. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80506. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80507. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80508. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80509. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80510. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80511. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80512. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80513. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80514. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80515. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80516. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80517. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80518. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80519. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80520. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80521. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80522. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80523. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80524. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80525. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80526. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80527. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80528. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80529. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80530. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80531. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80532. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80533. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80534. 0x9324fd72UL
  80535. },
  80536. {
  80537. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80538. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80539. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80540. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80541. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80542. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80543. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80544. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80545. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80546. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80547. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80548. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80549. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80550. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80551. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80552. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80553. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80554. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80555. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80556. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80557. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80558. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80559. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80560. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80561. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80562. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80563. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80564. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80565. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80566. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80567. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80568. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80569. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80570. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80571. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80572. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80573. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80574. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80575. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80576. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80577. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80578. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80579. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80580. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80581. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80582. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80583. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80584. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80585. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80586. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80587. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80588. 0xbe9834edUL
  80589. },
  80590. {
  80591. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80592. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80593. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80594. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80595. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80596. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80597. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80598. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80599. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80600. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80601. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80602. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80603. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80604. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80605. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80606. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80607. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80608. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80609. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80610. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80611. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80612. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80613. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80614. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80615. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80616. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80617. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80618. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80619. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80620. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80621. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80622. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80623. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80624. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80625. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80626. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80627. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80628. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80629. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80630. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80631. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80632. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80633. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80634. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80635. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80636. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80637. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80638. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80639. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80640. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80641. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80642. 0xde0506f1UL
  80643. },
  80644. {
  80645. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80646. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80647. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80648. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80649. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80650. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80651. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80652. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80653. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80654. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80655. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80656. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80657. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80658. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80659. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80660. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80661. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80662. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80663. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80664. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80665. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80666. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80667. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80668. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80669. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80670. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80671. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80672. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80673. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80674. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80675. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80676. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80677. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80678. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80679. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80680. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80681. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80682. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80683. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80684. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80685. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80686. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80687. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80688. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80689. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80690. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80691. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80692. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80693. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80694. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80695. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80696. 0x8def022dUL
  80697. },
  80698. {
  80699. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80700. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80701. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80702. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80703. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80704. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80705. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80706. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80707. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80708. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80709. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80710. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80711. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80712. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80713. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80714. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80715. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80716. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80717. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80718. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80719. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80720. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80721. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80722. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80723. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80724. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80725. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80726. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80727. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80728. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80729. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80730. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80731. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80732. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80733. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80734. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80735. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80736. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80737. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80738. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80739. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80740. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80741. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80742. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80743. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80744. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80745. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80746. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80747. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80748. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80749. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80750. 0x72fd2493UL
  80751. },
  80752. {
  80753. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80754. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80755. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80756. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80757. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80758. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80759. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80760. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80761. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80762. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80763. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80764. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80765. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80766. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80767. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80768. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80769. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80770. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80771. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80772. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80773. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80774. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80775. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80776. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80777. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80778. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80779. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80780. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80781. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80782. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80783. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80784. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80785. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80786. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80787. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80788. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80789. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80790. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80791. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80792. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80793. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80794. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80795. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80796. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80797. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80798. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80799. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80800. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80801. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80802. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80803. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80804. 0xed3498beUL
  80805. },
  80806. {
  80807. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80808. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80809. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80810. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80811. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80812. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80813. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80814. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80815. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80816. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80817. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80818. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80819. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80820. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80821. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80822. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80823. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80824. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80825. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80826. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80827. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80828. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80829. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80830. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80831. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80832. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80833. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80834. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80835. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80836. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80837. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80838. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80839. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80840. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80841. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80842. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80843. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80844. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80845. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80846. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80847. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80848. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80849. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80850. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80851. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80852. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80853. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80854. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80855. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80856. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80857. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80858. 0xf10605deUL
  80859. #endif
  80860. }
  80861. };
  80862. /*** End of inlined file: crc32.h ***/
  80863. #endif /* DYNAMIC_CRC_TABLE */
  80864. /* =========================================================================
  80865. * This function can be used by asm versions of crc32()
  80866. */
  80867. const unsigned long FAR * ZEXPORT get_crc_table()
  80868. {
  80869. #ifdef DYNAMIC_CRC_TABLE
  80870. if (crc_table_empty)
  80871. make_crc_table();
  80872. #endif /* DYNAMIC_CRC_TABLE */
  80873. return (const unsigned long FAR *)crc_table;
  80874. }
  80875. /* ========================================================================= */
  80876. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80877. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80878. /* ========================================================================= */
  80879. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80880. {
  80881. if (buf == Z_NULL) return 0UL;
  80882. #ifdef DYNAMIC_CRC_TABLE
  80883. if (crc_table_empty)
  80884. make_crc_table();
  80885. #endif /* DYNAMIC_CRC_TABLE */
  80886. #ifdef BYFOUR
  80887. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80888. u4 endian;
  80889. endian = 1;
  80890. if (*((unsigned char *)(&endian)))
  80891. return crc32_little(crc, buf, len);
  80892. else
  80893. return crc32_big(crc, buf, len);
  80894. }
  80895. #endif /* BYFOUR */
  80896. crc = crc ^ 0xffffffffUL;
  80897. while (len >= 8) {
  80898. DO8;
  80899. len -= 8;
  80900. }
  80901. if (len) do {
  80902. DO1;
  80903. } while (--len);
  80904. return crc ^ 0xffffffffUL;
  80905. }
  80906. #ifdef BYFOUR
  80907. /* ========================================================================= */
  80908. #define DOLIT4 c ^= *buf4++; \
  80909. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80910. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80911. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80912. /* ========================================================================= */
  80913. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80914. {
  80915. register u4 c;
  80916. register const u4 FAR *buf4;
  80917. c = (u4)crc;
  80918. c = ~c;
  80919. while (len && ((ptrdiff_t)buf & 3)) {
  80920. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80921. len--;
  80922. }
  80923. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80924. while (len >= 32) {
  80925. DOLIT32;
  80926. len -= 32;
  80927. }
  80928. while (len >= 4) {
  80929. DOLIT4;
  80930. len -= 4;
  80931. }
  80932. buf = (const unsigned char FAR *)buf4;
  80933. if (len) do {
  80934. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80935. } while (--len);
  80936. c = ~c;
  80937. return (unsigned long)c;
  80938. }
  80939. /* ========================================================================= */
  80940. #define DOBIG4 c ^= *++buf4; \
  80941. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80942. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80943. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80944. /* ========================================================================= */
  80945. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80946. {
  80947. register u4 c;
  80948. register const u4 FAR *buf4;
  80949. c = REV((u4)crc);
  80950. c = ~c;
  80951. while (len && ((ptrdiff_t)buf & 3)) {
  80952. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80953. len--;
  80954. }
  80955. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80956. buf4--;
  80957. while (len >= 32) {
  80958. DOBIG32;
  80959. len -= 32;
  80960. }
  80961. while (len >= 4) {
  80962. DOBIG4;
  80963. len -= 4;
  80964. }
  80965. buf4++;
  80966. buf = (const unsigned char FAR *)buf4;
  80967. if (len) do {
  80968. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80969. } while (--len);
  80970. c = ~c;
  80971. return (unsigned long)(REV(c));
  80972. }
  80973. #endif /* BYFOUR */
  80974. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80975. /* ========================================================================= */
  80976. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80977. {
  80978. unsigned long sum;
  80979. sum = 0;
  80980. while (vec) {
  80981. if (vec & 1)
  80982. sum ^= *mat;
  80983. vec >>= 1;
  80984. mat++;
  80985. }
  80986. return sum;
  80987. }
  80988. /* ========================================================================= */
  80989. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80990. {
  80991. int n;
  80992. for (n = 0; n < GF2_DIM; n++)
  80993. square[n] = gf2_matrix_times(mat, mat[n]);
  80994. }
  80995. /* ========================================================================= */
  80996. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80997. {
  80998. int n;
  80999. unsigned long row;
  81000. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81001. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81002. /* degenerate case */
  81003. if (len2 == 0)
  81004. return crc1;
  81005. /* put operator for one zero bit in odd */
  81006. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81007. row = 1;
  81008. for (n = 1; n < GF2_DIM; n++) {
  81009. odd[n] = row;
  81010. row <<= 1;
  81011. }
  81012. /* put operator for two zero bits in even */
  81013. gf2_matrix_square(even, odd);
  81014. /* put operator for four zero bits in odd */
  81015. gf2_matrix_square(odd, even);
  81016. /* apply len2 zeros to crc1 (first square will put the operator for one
  81017. zero byte, eight zero bits, in even) */
  81018. do {
  81019. /* apply zeros operator for this bit of len2 */
  81020. gf2_matrix_square(even, odd);
  81021. if (len2 & 1)
  81022. crc1 = gf2_matrix_times(even, crc1);
  81023. len2 >>= 1;
  81024. /* if no more bits set, then done */
  81025. if (len2 == 0)
  81026. break;
  81027. /* another iteration of the loop with odd and even swapped */
  81028. gf2_matrix_square(odd, even);
  81029. if (len2 & 1)
  81030. crc1 = gf2_matrix_times(odd, crc1);
  81031. len2 >>= 1;
  81032. /* if no more bits set, then done */
  81033. } while (len2 != 0);
  81034. /* return combined crc */
  81035. crc1 ^= crc2;
  81036. return crc1;
  81037. }
  81038. /*** End of inlined file: crc32.c ***/
  81039. /*** Start of inlined file: deflate.c ***/
  81040. /*
  81041. * ALGORITHM
  81042. *
  81043. * The "deflation" process depends on being able to identify portions
  81044. * of the input text which are identical to earlier input (within a
  81045. * sliding window trailing behind the input currently being processed).
  81046. *
  81047. * The most straightforward technique turns out to be the fastest for
  81048. * most input files: try all possible matches and select the longest.
  81049. * The key feature of this algorithm is that insertions into the string
  81050. * dictionary are very simple and thus fast, and deletions are avoided
  81051. * completely. Insertions are performed at each input character, whereas
  81052. * string matches are performed only when the previous match ends. So it
  81053. * is preferable to spend more time in matches to allow very fast string
  81054. * insertions and avoid deletions. The matching algorithm for small
  81055. * strings is inspired from that of Rabin & Karp. A brute force approach
  81056. * is used to find longer strings when a small match has been found.
  81057. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81058. * (by Leonid Broukhis).
  81059. * A previous version of this file used a more sophisticated algorithm
  81060. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81061. * time, but has a larger average cost, uses more memory and is patented.
  81062. * However the F&G algorithm may be faster for some highly redundant
  81063. * files if the parameter max_chain_length (described below) is too large.
  81064. *
  81065. * ACKNOWLEDGEMENTS
  81066. *
  81067. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81068. * I found it in 'freeze' written by Leonid Broukhis.
  81069. * Thanks to many people for bug reports and testing.
  81070. *
  81071. * REFERENCES
  81072. *
  81073. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81074. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81075. *
  81076. * A description of the Rabin and Karp algorithm is given in the book
  81077. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81078. *
  81079. * Fiala,E.R., and Greene,D.H.
  81080. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81081. *
  81082. */
  81083. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81084. /*** Start of inlined file: deflate.h ***/
  81085. /* WARNING: this file should *not* be used by applications. It is
  81086. part of the implementation of the compression library and is
  81087. subject to change. Applications should only use zlib.h.
  81088. */
  81089. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81090. #ifndef DEFLATE_H
  81091. #define DEFLATE_H
  81092. /* define NO_GZIP when compiling if you want to disable gzip header and
  81093. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81094. the crc code when it is not needed. For shared libraries, gzip encoding
  81095. should be left enabled. */
  81096. #ifndef NO_GZIP
  81097. # define GZIP
  81098. #endif
  81099. #define NO_DUMMY_DECL
  81100. /* ===========================================================================
  81101. * Internal compression state.
  81102. */
  81103. #define LENGTH_CODES 29
  81104. /* number of length codes, not counting the special END_BLOCK code */
  81105. #define LITERALS 256
  81106. /* number of literal bytes 0..255 */
  81107. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81108. /* number of Literal or Length codes, including the END_BLOCK code */
  81109. #define D_CODES 30
  81110. /* number of distance codes */
  81111. #define BL_CODES 19
  81112. /* number of codes used to transfer the bit lengths */
  81113. #define HEAP_SIZE (2*L_CODES+1)
  81114. /* maximum heap size */
  81115. #define MAX_BITS 15
  81116. /* All codes must not exceed MAX_BITS bits */
  81117. #define INIT_STATE 42
  81118. #define EXTRA_STATE 69
  81119. #define NAME_STATE 73
  81120. #define COMMENT_STATE 91
  81121. #define HCRC_STATE 103
  81122. #define BUSY_STATE 113
  81123. #define FINISH_STATE 666
  81124. /* Stream status */
  81125. /* Data structure describing a single value and its code string. */
  81126. typedef struct ct_data_s {
  81127. union {
  81128. ush freq; /* frequency count */
  81129. ush code; /* bit string */
  81130. } fc;
  81131. union {
  81132. ush dad; /* father node in Huffman tree */
  81133. ush len; /* length of bit string */
  81134. } dl;
  81135. } FAR ct_data;
  81136. #define Freq fc.freq
  81137. #define Code fc.code
  81138. #define Dad dl.dad
  81139. #define Len dl.len
  81140. typedef struct static_tree_desc_s static_tree_desc;
  81141. typedef struct tree_desc_s {
  81142. ct_data *dyn_tree; /* the dynamic tree */
  81143. int max_code; /* largest code with non zero frequency */
  81144. static_tree_desc *stat_desc; /* the corresponding static tree */
  81145. } FAR tree_desc;
  81146. typedef ush Pos;
  81147. typedef Pos FAR Posf;
  81148. typedef unsigned IPos;
  81149. /* A Pos is an index in the character window. We use short instead of int to
  81150. * save space in the various tables. IPos is used only for parameter passing.
  81151. */
  81152. typedef struct internal_state {
  81153. z_streamp strm; /* pointer back to this zlib stream */
  81154. int status; /* as the name implies */
  81155. Bytef *pending_buf; /* output still pending */
  81156. ulg pending_buf_size; /* size of pending_buf */
  81157. Bytef *pending_out; /* next pending byte to output to the stream */
  81158. uInt pending; /* nb of bytes in the pending buffer */
  81159. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81160. gz_headerp gzhead; /* gzip header information to write */
  81161. uInt gzindex; /* where in extra, name, or comment */
  81162. Byte method; /* STORED (for zip only) or DEFLATED */
  81163. int last_flush; /* value of flush param for previous deflate call */
  81164. /* used by deflate.c: */
  81165. uInt w_size; /* LZ77 window size (32K by default) */
  81166. uInt w_bits; /* log2(w_size) (8..16) */
  81167. uInt w_mask; /* w_size - 1 */
  81168. Bytef *window;
  81169. /* Sliding window. Input bytes are read into the second half of the window,
  81170. * and move to the first half later to keep a dictionary of at least wSize
  81171. * bytes. With this organization, matches are limited to a distance of
  81172. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81173. * performed with a length multiple of the block size. Also, it limits
  81174. * the window size to 64K, which is quite useful on MSDOS.
  81175. * To do: use the user input buffer as sliding window.
  81176. */
  81177. ulg window_size;
  81178. /* Actual size of window: 2*wSize, except when the user input buffer
  81179. * is directly used as sliding window.
  81180. */
  81181. Posf *prev;
  81182. /* Link to older string with same hash index. To limit the size of this
  81183. * array to 64K, this link is maintained only for the last 32K strings.
  81184. * An index in this array is thus a window index modulo 32K.
  81185. */
  81186. Posf *head; /* Heads of the hash chains or NIL. */
  81187. uInt ins_h; /* hash index of string to be inserted */
  81188. uInt hash_size; /* number of elements in hash table */
  81189. uInt hash_bits; /* log2(hash_size) */
  81190. uInt hash_mask; /* hash_size-1 */
  81191. uInt hash_shift;
  81192. /* Number of bits by which ins_h must be shifted at each input
  81193. * step. It must be such that after MIN_MATCH steps, the oldest
  81194. * byte no longer takes part in the hash key, that is:
  81195. * hash_shift * MIN_MATCH >= hash_bits
  81196. */
  81197. long block_start;
  81198. /* Window position at the beginning of the current output block. Gets
  81199. * negative when the window is moved backwards.
  81200. */
  81201. uInt match_length; /* length of best match */
  81202. IPos prev_match; /* previous match */
  81203. int match_available; /* set if previous match exists */
  81204. uInt strstart; /* start of string to insert */
  81205. uInt match_start; /* start of matching string */
  81206. uInt lookahead; /* number of valid bytes ahead in window */
  81207. uInt prev_length;
  81208. /* Length of the best match at previous step. Matches not greater than this
  81209. * are discarded. This is used in the lazy match evaluation.
  81210. */
  81211. uInt max_chain_length;
  81212. /* To speed up deflation, hash chains are never searched beyond this
  81213. * length. A higher limit improves compression ratio but degrades the
  81214. * speed.
  81215. */
  81216. uInt max_lazy_match;
  81217. /* Attempt to find a better match only when the current match is strictly
  81218. * smaller than this value. This mechanism is used only for compression
  81219. * levels >= 4.
  81220. */
  81221. # define max_insert_length max_lazy_match
  81222. /* Insert new strings in the hash table only if the match length is not
  81223. * greater than this length. This saves time but degrades compression.
  81224. * max_insert_length is used only for compression levels <= 3.
  81225. */
  81226. int level; /* compression level (1..9) */
  81227. int strategy; /* favor or force Huffman coding*/
  81228. uInt good_match;
  81229. /* Use a faster search when the previous match is longer than this */
  81230. int nice_match; /* Stop searching when current match exceeds this */
  81231. /* used by trees.c: */
  81232. /* Didn't use ct_data typedef below to supress compiler warning */
  81233. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81234. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81235. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81236. struct tree_desc_s l_desc; /* desc. for literal tree */
  81237. struct tree_desc_s d_desc; /* desc. for distance tree */
  81238. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81239. ush bl_count[MAX_BITS+1];
  81240. /* number of codes at each bit length for an optimal tree */
  81241. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81242. int heap_len; /* number of elements in the heap */
  81243. int heap_max; /* element of largest frequency */
  81244. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81245. * The same heap array is used to build all trees.
  81246. */
  81247. uch depth[2*L_CODES+1];
  81248. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81249. */
  81250. uchf *l_buf; /* buffer for literals or lengths */
  81251. uInt lit_bufsize;
  81252. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81253. * limiting lit_bufsize to 64K:
  81254. * - frequencies can be kept in 16 bit counters
  81255. * - if compression is not successful for the first block, all input
  81256. * data is still in the window so we can still emit a stored block even
  81257. * when input comes from standard input. (This can also be done for
  81258. * all blocks if lit_bufsize is not greater than 32K.)
  81259. * - if compression is not successful for a file smaller than 64K, we can
  81260. * even emit a stored file instead of a stored block (saving 5 bytes).
  81261. * This is applicable only for zip (not gzip or zlib).
  81262. * - creating new Huffman trees less frequently may not provide fast
  81263. * adaptation to changes in the input data statistics. (Take for
  81264. * example a binary file with poorly compressible code followed by
  81265. * a highly compressible string table.) Smaller buffer sizes give
  81266. * fast adaptation but have of course the overhead of transmitting
  81267. * trees more frequently.
  81268. * - I can't count above 4
  81269. */
  81270. uInt last_lit; /* running index in l_buf */
  81271. ushf *d_buf;
  81272. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81273. * the same number of elements. To use different lengths, an extra flag
  81274. * array would be necessary.
  81275. */
  81276. ulg opt_len; /* bit length of current block with optimal trees */
  81277. ulg static_len; /* bit length of current block with static trees */
  81278. uInt matches; /* number of string matches in current block */
  81279. int last_eob_len; /* bit length of EOB code for last block */
  81280. #ifdef DEBUG
  81281. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81282. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81283. #endif
  81284. ush bi_buf;
  81285. /* Output buffer. bits are inserted starting at the bottom (least
  81286. * significant bits).
  81287. */
  81288. int bi_valid;
  81289. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81290. * are always zero.
  81291. */
  81292. } FAR deflate_state;
  81293. /* Output a byte on the stream.
  81294. * IN assertion: there is enough room in pending_buf.
  81295. */
  81296. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81297. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81298. /* Minimum amount of lookahead, except at the end of the input file.
  81299. * See deflate.c for comments about the MIN_MATCH+1.
  81300. */
  81301. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81302. /* In order to simplify the code, particularly on 16 bit machines, match
  81303. * distances are limited to MAX_DIST instead of WSIZE.
  81304. */
  81305. /* in trees.c */
  81306. void _tr_init OF((deflate_state *s));
  81307. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81308. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81309. int eof));
  81310. void _tr_align OF((deflate_state *s));
  81311. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81312. int eof));
  81313. #define d_code(dist) \
  81314. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81315. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81316. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81317. * used.
  81318. */
  81319. #ifndef DEBUG
  81320. /* Inline versions of _tr_tally for speed: */
  81321. #if defined(GEN_TREES_H) || !defined(STDC)
  81322. extern uch _length_code[];
  81323. extern uch _dist_code[];
  81324. #else
  81325. extern const uch _length_code[];
  81326. extern const uch _dist_code[];
  81327. #endif
  81328. # define _tr_tally_lit(s, c, flush) \
  81329. { uch cc = (c); \
  81330. s->d_buf[s->last_lit] = 0; \
  81331. s->l_buf[s->last_lit++] = cc; \
  81332. s->dyn_ltree[cc].Freq++; \
  81333. flush = (s->last_lit == s->lit_bufsize-1); \
  81334. }
  81335. # define _tr_tally_dist(s, distance, length, flush) \
  81336. { uch len = (length); \
  81337. ush dist = (distance); \
  81338. s->d_buf[s->last_lit] = dist; \
  81339. s->l_buf[s->last_lit++] = len; \
  81340. dist--; \
  81341. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81342. s->dyn_dtree[d_code(dist)].Freq++; \
  81343. flush = (s->last_lit == s->lit_bufsize-1); \
  81344. }
  81345. #else
  81346. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81347. # define _tr_tally_dist(s, distance, length, flush) \
  81348. flush = _tr_tally(s, distance, length)
  81349. #endif
  81350. #endif /* DEFLATE_H */
  81351. /*** End of inlined file: deflate.h ***/
  81352. const char deflate_copyright[] =
  81353. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81354. /*
  81355. If you use the zlib library in a product, an acknowledgment is welcome
  81356. in the documentation of your product. If for some reason you cannot
  81357. include such an acknowledgment, I would appreciate that you keep this
  81358. copyright string in the executable of your product.
  81359. */
  81360. /* ===========================================================================
  81361. * Function prototypes.
  81362. */
  81363. typedef enum {
  81364. need_more, /* block not completed, need more input or more output */
  81365. block_done, /* block flush performed */
  81366. finish_started, /* finish started, need only more output at next deflate */
  81367. finish_done /* finish done, accept no more input or output */
  81368. } block_state;
  81369. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81370. /* Compression function. Returns the block state after the call. */
  81371. local void fill_window OF((deflate_state *s));
  81372. local block_state deflate_stored OF((deflate_state *s, int flush));
  81373. local block_state deflate_fast OF((deflate_state *s, int flush));
  81374. #ifndef FASTEST
  81375. local block_state deflate_slow OF((deflate_state *s, int flush));
  81376. #endif
  81377. local void lm_init OF((deflate_state *s));
  81378. local void putShortMSB OF((deflate_state *s, uInt b));
  81379. local void flush_pending OF((z_streamp strm));
  81380. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81381. #ifndef FASTEST
  81382. #ifdef ASMV
  81383. void match_init OF((void)); /* asm code initialization */
  81384. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81385. #else
  81386. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81387. #endif
  81388. #endif
  81389. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81390. #ifdef DEBUG
  81391. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81392. int length));
  81393. #endif
  81394. /* ===========================================================================
  81395. * Local data
  81396. */
  81397. #define NIL 0
  81398. /* Tail of hash chains */
  81399. #ifndef TOO_FAR
  81400. # define TOO_FAR 4096
  81401. #endif
  81402. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81403. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81404. /* Minimum amount of lookahead, except at the end of the input file.
  81405. * See deflate.c for comments about the MIN_MATCH+1.
  81406. */
  81407. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81408. * the desired pack level (0..9). The values given below have been tuned to
  81409. * exclude worst case performance for pathological files. Better values may be
  81410. * found for specific files.
  81411. */
  81412. typedef struct config_s {
  81413. ush good_length; /* reduce lazy search above this match length */
  81414. ush max_lazy; /* do not perform lazy search above this match length */
  81415. ush nice_length; /* quit search above this match length */
  81416. ush max_chain;
  81417. compress_func func;
  81418. } config;
  81419. #ifdef FASTEST
  81420. local const config configuration_table[2] = {
  81421. /* good lazy nice chain */
  81422. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81423. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81424. #else
  81425. local const config configuration_table[10] = {
  81426. /* good lazy nice chain */
  81427. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81428. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81429. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81430. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81431. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81432. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81433. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81434. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81435. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81436. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81437. #endif
  81438. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81439. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81440. * meaning.
  81441. */
  81442. #define EQUAL 0
  81443. /* result of memcmp for equal strings */
  81444. #ifndef NO_DUMMY_DECL
  81445. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81446. #endif
  81447. /* ===========================================================================
  81448. * Update a hash value with the given input byte
  81449. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81450. * input characters, so that a running hash key can be computed from the
  81451. * previous key instead of complete recalculation each time.
  81452. */
  81453. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81454. /* ===========================================================================
  81455. * Insert string str in the dictionary and set match_head to the previous head
  81456. * of the hash chain (the most recent string with same hash key). Return
  81457. * the previous length of the hash chain.
  81458. * If this file is compiled with -DFASTEST, the compression level is forced
  81459. * to 1, and no hash chains are maintained.
  81460. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81461. * input characters and the first MIN_MATCH bytes of str are valid
  81462. * (except for the last MIN_MATCH-1 bytes of the input file).
  81463. */
  81464. #ifdef FASTEST
  81465. #define INSERT_STRING(s, str, match_head) \
  81466. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81467. match_head = s->head[s->ins_h], \
  81468. s->head[s->ins_h] = (Pos)(str))
  81469. #else
  81470. #define INSERT_STRING(s, str, match_head) \
  81471. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81472. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81473. s->head[s->ins_h] = (Pos)(str))
  81474. #endif
  81475. /* ===========================================================================
  81476. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81477. * prev[] will be initialized on the fly.
  81478. */
  81479. #define CLEAR_HASH(s) \
  81480. s->head[s->hash_size-1] = NIL; \
  81481. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81482. /* ========================================================================= */
  81483. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81484. {
  81485. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81486. Z_DEFAULT_STRATEGY, version, stream_size);
  81487. /* To do: ignore strm->next_in if we use it as window */
  81488. }
  81489. /* ========================================================================= */
  81490. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81491. {
  81492. deflate_state *s;
  81493. int wrap = 1;
  81494. static const char my_version[] = ZLIB_VERSION;
  81495. ushf *overlay;
  81496. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81497. * output size for (length,distance) codes is <= 24 bits.
  81498. */
  81499. if (version == Z_NULL || version[0] != my_version[0] ||
  81500. stream_size != sizeof(z_stream)) {
  81501. return Z_VERSION_ERROR;
  81502. }
  81503. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81504. strm->msg = Z_NULL;
  81505. if (strm->zalloc == (alloc_func)0) {
  81506. strm->zalloc = zcalloc;
  81507. strm->opaque = (voidpf)0;
  81508. }
  81509. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81510. #ifdef FASTEST
  81511. if (level != 0) level = 1;
  81512. #else
  81513. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81514. #endif
  81515. if (windowBits < 0) { /* suppress zlib wrapper */
  81516. wrap = 0;
  81517. windowBits = -windowBits;
  81518. }
  81519. #ifdef GZIP
  81520. else if (windowBits > 15) {
  81521. wrap = 2; /* write gzip wrapper instead */
  81522. windowBits -= 16;
  81523. }
  81524. #endif
  81525. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81526. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81527. strategy < 0 || strategy > Z_FIXED) {
  81528. return Z_STREAM_ERROR;
  81529. }
  81530. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81531. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81532. if (s == Z_NULL) return Z_MEM_ERROR;
  81533. strm->state = (struct internal_state FAR *)s;
  81534. s->strm = strm;
  81535. s->wrap = wrap;
  81536. s->gzhead = Z_NULL;
  81537. s->w_bits = windowBits;
  81538. s->w_size = 1 << s->w_bits;
  81539. s->w_mask = s->w_size - 1;
  81540. s->hash_bits = memLevel + 7;
  81541. s->hash_size = 1 << s->hash_bits;
  81542. s->hash_mask = s->hash_size - 1;
  81543. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81544. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81545. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81546. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81547. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81548. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81549. s->pending_buf = (uchf *) overlay;
  81550. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81551. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81552. s->pending_buf == Z_NULL) {
  81553. s->status = FINISH_STATE;
  81554. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81555. deflateEnd (strm);
  81556. return Z_MEM_ERROR;
  81557. }
  81558. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81559. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81560. s->level = level;
  81561. s->strategy = strategy;
  81562. s->method = (Byte)method;
  81563. return deflateReset(strm);
  81564. }
  81565. /* ========================================================================= */
  81566. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81567. {
  81568. deflate_state *s;
  81569. uInt length = dictLength;
  81570. uInt n;
  81571. IPos hash_head = 0;
  81572. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81573. strm->state->wrap == 2 ||
  81574. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81575. return Z_STREAM_ERROR;
  81576. s = strm->state;
  81577. if (s->wrap)
  81578. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81579. if (length < MIN_MATCH) return Z_OK;
  81580. if (length > MAX_DIST(s)) {
  81581. length = MAX_DIST(s);
  81582. dictionary += dictLength - length; /* use the tail of the dictionary */
  81583. }
  81584. zmemcpy(s->window, dictionary, length);
  81585. s->strstart = length;
  81586. s->block_start = (long)length;
  81587. /* Insert all strings in the hash table (except for the last two bytes).
  81588. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81589. * call of fill_window.
  81590. */
  81591. s->ins_h = s->window[0];
  81592. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81593. for (n = 0; n <= length - MIN_MATCH; n++) {
  81594. INSERT_STRING(s, n, hash_head);
  81595. }
  81596. if (hash_head) hash_head = 0; /* to make compiler happy */
  81597. return Z_OK;
  81598. }
  81599. /* ========================================================================= */
  81600. int ZEXPORT deflateReset (z_streamp strm)
  81601. {
  81602. deflate_state *s;
  81603. if (strm == Z_NULL || strm->state == Z_NULL ||
  81604. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81605. return Z_STREAM_ERROR;
  81606. }
  81607. strm->total_in = strm->total_out = 0;
  81608. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81609. strm->data_type = Z_UNKNOWN;
  81610. s = (deflate_state *)strm->state;
  81611. s->pending = 0;
  81612. s->pending_out = s->pending_buf;
  81613. if (s->wrap < 0) {
  81614. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81615. }
  81616. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81617. strm->adler =
  81618. #ifdef GZIP
  81619. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81620. #endif
  81621. adler32(0L, Z_NULL, 0);
  81622. s->last_flush = Z_NO_FLUSH;
  81623. _tr_init(s);
  81624. lm_init(s);
  81625. return Z_OK;
  81626. }
  81627. /* ========================================================================= */
  81628. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81629. {
  81630. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81631. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81632. strm->state->gzhead = head;
  81633. return Z_OK;
  81634. }
  81635. /* ========================================================================= */
  81636. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81637. {
  81638. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81639. strm->state->bi_valid = bits;
  81640. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81641. return Z_OK;
  81642. }
  81643. /* ========================================================================= */
  81644. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81645. {
  81646. deflate_state *s;
  81647. compress_func func;
  81648. int err = Z_OK;
  81649. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81650. s = strm->state;
  81651. #ifdef FASTEST
  81652. if (level != 0) level = 1;
  81653. #else
  81654. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81655. #endif
  81656. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81657. return Z_STREAM_ERROR;
  81658. }
  81659. func = configuration_table[s->level].func;
  81660. if (func != configuration_table[level].func && strm->total_in != 0) {
  81661. /* Flush the last buffer: */
  81662. err = deflate(strm, Z_PARTIAL_FLUSH);
  81663. }
  81664. if (s->level != level) {
  81665. s->level = level;
  81666. s->max_lazy_match = configuration_table[level].max_lazy;
  81667. s->good_match = configuration_table[level].good_length;
  81668. s->nice_match = configuration_table[level].nice_length;
  81669. s->max_chain_length = configuration_table[level].max_chain;
  81670. }
  81671. s->strategy = strategy;
  81672. return err;
  81673. }
  81674. /* ========================================================================= */
  81675. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81676. {
  81677. deflate_state *s;
  81678. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81679. s = strm->state;
  81680. s->good_match = good_length;
  81681. s->max_lazy_match = max_lazy;
  81682. s->nice_match = nice_length;
  81683. s->max_chain_length = max_chain;
  81684. return Z_OK;
  81685. }
  81686. /* =========================================================================
  81687. * For the default windowBits of 15 and memLevel of 8, this function returns
  81688. * a close to exact, as well as small, upper bound on the compressed size.
  81689. * They are coded as constants here for a reason--if the #define's are
  81690. * changed, then this function needs to be changed as well. The return
  81691. * value for 15 and 8 only works for those exact settings.
  81692. *
  81693. * For any setting other than those defaults for windowBits and memLevel,
  81694. * the value returned is a conservative worst case for the maximum expansion
  81695. * resulting from using fixed blocks instead of stored blocks, which deflate
  81696. * can emit on compressed data for some combinations of the parameters.
  81697. *
  81698. * This function could be more sophisticated to provide closer upper bounds
  81699. * for every combination of windowBits and memLevel, as well as wrap.
  81700. * But even the conservative upper bound of about 14% expansion does not
  81701. * seem onerous for output buffer allocation.
  81702. */
  81703. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81704. {
  81705. deflate_state *s;
  81706. uLong destLen;
  81707. /* conservative upper bound */
  81708. destLen = sourceLen +
  81709. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81710. /* if can't get parameters, return conservative bound */
  81711. if (strm == Z_NULL || strm->state == Z_NULL)
  81712. return destLen;
  81713. /* if not default parameters, return conservative bound */
  81714. s = strm->state;
  81715. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81716. return destLen;
  81717. /* default settings: return tight bound for that case */
  81718. return compressBound(sourceLen);
  81719. }
  81720. /* =========================================================================
  81721. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81722. * IN assertion: the stream state is correct and there is enough room in
  81723. * pending_buf.
  81724. */
  81725. local void putShortMSB (deflate_state *s, uInt b)
  81726. {
  81727. put_byte(s, (Byte)(b >> 8));
  81728. put_byte(s, (Byte)(b & 0xff));
  81729. }
  81730. /* =========================================================================
  81731. * Flush as much pending output as possible. All deflate() output goes
  81732. * through this function so some applications may wish to modify it
  81733. * to avoid allocating a large strm->next_out buffer and copying into it.
  81734. * (See also read_buf()).
  81735. */
  81736. local void flush_pending (z_streamp strm)
  81737. {
  81738. unsigned len = strm->state->pending;
  81739. if (len > strm->avail_out) len = strm->avail_out;
  81740. if (len == 0) return;
  81741. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81742. strm->next_out += len;
  81743. strm->state->pending_out += len;
  81744. strm->total_out += len;
  81745. strm->avail_out -= len;
  81746. strm->state->pending -= len;
  81747. if (strm->state->pending == 0) {
  81748. strm->state->pending_out = strm->state->pending_buf;
  81749. }
  81750. }
  81751. /* ========================================================================= */
  81752. int ZEXPORT deflate (z_streamp strm, int flush)
  81753. {
  81754. int old_flush; /* value of flush param for previous deflate call */
  81755. deflate_state *s;
  81756. if (strm == Z_NULL || strm->state == Z_NULL ||
  81757. flush > Z_FINISH || flush < 0) {
  81758. return Z_STREAM_ERROR;
  81759. }
  81760. s = strm->state;
  81761. if (strm->next_out == Z_NULL ||
  81762. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81763. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81764. ERR_RETURN(strm, Z_STREAM_ERROR);
  81765. }
  81766. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81767. s->strm = strm; /* just in case */
  81768. old_flush = s->last_flush;
  81769. s->last_flush = flush;
  81770. /* Write the header */
  81771. if (s->status == INIT_STATE) {
  81772. #ifdef GZIP
  81773. if (s->wrap == 2) {
  81774. strm->adler = crc32(0L, Z_NULL, 0);
  81775. put_byte(s, 31);
  81776. put_byte(s, 139);
  81777. put_byte(s, 8);
  81778. if (s->gzhead == NULL) {
  81779. put_byte(s, 0);
  81780. put_byte(s, 0);
  81781. put_byte(s, 0);
  81782. put_byte(s, 0);
  81783. put_byte(s, 0);
  81784. put_byte(s, s->level == 9 ? 2 :
  81785. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81786. 4 : 0));
  81787. put_byte(s, OS_CODE);
  81788. s->status = BUSY_STATE;
  81789. }
  81790. else {
  81791. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81792. (s->gzhead->hcrc ? 2 : 0) +
  81793. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81794. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81795. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81796. );
  81797. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81798. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81799. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81800. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81801. put_byte(s, s->level == 9 ? 2 :
  81802. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81803. 4 : 0));
  81804. put_byte(s, s->gzhead->os & 0xff);
  81805. if (s->gzhead->extra != NULL) {
  81806. put_byte(s, s->gzhead->extra_len & 0xff);
  81807. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81808. }
  81809. if (s->gzhead->hcrc)
  81810. strm->adler = crc32(strm->adler, s->pending_buf,
  81811. s->pending);
  81812. s->gzindex = 0;
  81813. s->status = EXTRA_STATE;
  81814. }
  81815. }
  81816. else
  81817. #endif
  81818. {
  81819. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81820. uInt level_flags;
  81821. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81822. level_flags = 0;
  81823. else if (s->level < 6)
  81824. level_flags = 1;
  81825. else if (s->level == 6)
  81826. level_flags = 2;
  81827. else
  81828. level_flags = 3;
  81829. header |= (level_flags << 6);
  81830. if (s->strstart != 0) header |= PRESET_DICT;
  81831. header += 31 - (header % 31);
  81832. s->status = BUSY_STATE;
  81833. putShortMSB(s, header);
  81834. /* Save the adler32 of the preset dictionary: */
  81835. if (s->strstart != 0) {
  81836. putShortMSB(s, (uInt)(strm->adler >> 16));
  81837. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81838. }
  81839. strm->adler = adler32(0L, Z_NULL, 0);
  81840. }
  81841. }
  81842. #ifdef GZIP
  81843. if (s->status == EXTRA_STATE) {
  81844. if (s->gzhead->extra != NULL) {
  81845. uInt beg = s->pending; /* start of bytes to update crc */
  81846. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81847. if (s->pending == s->pending_buf_size) {
  81848. if (s->gzhead->hcrc && s->pending > beg)
  81849. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81850. s->pending - beg);
  81851. flush_pending(strm);
  81852. beg = s->pending;
  81853. if (s->pending == s->pending_buf_size)
  81854. break;
  81855. }
  81856. put_byte(s, s->gzhead->extra[s->gzindex]);
  81857. s->gzindex++;
  81858. }
  81859. if (s->gzhead->hcrc && s->pending > beg)
  81860. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81861. s->pending - beg);
  81862. if (s->gzindex == s->gzhead->extra_len) {
  81863. s->gzindex = 0;
  81864. s->status = NAME_STATE;
  81865. }
  81866. }
  81867. else
  81868. s->status = NAME_STATE;
  81869. }
  81870. if (s->status == NAME_STATE) {
  81871. if (s->gzhead->name != NULL) {
  81872. uInt beg = s->pending; /* start of bytes to update crc */
  81873. int val;
  81874. do {
  81875. if (s->pending == s->pending_buf_size) {
  81876. if (s->gzhead->hcrc && s->pending > beg)
  81877. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81878. s->pending - beg);
  81879. flush_pending(strm);
  81880. beg = s->pending;
  81881. if (s->pending == s->pending_buf_size) {
  81882. val = 1;
  81883. break;
  81884. }
  81885. }
  81886. val = s->gzhead->name[s->gzindex++];
  81887. put_byte(s, val);
  81888. } while (val != 0);
  81889. if (s->gzhead->hcrc && s->pending > beg)
  81890. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81891. s->pending - beg);
  81892. if (val == 0) {
  81893. s->gzindex = 0;
  81894. s->status = COMMENT_STATE;
  81895. }
  81896. }
  81897. else
  81898. s->status = COMMENT_STATE;
  81899. }
  81900. if (s->status == COMMENT_STATE) {
  81901. if (s->gzhead->comment != NULL) {
  81902. uInt beg = s->pending; /* start of bytes to update crc */
  81903. int val;
  81904. do {
  81905. if (s->pending == s->pending_buf_size) {
  81906. if (s->gzhead->hcrc && s->pending > beg)
  81907. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81908. s->pending - beg);
  81909. flush_pending(strm);
  81910. beg = s->pending;
  81911. if (s->pending == s->pending_buf_size) {
  81912. val = 1;
  81913. break;
  81914. }
  81915. }
  81916. val = s->gzhead->comment[s->gzindex++];
  81917. put_byte(s, val);
  81918. } while (val != 0);
  81919. if (s->gzhead->hcrc && s->pending > beg)
  81920. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81921. s->pending - beg);
  81922. if (val == 0)
  81923. s->status = HCRC_STATE;
  81924. }
  81925. else
  81926. s->status = HCRC_STATE;
  81927. }
  81928. if (s->status == HCRC_STATE) {
  81929. if (s->gzhead->hcrc) {
  81930. if (s->pending + 2 > s->pending_buf_size)
  81931. flush_pending(strm);
  81932. if (s->pending + 2 <= s->pending_buf_size) {
  81933. put_byte(s, (Byte)(strm->adler & 0xff));
  81934. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81935. strm->adler = crc32(0L, Z_NULL, 0);
  81936. s->status = BUSY_STATE;
  81937. }
  81938. }
  81939. else
  81940. s->status = BUSY_STATE;
  81941. }
  81942. #endif
  81943. /* Flush as much pending output as possible */
  81944. if (s->pending != 0) {
  81945. flush_pending(strm);
  81946. if (strm->avail_out == 0) {
  81947. /* Since avail_out is 0, deflate will be called again with
  81948. * more output space, but possibly with both pending and
  81949. * avail_in equal to zero. There won't be anything to do,
  81950. * but this is not an error situation so make sure we
  81951. * return OK instead of BUF_ERROR at next call of deflate:
  81952. */
  81953. s->last_flush = -1;
  81954. return Z_OK;
  81955. }
  81956. /* Make sure there is something to do and avoid duplicate consecutive
  81957. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81958. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81959. */
  81960. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81961. flush != Z_FINISH) {
  81962. ERR_RETURN(strm, Z_BUF_ERROR);
  81963. }
  81964. /* User must not provide more input after the first FINISH: */
  81965. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81966. ERR_RETURN(strm, Z_BUF_ERROR);
  81967. }
  81968. /* Start a new block or continue the current one.
  81969. */
  81970. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81971. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81972. block_state bstate;
  81973. bstate = (*(configuration_table[s->level].func))(s, flush);
  81974. if (bstate == finish_started || bstate == finish_done) {
  81975. s->status = FINISH_STATE;
  81976. }
  81977. if (bstate == need_more || bstate == finish_started) {
  81978. if (strm->avail_out == 0) {
  81979. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81980. }
  81981. return Z_OK;
  81982. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81983. * of deflate should use the same flush parameter to make sure
  81984. * that the flush is complete. So we don't have to output an
  81985. * empty block here, this will be done at next call. This also
  81986. * ensures that for a very small output buffer, we emit at most
  81987. * one empty block.
  81988. */
  81989. }
  81990. if (bstate == block_done) {
  81991. if (flush == Z_PARTIAL_FLUSH) {
  81992. _tr_align(s);
  81993. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81994. _tr_stored_block(s, (char*)0, 0L, 0);
  81995. /* For a full flush, this empty block will be recognized
  81996. * as a special marker by inflate_sync().
  81997. */
  81998. if (flush == Z_FULL_FLUSH) {
  81999. CLEAR_HASH(s); /* forget history */
  82000. }
  82001. }
  82002. flush_pending(strm);
  82003. if (strm->avail_out == 0) {
  82004. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82005. return Z_OK;
  82006. }
  82007. }
  82008. }
  82009. Assert(strm->avail_out > 0, "bug2");
  82010. if (flush != Z_FINISH) return Z_OK;
  82011. if (s->wrap <= 0) return Z_STREAM_END;
  82012. /* Write the trailer */
  82013. #ifdef GZIP
  82014. if (s->wrap == 2) {
  82015. put_byte(s, (Byte)(strm->adler & 0xff));
  82016. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82017. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82018. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82019. put_byte(s, (Byte)(strm->total_in & 0xff));
  82020. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82021. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82022. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82023. }
  82024. else
  82025. #endif
  82026. {
  82027. putShortMSB(s, (uInt)(strm->adler >> 16));
  82028. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82029. }
  82030. flush_pending(strm);
  82031. /* If avail_out is zero, the application will call deflate again
  82032. * to flush the rest.
  82033. */
  82034. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82035. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82036. }
  82037. /* ========================================================================= */
  82038. int ZEXPORT deflateEnd (z_streamp strm)
  82039. {
  82040. int status;
  82041. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82042. status = strm->state->status;
  82043. if (status != INIT_STATE &&
  82044. status != EXTRA_STATE &&
  82045. status != NAME_STATE &&
  82046. status != COMMENT_STATE &&
  82047. status != HCRC_STATE &&
  82048. status != BUSY_STATE &&
  82049. status != FINISH_STATE) {
  82050. return Z_STREAM_ERROR;
  82051. }
  82052. /* Deallocate in reverse order of allocations: */
  82053. TRY_FREE(strm, strm->state->pending_buf);
  82054. TRY_FREE(strm, strm->state->head);
  82055. TRY_FREE(strm, strm->state->prev);
  82056. TRY_FREE(strm, strm->state->window);
  82057. ZFREE(strm, strm->state);
  82058. strm->state = Z_NULL;
  82059. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82060. }
  82061. /* =========================================================================
  82062. * Copy the source state to the destination state.
  82063. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82064. * doesn't have enough memory anyway to duplicate compression states).
  82065. */
  82066. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82067. {
  82068. #ifdef MAXSEG_64K
  82069. return Z_STREAM_ERROR;
  82070. #else
  82071. deflate_state *ds;
  82072. deflate_state *ss;
  82073. ushf *overlay;
  82074. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82075. return Z_STREAM_ERROR;
  82076. }
  82077. ss = source->state;
  82078. zmemcpy(dest, source, sizeof(z_stream));
  82079. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82080. if (ds == Z_NULL) return Z_MEM_ERROR;
  82081. dest->state = (struct internal_state FAR *) ds;
  82082. zmemcpy(ds, ss, sizeof(deflate_state));
  82083. ds->strm = dest;
  82084. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82085. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82086. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82087. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82088. ds->pending_buf = (uchf *) overlay;
  82089. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82090. ds->pending_buf == Z_NULL) {
  82091. deflateEnd (dest);
  82092. return Z_MEM_ERROR;
  82093. }
  82094. /* following zmemcpy do not work for 16-bit MSDOS */
  82095. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82096. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82097. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82098. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82099. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82100. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82101. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82102. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82103. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82104. ds->bl_desc.dyn_tree = ds->bl_tree;
  82105. return Z_OK;
  82106. #endif /* MAXSEG_64K */
  82107. }
  82108. /* ===========================================================================
  82109. * Read a new buffer from the current input stream, update the adler32
  82110. * and total number of bytes read. All deflate() input goes through
  82111. * this function so some applications may wish to modify it to avoid
  82112. * allocating a large strm->next_in buffer and copying from it.
  82113. * (See also flush_pending()).
  82114. */
  82115. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82116. {
  82117. unsigned len = strm->avail_in;
  82118. if (len > size) len = size;
  82119. if (len == 0) return 0;
  82120. strm->avail_in -= len;
  82121. if (strm->state->wrap == 1) {
  82122. strm->adler = adler32(strm->adler, strm->next_in, len);
  82123. }
  82124. #ifdef GZIP
  82125. else if (strm->state->wrap == 2) {
  82126. strm->adler = crc32(strm->adler, strm->next_in, len);
  82127. }
  82128. #endif
  82129. zmemcpy(buf, strm->next_in, len);
  82130. strm->next_in += len;
  82131. strm->total_in += len;
  82132. return (int)len;
  82133. }
  82134. /* ===========================================================================
  82135. * Initialize the "longest match" routines for a new zlib stream
  82136. */
  82137. local void lm_init (deflate_state *s)
  82138. {
  82139. s->window_size = (ulg)2L*s->w_size;
  82140. CLEAR_HASH(s);
  82141. /* Set the default configuration parameters:
  82142. */
  82143. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82144. s->good_match = configuration_table[s->level].good_length;
  82145. s->nice_match = configuration_table[s->level].nice_length;
  82146. s->max_chain_length = configuration_table[s->level].max_chain;
  82147. s->strstart = 0;
  82148. s->block_start = 0L;
  82149. s->lookahead = 0;
  82150. s->match_length = s->prev_length = MIN_MATCH-1;
  82151. s->match_available = 0;
  82152. s->ins_h = 0;
  82153. #ifndef FASTEST
  82154. #ifdef ASMV
  82155. match_init(); /* initialize the asm code */
  82156. #endif
  82157. #endif
  82158. }
  82159. #ifndef FASTEST
  82160. /* ===========================================================================
  82161. * Set match_start to the longest match starting at the given string and
  82162. * return its length. Matches shorter or equal to prev_length are discarded,
  82163. * in which case the result is equal to prev_length and match_start is
  82164. * garbage.
  82165. * IN assertions: cur_match is the head of the hash chain for the current
  82166. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82167. * OUT assertion: the match length is not greater than s->lookahead.
  82168. */
  82169. #ifndef ASMV
  82170. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82171. * match.S. The code will be functionally equivalent.
  82172. */
  82173. local uInt longest_match(deflate_state *s, IPos cur_match)
  82174. {
  82175. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82176. register Bytef *scan = s->window + s->strstart; /* current string */
  82177. register Bytef *match; /* matched string */
  82178. register int len; /* length of current match */
  82179. int best_len = s->prev_length; /* best match length so far */
  82180. int nice_match = s->nice_match; /* stop if match long enough */
  82181. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82182. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82183. /* Stop when cur_match becomes <= limit. To simplify the code,
  82184. * we prevent matches with the string of window index 0.
  82185. */
  82186. Posf *prev = s->prev;
  82187. uInt wmask = s->w_mask;
  82188. #ifdef UNALIGNED_OK
  82189. /* Compare two bytes at a time. Note: this is not always beneficial.
  82190. * Try with and without -DUNALIGNED_OK to check.
  82191. */
  82192. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82193. register ush scan_start = *(ushf*)scan;
  82194. register ush scan_end = *(ushf*)(scan+best_len-1);
  82195. #else
  82196. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82197. register Byte scan_end1 = scan[best_len-1];
  82198. register Byte scan_end = scan[best_len];
  82199. #endif
  82200. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82201. * It is easy to get rid of this optimization if necessary.
  82202. */
  82203. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82204. /* Do not waste too much time if we already have a good match: */
  82205. if (s->prev_length >= s->good_match) {
  82206. chain_length >>= 2;
  82207. }
  82208. /* Do not look for matches beyond the end of the input. This is necessary
  82209. * to make deflate deterministic.
  82210. */
  82211. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82212. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82213. do {
  82214. Assert(cur_match < s->strstart, "no future");
  82215. match = s->window + cur_match;
  82216. /* Skip to next match if the match length cannot increase
  82217. * or if the match length is less than 2. Note that the checks below
  82218. * for insufficient lookahead only occur occasionally for performance
  82219. * reasons. Therefore uninitialized memory will be accessed, and
  82220. * conditional jumps will be made that depend on those values.
  82221. * However the length of the match is limited to the lookahead, so
  82222. * the output of deflate is not affected by the uninitialized values.
  82223. */
  82224. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82225. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82226. * UNALIGNED_OK if your compiler uses a different size.
  82227. */
  82228. if (*(ushf*)(match+best_len-1) != scan_end ||
  82229. *(ushf*)match != scan_start) continue;
  82230. /* It is not necessary to compare scan[2] and match[2] since they are
  82231. * always equal when the other bytes match, given that the hash keys
  82232. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82233. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82234. * lookahead only every 4th comparison; the 128th check will be made
  82235. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82236. * necessary to put more guard bytes at the end of the window, or
  82237. * to check more often for insufficient lookahead.
  82238. */
  82239. Assert(scan[2] == match[2], "scan[2]?");
  82240. scan++, match++;
  82241. do {
  82242. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82243. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82244. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82245. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82246. scan < strend);
  82247. /* The funny "do {}" generates better code on most compilers */
  82248. /* Here, scan <= window+strstart+257 */
  82249. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82250. if (*scan == *match) scan++;
  82251. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82252. scan = strend - (MAX_MATCH-1);
  82253. #else /* UNALIGNED_OK */
  82254. if (match[best_len] != scan_end ||
  82255. match[best_len-1] != scan_end1 ||
  82256. *match != *scan ||
  82257. *++match != scan[1]) continue;
  82258. /* The check at best_len-1 can be removed because it will be made
  82259. * again later. (This heuristic is not always a win.)
  82260. * It is not necessary to compare scan[2] and match[2] since they
  82261. * are always equal when the other bytes match, given that
  82262. * the hash keys are equal and that HASH_BITS >= 8.
  82263. */
  82264. scan += 2, match++;
  82265. Assert(*scan == *match, "match[2]?");
  82266. /* We check for insufficient lookahead only every 8th comparison;
  82267. * the 256th check will be made at strstart+258.
  82268. */
  82269. do {
  82270. } while (*++scan == *++match && *++scan == *++match &&
  82271. *++scan == *++match && *++scan == *++match &&
  82272. *++scan == *++match && *++scan == *++match &&
  82273. *++scan == *++match && *++scan == *++match &&
  82274. scan < strend);
  82275. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82276. len = MAX_MATCH - (int)(strend - scan);
  82277. scan = strend - MAX_MATCH;
  82278. #endif /* UNALIGNED_OK */
  82279. if (len > best_len) {
  82280. s->match_start = cur_match;
  82281. best_len = len;
  82282. if (len >= nice_match) break;
  82283. #ifdef UNALIGNED_OK
  82284. scan_end = *(ushf*)(scan+best_len-1);
  82285. #else
  82286. scan_end1 = scan[best_len-1];
  82287. scan_end = scan[best_len];
  82288. #endif
  82289. }
  82290. } while ((cur_match = prev[cur_match & wmask]) > limit
  82291. && --chain_length != 0);
  82292. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82293. return s->lookahead;
  82294. }
  82295. #endif /* ASMV */
  82296. #endif /* FASTEST */
  82297. /* ---------------------------------------------------------------------------
  82298. * Optimized version for level == 1 or strategy == Z_RLE only
  82299. */
  82300. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82301. {
  82302. register Bytef *scan = s->window + s->strstart; /* current string */
  82303. register Bytef *match; /* matched string */
  82304. register int len; /* length of current match */
  82305. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82306. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82307. * It is easy to get rid of this optimization if necessary.
  82308. */
  82309. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82310. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82311. Assert(cur_match < s->strstart, "no future");
  82312. match = s->window + cur_match;
  82313. /* Return failure if the match length is less than 2:
  82314. */
  82315. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82316. /* The check at best_len-1 can be removed because it will be made
  82317. * again later. (This heuristic is not always a win.)
  82318. * It is not necessary to compare scan[2] and match[2] since they
  82319. * are always equal when the other bytes match, given that
  82320. * the hash keys are equal and that HASH_BITS >= 8.
  82321. */
  82322. scan += 2, match += 2;
  82323. Assert(*scan == *match, "match[2]?");
  82324. /* We check for insufficient lookahead only every 8th comparison;
  82325. * the 256th check will be made at strstart+258.
  82326. */
  82327. do {
  82328. } while (*++scan == *++match && *++scan == *++match &&
  82329. *++scan == *++match && *++scan == *++match &&
  82330. *++scan == *++match && *++scan == *++match &&
  82331. *++scan == *++match && *++scan == *++match &&
  82332. scan < strend);
  82333. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82334. len = MAX_MATCH - (int)(strend - scan);
  82335. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82336. s->match_start = cur_match;
  82337. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82338. }
  82339. #ifdef DEBUG
  82340. /* ===========================================================================
  82341. * Check that the match at match_start is indeed a match.
  82342. */
  82343. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82344. {
  82345. /* check that the match is indeed a match */
  82346. if (zmemcmp(s->window + match,
  82347. s->window + start, length) != EQUAL) {
  82348. fprintf(stderr, " start %u, match %u, length %d\n",
  82349. start, match, length);
  82350. do {
  82351. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82352. } while (--length != 0);
  82353. z_error("invalid match");
  82354. }
  82355. if (z_verbose > 1) {
  82356. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82357. do { putc(s->window[start++], stderr); } while (--length != 0);
  82358. }
  82359. }
  82360. #else
  82361. # define check_match(s, start, match, length)
  82362. #endif /* DEBUG */
  82363. /* ===========================================================================
  82364. * Fill the window when the lookahead becomes insufficient.
  82365. * Updates strstart and lookahead.
  82366. *
  82367. * IN assertion: lookahead < MIN_LOOKAHEAD
  82368. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82369. * At least one byte has been read, or avail_in == 0; reads are
  82370. * performed for at least two bytes (required for the zip translate_eol
  82371. * option -- not supported here).
  82372. */
  82373. local void fill_window (deflate_state *s)
  82374. {
  82375. register unsigned n, m;
  82376. register Posf *p;
  82377. unsigned more; /* Amount of free space at the end of the window. */
  82378. uInt wsize = s->w_size;
  82379. do {
  82380. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82381. /* Deal with !@#$% 64K limit: */
  82382. if (sizeof(int) <= 2) {
  82383. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82384. more = wsize;
  82385. } else if (more == (unsigned)(-1)) {
  82386. /* Very unlikely, but possible on 16 bit machine if
  82387. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82388. */
  82389. more--;
  82390. }
  82391. }
  82392. /* If the window is almost full and there is insufficient lookahead,
  82393. * move the upper half to the lower one to make room in the upper half.
  82394. */
  82395. if (s->strstart >= wsize+MAX_DIST(s)) {
  82396. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82397. s->match_start -= wsize;
  82398. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82399. s->block_start -= (long) wsize;
  82400. /* Slide the hash table (could be avoided with 32 bit values
  82401. at the expense of memory usage). We slide even when level == 0
  82402. to keep the hash table consistent if we switch back to level > 0
  82403. later. (Using level 0 permanently is not an optimal usage of
  82404. zlib, so we don't care about this pathological case.)
  82405. */
  82406. /* %%% avoid this when Z_RLE */
  82407. n = s->hash_size;
  82408. p = &s->head[n];
  82409. do {
  82410. m = *--p;
  82411. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82412. } while (--n);
  82413. n = wsize;
  82414. #ifndef FASTEST
  82415. p = &s->prev[n];
  82416. do {
  82417. m = *--p;
  82418. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82419. /* If n is not on any hash chain, prev[n] is garbage but
  82420. * its value will never be used.
  82421. */
  82422. } while (--n);
  82423. #endif
  82424. more += wsize;
  82425. }
  82426. if (s->strm->avail_in == 0) return;
  82427. /* If there was no sliding:
  82428. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82429. * more == window_size - lookahead - strstart
  82430. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82431. * => more >= window_size - 2*WSIZE + 2
  82432. * In the BIG_MEM or MMAP case (not yet supported),
  82433. * window_size == input_size + MIN_LOOKAHEAD &&
  82434. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82435. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82436. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82437. */
  82438. Assert(more >= 2, "more < 2");
  82439. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82440. s->lookahead += n;
  82441. /* Initialize the hash value now that we have some input: */
  82442. if (s->lookahead >= MIN_MATCH) {
  82443. s->ins_h = s->window[s->strstart];
  82444. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82445. #if MIN_MATCH != 3
  82446. Call UPDATE_HASH() MIN_MATCH-3 more times
  82447. #endif
  82448. }
  82449. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82450. * but this is not important since only literal bytes will be emitted.
  82451. */
  82452. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82453. }
  82454. /* ===========================================================================
  82455. * Flush the current block, with given end-of-file flag.
  82456. * IN assertion: strstart is set to the end of the current match.
  82457. */
  82458. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82459. _tr_flush_block(s, (s->block_start >= 0L ? \
  82460. (charf *)&s->window[(unsigned)s->block_start] : \
  82461. (charf *)Z_NULL), \
  82462. (ulg)((long)s->strstart - s->block_start), \
  82463. (eof)); \
  82464. s->block_start = s->strstart; \
  82465. flush_pending(s->strm); \
  82466. Tracev((stderr,"[FLUSH]")); \
  82467. }
  82468. /* Same but force premature exit if necessary. */
  82469. #define FLUSH_BLOCK(s, eof) { \
  82470. FLUSH_BLOCK_ONLY(s, eof); \
  82471. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82472. }
  82473. /* ===========================================================================
  82474. * Copy without compression as much as possible from the input stream, return
  82475. * the current block state.
  82476. * This function does not insert new strings in the dictionary since
  82477. * uncompressible data is probably not useful. This function is used
  82478. * only for the level=0 compression option.
  82479. * NOTE: this function should be optimized to avoid extra copying from
  82480. * window to pending_buf.
  82481. */
  82482. local block_state deflate_stored(deflate_state *s, int flush)
  82483. {
  82484. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82485. * to pending_buf_size, and each stored block has a 5 byte header:
  82486. */
  82487. ulg max_block_size = 0xffff;
  82488. ulg max_start;
  82489. if (max_block_size > s->pending_buf_size - 5) {
  82490. max_block_size = s->pending_buf_size - 5;
  82491. }
  82492. /* Copy as much as possible from input to output: */
  82493. for (;;) {
  82494. /* Fill the window as much as possible: */
  82495. if (s->lookahead <= 1) {
  82496. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82497. s->block_start >= (long)s->w_size, "slide too late");
  82498. fill_window(s);
  82499. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82500. if (s->lookahead == 0) break; /* flush the current block */
  82501. }
  82502. Assert(s->block_start >= 0L, "block gone");
  82503. s->strstart += s->lookahead;
  82504. s->lookahead = 0;
  82505. /* Emit a stored block if pending_buf will be full: */
  82506. max_start = s->block_start + max_block_size;
  82507. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82508. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82509. s->lookahead = (uInt)(s->strstart - max_start);
  82510. s->strstart = (uInt)max_start;
  82511. FLUSH_BLOCK(s, 0);
  82512. }
  82513. /* Flush if we may have to slide, otherwise block_start may become
  82514. * negative and the data will be gone:
  82515. */
  82516. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82517. FLUSH_BLOCK(s, 0);
  82518. }
  82519. }
  82520. FLUSH_BLOCK(s, flush == Z_FINISH);
  82521. return flush == Z_FINISH ? finish_done : block_done;
  82522. }
  82523. /* ===========================================================================
  82524. * Compress as much as possible from the input stream, return the current
  82525. * block state.
  82526. * This function does not perform lazy evaluation of matches and inserts
  82527. * new strings in the dictionary only for unmatched strings or for short
  82528. * matches. It is used only for the fast compression options.
  82529. */
  82530. local block_state deflate_fast(deflate_state *s, int flush)
  82531. {
  82532. IPos hash_head = NIL; /* head of the hash chain */
  82533. int bflush; /* set if current block must be flushed */
  82534. for (;;) {
  82535. /* Make sure that we always have enough lookahead, except
  82536. * at the end of the input file. We need MAX_MATCH bytes
  82537. * for the next match, plus MIN_MATCH bytes to insert the
  82538. * string following the next match.
  82539. */
  82540. if (s->lookahead < MIN_LOOKAHEAD) {
  82541. fill_window(s);
  82542. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82543. return need_more;
  82544. }
  82545. if (s->lookahead == 0) break; /* flush the current block */
  82546. }
  82547. /* Insert the string window[strstart .. strstart+2] in the
  82548. * dictionary, and set hash_head to the head of the hash chain:
  82549. */
  82550. if (s->lookahead >= MIN_MATCH) {
  82551. INSERT_STRING(s, s->strstart, hash_head);
  82552. }
  82553. /* Find the longest match, discarding those <= prev_length.
  82554. * At this point we have always match_length < MIN_MATCH
  82555. */
  82556. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82557. /* To simplify the code, we prevent matches with the string
  82558. * of window index 0 (in particular we have to avoid a match
  82559. * of the string with itself at the start of the input file).
  82560. */
  82561. #ifdef FASTEST
  82562. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82563. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82564. s->match_length = longest_match_fast (s, hash_head);
  82565. }
  82566. #else
  82567. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82568. s->match_length = longest_match (s, hash_head);
  82569. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82570. s->match_length = longest_match_fast (s, hash_head);
  82571. }
  82572. #endif
  82573. /* longest_match() or longest_match_fast() sets match_start */
  82574. }
  82575. if (s->match_length >= MIN_MATCH) {
  82576. check_match(s, s->strstart, s->match_start, s->match_length);
  82577. _tr_tally_dist(s, s->strstart - s->match_start,
  82578. s->match_length - MIN_MATCH, bflush);
  82579. s->lookahead -= s->match_length;
  82580. /* Insert new strings in the hash table only if the match length
  82581. * is not too large. This saves time but degrades compression.
  82582. */
  82583. #ifndef FASTEST
  82584. if (s->match_length <= s->max_insert_length &&
  82585. s->lookahead >= MIN_MATCH) {
  82586. s->match_length--; /* string at strstart already in table */
  82587. do {
  82588. s->strstart++;
  82589. INSERT_STRING(s, s->strstart, hash_head);
  82590. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82591. * always MIN_MATCH bytes ahead.
  82592. */
  82593. } while (--s->match_length != 0);
  82594. s->strstart++;
  82595. } else
  82596. #endif
  82597. {
  82598. s->strstart += s->match_length;
  82599. s->match_length = 0;
  82600. s->ins_h = s->window[s->strstart];
  82601. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82602. #if MIN_MATCH != 3
  82603. Call UPDATE_HASH() MIN_MATCH-3 more times
  82604. #endif
  82605. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82606. * matter since it will be recomputed at next deflate call.
  82607. */
  82608. }
  82609. } else {
  82610. /* No match, output a literal byte */
  82611. Tracevv((stderr,"%c", s->window[s->strstart]));
  82612. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82613. s->lookahead--;
  82614. s->strstart++;
  82615. }
  82616. if (bflush) FLUSH_BLOCK(s, 0);
  82617. }
  82618. FLUSH_BLOCK(s, flush == Z_FINISH);
  82619. return flush == Z_FINISH ? finish_done : block_done;
  82620. }
  82621. #ifndef FASTEST
  82622. /* ===========================================================================
  82623. * Same as above, but achieves better compression. We use a lazy
  82624. * evaluation for matches: a match is finally adopted only if there is
  82625. * no better match at the next window position.
  82626. */
  82627. local block_state deflate_slow(deflate_state *s, int flush)
  82628. {
  82629. IPos hash_head = NIL; /* head of hash chain */
  82630. int bflush; /* set if current block must be flushed */
  82631. /* Process the input block. */
  82632. for (;;) {
  82633. /* Make sure that we always have enough lookahead, except
  82634. * at the end of the input file. We need MAX_MATCH bytes
  82635. * for the next match, plus MIN_MATCH bytes to insert the
  82636. * string following the next match.
  82637. */
  82638. if (s->lookahead < MIN_LOOKAHEAD) {
  82639. fill_window(s);
  82640. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82641. return need_more;
  82642. }
  82643. if (s->lookahead == 0) break; /* flush the current block */
  82644. }
  82645. /* Insert the string window[strstart .. strstart+2] in the
  82646. * dictionary, and set hash_head to the head of the hash chain:
  82647. */
  82648. if (s->lookahead >= MIN_MATCH) {
  82649. INSERT_STRING(s, s->strstart, hash_head);
  82650. }
  82651. /* Find the longest match, discarding those <= prev_length.
  82652. */
  82653. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82654. s->match_length = MIN_MATCH-1;
  82655. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82656. s->strstart - hash_head <= MAX_DIST(s)) {
  82657. /* To simplify the code, we prevent matches with the string
  82658. * of window index 0 (in particular we have to avoid a match
  82659. * of the string with itself at the start of the input file).
  82660. */
  82661. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82662. s->match_length = longest_match (s, hash_head);
  82663. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82664. s->match_length = longest_match_fast (s, hash_head);
  82665. }
  82666. /* longest_match() or longest_match_fast() sets match_start */
  82667. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82668. #if TOO_FAR <= 32767
  82669. || (s->match_length == MIN_MATCH &&
  82670. s->strstart - s->match_start > TOO_FAR)
  82671. #endif
  82672. )) {
  82673. /* If prev_match is also MIN_MATCH, match_start is garbage
  82674. * but we will ignore the current match anyway.
  82675. */
  82676. s->match_length = MIN_MATCH-1;
  82677. }
  82678. }
  82679. /* If there was a match at the previous step and the current
  82680. * match is not better, output the previous match:
  82681. */
  82682. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82683. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82684. /* Do not insert strings in hash table beyond this. */
  82685. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82686. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82687. s->prev_length - MIN_MATCH, bflush);
  82688. /* Insert in hash table all strings up to the end of the match.
  82689. * strstart-1 and strstart are already inserted. If there is not
  82690. * enough lookahead, the last two strings are not inserted in
  82691. * the hash table.
  82692. */
  82693. s->lookahead -= s->prev_length-1;
  82694. s->prev_length -= 2;
  82695. do {
  82696. if (++s->strstart <= max_insert) {
  82697. INSERT_STRING(s, s->strstart, hash_head);
  82698. }
  82699. } while (--s->prev_length != 0);
  82700. s->match_available = 0;
  82701. s->match_length = MIN_MATCH-1;
  82702. s->strstart++;
  82703. if (bflush) FLUSH_BLOCK(s, 0);
  82704. } else if (s->match_available) {
  82705. /* If there was no match at the previous position, output a
  82706. * single literal. If there was a match but the current match
  82707. * is longer, truncate the previous match to a single literal.
  82708. */
  82709. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82710. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82711. if (bflush) {
  82712. FLUSH_BLOCK_ONLY(s, 0);
  82713. }
  82714. s->strstart++;
  82715. s->lookahead--;
  82716. if (s->strm->avail_out == 0) return need_more;
  82717. } else {
  82718. /* There is no previous match to compare with, wait for
  82719. * the next step to decide.
  82720. */
  82721. s->match_available = 1;
  82722. s->strstart++;
  82723. s->lookahead--;
  82724. }
  82725. }
  82726. Assert (flush != Z_NO_FLUSH, "no flush?");
  82727. if (s->match_available) {
  82728. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82729. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82730. s->match_available = 0;
  82731. }
  82732. FLUSH_BLOCK(s, flush == Z_FINISH);
  82733. return flush == Z_FINISH ? finish_done : block_done;
  82734. }
  82735. #endif /* FASTEST */
  82736. #if 0
  82737. /* ===========================================================================
  82738. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82739. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82740. * deflate switches away from Z_RLE.)
  82741. */
  82742. local block_state deflate_rle(s, flush)
  82743. deflate_state *s;
  82744. int flush;
  82745. {
  82746. int bflush; /* set if current block must be flushed */
  82747. uInt run; /* length of run */
  82748. uInt max; /* maximum length of run */
  82749. uInt prev; /* byte at distance one to match */
  82750. Bytef *scan; /* scan for end of run */
  82751. for (;;) {
  82752. /* Make sure that we always have enough lookahead, except
  82753. * at the end of the input file. We need MAX_MATCH bytes
  82754. * for the longest encodable run.
  82755. */
  82756. if (s->lookahead < MAX_MATCH) {
  82757. fill_window(s);
  82758. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82759. return need_more;
  82760. }
  82761. if (s->lookahead == 0) break; /* flush the current block */
  82762. }
  82763. /* See how many times the previous byte repeats */
  82764. run = 0;
  82765. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82766. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82767. scan = s->window + s->strstart - 1;
  82768. prev = *scan++;
  82769. do {
  82770. if (*scan++ != prev)
  82771. break;
  82772. } while (++run < max);
  82773. }
  82774. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82775. if (run >= MIN_MATCH) {
  82776. check_match(s, s->strstart, s->strstart - 1, run);
  82777. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82778. s->lookahead -= run;
  82779. s->strstart += run;
  82780. } else {
  82781. /* No match, output a literal byte */
  82782. Tracevv((stderr,"%c", s->window[s->strstart]));
  82783. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82784. s->lookahead--;
  82785. s->strstart++;
  82786. }
  82787. if (bflush) FLUSH_BLOCK(s, 0);
  82788. }
  82789. FLUSH_BLOCK(s, flush == Z_FINISH);
  82790. return flush == Z_FINISH ? finish_done : block_done;
  82791. }
  82792. #endif
  82793. /*** End of inlined file: deflate.c ***/
  82794. /*** Start of inlined file: inffast.c ***/
  82795. /*** Start of inlined file: inftrees.h ***/
  82796. /* WARNING: this file should *not* be used by applications. It is
  82797. part of the implementation of the compression library and is
  82798. subject to change. Applications should only use zlib.h.
  82799. */
  82800. #ifndef _INFTREES_H_
  82801. #define _INFTREES_H_
  82802. /* Structure for decoding tables. Each entry provides either the
  82803. information needed to do the operation requested by the code that
  82804. indexed that table entry, or it provides a pointer to another
  82805. table that indexes more bits of the code. op indicates whether
  82806. the entry is a pointer to another table, a literal, a length or
  82807. distance, an end-of-block, or an invalid code. For a table
  82808. pointer, the low four bits of op is the number of index bits of
  82809. that table. For a length or distance, the low four bits of op
  82810. is the number of extra bits to get after the code. bits is
  82811. the number of bits in this code or part of the code to drop off
  82812. of the bit buffer. val is the actual byte to output in the case
  82813. of a literal, the base length or distance, or the offset from
  82814. the current table to the next table. Each entry is four bytes. */
  82815. typedef struct {
  82816. unsigned char op; /* operation, extra bits, table bits */
  82817. unsigned char bits; /* bits in this part of the code */
  82818. unsigned short val; /* offset in table or code value */
  82819. } code;
  82820. /* op values as set by inflate_table():
  82821. 00000000 - literal
  82822. 0000tttt - table link, tttt != 0 is the number of table index bits
  82823. 0001eeee - length or distance, eeee is the number of extra bits
  82824. 01100000 - end of block
  82825. 01000000 - invalid code
  82826. */
  82827. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82828. exhaustive search was 1444 code structures (852 for length/literals
  82829. and 592 for distances, the latter actually the result of an
  82830. exhaustive search). The true maximum is not known, but the value
  82831. below is more than safe. */
  82832. #define ENOUGH 2048
  82833. #define MAXD 592
  82834. /* Type of code to build for inftable() */
  82835. typedef enum {
  82836. CODES,
  82837. LENS,
  82838. DISTS
  82839. } codetype;
  82840. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82841. unsigned codes, code FAR * FAR *table,
  82842. unsigned FAR *bits, unsigned short FAR *work));
  82843. #endif
  82844. /*** End of inlined file: inftrees.h ***/
  82845. /*** Start of inlined file: inflate.h ***/
  82846. /* WARNING: this file should *not* be used by applications. It is
  82847. part of the implementation of the compression library and is
  82848. subject to change. Applications should only use zlib.h.
  82849. */
  82850. #ifndef _INFLATE_H_
  82851. #define _INFLATE_H_
  82852. /* define NO_GZIP when compiling if you want to disable gzip header and
  82853. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82854. the crc code when it is not needed. For shared libraries, gzip decoding
  82855. should be left enabled. */
  82856. #ifndef NO_GZIP
  82857. # define GUNZIP
  82858. #endif
  82859. /* Possible inflate modes between inflate() calls */
  82860. typedef enum {
  82861. HEAD, /* i: waiting for magic header */
  82862. FLAGS, /* i: waiting for method and flags (gzip) */
  82863. TIME, /* i: waiting for modification time (gzip) */
  82864. OS, /* i: waiting for extra flags and operating system (gzip) */
  82865. EXLEN, /* i: waiting for extra length (gzip) */
  82866. EXTRA, /* i: waiting for extra bytes (gzip) */
  82867. NAME, /* i: waiting for end of file name (gzip) */
  82868. COMMENT, /* i: waiting for end of comment (gzip) */
  82869. HCRC, /* i: waiting for header crc (gzip) */
  82870. DICTID, /* i: waiting for dictionary check value */
  82871. DICT, /* waiting for inflateSetDictionary() call */
  82872. TYPE, /* i: waiting for type bits, including last-flag bit */
  82873. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82874. STORED, /* i: waiting for stored size (length and complement) */
  82875. COPY, /* i/o: waiting for input or output to copy stored block */
  82876. TABLE, /* i: waiting for dynamic block table lengths */
  82877. LENLENS, /* i: waiting for code length code lengths */
  82878. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82879. LEN, /* i: waiting for length/lit code */
  82880. LENEXT, /* i: waiting for length extra bits */
  82881. DIST, /* i: waiting for distance code */
  82882. DISTEXT, /* i: waiting for distance extra bits */
  82883. MATCH, /* o: waiting for output space to copy string */
  82884. LIT, /* o: waiting for output space to write literal */
  82885. CHECK, /* i: waiting for 32-bit check value */
  82886. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82887. DONE, /* finished check, done -- remain here until reset */
  82888. BAD, /* got a data error -- remain here until reset */
  82889. MEM, /* got an inflate() memory error -- remain here until reset */
  82890. SYNC /* looking for synchronization bytes to restart inflate() */
  82891. } inflate_mode;
  82892. /*
  82893. State transitions between above modes -
  82894. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82895. Process header:
  82896. HEAD -> (gzip) or (zlib)
  82897. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82898. NAME -> COMMENT -> HCRC -> TYPE
  82899. (zlib) -> DICTID or TYPE
  82900. DICTID -> DICT -> TYPE
  82901. Read deflate blocks:
  82902. TYPE -> STORED or TABLE or LEN or CHECK
  82903. STORED -> COPY -> TYPE
  82904. TABLE -> LENLENS -> CODELENS -> LEN
  82905. Read deflate codes:
  82906. LEN -> LENEXT or LIT or TYPE
  82907. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82908. LIT -> LEN
  82909. Process trailer:
  82910. CHECK -> LENGTH -> DONE
  82911. */
  82912. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82913. struct inflate_state {
  82914. inflate_mode mode; /* current inflate mode */
  82915. int last; /* true if processing last block */
  82916. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82917. int havedict; /* true if dictionary provided */
  82918. int flags; /* gzip header method and flags (0 if zlib) */
  82919. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82920. unsigned long check; /* protected copy of check value */
  82921. unsigned long total; /* protected copy of output count */
  82922. gz_headerp head; /* where to save gzip header information */
  82923. /* sliding window */
  82924. unsigned wbits; /* log base 2 of requested window size */
  82925. unsigned wsize; /* window size or zero if not using window */
  82926. unsigned whave; /* valid bytes in the window */
  82927. unsigned write; /* window write index */
  82928. unsigned char FAR *window; /* allocated sliding window, if needed */
  82929. /* bit accumulator */
  82930. unsigned long hold; /* input bit accumulator */
  82931. unsigned bits; /* number of bits in "in" */
  82932. /* for string and stored block copying */
  82933. unsigned length; /* literal or length of data to copy */
  82934. unsigned offset; /* distance back to copy string from */
  82935. /* for table and code decoding */
  82936. unsigned extra; /* extra bits needed */
  82937. /* fixed and dynamic code tables */
  82938. code const FAR *lencode; /* starting table for length/literal codes */
  82939. code const FAR *distcode; /* starting table for distance codes */
  82940. unsigned lenbits; /* index bits for lencode */
  82941. unsigned distbits; /* index bits for distcode */
  82942. /* dynamic table building */
  82943. unsigned ncode; /* number of code length code lengths */
  82944. unsigned nlen; /* number of length code lengths */
  82945. unsigned ndist; /* number of distance code lengths */
  82946. unsigned have; /* number of code lengths in lens[] */
  82947. code FAR *next; /* next available space in codes[] */
  82948. unsigned short lens[320]; /* temporary storage for code lengths */
  82949. unsigned short work[288]; /* work area for code table building */
  82950. code codes[ENOUGH]; /* space for code tables */
  82951. };
  82952. #endif
  82953. /*** End of inlined file: inflate.h ***/
  82954. /*** Start of inlined file: inffast.h ***/
  82955. /* WARNING: this file should *not* be used by applications. It is
  82956. part of the implementation of the compression library and is
  82957. subject to change. Applications should only use zlib.h.
  82958. */
  82959. void inflate_fast OF((z_streamp strm, unsigned start));
  82960. /*** End of inlined file: inffast.h ***/
  82961. #ifndef ASMINF
  82962. /* Allow machine dependent optimization for post-increment or pre-increment.
  82963. Based on testing to date,
  82964. Pre-increment preferred for:
  82965. - PowerPC G3 (Adler)
  82966. - MIPS R5000 (Randers-Pehrson)
  82967. Post-increment preferred for:
  82968. - none
  82969. No measurable difference:
  82970. - Pentium III (Anderson)
  82971. - M68060 (Nikl)
  82972. */
  82973. #ifdef POSTINC
  82974. # define OFF 0
  82975. # define PUP(a) *(a)++
  82976. #else
  82977. # define OFF 1
  82978. # define PUP(a) *++(a)
  82979. #endif
  82980. /*
  82981. Decode literal, length, and distance codes and write out the resulting
  82982. literal and match bytes until either not enough input or output is
  82983. available, an end-of-block is encountered, or a data error is encountered.
  82984. When large enough input and output buffers are supplied to inflate(), for
  82985. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82986. inflate execution time is spent in this routine.
  82987. Entry assumptions:
  82988. state->mode == LEN
  82989. strm->avail_in >= 6
  82990. strm->avail_out >= 258
  82991. start >= strm->avail_out
  82992. state->bits < 8
  82993. On return, state->mode is one of:
  82994. LEN -- ran out of enough output space or enough available input
  82995. TYPE -- reached end of block code, inflate() to interpret next block
  82996. BAD -- error in block data
  82997. Notes:
  82998. - The maximum input bits used by a length/distance pair is 15 bits for the
  82999. length code, 5 bits for the length extra, 15 bits for the distance code,
  83000. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83001. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83002. checking for available input while decoding.
  83003. - The maximum bytes that a single length/distance pair can output is 258
  83004. bytes, which is the maximum length that can be coded. inflate_fast()
  83005. requires strm->avail_out >= 258 for each loop to avoid checking for
  83006. output space.
  83007. */
  83008. void inflate_fast (z_streamp strm, unsigned start)
  83009. {
  83010. struct inflate_state FAR *state;
  83011. unsigned char FAR *in; /* local strm->next_in */
  83012. unsigned char FAR *last; /* while in < last, enough input available */
  83013. unsigned char FAR *out; /* local strm->next_out */
  83014. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83015. unsigned char FAR *end; /* while out < end, enough space available */
  83016. #ifdef INFLATE_STRICT
  83017. unsigned dmax; /* maximum distance from zlib header */
  83018. #endif
  83019. unsigned wsize; /* window size or zero if not using window */
  83020. unsigned whave; /* valid bytes in the window */
  83021. unsigned write; /* window write index */
  83022. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83023. unsigned long hold; /* local strm->hold */
  83024. unsigned bits; /* local strm->bits */
  83025. code const FAR *lcode; /* local strm->lencode */
  83026. code const FAR *dcode; /* local strm->distcode */
  83027. unsigned lmask; /* mask for first level of length codes */
  83028. unsigned dmask; /* mask for first level of distance codes */
  83029. code thisx; /* retrieved table entry */
  83030. unsigned op; /* code bits, operation, extra bits, or */
  83031. /* window position, window bytes to copy */
  83032. unsigned len; /* match length, unused bytes */
  83033. unsigned dist; /* match distance */
  83034. unsigned char FAR *from; /* where to copy match from */
  83035. /* copy state to local variables */
  83036. state = (struct inflate_state FAR *)strm->state;
  83037. in = strm->next_in - OFF;
  83038. last = in + (strm->avail_in - 5);
  83039. out = strm->next_out - OFF;
  83040. beg = out - (start - strm->avail_out);
  83041. end = out + (strm->avail_out - 257);
  83042. #ifdef INFLATE_STRICT
  83043. dmax = state->dmax;
  83044. #endif
  83045. wsize = state->wsize;
  83046. whave = state->whave;
  83047. write = state->write;
  83048. window = state->window;
  83049. hold = state->hold;
  83050. bits = state->bits;
  83051. lcode = state->lencode;
  83052. dcode = state->distcode;
  83053. lmask = (1U << state->lenbits) - 1;
  83054. dmask = (1U << state->distbits) - 1;
  83055. /* decode literals and length/distances until end-of-block or not enough
  83056. input data or output space */
  83057. do {
  83058. if (bits < 15) {
  83059. hold += (unsigned long)(PUP(in)) << bits;
  83060. bits += 8;
  83061. hold += (unsigned long)(PUP(in)) << bits;
  83062. bits += 8;
  83063. }
  83064. thisx = lcode[hold & lmask];
  83065. dolen:
  83066. op = (unsigned)(thisx.bits);
  83067. hold >>= op;
  83068. bits -= op;
  83069. op = (unsigned)(thisx.op);
  83070. if (op == 0) { /* literal */
  83071. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83072. "inflate: literal '%c'\n" :
  83073. "inflate: literal 0x%02x\n", thisx.val));
  83074. PUP(out) = (unsigned char)(thisx.val);
  83075. }
  83076. else if (op & 16) { /* length base */
  83077. len = (unsigned)(thisx.val);
  83078. op &= 15; /* number of extra bits */
  83079. if (op) {
  83080. if (bits < op) {
  83081. hold += (unsigned long)(PUP(in)) << bits;
  83082. bits += 8;
  83083. }
  83084. len += (unsigned)hold & ((1U << op) - 1);
  83085. hold >>= op;
  83086. bits -= op;
  83087. }
  83088. Tracevv((stderr, "inflate: length %u\n", len));
  83089. if (bits < 15) {
  83090. hold += (unsigned long)(PUP(in)) << bits;
  83091. bits += 8;
  83092. hold += (unsigned long)(PUP(in)) << bits;
  83093. bits += 8;
  83094. }
  83095. thisx = dcode[hold & dmask];
  83096. dodist:
  83097. op = (unsigned)(thisx.bits);
  83098. hold >>= op;
  83099. bits -= op;
  83100. op = (unsigned)(thisx.op);
  83101. if (op & 16) { /* distance base */
  83102. dist = (unsigned)(thisx.val);
  83103. op &= 15; /* number of extra bits */
  83104. if (bits < op) {
  83105. hold += (unsigned long)(PUP(in)) << bits;
  83106. bits += 8;
  83107. if (bits < op) {
  83108. hold += (unsigned long)(PUP(in)) << bits;
  83109. bits += 8;
  83110. }
  83111. }
  83112. dist += (unsigned)hold & ((1U << op) - 1);
  83113. #ifdef INFLATE_STRICT
  83114. if (dist > dmax) {
  83115. strm->msg = (char *)"invalid distance too far back";
  83116. state->mode = BAD;
  83117. break;
  83118. }
  83119. #endif
  83120. hold >>= op;
  83121. bits -= op;
  83122. Tracevv((stderr, "inflate: distance %u\n", dist));
  83123. op = (unsigned)(out - beg); /* max distance in output */
  83124. if (dist > op) { /* see if copy from window */
  83125. op = dist - op; /* distance back in window */
  83126. if (op > whave) {
  83127. strm->msg = (char *)"invalid distance too far back";
  83128. state->mode = BAD;
  83129. break;
  83130. }
  83131. from = window - OFF;
  83132. if (write == 0) { /* very common case */
  83133. from += wsize - op;
  83134. if (op < len) { /* some from window */
  83135. len -= op;
  83136. do {
  83137. PUP(out) = PUP(from);
  83138. } while (--op);
  83139. from = out - dist; /* rest from output */
  83140. }
  83141. }
  83142. else if (write < op) { /* wrap around window */
  83143. from += wsize + write - op;
  83144. op -= write;
  83145. if (op < len) { /* some from end of window */
  83146. len -= op;
  83147. do {
  83148. PUP(out) = PUP(from);
  83149. } while (--op);
  83150. from = window - OFF;
  83151. if (write < len) { /* some from start of window */
  83152. op = write;
  83153. len -= op;
  83154. do {
  83155. PUP(out) = PUP(from);
  83156. } while (--op);
  83157. from = out - dist; /* rest from output */
  83158. }
  83159. }
  83160. }
  83161. else { /* contiguous in window */
  83162. from += write - op;
  83163. if (op < len) { /* some from window */
  83164. len -= op;
  83165. do {
  83166. PUP(out) = PUP(from);
  83167. } while (--op);
  83168. from = out - dist; /* rest from output */
  83169. }
  83170. }
  83171. while (len > 2) {
  83172. PUP(out) = PUP(from);
  83173. PUP(out) = PUP(from);
  83174. PUP(out) = PUP(from);
  83175. len -= 3;
  83176. }
  83177. if (len) {
  83178. PUP(out) = PUP(from);
  83179. if (len > 1)
  83180. PUP(out) = PUP(from);
  83181. }
  83182. }
  83183. else {
  83184. from = out - dist; /* copy direct from output */
  83185. do { /* minimum length is three */
  83186. PUP(out) = PUP(from);
  83187. PUP(out) = PUP(from);
  83188. PUP(out) = PUP(from);
  83189. len -= 3;
  83190. } while (len > 2);
  83191. if (len) {
  83192. PUP(out) = PUP(from);
  83193. if (len > 1)
  83194. PUP(out) = PUP(from);
  83195. }
  83196. }
  83197. }
  83198. else if ((op & 64) == 0) { /* 2nd level distance code */
  83199. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83200. goto dodist;
  83201. }
  83202. else {
  83203. strm->msg = (char *)"invalid distance code";
  83204. state->mode = BAD;
  83205. break;
  83206. }
  83207. }
  83208. else if ((op & 64) == 0) { /* 2nd level length code */
  83209. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83210. goto dolen;
  83211. }
  83212. else if (op & 32) { /* end-of-block */
  83213. Tracevv((stderr, "inflate: end of block\n"));
  83214. state->mode = TYPE;
  83215. break;
  83216. }
  83217. else {
  83218. strm->msg = (char *)"invalid literal/length code";
  83219. state->mode = BAD;
  83220. break;
  83221. }
  83222. } while (in < last && out < end);
  83223. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83224. len = bits >> 3;
  83225. in -= len;
  83226. bits -= len << 3;
  83227. hold &= (1U << bits) - 1;
  83228. /* update state and return */
  83229. strm->next_in = in + OFF;
  83230. strm->next_out = out + OFF;
  83231. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83232. strm->avail_out = (unsigned)(out < end ?
  83233. 257 + (end - out) : 257 - (out - end));
  83234. state->hold = hold;
  83235. state->bits = bits;
  83236. return;
  83237. }
  83238. /*
  83239. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83240. - Using bit fields for code structure
  83241. - Different op definition to avoid & for extra bits (do & for table bits)
  83242. - Three separate decoding do-loops for direct, window, and write == 0
  83243. - Special case for distance > 1 copies to do overlapped load and store copy
  83244. - Explicit branch predictions (based on measured branch probabilities)
  83245. - Deferring match copy and interspersed it with decoding subsequent codes
  83246. - Swapping literal/length else
  83247. - Swapping window/direct else
  83248. - Larger unrolled copy loops (three is about right)
  83249. - Moving len -= 3 statement into middle of loop
  83250. */
  83251. #endif /* !ASMINF */
  83252. /*** End of inlined file: inffast.c ***/
  83253. #undef PULLBYTE
  83254. #undef LOAD
  83255. #undef RESTORE
  83256. #undef INITBITS
  83257. #undef NEEDBITS
  83258. #undef DROPBITS
  83259. #undef BYTEBITS
  83260. /*** Start of inlined file: inflate.c ***/
  83261. /*
  83262. * Change history:
  83263. *
  83264. * 1.2.beta0 24 Nov 2002
  83265. * - First version -- complete rewrite of inflate to simplify code, avoid
  83266. * creation of window when not needed, minimize use of window when it is
  83267. * needed, make inffast.c even faster, implement gzip decoding, and to
  83268. * improve code readability and style over the previous zlib inflate code
  83269. *
  83270. * 1.2.beta1 25 Nov 2002
  83271. * - Use pointers for available input and output checking in inffast.c
  83272. * - Remove input and output counters in inffast.c
  83273. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83274. * - Remove unnecessary second byte pull from length extra in inffast.c
  83275. * - Unroll direct copy to three copies per loop in inffast.c
  83276. *
  83277. * 1.2.beta2 4 Dec 2002
  83278. * - Change external routine names to reduce potential conflicts
  83279. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83280. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83281. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83282. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83283. *
  83284. * 1.2.beta3 22 Dec 2002
  83285. * - Add comments on state->bits assertion in inffast.c
  83286. * - Add comments on op field in inftrees.h
  83287. * - Fix bug in reuse of allocated window after inflateReset()
  83288. * - Remove bit fields--back to byte structure for speed
  83289. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83290. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83291. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83292. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83293. * - Use local copies of stream next and avail values, as well as local bit
  83294. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83295. *
  83296. * 1.2.beta4 1 Jan 2003
  83297. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83298. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83299. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83300. * - Rearrange window copies in inflate_fast() for speed and simplification
  83301. * - Unroll last copy for window match in inflate_fast()
  83302. * - Use local copies of window variables in inflate_fast() for speed
  83303. * - Pull out common write == 0 case for speed in inflate_fast()
  83304. * - Make op and len in inflate_fast() unsigned for consistency
  83305. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83306. * - Simplified bad distance check in inflate_fast()
  83307. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83308. * source file infback.c to provide a call-back interface to inflate for
  83309. * programs like gzip and unzip -- uses window as output buffer to avoid
  83310. * window copying
  83311. *
  83312. * 1.2.beta5 1 Jan 2003
  83313. * - Improved inflateBack() interface to allow the caller to provide initial
  83314. * input in strm.
  83315. * - Fixed stored blocks bug in inflateBack()
  83316. *
  83317. * 1.2.beta6 4 Jan 2003
  83318. * - Added comments in inffast.c on effectiveness of POSTINC
  83319. * - Typecasting all around to reduce compiler warnings
  83320. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83321. * make compilers happy
  83322. * - Changed type of window in inflateBackInit() to unsigned char *
  83323. *
  83324. * 1.2.beta7 27 Jan 2003
  83325. * - Changed many types to unsigned or unsigned short to avoid warnings
  83326. * - Added inflateCopy() function
  83327. *
  83328. * 1.2.0 9 Mar 2003
  83329. * - Changed inflateBack() interface to provide separate opaque descriptors
  83330. * for the in() and out() functions
  83331. * - Changed inflateBack() argument and in_func typedef to swap the length
  83332. * and buffer address return values for the input function
  83333. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83334. *
  83335. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83336. */
  83337. /*** Start of inlined file: inffast.h ***/
  83338. /* WARNING: this file should *not* be used by applications. It is
  83339. part of the implementation of the compression library and is
  83340. subject to change. Applications should only use zlib.h.
  83341. */
  83342. void inflate_fast OF((z_streamp strm, unsigned start));
  83343. /*** End of inlined file: inffast.h ***/
  83344. #ifdef MAKEFIXED
  83345. # ifndef BUILDFIXED
  83346. # define BUILDFIXED
  83347. # endif
  83348. #endif
  83349. /* function prototypes */
  83350. local void fixedtables OF((struct inflate_state FAR *state));
  83351. local int updatewindow OF((z_streamp strm, unsigned out));
  83352. #ifdef BUILDFIXED
  83353. void makefixed OF((void));
  83354. #endif
  83355. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83356. unsigned len));
  83357. int ZEXPORT inflateReset (z_streamp strm)
  83358. {
  83359. struct inflate_state FAR *state;
  83360. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83361. state = (struct inflate_state FAR *)strm->state;
  83362. strm->total_in = strm->total_out = state->total = 0;
  83363. strm->msg = Z_NULL;
  83364. strm->adler = 1; /* to support ill-conceived Java test suite */
  83365. state->mode = HEAD;
  83366. state->last = 0;
  83367. state->havedict = 0;
  83368. state->dmax = 32768U;
  83369. state->head = Z_NULL;
  83370. state->wsize = 0;
  83371. state->whave = 0;
  83372. state->write = 0;
  83373. state->hold = 0;
  83374. state->bits = 0;
  83375. state->lencode = state->distcode = state->next = state->codes;
  83376. Tracev((stderr, "inflate: reset\n"));
  83377. return Z_OK;
  83378. }
  83379. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83380. {
  83381. struct inflate_state FAR *state;
  83382. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83383. state = (struct inflate_state FAR *)strm->state;
  83384. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83385. value &= (1L << bits) - 1;
  83386. state->hold += value << state->bits;
  83387. state->bits += bits;
  83388. return Z_OK;
  83389. }
  83390. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83391. {
  83392. struct inflate_state FAR *state;
  83393. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83394. stream_size != (int)(sizeof(z_stream)))
  83395. return Z_VERSION_ERROR;
  83396. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83397. strm->msg = Z_NULL; /* in case we return an error */
  83398. if (strm->zalloc == (alloc_func)0) {
  83399. strm->zalloc = zcalloc;
  83400. strm->opaque = (voidpf)0;
  83401. }
  83402. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83403. state = (struct inflate_state FAR *)
  83404. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83405. if (state == Z_NULL) return Z_MEM_ERROR;
  83406. Tracev((stderr, "inflate: allocated\n"));
  83407. strm->state = (struct internal_state FAR *)state;
  83408. if (windowBits < 0) {
  83409. state->wrap = 0;
  83410. windowBits = -windowBits;
  83411. }
  83412. else {
  83413. state->wrap = (windowBits >> 4) + 1;
  83414. #ifdef GUNZIP
  83415. if (windowBits < 48) windowBits &= 15;
  83416. #endif
  83417. }
  83418. if (windowBits < 8 || windowBits > 15) {
  83419. ZFREE(strm, state);
  83420. strm->state = Z_NULL;
  83421. return Z_STREAM_ERROR;
  83422. }
  83423. state->wbits = (unsigned)windowBits;
  83424. state->window = Z_NULL;
  83425. return inflateReset(strm);
  83426. }
  83427. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83428. {
  83429. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83430. }
  83431. /*
  83432. Return state with length and distance decoding tables and index sizes set to
  83433. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83434. If BUILDFIXED is defined, then instead this routine builds the tables the
  83435. first time it's called, and returns those tables the first time and
  83436. thereafter. This reduces the size of the code by about 2K bytes, in
  83437. exchange for a little execution time. However, BUILDFIXED should not be
  83438. used for threaded applications, since the rewriting of the tables and virgin
  83439. may not be thread-safe.
  83440. */
  83441. local void fixedtables (struct inflate_state FAR *state)
  83442. {
  83443. #ifdef BUILDFIXED
  83444. static int virgin = 1;
  83445. static code *lenfix, *distfix;
  83446. static code fixed[544];
  83447. /* build fixed huffman tables if first call (may not be thread safe) */
  83448. if (virgin) {
  83449. unsigned sym, bits;
  83450. static code *next;
  83451. /* literal/length table */
  83452. sym = 0;
  83453. while (sym < 144) state->lens[sym++] = 8;
  83454. while (sym < 256) state->lens[sym++] = 9;
  83455. while (sym < 280) state->lens[sym++] = 7;
  83456. while (sym < 288) state->lens[sym++] = 8;
  83457. next = fixed;
  83458. lenfix = next;
  83459. bits = 9;
  83460. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83461. /* distance table */
  83462. sym = 0;
  83463. while (sym < 32) state->lens[sym++] = 5;
  83464. distfix = next;
  83465. bits = 5;
  83466. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83467. /* do this just once */
  83468. virgin = 0;
  83469. }
  83470. #else /* !BUILDFIXED */
  83471. /*** Start of inlined file: inffixed.h ***/
  83472. /* WARNING: this file should *not* be used by applications. It
  83473. is part of the implementation of the compression library and
  83474. is subject to change. Applications should only use zlib.h.
  83475. */
  83476. static const code lenfix[512] = {
  83477. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83478. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83479. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83480. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83481. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83482. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83483. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83484. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83485. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83486. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83487. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83488. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83489. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83490. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83491. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83492. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83493. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83494. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83495. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83496. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83497. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83498. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83499. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83500. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83501. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83502. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83503. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83504. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83505. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83506. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83507. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83508. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83509. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83510. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83511. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83512. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83513. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83514. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83515. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83516. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83517. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83518. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83519. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83520. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83521. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83522. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83523. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83524. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83525. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83526. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83527. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83528. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83529. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83530. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83531. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83532. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83533. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83534. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83535. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83536. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83537. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83538. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83539. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83540. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83541. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83542. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83543. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83544. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83545. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83546. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83547. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83548. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83549. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83550. {0,9,255}
  83551. };
  83552. static const code distfix[32] = {
  83553. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83554. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83555. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83556. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83557. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83558. {22,5,193},{64,5,0}
  83559. };
  83560. /*** End of inlined file: inffixed.h ***/
  83561. #endif /* BUILDFIXED */
  83562. state->lencode = lenfix;
  83563. state->lenbits = 9;
  83564. state->distcode = distfix;
  83565. state->distbits = 5;
  83566. }
  83567. #ifdef MAKEFIXED
  83568. #include <stdio.h>
  83569. /*
  83570. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83571. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83572. those tables to stdout, which would be piped to inffixed.h. A small program
  83573. can simply call makefixed to do this:
  83574. void makefixed(void);
  83575. int main(void)
  83576. {
  83577. makefixed();
  83578. return 0;
  83579. }
  83580. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83581. a.out > inffixed.h
  83582. */
  83583. void makefixed()
  83584. {
  83585. unsigned low, size;
  83586. struct inflate_state state;
  83587. fixedtables(&state);
  83588. puts(" /* inffixed.h -- table for decoding fixed codes");
  83589. puts(" * Generated automatically by makefixed().");
  83590. puts(" */");
  83591. puts("");
  83592. puts(" /* WARNING: this file should *not* be used by applications.");
  83593. puts(" It is part of the implementation of this library and is");
  83594. puts(" subject to change. Applications should only use zlib.h.");
  83595. puts(" */");
  83596. puts("");
  83597. size = 1U << 9;
  83598. printf(" static const code lenfix[%u] = {", size);
  83599. low = 0;
  83600. for (;;) {
  83601. if ((low % 7) == 0) printf("\n ");
  83602. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83603. state.lencode[low].val);
  83604. if (++low == size) break;
  83605. putchar(',');
  83606. }
  83607. puts("\n };");
  83608. size = 1U << 5;
  83609. printf("\n static const code distfix[%u] = {", size);
  83610. low = 0;
  83611. for (;;) {
  83612. if ((low % 6) == 0) printf("\n ");
  83613. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83614. state.distcode[low].val);
  83615. if (++low == size) break;
  83616. putchar(',');
  83617. }
  83618. puts("\n };");
  83619. }
  83620. #endif /* MAKEFIXED */
  83621. /*
  83622. Update the window with the last wsize (normally 32K) bytes written before
  83623. returning. If window does not exist yet, create it. This is only called
  83624. when a window is already in use, or when output has been written during this
  83625. inflate call, but the end of the deflate stream has not been reached yet.
  83626. It is also called to create a window for dictionary data when a dictionary
  83627. is loaded.
  83628. Providing output buffers larger than 32K to inflate() should provide a speed
  83629. advantage, since only the last 32K of output is copied to the sliding window
  83630. upon return from inflate(), and since all distances after the first 32K of
  83631. output will fall in the output data, making match copies simpler and faster.
  83632. The advantage may be dependent on the size of the processor's data caches.
  83633. */
  83634. local int updatewindow (z_streamp strm, unsigned out)
  83635. {
  83636. struct inflate_state FAR *state;
  83637. unsigned copy, dist;
  83638. state = (struct inflate_state FAR *)strm->state;
  83639. /* if it hasn't been done already, allocate space for the window */
  83640. if (state->window == Z_NULL) {
  83641. state->window = (unsigned char FAR *)
  83642. ZALLOC(strm, 1U << state->wbits,
  83643. sizeof(unsigned char));
  83644. if (state->window == Z_NULL) return 1;
  83645. }
  83646. /* if window not in use yet, initialize */
  83647. if (state->wsize == 0) {
  83648. state->wsize = 1U << state->wbits;
  83649. state->write = 0;
  83650. state->whave = 0;
  83651. }
  83652. /* copy state->wsize or less output bytes into the circular window */
  83653. copy = out - strm->avail_out;
  83654. if (copy >= state->wsize) {
  83655. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83656. state->write = 0;
  83657. state->whave = state->wsize;
  83658. }
  83659. else {
  83660. dist = state->wsize - state->write;
  83661. if (dist > copy) dist = copy;
  83662. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83663. copy -= dist;
  83664. if (copy) {
  83665. zmemcpy(state->window, strm->next_out - copy, copy);
  83666. state->write = copy;
  83667. state->whave = state->wsize;
  83668. }
  83669. else {
  83670. state->write += dist;
  83671. if (state->write == state->wsize) state->write = 0;
  83672. if (state->whave < state->wsize) state->whave += dist;
  83673. }
  83674. }
  83675. return 0;
  83676. }
  83677. /* Macros for inflate(): */
  83678. /* check function to use adler32() for zlib or crc32() for gzip */
  83679. #ifdef GUNZIP
  83680. # define UPDATE(check, buf, len) \
  83681. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83682. #else
  83683. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83684. #endif
  83685. /* check macros for header crc */
  83686. #ifdef GUNZIP
  83687. # define CRC2(check, word) \
  83688. do { \
  83689. hbuf[0] = (unsigned char)(word); \
  83690. hbuf[1] = (unsigned char)((word) >> 8); \
  83691. check = crc32(check, hbuf, 2); \
  83692. } while (0)
  83693. # define CRC4(check, word) \
  83694. do { \
  83695. hbuf[0] = (unsigned char)(word); \
  83696. hbuf[1] = (unsigned char)((word) >> 8); \
  83697. hbuf[2] = (unsigned char)((word) >> 16); \
  83698. hbuf[3] = (unsigned char)((word) >> 24); \
  83699. check = crc32(check, hbuf, 4); \
  83700. } while (0)
  83701. #endif
  83702. /* Load registers with state in inflate() for speed */
  83703. #define LOAD() \
  83704. do { \
  83705. put = strm->next_out; \
  83706. left = strm->avail_out; \
  83707. next = strm->next_in; \
  83708. have = strm->avail_in; \
  83709. hold = state->hold; \
  83710. bits = state->bits; \
  83711. } while (0)
  83712. /* Restore state from registers in inflate() */
  83713. #define RESTORE() \
  83714. do { \
  83715. strm->next_out = put; \
  83716. strm->avail_out = left; \
  83717. strm->next_in = next; \
  83718. strm->avail_in = have; \
  83719. state->hold = hold; \
  83720. state->bits = bits; \
  83721. } while (0)
  83722. /* Clear the input bit accumulator */
  83723. #define INITBITS() \
  83724. do { \
  83725. hold = 0; \
  83726. bits = 0; \
  83727. } while (0)
  83728. /* Get a byte of input into the bit accumulator, or return from inflate()
  83729. if there is no input available. */
  83730. #define PULLBYTE() \
  83731. do { \
  83732. if (have == 0) goto inf_leave; \
  83733. have--; \
  83734. hold += (unsigned long)(*next++) << bits; \
  83735. bits += 8; \
  83736. } while (0)
  83737. /* Assure that there are at least n bits in the bit accumulator. If there is
  83738. not enough available input to do that, then return from inflate(). */
  83739. #define NEEDBITS(n) \
  83740. do { \
  83741. while (bits < (unsigned)(n)) \
  83742. PULLBYTE(); \
  83743. } while (0)
  83744. /* Return the low n bits of the bit accumulator (n < 16) */
  83745. #define BITS(n) \
  83746. ((unsigned)hold & ((1U << (n)) - 1))
  83747. /* Remove n bits from the bit accumulator */
  83748. #define DROPBITS(n) \
  83749. do { \
  83750. hold >>= (n); \
  83751. bits -= (unsigned)(n); \
  83752. } while (0)
  83753. /* Remove zero to seven bits as needed to go to a byte boundary */
  83754. #define BYTEBITS() \
  83755. do { \
  83756. hold >>= bits & 7; \
  83757. bits -= bits & 7; \
  83758. } while (0)
  83759. /* Reverse the bytes in a 32-bit value */
  83760. #define REVERSE(q) \
  83761. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83762. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83763. /*
  83764. inflate() uses a state machine to process as much input data and generate as
  83765. much output data as possible before returning. The state machine is
  83766. structured roughly as follows:
  83767. for (;;) switch (state) {
  83768. ...
  83769. case STATEn:
  83770. if (not enough input data or output space to make progress)
  83771. return;
  83772. ... make progress ...
  83773. state = STATEm;
  83774. break;
  83775. ...
  83776. }
  83777. so when inflate() is called again, the same case is attempted again, and
  83778. if the appropriate resources are provided, the machine proceeds to the
  83779. next state. The NEEDBITS() macro is usually the way the state evaluates
  83780. whether it can proceed or should return. NEEDBITS() does the return if
  83781. the requested bits are not available. The typical use of the BITS macros
  83782. is:
  83783. NEEDBITS(n);
  83784. ... do something with BITS(n) ...
  83785. DROPBITS(n);
  83786. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83787. input left to load n bits into the accumulator, or it continues. BITS(n)
  83788. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83789. the low n bits off the accumulator. INITBITS() clears the accumulator
  83790. and sets the number of available bits to zero. BYTEBITS() discards just
  83791. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83792. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83793. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83794. if there is no input available. The decoding of variable length codes uses
  83795. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83796. code, and no more.
  83797. Some states loop until they get enough input, making sure that enough
  83798. state information is maintained to continue the loop where it left off
  83799. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83800. would all have to actually be part of the saved state in case NEEDBITS()
  83801. returns:
  83802. case STATEw:
  83803. while (want < need) {
  83804. NEEDBITS(n);
  83805. keep[want++] = BITS(n);
  83806. DROPBITS(n);
  83807. }
  83808. state = STATEx;
  83809. case STATEx:
  83810. As shown above, if the next state is also the next case, then the break
  83811. is omitted.
  83812. A state may also return if there is not enough output space available to
  83813. complete that state. Those states are copying stored data, writing a
  83814. literal byte, and copying a matching string.
  83815. When returning, a "goto inf_leave" is used to update the total counters,
  83816. update the check value, and determine whether any progress has been made
  83817. during that inflate() call in order to return the proper return code.
  83818. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83819. When there is a window, goto inf_leave will update the window with the last
  83820. output written. If a goto inf_leave occurs in the middle of decompression
  83821. and there is no window currently, goto inf_leave will create one and copy
  83822. output to the window for the next call of inflate().
  83823. In this implementation, the flush parameter of inflate() only affects the
  83824. return code (per zlib.h). inflate() always writes as much as possible to
  83825. strm->next_out, given the space available and the provided input--the effect
  83826. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83827. the allocation of and copying into a sliding window until necessary, which
  83828. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83829. stream available. So the only thing the flush parameter actually does is:
  83830. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83831. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83832. */
  83833. int ZEXPORT inflate (z_streamp strm, int flush)
  83834. {
  83835. struct inflate_state FAR *state;
  83836. unsigned char FAR *next; /* next input */
  83837. unsigned char FAR *put; /* next output */
  83838. unsigned have, left; /* available input and output */
  83839. unsigned long hold; /* bit buffer */
  83840. unsigned bits; /* bits in bit buffer */
  83841. unsigned in, out; /* save starting available input and output */
  83842. unsigned copy; /* number of stored or match bytes to copy */
  83843. unsigned char FAR *from; /* where to copy match bytes from */
  83844. code thisx; /* current decoding table entry */
  83845. code last; /* parent table entry */
  83846. unsigned len; /* length to copy for repeats, bits to drop */
  83847. int ret; /* return code */
  83848. #ifdef GUNZIP
  83849. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83850. #endif
  83851. static const unsigned short order[19] = /* permutation of code lengths */
  83852. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83853. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83854. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83855. return Z_STREAM_ERROR;
  83856. state = (struct inflate_state FAR *)strm->state;
  83857. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83858. LOAD();
  83859. in = have;
  83860. out = left;
  83861. ret = Z_OK;
  83862. for (;;)
  83863. switch (state->mode) {
  83864. case HEAD:
  83865. if (state->wrap == 0) {
  83866. state->mode = TYPEDO;
  83867. break;
  83868. }
  83869. NEEDBITS(16);
  83870. #ifdef GUNZIP
  83871. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83872. state->check = crc32(0L, Z_NULL, 0);
  83873. CRC2(state->check, hold);
  83874. INITBITS();
  83875. state->mode = FLAGS;
  83876. break;
  83877. }
  83878. state->flags = 0; /* expect zlib header */
  83879. if (state->head != Z_NULL)
  83880. state->head->done = -1;
  83881. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83882. #else
  83883. if (
  83884. #endif
  83885. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83886. strm->msg = (char *)"incorrect header check";
  83887. state->mode = BAD;
  83888. break;
  83889. }
  83890. if (BITS(4) != Z_DEFLATED) {
  83891. strm->msg = (char *)"unknown compression method";
  83892. state->mode = BAD;
  83893. break;
  83894. }
  83895. DROPBITS(4);
  83896. len = BITS(4) + 8;
  83897. if (len > state->wbits) {
  83898. strm->msg = (char *)"invalid window size";
  83899. state->mode = BAD;
  83900. break;
  83901. }
  83902. state->dmax = 1U << len;
  83903. Tracev((stderr, "inflate: zlib header ok\n"));
  83904. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83905. state->mode = hold & 0x200 ? DICTID : TYPE;
  83906. INITBITS();
  83907. break;
  83908. #ifdef GUNZIP
  83909. case FLAGS:
  83910. NEEDBITS(16);
  83911. state->flags = (int)(hold);
  83912. if ((state->flags & 0xff) != Z_DEFLATED) {
  83913. strm->msg = (char *)"unknown compression method";
  83914. state->mode = BAD;
  83915. break;
  83916. }
  83917. if (state->flags & 0xe000) {
  83918. strm->msg = (char *)"unknown header flags set";
  83919. state->mode = BAD;
  83920. break;
  83921. }
  83922. if (state->head != Z_NULL)
  83923. state->head->text = (int)((hold >> 8) & 1);
  83924. if (state->flags & 0x0200) CRC2(state->check, hold);
  83925. INITBITS();
  83926. state->mode = TIME;
  83927. case TIME:
  83928. NEEDBITS(32);
  83929. if (state->head != Z_NULL)
  83930. state->head->time = hold;
  83931. if (state->flags & 0x0200) CRC4(state->check, hold);
  83932. INITBITS();
  83933. state->mode = OS;
  83934. case OS:
  83935. NEEDBITS(16);
  83936. if (state->head != Z_NULL) {
  83937. state->head->xflags = (int)(hold & 0xff);
  83938. state->head->os = (int)(hold >> 8);
  83939. }
  83940. if (state->flags & 0x0200) CRC2(state->check, hold);
  83941. INITBITS();
  83942. state->mode = EXLEN;
  83943. case EXLEN:
  83944. if (state->flags & 0x0400) {
  83945. NEEDBITS(16);
  83946. state->length = (unsigned)(hold);
  83947. if (state->head != Z_NULL)
  83948. state->head->extra_len = (unsigned)hold;
  83949. if (state->flags & 0x0200) CRC2(state->check, hold);
  83950. INITBITS();
  83951. }
  83952. else if (state->head != Z_NULL)
  83953. state->head->extra = Z_NULL;
  83954. state->mode = EXTRA;
  83955. case EXTRA:
  83956. if (state->flags & 0x0400) {
  83957. copy = state->length;
  83958. if (copy > have) copy = have;
  83959. if (copy) {
  83960. if (state->head != Z_NULL &&
  83961. state->head->extra != Z_NULL) {
  83962. len = state->head->extra_len - state->length;
  83963. zmemcpy(state->head->extra + len, next,
  83964. len + copy > state->head->extra_max ?
  83965. state->head->extra_max - len : copy);
  83966. }
  83967. if (state->flags & 0x0200)
  83968. state->check = crc32(state->check, next, copy);
  83969. have -= copy;
  83970. next += copy;
  83971. state->length -= copy;
  83972. }
  83973. if (state->length) goto inf_leave;
  83974. }
  83975. state->length = 0;
  83976. state->mode = NAME;
  83977. case NAME:
  83978. if (state->flags & 0x0800) {
  83979. if (have == 0) goto inf_leave;
  83980. copy = 0;
  83981. do {
  83982. len = (unsigned)(next[copy++]);
  83983. if (state->head != Z_NULL &&
  83984. state->head->name != Z_NULL &&
  83985. state->length < state->head->name_max)
  83986. state->head->name[state->length++] = len;
  83987. } while (len && copy < have);
  83988. if (state->flags & 0x0200)
  83989. state->check = crc32(state->check, next, copy);
  83990. have -= copy;
  83991. next += copy;
  83992. if (len) goto inf_leave;
  83993. }
  83994. else if (state->head != Z_NULL)
  83995. state->head->name = Z_NULL;
  83996. state->length = 0;
  83997. state->mode = COMMENT;
  83998. case COMMENT:
  83999. if (state->flags & 0x1000) {
  84000. if (have == 0) goto inf_leave;
  84001. copy = 0;
  84002. do {
  84003. len = (unsigned)(next[copy++]);
  84004. if (state->head != Z_NULL &&
  84005. state->head->comment != Z_NULL &&
  84006. state->length < state->head->comm_max)
  84007. state->head->comment[state->length++] = len;
  84008. } while (len && copy < have);
  84009. if (state->flags & 0x0200)
  84010. state->check = crc32(state->check, next, copy);
  84011. have -= copy;
  84012. next += copy;
  84013. if (len) goto inf_leave;
  84014. }
  84015. else if (state->head != Z_NULL)
  84016. state->head->comment = Z_NULL;
  84017. state->mode = HCRC;
  84018. case HCRC:
  84019. if (state->flags & 0x0200) {
  84020. NEEDBITS(16);
  84021. if (hold != (state->check & 0xffff)) {
  84022. strm->msg = (char *)"header crc mismatch";
  84023. state->mode = BAD;
  84024. break;
  84025. }
  84026. INITBITS();
  84027. }
  84028. if (state->head != Z_NULL) {
  84029. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84030. state->head->done = 1;
  84031. }
  84032. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84033. state->mode = TYPE;
  84034. break;
  84035. #endif
  84036. case DICTID:
  84037. NEEDBITS(32);
  84038. strm->adler = state->check = REVERSE(hold);
  84039. INITBITS();
  84040. state->mode = DICT;
  84041. case DICT:
  84042. if (state->havedict == 0) {
  84043. RESTORE();
  84044. return Z_NEED_DICT;
  84045. }
  84046. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84047. state->mode = TYPE;
  84048. case TYPE:
  84049. if (flush == Z_BLOCK) goto inf_leave;
  84050. case TYPEDO:
  84051. if (state->last) {
  84052. BYTEBITS();
  84053. state->mode = CHECK;
  84054. break;
  84055. }
  84056. NEEDBITS(3);
  84057. state->last = BITS(1);
  84058. DROPBITS(1);
  84059. switch (BITS(2)) {
  84060. case 0: /* stored block */
  84061. Tracev((stderr, "inflate: stored block%s\n",
  84062. state->last ? " (last)" : ""));
  84063. state->mode = STORED;
  84064. break;
  84065. case 1: /* fixed block */
  84066. fixedtables(state);
  84067. Tracev((stderr, "inflate: fixed codes block%s\n",
  84068. state->last ? " (last)" : ""));
  84069. state->mode = LEN; /* decode codes */
  84070. break;
  84071. case 2: /* dynamic block */
  84072. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84073. state->last ? " (last)" : ""));
  84074. state->mode = TABLE;
  84075. break;
  84076. case 3:
  84077. strm->msg = (char *)"invalid block type";
  84078. state->mode = BAD;
  84079. }
  84080. DROPBITS(2);
  84081. break;
  84082. case STORED:
  84083. BYTEBITS(); /* go to byte boundary */
  84084. NEEDBITS(32);
  84085. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84086. strm->msg = (char *)"invalid stored block lengths";
  84087. state->mode = BAD;
  84088. break;
  84089. }
  84090. state->length = (unsigned)hold & 0xffff;
  84091. Tracev((stderr, "inflate: stored length %u\n",
  84092. state->length));
  84093. INITBITS();
  84094. state->mode = COPY;
  84095. case COPY:
  84096. copy = state->length;
  84097. if (copy) {
  84098. if (copy > have) copy = have;
  84099. if (copy > left) copy = left;
  84100. if (copy == 0) goto inf_leave;
  84101. zmemcpy(put, next, copy);
  84102. have -= copy;
  84103. next += copy;
  84104. left -= copy;
  84105. put += copy;
  84106. state->length -= copy;
  84107. break;
  84108. }
  84109. Tracev((stderr, "inflate: stored end\n"));
  84110. state->mode = TYPE;
  84111. break;
  84112. case TABLE:
  84113. NEEDBITS(14);
  84114. state->nlen = BITS(5) + 257;
  84115. DROPBITS(5);
  84116. state->ndist = BITS(5) + 1;
  84117. DROPBITS(5);
  84118. state->ncode = BITS(4) + 4;
  84119. DROPBITS(4);
  84120. #ifndef PKZIP_BUG_WORKAROUND
  84121. if (state->nlen > 286 || state->ndist > 30) {
  84122. strm->msg = (char *)"too many length or distance symbols";
  84123. state->mode = BAD;
  84124. break;
  84125. }
  84126. #endif
  84127. Tracev((stderr, "inflate: table sizes ok\n"));
  84128. state->have = 0;
  84129. state->mode = LENLENS;
  84130. case LENLENS:
  84131. while (state->have < state->ncode) {
  84132. NEEDBITS(3);
  84133. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84134. DROPBITS(3);
  84135. }
  84136. while (state->have < 19)
  84137. state->lens[order[state->have++]] = 0;
  84138. state->next = state->codes;
  84139. state->lencode = (code const FAR *)(state->next);
  84140. state->lenbits = 7;
  84141. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84142. &(state->lenbits), state->work);
  84143. if (ret) {
  84144. strm->msg = (char *)"invalid code lengths set";
  84145. state->mode = BAD;
  84146. break;
  84147. }
  84148. Tracev((stderr, "inflate: code lengths ok\n"));
  84149. state->have = 0;
  84150. state->mode = CODELENS;
  84151. case CODELENS:
  84152. while (state->have < state->nlen + state->ndist) {
  84153. for (;;) {
  84154. thisx = state->lencode[BITS(state->lenbits)];
  84155. if ((unsigned)(thisx.bits) <= bits) break;
  84156. PULLBYTE();
  84157. }
  84158. if (thisx.val < 16) {
  84159. NEEDBITS(thisx.bits);
  84160. DROPBITS(thisx.bits);
  84161. state->lens[state->have++] = thisx.val;
  84162. }
  84163. else {
  84164. if (thisx.val == 16) {
  84165. NEEDBITS(thisx.bits + 2);
  84166. DROPBITS(thisx.bits);
  84167. if (state->have == 0) {
  84168. strm->msg = (char *)"invalid bit length repeat";
  84169. state->mode = BAD;
  84170. break;
  84171. }
  84172. len = state->lens[state->have - 1];
  84173. copy = 3 + BITS(2);
  84174. DROPBITS(2);
  84175. }
  84176. else if (thisx.val == 17) {
  84177. NEEDBITS(thisx.bits + 3);
  84178. DROPBITS(thisx.bits);
  84179. len = 0;
  84180. copy = 3 + BITS(3);
  84181. DROPBITS(3);
  84182. }
  84183. else {
  84184. NEEDBITS(thisx.bits + 7);
  84185. DROPBITS(thisx.bits);
  84186. len = 0;
  84187. copy = 11 + BITS(7);
  84188. DROPBITS(7);
  84189. }
  84190. if (state->have + copy > state->nlen + state->ndist) {
  84191. strm->msg = (char *)"invalid bit length repeat";
  84192. state->mode = BAD;
  84193. break;
  84194. }
  84195. while (copy--)
  84196. state->lens[state->have++] = (unsigned short)len;
  84197. }
  84198. }
  84199. /* handle error breaks in while */
  84200. if (state->mode == BAD) break;
  84201. /* build code tables */
  84202. state->next = state->codes;
  84203. state->lencode = (code const FAR *)(state->next);
  84204. state->lenbits = 9;
  84205. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84206. &(state->lenbits), state->work);
  84207. if (ret) {
  84208. strm->msg = (char *)"invalid literal/lengths set";
  84209. state->mode = BAD;
  84210. break;
  84211. }
  84212. state->distcode = (code const FAR *)(state->next);
  84213. state->distbits = 6;
  84214. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84215. &(state->next), &(state->distbits), state->work);
  84216. if (ret) {
  84217. strm->msg = (char *)"invalid distances set";
  84218. state->mode = BAD;
  84219. break;
  84220. }
  84221. Tracev((stderr, "inflate: codes ok\n"));
  84222. state->mode = LEN;
  84223. case LEN:
  84224. if (have >= 6 && left >= 258) {
  84225. RESTORE();
  84226. inflate_fast(strm, out);
  84227. LOAD();
  84228. break;
  84229. }
  84230. for (;;) {
  84231. thisx = state->lencode[BITS(state->lenbits)];
  84232. if ((unsigned)(thisx.bits) <= bits) break;
  84233. PULLBYTE();
  84234. }
  84235. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84236. last = thisx;
  84237. for (;;) {
  84238. thisx = state->lencode[last.val +
  84239. (BITS(last.bits + last.op) >> last.bits)];
  84240. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84241. PULLBYTE();
  84242. }
  84243. DROPBITS(last.bits);
  84244. }
  84245. DROPBITS(thisx.bits);
  84246. state->length = (unsigned)thisx.val;
  84247. if ((int)(thisx.op) == 0) {
  84248. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84249. "inflate: literal '%c'\n" :
  84250. "inflate: literal 0x%02x\n", thisx.val));
  84251. state->mode = LIT;
  84252. break;
  84253. }
  84254. if (thisx.op & 32) {
  84255. Tracevv((stderr, "inflate: end of block\n"));
  84256. state->mode = TYPE;
  84257. break;
  84258. }
  84259. if (thisx.op & 64) {
  84260. strm->msg = (char *)"invalid literal/length code";
  84261. state->mode = BAD;
  84262. break;
  84263. }
  84264. state->extra = (unsigned)(thisx.op) & 15;
  84265. state->mode = LENEXT;
  84266. case LENEXT:
  84267. if (state->extra) {
  84268. NEEDBITS(state->extra);
  84269. state->length += BITS(state->extra);
  84270. DROPBITS(state->extra);
  84271. }
  84272. Tracevv((stderr, "inflate: length %u\n", state->length));
  84273. state->mode = DIST;
  84274. case DIST:
  84275. for (;;) {
  84276. thisx = state->distcode[BITS(state->distbits)];
  84277. if ((unsigned)(thisx.bits) <= bits) break;
  84278. PULLBYTE();
  84279. }
  84280. if ((thisx.op & 0xf0) == 0) {
  84281. last = thisx;
  84282. for (;;) {
  84283. thisx = state->distcode[last.val +
  84284. (BITS(last.bits + last.op) >> last.bits)];
  84285. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84286. PULLBYTE();
  84287. }
  84288. DROPBITS(last.bits);
  84289. }
  84290. DROPBITS(thisx.bits);
  84291. if (thisx.op & 64) {
  84292. strm->msg = (char *)"invalid distance code";
  84293. state->mode = BAD;
  84294. break;
  84295. }
  84296. state->offset = (unsigned)thisx.val;
  84297. state->extra = (unsigned)(thisx.op) & 15;
  84298. state->mode = DISTEXT;
  84299. case DISTEXT:
  84300. if (state->extra) {
  84301. NEEDBITS(state->extra);
  84302. state->offset += BITS(state->extra);
  84303. DROPBITS(state->extra);
  84304. }
  84305. #ifdef INFLATE_STRICT
  84306. if (state->offset > state->dmax) {
  84307. strm->msg = (char *)"invalid distance too far back";
  84308. state->mode = BAD;
  84309. break;
  84310. }
  84311. #endif
  84312. if (state->offset > state->whave + out - left) {
  84313. strm->msg = (char *)"invalid distance too far back";
  84314. state->mode = BAD;
  84315. break;
  84316. }
  84317. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84318. state->mode = MATCH;
  84319. case MATCH:
  84320. if (left == 0) goto inf_leave;
  84321. copy = out - left;
  84322. if (state->offset > copy) { /* copy from window */
  84323. copy = state->offset - copy;
  84324. if (copy > state->write) {
  84325. copy -= state->write;
  84326. from = state->window + (state->wsize - copy);
  84327. }
  84328. else
  84329. from = state->window + (state->write - copy);
  84330. if (copy > state->length) copy = state->length;
  84331. }
  84332. else { /* copy from output */
  84333. from = put - state->offset;
  84334. copy = state->length;
  84335. }
  84336. if (copy > left) copy = left;
  84337. left -= copy;
  84338. state->length -= copy;
  84339. do {
  84340. *put++ = *from++;
  84341. } while (--copy);
  84342. if (state->length == 0) state->mode = LEN;
  84343. break;
  84344. case LIT:
  84345. if (left == 0) goto inf_leave;
  84346. *put++ = (unsigned char)(state->length);
  84347. left--;
  84348. state->mode = LEN;
  84349. break;
  84350. case CHECK:
  84351. if (state->wrap) {
  84352. NEEDBITS(32);
  84353. out -= left;
  84354. strm->total_out += out;
  84355. state->total += out;
  84356. if (out)
  84357. strm->adler = state->check =
  84358. UPDATE(state->check, put - out, out);
  84359. out = left;
  84360. if ((
  84361. #ifdef GUNZIP
  84362. state->flags ? hold :
  84363. #endif
  84364. REVERSE(hold)) != state->check) {
  84365. strm->msg = (char *)"incorrect data check";
  84366. state->mode = BAD;
  84367. break;
  84368. }
  84369. INITBITS();
  84370. Tracev((stderr, "inflate: check matches trailer\n"));
  84371. }
  84372. #ifdef GUNZIP
  84373. state->mode = LENGTH;
  84374. case LENGTH:
  84375. if (state->wrap && state->flags) {
  84376. NEEDBITS(32);
  84377. if (hold != (state->total & 0xffffffffUL)) {
  84378. strm->msg = (char *)"incorrect length check";
  84379. state->mode = BAD;
  84380. break;
  84381. }
  84382. INITBITS();
  84383. Tracev((stderr, "inflate: length matches trailer\n"));
  84384. }
  84385. #endif
  84386. state->mode = DONE;
  84387. case DONE:
  84388. ret = Z_STREAM_END;
  84389. goto inf_leave;
  84390. case BAD:
  84391. ret = Z_DATA_ERROR;
  84392. goto inf_leave;
  84393. case MEM:
  84394. return Z_MEM_ERROR;
  84395. case SYNC:
  84396. default:
  84397. return Z_STREAM_ERROR;
  84398. }
  84399. /*
  84400. Return from inflate(), updating the total counts and the check value.
  84401. If there was no progress during the inflate() call, return a buffer
  84402. error. Call updatewindow() to create and/or update the window state.
  84403. Note: a memory error from inflate() is non-recoverable.
  84404. */
  84405. inf_leave:
  84406. RESTORE();
  84407. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84408. if (updatewindow(strm, out)) {
  84409. state->mode = MEM;
  84410. return Z_MEM_ERROR;
  84411. }
  84412. in -= strm->avail_in;
  84413. out -= strm->avail_out;
  84414. strm->total_in += in;
  84415. strm->total_out += out;
  84416. state->total += out;
  84417. if (state->wrap && out)
  84418. strm->adler = state->check =
  84419. UPDATE(state->check, strm->next_out - out, out);
  84420. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84421. (state->mode == TYPE ? 128 : 0);
  84422. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84423. ret = Z_BUF_ERROR;
  84424. return ret;
  84425. }
  84426. int ZEXPORT inflateEnd (z_streamp strm)
  84427. {
  84428. struct inflate_state FAR *state;
  84429. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84430. return Z_STREAM_ERROR;
  84431. state = (struct inflate_state FAR *)strm->state;
  84432. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84433. ZFREE(strm, strm->state);
  84434. strm->state = Z_NULL;
  84435. Tracev((stderr, "inflate: end\n"));
  84436. return Z_OK;
  84437. }
  84438. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84439. {
  84440. struct inflate_state FAR *state;
  84441. unsigned long id_;
  84442. /* check state */
  84443. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84444. state = (struct inflate_state FAR *)strm->state;
  84445. if (state->wrap != 0 && state->mode != DICT)
  84446. return Z_STREAM_ERROR;
  84447. /* check for correct dictionary id */
  84448. if (state->mode == DICT) {
  84449. id_ = adler32(0L, Z_NULL, 0);
  84450. id_ = adler32(id_, dictionary, dictLength);
  84451. if (id_ != state->check)
  84452. return Z_DATA_ERROR;
  84453. }
  84454. /* copy dictionary to window */
  84455. if (updatewindow(strm, strm->avail_out)) {
  84456. state->mode = MEM;
  84457. return Z_MEM_ERROR;
  84458. }
  84459. if (dictLength > state->wsize) {
  84460. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84461. state->wsize);
  84462. state->whave = state->wsize;
  84463. }
  84464. else {
  84465. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84466. dictLength);
  84467. state->whave = dictLength;
  84468. }
  84469. state->havedict = 1;
  84470. Tracev((stderr, "inflate: dictionary set\n"));
  84471. return Z_OK;
  84472. }
  84473. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84474. {
  84475. struct inflate_state FAR *state;
  84476. /* check state */
  84477. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84478. state = (struct inflate_state FAR *)strm->state;
  84479. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84480. /* save header structure */
  84481. state->head = head;
  84482. head->done = 0;
  84483. return Z_OK;
  84484. }
  84485. /*
  84486. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84487. or when out of input. When called, *have is the number of pattern bytes
  84488. found in order so far, in 0..3. On return *have is updated to the new
  84489. state. If on return *have equals four, then the pattern was found and the
  84490. return value is how many bytes were read including the last byte of the
  84491. pattern. If *have is less than four, then the pattern has not been found
  84492. yet and the return value is len. In the latter case, syncsearch() can be
  84493. called again with more data and the *have state. *have is initialized to
  84494. zero for the first call.
  84495. */
  84496. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84497. {
  84498. unsigned got;
  84499. unsigned next;
  84500. got = *have;
  84501. next = 0;
  84502. while (next < len && got < 4) {
  84503. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84504. got++;
  84505. else if (buf[next])
  84506. got = 0;
  84507. else
  84508. got = 4 - got;
  84509. next++;
  84510. }
  84511. *have = got;
  84512. return next;
  84513. }
  84514. int ZEXPORT inflateSync (z_streamp strm)
  84515. {
  84516. unsigned len; /* number of bytes to look at or looked at */
  84517. unsigned long in, out; /* temporary to save total_in and total_out */
  84518. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84519. struct inflate_state FAR *state;
  84520. /* check parameters */
  84521. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84522. state = (struct inflate_state FAR *)strm->state;
  84523. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84524. /* if first time, start search in bit buffer */
  84525. if (state->mode != SYNC) {
  84526. state->mode = SYNC;
  84527. state->hold <<= state->bits & 7;
  84528. state->bits -= state->bits & 7;
  84529. len = 0;
  84530. while (state->bits >= 8) {
  84531. buf[len++] = (unsigned char)(state->hold);
  84532. state->hold >>= 8;
  84533. state->bits -= 8;
  84534. }
  84535. state->have = 0;
  84536. syncsearch(&(state->have), buf, len);
  84537. }
  84538. /* search available input */
  84539. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84540. strm->avail_in -= len;
  84541. strm->next_in += len;
  84542. strm->total_in += len;
  84543. /* return no joy or set up to restart inflate() on a new block */
  84544. if (state->have != 4) return Z_DATA_ERROR;
  84545. in = strm->total_in; out = strm->total_out;
  84546. inflateReset(strm);
  84547. strm->total_in = in; strm->total_out = out;
  84548. state->mode = TYPE;
  84549. return Z_OK;
  84550. }
  84551. /*
  84552. Returns true if inflate is currently at the end of a block generated by
  84553. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84554. implementation to provide an additional safety check. PPP uses
  84555. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84556. block. When decompressing, PPP checks that at the end of input packet,
  84557. inflate is waiting for these length bytes.
  84558. */
  84559. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84560. {
  84561. struct inflate_state FAR *state;
  84562. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84563. state = (struct inflate_state FAR *)strm->state;
  84564. return state->mode == STORED && state->bits == 0;
  84565. }
  84566. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84567. {
  84568. struct inflate_state FAR *state;
  84569. struct inflate_state FAR *copy;
  84570. unsigned char FAR *window;
  84571. unsigned wsize;
  84572. /* check input */
  84573. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84574. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84575. return Z_STREAM_ERROR;
  84576. state = (struct inflate_state FAR *)source->state;
  84577. /* allocate space */
  84578. copy = (struct inflate_state FAR *)
  84579. ZALLOC(source, 1, sizeof(struct inflate_state));
  84580. if (copy == Z_NULL) return Z_MEM_ERROR;
  84581. window = Z_NULL;
  84582. if (state->window != Z_NULL) {
  84583. window = (unsigned char FAR *)
  84584. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84585. if (window == Z_NULL) {
  84586. ZFREE(source, copy);
  84587. return Z_MEM_ERROR;
  84588. }
  84589. }
  84590. /* copy state */
  84591. zmemcpy(dest, source, sizeof(z_stream));
  84592. zmemcpy(copy, state, sizeof(struct inflate_state));
  84593. if (state->lencode >= state->codes &&
  84594. state->lencode <= state->codes + ENOUGH - 1) {
  84595. copy->lencode = copy->codes + (state->lencode - state->codes);
  84596. copy->distcode = copy->codes + (state->distcode - state->codes);
  84597. }
  84598. copy->next = copy->codes + (state->next - state->codes);
  84599. if (window != Z_NULL) {
  84600. wsize = 1U << state->wbits;
  84601. zmemcpy(window, state->window, wsize);
  84602. }
  84603. copy->window = window;
  84604. dest->state = (struct internal_state FAR *)copy;
  84605. return Z_OK;
  84606. }
  84607. /*** End of inlined file: inflate.c ***/
  84608. /*** Start of inlined file: inftrees.c ***/
  84609. #define MAXBITS 15
  84610. const char inflate_copyright[] =
  84611. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84612. /*
  84613. If you use the zlib library in a product, an acknowledgment is welcome
  84614. in the documentation of your product. If for some reason you cannot
  84615. include such an acknowledgment, I would appreciate that you keep this
  84616. copyright string in the executable of your product.
  84617. */
  84618. /*
  84619. Build a set of tables to decode the provided canonical Huffman code.
  84620. The code lengths are lens[0..codes-1]. The result starts at *table,
  84621. whose indices are 0..2^bits-1. work is a writable array of at least
  84622. lens shorts, which is used as a work area. type is the type of code
  84623. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84624. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84625. on return points to the next available entry's address. bits is the
  84626. requested root table index bits, and on return it is the actual root
  84627. table index bits. It will differ if the request is greater than the
  84628. longest code or if it is less than the shortest code.
  84629. */
  84630. int inflate_table (codetype type,
  84631. unsigned short FAR *lens,
  84632. unsigned codes,
  84633. code FAR * FAR *table,
  84634. unsigned FAR *bits,
  84635. unsigned short FAR *work)
  84636. {
  84637. unsigned len; /* a code's length in bits */
  84638. unsigned sym; /* index of code symbols */
  84639. unsigned min, max; /* minimum and maximum code lengths */
  84640. unsigned root; /* number of index bits for root table */
  84641. unsigned curr; /* number of index bits for current table */
  84642. unsigned drop; /* code bits to drop for sub-table */
  84643. int left; /* number of prefix codes available */
  84644. unsigned used; /* code entries in table used */
  84645. unsigned huff; /* Huffman code */
  84646. unsigned incr; /* for incrementing code, index */
  84647. unsigned fill; /* index for replicating entries */
  84648. unsigned low; /* low bits for current root entry */
  84649. unsigned mask; /* mask for low root bits */
  84650. code thisx; /* table entry for duplication */
  84651. code FAR *next; /* next available space in table */
  84652. const unsigned short FAR *base; /* base value table to use */
  84653. const unsigned short FAR *extra; /* extra bits table to use */
  84654. int end; /* use base and extra for symbol > end */
  84655. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84656. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84657. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84658. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84659. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84660. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84661. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84662. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84663. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84664. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84665. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84666. 8193, 12289, 16385, 24577, 0, 0};
  84667. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84668. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84669. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84670. 28, 28, 29, 29, 64, 64};
  84671. /*
  84672. Process a set of code lengths to create a canonical Huffman code. The
  84673. code lengths are lens[0..codes-1]. Each length corresponds to the
  84674. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84675. symbols by length from short to long, and retaining the symbol order
  84676. for codes with equal lengths. Then the code starts with all zero bits
  84677. for the first code of the shortest length, and the codes are integer
  84678. increments for the same length, and zeros are appended as the length
  84679. increases. For the deflate format, these bits are stored backwards
  84680. from their more natural integer increment ordering, and so when the
  84681. decoding tables are built in the large loop below, the integer codes
  84682. are incremented backwards.
  84683. This routine assumes, but does not check, that all of the entries in
  84684. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84685. 1..MAXBITS is interpreted as that code length. zero means that that
  84686. symbol does not occur in this code.
  84687. The codes are sorted by computing a count of codes for each length,
  84688. creating from that a table of starting indices for each length in the
  84689. sorted table, and then entering the symbols in order in the sorted
  84690. table. The sorted table is work[], with that space being provided by
  84691. the caller.
  84692. The length counts are used for other purposes as well, i.e. finding
  84693. the minimum and maximum length codes, determining if there are any
  84694. codes at all, checking for a valid set of lengths, and looking ahead
  84695. at length counts to determine sub-table sizes when building the
  84696. decoding tables.
  84697. */
  84698. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84699. for (len = 0; len <= MAXBITS; len++)
  84700. count[len] = 0;
  84701. for (sym = 0; sym < codes; sym++)
  84702. count[lens[sym]]++;
  84703. /* bound code lengths, force root to be within code lengths */
  84704. root = *bits;
  84705. for (max = MAXBITS; max >= 1; max--)
  84706. if (count[max] != 0) break;
  84707. if (root > max) root = max;
  84708. if (max == 0) { /* no symbols to code at all */
  84709. thisx.op = (unsigned char)64; /* invalid code marker */
  84710. thisx.bits = (unsigned char)1;
  84711. thisx.val = (unsigned short)0;
  84712. *(*table)++ = thisx; /* make a table to force an error */
  84713. *(*table)++ = thisx;
  84714. *bits = 1;
  84715. return 0; /* no symbols, but wait for decoding to report error */
  84716. }
  84717. for (min = 1; min <= MAXBITS; min++)
  84718. if (count[min] != 0) break;
  84719. if (root < min) root = min;
  84720. /* check for an over-subscribed or incomplete set of lengths */
  84721. left = 1;
  84722. for (len = 1; len <= MAXBITS; len++) {
  84723. left <<= 1;
  84724. left -= count[len];
  84725. if (left < 0) return -1; /* over-subscribed */
  84726. }
  84727. if (left > 0 && (type == CODES || max != 1))
  84728. return -1; /* incomplete set */
  84729. /* generate offsets into symbol table for each length for sorting */
  84730. offs[1] = 0;
  84731. for (len = 1; len < MAXBITS; len++)
  84732. offs[len + 1] = offs[len] + count[len];
  84733. /* sort symbols by length, by symbol order within each length */
  84734. for (sym = 0; sym < codes; sym++)
  84735. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84736. /*
  84737. Create and fill in decoding tables. In this loop, the table being
  84738. filled is at next and has curr index bits. The code being used is huff
  84739. with length len. That code is converted to an index by dropping drop
  84740. bits off of the bottom. For codes where len is less than drop + curr,
  84741. those top drop + curr - len bits are incremented through all values to
  84742. fill the table with replicated entries.
  84743. root is the number of index bits for the root table. When len exceeds
  84744. root, sub-tables are created pointed to by the root entry with an index
  84745. of the low root bits of huff. This is saved in low to check for when a
  84746. new sub-table should be started. drop is zero when the root table is
  84747. being filled, and drop is root when sub-tables are being filled.
  84748. When a new sub-table is needed, it is necessary to look ahead in the
  84749. code lengths to determine what size sub-table is needed. The length
  84750. counts are used for this, and so count[] is decremented as codes are
  84751. entered in the tables.
  84752. used keeps track of how many table entries have been allocated from the
  84753. provided *table space. It is checked when a LENS table is being made
  84754. against the space in *table, ENOUGH, minus the maximum space needed by
  84755. the worst case distance code, MAXD. This should never happen, but the
  84756. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84757. This assumes that when type == LENS, bits == 9.
  84758. sym increments through all symbols, and the loop terminates when
  84759. all codes of length max, i.e. all codes, have been processed. This
  84760. routine permits incomplete codes, so another loop after this one fills
  84761. in the rest of the decoding tables with invalid code markers.
  84762. */
  84763. /* set up for code type */
  84764. switch (type) {
  84765. case CODES:
  84766. base = extra = work; /* dummy value--not used */
  84767. end = 19;
  84768. break;
  84769. case LENS:
  84770. base = lbase;
  84771. base -= 257;
  84772. extra = lext;
  84773. extra -= 257;
  84774. end = 256;
  84775. break;
  84776. default: /* DISTS */
  84777. base = dbase;
  84778. extra = dext;
  84779. end = -1;
  84780. }
  84781. /* initialize state for loop */
  84782. huff = 0; /* starting code */
  84783. sym = 0; /* starting code symbol */
  84784. len = min; /* starting code length */
  84785. next = *table; /* current table to fill in */
  84786. curr = root; /* current table index bits */
  84787. drop = 0; /* current bits to drop from code for index */
  84788. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84789. used = 1U << root; /* use root table entries */
  84790. mask = used - 1; /* mask for comparing low */
  84791. /* check available table space */
  84792. if (type == LENS && used >= ENOUGH - MAXD)
  84793. return 1;
  84794. /* process all codes and make table entries */
  84795. for (;;) {
  84796. /* create table entry */
  84797. thisx.bits = (unsigned char)(len - drop);
  84798. if ((int)(work[sym]) < end) {
  84799. thisx.op = (unsigned char)0;
  84800. thisx.val = work[sym];
  84801. }
  84802. else if ((int)(work[sym]) > end) {
  84803. thisx.op = (unsigned char)(extra[work[sym]]);
  84804. thisx.val = base[work[sym]];
  84805. }
  84806. else {
  84807. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84808. thisx.val = 0;
  84809. }
  84810. /* replicate for those indices with low len bits equal to huff */
  84811. incr = 1U << (len - drop);
  84812. fill = 1U << curr;
  84813. min = fill; /* save offset to next table */
  84814. do {
  84815. fill -= incr;
  84816. next[(huff >> drop) + fill] = thisx;
  84817. } while (fill != 0);
  84818. /* backwards increment the len-bit code huff */
  84819. incr = 1U << (len - 1);
  84820. while (huff & incr)
  84821. incr >>= 1;
  84822. if (incr != 0) {
  84823. huff &= incr - 1;
  84824. huff += incr;
  84825. }
  84826. else
  84827. huff = 0;
  84828. /* go to next symbol, update count, len */
  84829. sym++;
  84830. if (--(count[len]) == 0) {
  84831. if (len == max) break;
  84832. len = lens[work[sym]];
  84833. }
  84834. /* create new sub-table if needed */
  84835. if (len > root && (huff & mask) != low) {
  84836. /* if first time, transition to sub-tables */
  84837. if (drop == 0)
  84838. drop = root;
  84839. /* increment past last table */
  84840. next += min; /* here min is 1 << curr */
  84841. /* determine length of next table */
  84842. curr = len - drop;
  84843. left = (int)(1 << curr);
  84844. while (curr + drop < max) {
  84845. left -= count[curr + drop];
  84846. if (left <= 0) break;
  84847. curr++;
  84848. left <<= 1;
  84849. }
  84850. /* check for enough space */
  84851. used += 1U << curr;
  84852. if (type == LENS && used >= ENOUGH - MAXD)
  84853. return 1;
  84854. /* point entry in root table to sub-table */
  84855. low = huff & mask;
  84856. (*table)[low].op = (unsigned char)curr;
  84857. (*table)[low].bits = (unsigned char)root;
  84858. (*table)[low].val = (unsigned short)(next - *table);
  84859. }
  84860. }
  84861. /*
  84862. Fill in rest of table for incomplete codes. This loop is similar to the
  84863. loop above in incrementing huff for table indices. It is assumed that
  84864. len is equal to curr + drop, so there is no loop needed to increment
  84865. through high index bits. When the current sub-table is filled, the loop
  84866. drops back to the root table to fill in any remaining entries there.
  84867. */
  84868. thisx.op = (unsigned char)64; /* invalid code marker */
  84869. thisx.bits = (unsigned char)(len - drop);
  84870. thisx.val = (unsigned short)0;
  84871. while (huff != 0) {
  84872. /* when done with sub-table, drop back to root table */
  84873. if (drop != 0 && (huff & mask) != low) {
  84874. drop = 0;
  84875. len = root;
  84876. next = *table;
  84877. thisx.bits = (unsigned char)len;
  84878. }
  84879. /* put invalid code marker in table */
  84880. next[huff >> drop] = thisx;
  84881. /* backwards increment the len-bit code huff */
  84882. incr = 1U << (len - 1);
  84883. while (huff & incr)
  84884. incr >>= 1;
  84885. if (incr != 0) {
  84886. huff &= incr - 1;
  84887. huff += incr;
  84888. }
  84889. else
  84890. huff = 0;
  84891. }
  84892. /* set return parameters */
  84893. *table += used;
  84894. *bits = root;
  84895. return 0;
  84896. }
  84897. /*** End of inlined file: inftrees.c ***/
  84898. /*** Start of inlined file: trees.c ***/
  84899. /*
  84900. * ALGORITHM
  84901. *
  84902. * The "deflation" process uses several Huffman trees. The more
  84903. * common source values are represented by shorter bit sequences.
  84904. *
  84905. * Each code tree is stored in a compressed form which is itself
  84906. * a Huffman encoding of the lengths of all the code strings (in
  84907. * ascending order by source values). The actual code strings are
  84908. * reconstructed from the lengths in the inflate process, as described
  84909. * in the deflate specification.
  84910. *
  84911. * REFERENCES
  84912. *
  84913. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84914. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84915. *
  84916. * Storer, James A.
  84917. * Data Compression: Methods and Theory, pp. 49-50.
  84918. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84919. *
  84920. * Sedgewick, R.
  84921. * Algorithms, p290.
  84922. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84923. */
  84924. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84925. /* #define GEN_TREES_H */
  84926. #ifdef DEBUG
  84927. # include <ctype.h>
  84928. #endif
  84929. /* ===========================================================================
  84930. * Constants
  84931. */
  84932. #define MAX_BL_BITS 7
  84933. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84934. #define END_BLOCK 256
  84935. /* end of block literal code */
  84936. #define REP_3_6 16
  84937. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84938. #define REPZ_3_10 17
  84939. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84940. #define REPZ_11_138 18
  84941. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84942. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84943. = {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};
  84944. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84945. = {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};
  84946. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84947. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84948. local const uch bl_order[BL_CODES]
  84949. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84950. /* The lengths of the bit length codes are sent in order of decreasing
  84951. * probability, to avoid transmitting the lengths for unused bit length codes.
  84952. */
  84953. #define Buf_size (8 * 2*sizeof(char))
  84954. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84955. * more than 16 bits on some systems.)
  84956. */
  84957. /* ===========================================================================
  84958. * Local data. These are initialized only once.
  84959. */
  84960. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84961. #if defined(GEN_TREES_H) || !defined(STDC)
  84962. /* non ANSI compilers may not accept trees.h */
  84963. local ct_data static_ltree[L_CODES+2];
  84964. /* The static literal tree. Since the bit lengths are imposed, there is no
  84965. * need for the L_CODES extra codes used during heap construction. However
  84966. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84967. * below).
  84968. */
  84969. local ct_data static_dtree[D_CODES];
  84970. /* The static distance tree. (Actually a trivial tree since all codes use
  84971. * 5 bits.)
  84972. */
  84973. uch _dist_code[DIST_CODE_LEN];
  84974. /* Distance codes. The first 256 values correspond to the distances
  84975. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84976. * the 15 bit distances.
  84977. */
  84978. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84979. /* length code for each normalized match length (0 == MIN_MATCH) */
  84980. local int base_length[LENGTH_CODES];
  84981. /* First normalized length for each code (0 = MIN_MATCH) */
  84982. local int base_dist[D_CODES];
  84983. /* First normalized distance for each code (0 = distance of 1) */
  84984. #else
  84985. /*** Start of inlined file: trees.h ***/
  84986. local const ct_data static_ltree[L_CODES+2] = {
  84987. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84988. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84989. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84990. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84991. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84992. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84993. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84994. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84995. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84996. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84997. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84998. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84999. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85000. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85001. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85002. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85003. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85004. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85005. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85006. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85007. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85008. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85009. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85010. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85011. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85012. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85013. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85014. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85015. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85016. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85017. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85018. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85019. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85020. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85021. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85022. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85023. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85024. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85025. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85026. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85027. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85028. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85029. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85030. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85031. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85032. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85033. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85034. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85035. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85036. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85037. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85038. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85039. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85040. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85041. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85042. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85043. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85044. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85045. };
  85046. local const ct_data static_dtree[D_CODES] = {
  85047. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85048. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85049. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85050. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85051. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85052. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85053. };
  85054. const uch _dist_code[DIST_CODE_LEN] = {
  85055. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85056. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85057. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85058. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85059. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85060. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85061. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85062. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85063. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85064. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85065. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85066. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85067. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85068. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85069. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85070. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85071. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85072. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85073. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85074. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85075. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85076. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85077. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85078. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85079. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85080. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85081. };
  85082. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85083. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85084. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85085. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85086. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85087. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85088. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85089. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85090. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85091. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85092. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85093. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85094. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85095. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85096. };
  85097. local const int base_length[LENGTH_CODES] = {
  85098. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85099. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85100. };
  85101. local const int base_dist[D_CODES] = {
  85102. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85103. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85104. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85105. };
  85106. /*** End of inlined file: trees.h ***/
  85107. #endif /* GEN_TREES_H */
  85108. struct static_tree_desc_s {
  85109. const ct_data *static_tree; /* static tree or NULL */
  85110. const intf *extra_bits; /* extra bits for each code or NULL */
  85111. int extra_base; /* base index for extra_bits */
  85112. int elems; /* max number of elements in the tree */
  85113. int max_length; /* max bit length for the codes */
  85114. };
  85115. local static_tree_desc static_l_desc =
  85116. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85117. local static_tree_desc static_d_desc =
  85118. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85119. local static_tree_desc static_bl_desc =
  85120. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85121. /* ===========================================================================
  85122. * Local (static) routines in this file.
  85123. */
  85124. local void tr_static_init OF((void));
  85125. local void init_block OF((deflate_state *s));
  85126. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85127. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85128. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85129. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85130. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85131. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85132. local int build_bl_tree OF((deflate_state *s));
  85133. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85134. int blcodes));
  85135. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85136. ct_data *dtree));
  85137. local void set_data_type OF((deflate_state *s));
  85138. local unsigned bi_reverse OF((unsigned value, int length));
  85139. local void bi_windup OF((deflate_state *s));
  85140. local void bi_flush OF((deflate_state *s));
  85141. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85142. int header));
  85143. #ifdef GEN_TREES_H
  85144. local void gen_trees_header OF((void));
  85145. #endif
  85146. #ifndef DEBUG
  85147. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85148. /* Send a code of the given tree. c and tree must not have side effects */
  85149. #else /* DEBUG */
  85150. # define send_code(s, c, tree) \
  85151. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85152. send_bits(s, tree[c].Code, tree[c].Len); }
  85153. #endif
  85154. /* ===========================================================================
  85155. * Output a short LSB first on the stream.
  85156. * IN assertion: there is enough room in pendingBuf.
  85157. */
  85158. #define put_short(s, w) { \
  85159. put_byte(s, (uch)((w) & 0xff)); \
  85160. put_byte(s, (uch)((ush)(w) >> 8)); \
  85161. }
  85162. /* ===========================================================================
  85163. * Send a value on a given number of bits.
  85164. * IN assertion: length <= 16 and value fits in length bits.
  85165. */
  85166. #ifdef DEBUG
  85167. local void send_bits OF((deflate_state *s, int value, int length));
  85168. local void send_bits (deflate_state *s, int value, int length)
  85169. {
  85170. Tracevv((stderr," l %2d v %4x ", length, value));
  85171. Assert(length > 0 && length <= 15, "invalid length");
  85172. s->bits_sent += (ulg)length;
  85173. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85174. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85175. * unused bits in value.
  85176. */
  85177. if (s->bi_valid > (int)Buf_size - length) {
  85178. s->bi_buf |= (value << s->bi_valid);
  85179. put_short(s, s->bi_buf);
  85180. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85181. s->bi_valid += length - Buf_size;
  85182. } else {
  85183. s->bi_buf |= value << s->bi_valid;
  85184. s->bi_valid += length;
  85185. }
  85186. }
  85187. #else /* !DEBUG */
  85188. #define send_bits(s, value, length) \
  85189. { int len = length;\
  85190. if (s->bi_valid > (int)Buf_size - len) {\
  85191. int val = value;\
  85192. s->bi_buf |= (val << s->bi_valid);\
  85193. put_short(s, s->bi_buf);\
  85194. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85195. s->bi_valid += len - Buf_size;\
  85196. } else {\
  85197. s->bi_buf |= (value) << s->bi_valid;\
  85198. s->bi_valid += len;\
  85199. }\
  85200. }
  85201. #endif /* DEBUG */
  85202. /* the arguments must not have side effects */
  85203. /* ===========================================================================
  85204. * Initialize the various 'constant' tables.
  85205. */
  85206. local void tr_static_init()
  85207. {
  85208. #if defined(GEN_TREES_H) || !defined(STDC)
  85209. static int static_init_done = 0;
  85210. int n; /* iterates over tree elements */
  85211. int bits; /* bit counter */
  85212. int length; /* length value */
  85213. int code; /* code value */
  85214. int dist; /* distance index */
  85215. ush bl_count[MAX_BITS+1];
  85216. /* number of codes at each bit length for an optimal tree */
  85217. if (static_init_done) return;
  85218. /* For some embedded targets, global variables are not initialized: */
  85219. static_l_desc.static_tree = static_ltree;
  85220. static_l_desc.extra_bits = extra_lbits;
  85221. static_d_desc.static_tree = static_dtree;
  85222. static_d_desc.extra_bits = extra_dbits;
  85223. static_bl_desc.extra_bits = extra_blbits;
  85224. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85225. length = 0;
  85226. for (code = 0; code < LENGTH_CODES-1; code++) {
  85227. base_length[code] = length;
  85228. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85229. _length_code[length++] = (uch)code;
  85230. }
  85231. }
  85232. Assert (length == 256, "tr_static_init: length != 256");
  85233. /* Note that the length 255 (match length 258) can be represented
  85234. * in two different ways: code 284 + 5 bits or code 285, so we
  85235. * overwrite length_code[255] to use the best encoding:
  85236. */
  85237. _length_code[length-1] = (uch)code;
  85238. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85239. dist = 0;
  85240. for (code = 0 ; code < 16; code++) {
  85241. base_dist[code] = dist;
  85242. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85243. _dist_code[dist++] = (uch)code;
  85244. }
  85245. }
  85246. Assert (dist == 256, "tr_static_init: dist != 256");
  85247. dist >>= 7; /* from now on, all distances are divided by 128 */
  85248. for ( ; code < D_CODES; code++) {
  85249. base_dist[code] = dist << 7;
  85250. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85251. _dist_code[256 + dist++] = (uch)code;
  85252. }
  85253. }
  85254. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85255. /* Construct the codes of the static literal tree */
  85256. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85257. n = 0;
  85258. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85259. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85260. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85261. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85262. /* Codes 286 and 287 do not exist, but we must include them in the
  85263. * tree construction to get a canonical Huffman tree (longest code
  85264. * all ones)
  85265. */
  85266. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85267. /* The static distance tree is trivial: */
  85268. for (n = 0; n < D_CODES; n++) {
  85269. static_dtree[n].Len = 5;
  85270. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85271. }
  85272. static_init_done = 1;
  85273. # ifdef GEN_TREES_H
  85274. gen_trees_header();
  85275. # endif
  85276. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85277. }
  85278. /* ===========================================================================
  85279. * Genererate the file trees.h describing the static trees.
  85280. */
  85281. #ifdef GEN_TREES_H
  85282. # ifndef DEBUG
  85283. # include <stdio.h>
  85284. # endif
  85285. # define SEPARATOR(i, last, width) \
  85286. ((i) == (last)? "\n};\n\n" : \
  85287. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85288. void gen_trees_header()
  85289. {
  85290. FILE *header = fopen("trees.h", "w");
  85291. int i;
  85292. Assert (header != NULL, "Can't open trees.h");
  85293. fprintf(header,
  85294. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85295. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85296. for (i = 0; i < L_CODES+2; i++) {
  85297. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85298. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85299. }
  85300. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85301. for (i = 0; i < D_CODES; i++) {
  85302. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85303. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85304. }
  85305. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85306. for (i = 0; i < DIST_CODE_LEN; i++) {
  85307. fprintf(header, "%2u%s", _dist_code[i],
  85308. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85309. }
  85310. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85311. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85312. fprintf(header, "%2u%s", _length_code[i],
  85313. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85314. }
  85315. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85316. for (i = 0; i < LENGTH_CODES; i++) {
  85317. fprintf(header, "%1u%s", base_length[i],
  85318. SEPARATOR(i, LENGTH_CODES-1, 20));
  85319. }
  85320. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85321. for (i = 0; i < D_CODES; i++) {
  85322. fprintf(header, "%5u%s", base_dist[i],
  85323. SEPARATOR(i, D_CODES-1, 10));
  85324. }
  85325. fclose(header);
  85326. }
  85327. #endif /* GEN_TREES_H */
  85328. /* ===========================================================================
  85329. * Initialize the tree data structures for a new zlib stream.
  85330. */
  85331. void _tr_init(deflate_state *s)
  85332. {
  85333. tr_static_init();
  85334. s->l_desc.dyn_tree = s->dyn_ltree;
  85335. s->l_desc.stat_desc = &static_l_desc;
  85336. s->d_desc.dyn_tree = s->dyn_dtree;
  85337. s->d_desc.stat_desc = &static_d_desc;
  85338. s->bl_desc.dyn_tree = s->bl_tree;
  85339. s->bl_desc.stat_desc = &static_bl_desc;
  85340. s->bi_buf = 0;
  85341. s->bi_valid = 0;
  85342. s->last_eob_len = 8; /* enough lookahead for inflate */
  85343. #ifdef DEBUG
  85344. s->compressed_len = 0L;
  85345. s->bits_sent = 0L;
  85346. #endif
  85347. /* Initialize the first block of the first file: */
  85348. init_block(s);
  85349. }
  85350. /* ===========================================================================
  85351. * Initialize a new block.
  85352. */
  85353. local void init_block (deflate_state *s)
  85354. {
  85355. int n; /* iterates over tree elements */
  85356. /* Initialize the trees. */
  85357. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85358. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85359. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85360. s->dyn_ltree[END_BLOCK].Freq = 1;
  85361. s->opt_len = s->static_len = 0L;
  85362. s->last_lit = s->matches = 0;
  85363. }
  85364. #define SMALLEST 1
  85365. /* Index within the heap array of least frequent node in the Huffman tree */
  85366. /* ===========================================================================
  85367. * Remove the smallest element from the heap and recreate the heap with
  85368. * one less element. Updates heap and heap_len.
  85369. */
  85370. #define pqremove(s, tree, top) \
  85371. {\
  85372. top = s->heap[SMALLEST]; \
  85373. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85374. pqdownheap(s, tree, SMALLEST); \
  85375. }
  85376. /* ===========================================================================
  85377. * Compares to subtrees, using the tree depth as tie breaker when
  85378. * the subtrees have equal frequency. This minimizes the worst case length.
  85379. */
  85380. #define smaller(tree, n, m, depth) \
  85381. (tree[n].Freq < tree[m].Freq || \
  85382. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85383. /* ===========================================================================
  85384. * Restore the heap property by moving down the tree starting at node k,
  85385. * exchanging a node with the smallest of its two sons if necessary, stopping
  85386. * when the heap property is re-established (each father smaller than its
  85387. * two sons).
  85388. */
  85389. local void pqdownheap (deflate_state *s,
  85390. ct_data *tree, /* the tree to restore */
  85391. int k) /* node to move down */
  85392. {
  85393. int v = s->heap[k];
  85394. int j = k << 1; /* left son of k */
  85395. while (j <= s->heap_len) {
  85396. /* Set j to the smallest of the two sons: */
  85397. if (j < s->heap_len &&
  85398. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85399. j++;
  85400. }
  85401. /* Exit if v is smaller than both sons */
  85402. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85403. /* Exchange v with the smallest son */
  85404. s->heap[k] = s->heap[j]; k = j;
  85405. /* And continue down the tree, setting j to the left son of k */
  85406. j <<= 1;
  85407. }
  85408. s->heap[k] = v;
  85409. }
  85410. /* ===========================================================================
  85411. * Compute the optimal bit lengths for a tree and update the total bit length
  85412. * for the current block.
  85413. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85414. * above are the tree nodes sorted by increasing frequency.
  85415. * OUT assertions: the field len is set to the optimal bit length, the
  85416. * array bl_count contains the frequencies for each bit length.
  85417. * The length opt_len is updated; static_len is also updated if stree is
  85418. * not null.
  85419. */
  85420. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85421. {
  85422. ct_data *tree = desc->dyn_tree;
  85423. int max_code = desc->max_code;
  85424. const ct_data *stree = desc->stat_desc->static_tree;
  85425. const intf *extra = desc->stat_desc->extra_bits;
  85426. int base = desc->stat_desc->extra_base;
  85427. int max_length = desc->stat_desc->max_length;
  85428. int h; /* heap index */
  85429. int n, m; /* iterate over the tree elements */
  85430. int bits; /* bit length */
  85431. int xbits; /* extra bits */
  85432. ush f; /* frequency */
  85433. int overflow = 0; /* number of elements with bit length too large */
  85434. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85435. /* In a first pass, compute the optimal bit lengths (which may
  85436. * overflow in the case of the bit length tree).
  85437. */
  85438. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85439. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85440. n = s->heap[h];
  85441. bits = tree[tree[n].Dad].Len + 1;
  85442. if (bits > max_length) bits = max_length, overflow++;
  85443. tree[n].Len = (ush)bits;
  85444. /* We overwrite tree[n].Dad which is no longer needed */
  85445. if (n > max_code) continue; /* not a leaf node */
  85446. s->bl_count[bits]++;
  85447. xbits = 0;
  85448. if (n >= base) xbits = extra[n-base];
  85449. f = tree[n].Freq;
  85450. s->opt_len += (ulg)f * (bits + xbits);
  85451. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85452. }
  85453. if (overflow == 0) return;
  85454. Trace((stderr,"\nbit length overflow\n"));
  85455. /* This happens for example on obj2 and pic of the Calgary corpus */
  85456. /* Find the first bit length which could increase: */
  85457. do {
  85458. bits = max_length-1;
  85459. while (s->bl_count[bits] == 0) bits--;
  85460. s->bl_count[bits]--; /* move one leaf down the tree */
  85461. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85462. s->bl_count[max_length]--;
  85463. /* The brother of the overflow item also moves one step up,
  85464. * but this does not affect bl_count[max_length]
  85465. */
  85466. overflow -= 2;
  85467. } while (overflow > 0);
  85468. /* Now recompute all bit lengths, scanning in increasing frequency.
  85469. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85470. * lengths instead of fixing only the wrong ones. This idea is taken
  85471. * from 'ar' written by Haruhiko Okumura.)
  85472. */
  85473. for (bits = max_length; bits != 0; bits--) {
  85474. n = s->bl_count[bits];
  85475. while (n != 0) {
  85476. m = s->heap[--h];
  85477. if (m > max_code) continue;
  85478. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85479. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85480. s->opt_len += ((long)bits - (long)tree[m].Len)
  85481. *(long)tree[m].Freq;
  85482. tree[m].Len = (ush)bits;
  85483. }
  85484. n--;
  85485. }
  85486. }
  85487. }
  85488. /* ===========================================================================
  85489. * Generate the codes for a given tree and bit counts (which need not be
  85490. * optimal).
  85491. * IN assertion: the array bl_count contains the bit length statistics for
  85492. * the given tree and the field len is set for all tree elements.
  85493. * OUT assertion: the field code is set for all tree elements of non
  85494. * zero code length.
  85495. */
  85496. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85497. int max_code, /* largest code with non zero frequency */
  85498. ushf *bl_count) /* number of codes at each bit length */
  85499. {
  85500. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85501. ush code = 0; /* running code value */
  85502. int bits; /* bit index */
  85503. int n; /* code index */
  85504. /* The distribution counts are first used to generate the code values
  85505. * without bit reversal.
  85506. */
  85507. for (bits = 1; bits <= MAX_BITS; bits++) {
  85508. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85509. }
  85510. /* Check that the bit counts in bl_count are consistent. The last code
  85511. * must be all ones.
  85512. */
  85513. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85514. "inconsistent bit counts");
  85515. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85516. for (n = 0; n <= max_code; n++) {
  85517. int len = tree[n].Len;
  85518. if (len == 0) continue;
  85519. /* Now reverse the bits */
  85520. tree[n].Code = bi_reverse(next_code[len]++, len);
  85521. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85522. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85523. }
  85524. }
  85525. /* ===========================================================================
  85526. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85527. * Update the total bit length for the current block.
  85528. * IN assertion: the field freq is set for all tree elements.
  85529. * OUT assertions: the fields len and code are set to the optimal bit length
  85530. * and corresponding code. The length opt_len is updated; static_len is
  85531. * also updated if stree is not null. The field max_code is set.
  85532. */
  85533. local void build_tree (deflate_state *s,
  85534. tree_desc *desc) /* the tree descriptor */
  85535. {
  85536. ct_data *tree = desc->dyn_tree;
  85537. const ct_data *stree = desc->stat_desc->static_tree;
  85538. int elems = desc->stat_desc->elems;
  85539. int n, m; /* iterate over heap elements */
  85540. int max_code = -1; /* largest code with non zero frequency */
  85541. int node; /* new node being created */
  85542. /* Construct the initial heap, with least frequent element in
  85543. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85544. * heap[0] is not used.
  85545. */
  85546. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85547. for (n = 0; n < elems; n++) {
  85548. if (tree[n].Freq != 0) {
  85549. s->heap[++(s->heap_len)] = max_code = n;
  85550. s->depth[n] = 0;
  85551. } else {
  85552. tree[n].Len = 0;
  85553. }
  85554. }
  85555. /* The pkzip format requires that at least one distance code exists,
  85556. * and that at least one bit should be sent even if there is only one
  85557. * possible code. So to avoid special checks later on we force at least
  85558. * two codes of non zero frequency.
  85559. */
  85560. while (s->heap_len < 2) {
  85561. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85562. tree[node].Freq = 1;
  85563. s->depth[node] = 0;
  85564. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85565. /* node is 0 or 1 so it does not have extra bits */
  85566. }
  85567. desc->max_code = max_code;
  85568. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85569. * establish sub-heaps of increasing lengths:
  85570. */
  85571. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85572. /* Construct the Huffman tree by repeatedly combining the least two
  85573. * frequent nodes.
  85574. */
  85575. node = elems; /* next internal node of the tree */
  85576. do {
  85577. pqremove(s, tree, n); /* n = node of least frequency */
  85578. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85579. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85580. s->heap[--(s->heap_max)] = m;
  85581. /* Create a new node father of n and m */
  85582. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85583. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85584. s->depth[n] : s->depth[m]) + 1);
  85585. tree[n].Dad = tree[m].Dad = (ush)node;
  85586. #ifdef DUMP_BL_TREE
  85587. if (tree == s->bl_tree) {
  85588. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85589. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85590. }
  85591. #endif
  85592. /* and insert the new node in the heap */
  85593. s->heap[SMALLEST] = node++;
  85594. pqdownheap(s, tree, SMALLEST);
  85595. } while (s->heap_len >= 2);
  85596. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85597. /* At this point, the fields freq and dad are set. We can now
  85598. * generate the bit lengths.
  85599. */
  85600. gen_bitlen(s, (tree_desc *)desc);
  85601. /* The field len is now set, we can generate the bit codes */
  85602. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85603. }
  85604. /* ===========================================================================
  85605. * Scan a literal or distance tree to determine the frequencies of the codes
  85606. * in the bit length tree.
  85607. */
  85608. local void scan_tree (deflate_state *s,
  85609. ct_data *tree, /* the tree to be scanned */
  85610. int max_code) /* and its largest code of non zero frequency */
  85611. {
  85612. int n; /* iterates over all tree elements */
  85613. int prevlen = -1; /* last emitted length */
  85614. int curlen; /* length of current code */
  85615. int nextlen = tree[0].Len; /* length of next code */
  85616. int count = 0; /* repeat count of the current code */
  85617. int max_count = 7; /* max repeat count */
  85618. int min_count = 4; /* min repeat count */
  85619. if (nextlen == 0) max_count = 138, min_count = 3;
  85620. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85621. for (n = 0; n <= max_code; n++) {
  85622. curlen = nextlen; nextlen = tree[n+1].Len;
  85623. if (++count < max_count && curlen == nextlen) {
  85624. continue;
  85625. } else if (count < min_count) {
  85626. s->bl_tree[curlen].Freq += count;
  85627. } else if (curlen != 0) {
  85628. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85629. s->bl_tree[REP_3_6].Freq++;
  85630. } else if (count <= 10) {
  85631. s->bl_tree[REPZ_3_10].Freq++;
  85632. } else {
  85633. s->bl_tree[REPZ_11_138].Freq++;
  85634. }
  85635. count = 0; prevlen = curlen;
  85636. if (nextlen == 0) {
  85637. max_count = 138, min_count = 3;
  85638. } else if (curlen == nextlen) {
  85639. max_count = 6, min_count = 3;
  85640. } else {
  85641. max_count = 7, min_count = 4;
  85642. }
  85643. }
  85644. }
  85645. /* ===========================================================================
  85646. * Send a literal or distance tree in compressed form, using the codes in
  85647. * bl_tree.
  85648. */
  85649. local void send_tree (deflate_state *s,
  85650. ct_data *tree, /* the tree to be scanned */
  85651. int max_code) /* and its largest code of non zero frequency */
  85652. {
  85653. int n; /* iterates over all tree elements */
  85654. int prevlen = -1; /* last emitted length */
  85655. int curlen; /* length of current code */
  85656. int nextlen = tree[0].Len; /* length of next code */
  85657. int count = 0; /* repeat count of the current code */
  85658. int max_count = 7; /* max repeat count */
  85659. int min_count = 4; /* min repeat count */
  85660. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85661. if (nextlen == 0) max_count = 138, min_count = 3;
  85662. for (n = 0; n <= max_code; n++) {
  85663. curlen = nextlen; nextlen = tree[n+1].Len;
  85664. if (++count < max_count && curlen == nextlen) {
  85665. continue;
  85666. } else if (count < min_count) {
  85667. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85668. } else if (curlen != 0) {
  85669. if (curlen != prevlen) {
  85670. send_code(s, curlen, s->bl_tree); count--;
  85671. }
  85672. Assert(count >= 3 && count <= 6, " 3_6?");
  85673. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85674. } else if (count <= 10) {
  85675. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85676. } else {
  85677. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85678. }
  85679. count = 0; prevlen = curlen;
  85680. if (nextlen == 0) {
  85681. max_count = 138, min_count = 3;
  85682. } else if (curlen == nextlen) {
  85683. max_count = 6, min_count = 3;
  85684. } else {
  85685. max_count = 7, min_count = 4;
  85686. }
  85687. }
  85688. }
  85689. /* ===========================================================================
  85690. * Construct the Huffman tree for the bit lengths and return the index in
  85691. * bl_order of the last bit length code to send.
  85692. */
  85693. local int build_bl_tree (deflate_state *s)
  85694. {
  85695. int max_blindex; /* index of last bit length code of non zero freq */
  85696. /* Determine the bit length frequencies for literal and distance trees */
  85697. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85698. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85699. /* Build the bit length tree: */
  85700. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85701. /* opt_len now includes the length of the tree representations, except
  85702. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85703. */
  85704. /* Determine the number of bit length codes to send. The pkzip format
  85705. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85706. * 3 but the actual value used is 4.)
  85707. */
  85708. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85709. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85710. }
  85711. /* Update opt_len to include the bit length tree and counts */
  85712. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85713. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85714. s->opt_len, s->static_len));
  85715. return max_blindex;
  85716. }
  85717. /* ===========================================================================
  85718. * Send the header for a block using dynamic Huffman trees: the counts, the
  85719. * lengths of the bit length codes, the literal tree and the distance tree.
  85720. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85721. */
  85722. local void send_all_trees (deflate_state *s,
  85723. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85724. {
  85725. int rank; /* index in bl_order */
  85726. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85727. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85728. "too many codes");
  85729. Tracev((stderr, "\nbl counts: "));
  85730. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85731. send_bits(s, dcodes-1, 5);
  85732. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85733. for (rank = 0; rank < blcodes; rank++) {
  85734. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85735. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85736. }
  85737. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85738. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85739. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85740. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85741. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85742. }
  85743. /* ===========================================================================
  85744. * Send a stored block
  85745. */
  85746. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85747. {
  85748. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85749. #ifdef DEBUG
  85750. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85751. s->compressed_len += (stored_len + 4) << 3;
  85752. #endif
  85753. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85754. }
  85755. /* ===========================================================================
  85756. * Send one empty static block to give enough lookahead for inflate.
  85757. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85758. * The current inflate code requires 9 bits of lookahead. If the
  85759. * last two codes for the previous block (real code plus EOB) were coded
  85760. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85761. * the last real code. In this case we send two empty static blocks instead
  85762. * of one. (There are no problems if the previous block is stored or fixed.)
  85763. * To simplify the code, we assume the worst case of last real code encoded
  85764. * on one bit only.
  85765. */
  85766. void _tr_align (deflate_state *s)
  85767. {
  85768. send_bits(s, STATIC_TREES<<1, 3);
  85769. send_code(s, END_BLOCK, static_ltree);
  85770. #ifdef DEBUG
  85771. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85772. #endif
  85773. bi_flush(s);
  85774. /* Of the 10 bits for the empty block, we have already sent
  85775. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85776. * the EOB of the previous block) was thus at least one plus the length
  85777. * of the EOB plus what we have just sent of the empty static block.
  85778. */
  85779. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85780. send_bits(s, STATIC_TREES<<1, 3);
  85781. send_code(s, END_BLOCK, static_ltree);
  85782. #ifdef DEBUG
  85783. s->compressed_len += 10L;
  85784. #endif
  85785. bi_flush(s);
  85786. }
  85787. s->last_eob_len = 7;
  85788. }
  85789. /* ===========================================================================
  85790. * Determine the best encoding for the current block: dynamic trees, static
  85791. * trees or store, and output the encoded block to the zip file.
  85792. */
  85793. void _tr_flush_block (deflate_state *s,
  85794. charf *buf, /* input block, or NULL if too old */
  85795. ulg stored_len, /* length of input block */
  85796. int eof) /* true if this is the last block for a file */
  85797. {
  85798. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85799. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85800. /* Build the Huffman trees unless a stored block is forced */
  85801. if (s->level > 0) {
  85802. /* Check if the file is binary or text */
  85803. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85804. set_data_type(s);
  85805. /* Construct the literal and distance trees */
  85806. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85807. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85808. s->static_len));
  85809. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85810. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85811. s->static_len));
  85812. /* At this point, opt_len and static_len are the total bit lengths of
  85813. * the compressed block data, excluding the tree representations.
  85814. */
  85815. /* Build the bit length tree for the above two trees, and get the index
  85816. * in bl_order of the last bit length code to send.
  85817. */
  85818. max_blindex = build_bl_tree(s);
  85819. /* Determine the best encoding. Compute the block lengths in bytes. */
  85820. opt_lenb = (s->opt_len+3+7)>>3;
  85821. static_lenb = (s->static_len+3+7)>>3;
  85822. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85823. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85824. s->last_lit));
  85825. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85826. } else {
  85827. Assert(buf != (char*)0, "lost buf");
  85828. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85829. }
  85830. #ifdef FORCE_STORED
  85831. if (buf != (char*)0) { /* force stored block */
  85832. #else
  85833. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85834. /* 4: two words for the lengths */
  85835. #endif
  85836. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85837. * Otherwise we can't have processed more than WSIZE input bytes since
  85838. * the last block flush, because compression would have been
  85839. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85840. * transform a block into a stored block.
  85841. */
  85842. _tr_stored_block(s, buf, stored_len, eof);
  85843. #ifdef FORCE_STATIC
  85844. } else if (static_lenb >= 0) { /* force static trees */
  85845. #else
  85846. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85847. #endif
  85848. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85849. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85850. #ifdef DEBUG
  85851. s->compressed_len += 3 + s->static_len;
  85852. #endif
  85853. } else {
  85854. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85855. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85856. max_blindex+1);
  85857. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85858. #ifdef DEBUG
  85859. s->compressed_len += 3 + s->opt_len;
  85860. #endif
  85861. }
  85862. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85863. /* The above check is made mod 2^32, for files larger than 512 MB
  85864. * and uLong implemented on 32 bits.
  85865. */
  85866. init_block(s);
  85867. if (eof) {
  85868. bi_windup(s);
  85869. #ifdef DEBUG
  85870. s->compressed_len += 7; /* align on byte boundary */
  85871. #endif
  85872. }
  85873. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85874. s->compressed_len-7*eof));
  85875. }
  85876. /* ===========================================================================
  85877. * Save the match info and tally the frequency counts. Return true if
  85878. * the current block must be flushed.
  85879. */
  85880. int _tr_tally (deflate_state *s,
  85881. unsigned dist, /* distance of matched string */
  85882. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85883. {
  85884. s->d_buf[s->last_lit] = (ush)dist;
  85885. s->l_buf[s->last_lit++] = (uch)lc;
  85886. if (dist == 0) {
  85887. /* lc is the unmatched char */
  85888. s->dyn_ltree[lc].Freq++;
  85889. } else {
  85890. s->matches++;
  85891. /* Here, lc is the match length - MIN_MATCH */
  85892. dist--; /* dist = match distance - 1 */
  85893. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85894. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85895. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85896. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85897. s->dyn_dtree[d_code(dist)].Freq++;
  85898. }
  85899. #ifdef TRUNCATE_BLOCK
  85900. /* Try to guess if it is profitable to stop the current block here */
  85901. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85902. /* Compute an upper bound for the compressed length */
  85903. ulg out_length = (ulg)s->last_lit*8L;
  85904. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85905. int dcode;
  85906. for (dcode = 0; dcode < D_CODES; dcode++) {
  85907. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85908. (5L+extra_dbits[dcode]);
  85909. }
  85910. out_length >>= 3;
  85911. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85912. s->last_lit, in_length, out_length,
  85913. 100L - out_length*100L/in_length));
  85914. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85915. }
  85916. #endif
  85917. return (s->last_lit == s->lit_bufsize-1);
  85918. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85919. * on 16 bit machines and because stored blocks are restricted to
  85920. * 64K-1 bytes.
  85921. */
  85922. }
  85923. /* ===========================================================================
  85924. * Send the block data compressed using the given Huffman trees
  85925. */
  85926. local void compress_block (deflate_state *s,
  85927. ct_data *ltree, /* literal tree */
  85928. ct_data *dtree) /* distance tree */
  85929. {
  85930. unsigned dist; /* distance of matched string */
  85931. int lc; /* match length or unmatched char (if dist == 0) */
  85932. unsigned lx = 0; /* running index in l_buf */
  85933. unsigned code; /* the code to send */
  85934. int extra; /* number of extra bits to send */
  85935. if (s->last_lit != 0) do {
  85936. dist = s->d_buf[lx];
  85937. lc = s->l_buf[lx++];
  85938. if (dist == 0) {
  85939. send_code(s, lc, ltree); /* send a literal byte */
  85940. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85941. } else {
  85942. /* Here, lc is the match length - MIN_MATCH */
  85943. code = _length_code[lc];
  85944. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85945. extra = extra_lbits[code];
  85946. if (extra != 0) {
  85947. lc -= base_length[code];
  85948. send_bits(s, lc, extra); /* send the extra length bits */
  85949. }
  85950. dist--; /* dist is now the match distance - 1 */
  85951. code = d_code(dist);
  85952. Assert (code < D_CODES, "bad d_code");
  85953. send_code(s, code, dtree); /* send the distance code */
  85954. extra = extra_dbits[code];
  85955. if (extra != 0) {
  85956. dist -= base_dist[code];
  85957. send_bits(s, dist, extra); /* send the extra distance bits */
  85958. }
  85959. } /* literal or match pair ? */
  85960. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85961. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85962. "pendingBuf overflow");
  85963. } while (lx < s->last_lit);
  85964. send_code(s, END_BLOCK, ltree);
  85965. s->last_eob_len = ltree[END_BLOCK].Len;
  85966. }
  85967. /* ===========================================================================
  85968. * Set the data type to BINARY or TEXT, using a crude approximation:
  85969. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85970. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85971. * IN assertion: the fields Freq of dyn_ltree are set.
  85972. */
  85973. local void set_data_type (deflate_state *s)
  85974. {
  85975. int n;
  85976. for (n = 0; n < 9; n++)
  85977. if (s->dyn_ltree[n].Freq != 0)
  85978. break;
  85979. if (n == 9)
  85980. for (n = 14; n < 32; n++)
  85981. if (s->dyn_ltree[n].Freq != 0)
  85982. break;
  85983. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85984. }
  85985. /* ===========================================================================
  85986. * Reverse the first len bits of a code, using straightforward code (a faster
  85987. * method would use a table)
  85988. * IN assertion: 1 <= len <= 15
  85989. */
  85990. local unsigned bi_reverse (unsigned code, int len)
  85991. {
  85992. register unsigned res = 0;
  85993. do {
  85994. res |= code & 1;
  85995. code >>= 1, res <<= 1;
  85996. } while (--len > 0);
  85997. return res >> 1;
  85998. }
  85999. /* ===========================================================================
  86000. * Flush the bit buffer, keeping at most 7 bits in it.
  86001. */
  86002. local void bi_flush (deflate_state *s)
  86003. {
  86004. if (s->bi_valid == 16) {
  86005. put_short(s, s->bi_buf);
  86006. s->bi_buf = 0;
  86007. s->bi_valid = 0;
  86008. } else if (s->bi_valid >= 8) {
  86009. put_byte(s, (Byte)s->bi_buf);
  86010. s->bi_buf >>= 8;
  86011. s->bi_valid -= 8;
  86012. }
  86013. }
  86014. /* ===========================================================================
  86015. * Flush the bit buffer and align the output on a byte boundary
  86016. */
  86017. local void bi_windup (deflate_state *s)
  86018. {
  86019. if (s->bi_valid > 8) {
  86020. put_short(s, s->bi_buf);
  86021. } else if (s->bi_valid > 0) {
  86022. put_byte(s, (Byte)s->bi_buf);
  86023. }
  86024. s->bi_buf = 0;
  86025. s->bi_valid = 0;
  86026. #ifdef DEBUG
  86027. s->bits_sent = (s->bits_sent+7) & ~7;
  86028. #endif
  86029. }
  86030. /* ===========================================================================
  86031. * Copy a stored block, storing first the length and its
  86032. * one's complement if requested.
  86033. */
  86034. local void copy_block(deflate_state *s,
  86035. charf *buf, /* the input data */
  86036. unsigned len, /* its length */
  86037. int header) /* true if block header must be written */
  86038. {
  86039. bi_windup(s); /* align on byte boundary */
  86040. s->last_eob_len = 8; /* enough lookahead for inflate */
  86041. if (header) {
  86042. put_short(s, (ush)len);
  86043. put_short(s, (ush)~len);
  86044. #ifdef DEBUG
  86045. s->bits_sent += 2*16;
  86046. #endif
  86047. }
  86048. #ifdef DEBUG
  86049. s->bits_sent += (ulg)len<<3;
  86050. #endif
  86051. while (len--) {
  86052. put_byte(s, *buf++);
  86053. }
  86054. }
  86055. /*** End of inlined file: trees.c ***/
  86056. /*** Start of inlined file: zutil.c ***/
  86057. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86058. #ifndef NO_DUMMY_DECL
  86059. struct internal_state {int dummy;}; /* for buggy compilers */
  86060. #endif
  86061. const char * const z_errmsg[10] = {
  86062. "need dictionary", /* Z_NEED_DICT 2 */
  86063. "stream end", /* Z_STREAM_END 1 */
  86064. "", /* Z_OK 0 */
  86065. "file error", /* Z_ERRNO (-1) */
  86066. "stream error", /* Z_STREAM_ERROR (-2) */
  86067. "data error", /* Z_DATA_ERROR (-3) */
  86068. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86069. "buffer error", /* Z_BUF_ERROR (-5) */
  86070. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86071. ""};
  86072. /*const char * ZEXPORT zlibVersion()
  86073. {
  86074. return ZLIB_VERSION;
  86075. }
  86076. uLong ZEXPORT zlibCompileFlags()
  86077. {
  86078. uLong flags;
  86079. flags = 0;
  86080. switch (sizeof(uInt)) {
  86081. case 2: break;
  86082. case 4: flags += 1; break;
  86083. case 8: flags += 2; break;
  86084. default: flags += 3;
  86085. }
  86086. switch (sizeof(uLong)) {
  86087. case 2: break;
  86088. case 4: flags += 1 << 2; break;
  86089. case 8: flags += 2 << 2; break;
  86090. default: flags += 3 << 2;
  86091. }
  86092. switch (sizeof(voidpf)) {
  86093. case 2: break;
  86094. case 4: flags += 1 << 4; break;
  86095. case 8: flags += 2 << 4; break;
  86096. default: flags += 3 << 4;
  86097. }
  86098. switch (sizeof(z_off_t)) {
  86099. case 2: break;
  86100. case 4: flags += 1 << 6; break;
  86101. case 8: flags += 2 << 6; break;
  86102. default: flags += 3 << 6;
  86103. }
  86104. #ifdef DEBUG
  86105. flags += 1 << 8;
  86106. #endif
  86107. #if defined(ASMV) || defined(ASMINF)
  86108. flags += 1 << 9;
  86109. #endif
  86110. #ifdef ZLIB_WINAPI
  86111. flags += 1 << 10;
  86112. #endif
  86113. #ifdef BUILDFIXED
  86114. flags += 1 << 12;
  86115. #endif
  86116. #ifdef DYNAMIC_CRC_TABLE
  86117. flags += 1 << 13;
  86118. #endif
  86119. #ifdef NO_GZCOMPRESS
  86120. flags += 1L << 16;
  86121. #endif
  86122. #ifdef NO_GZIP
  86123. flags += 1L << 17;
  86124. #endif
  86125. #ifdef PKZIP_BUG_WORKAROUND
  86126. flags += 1L << 20;
  86127. #endif
  86128. #ifdef FASTEST
  86129. flags += 1L << 21;
  86130. #endif
  86131. #ifdef STDC
  86132. # ifdef NO_vsnprintf
  86133. flags += 1L << 25;
  86134. # ifdef HAS_vsprintf_void
  86135. flags += 1L << 26;
  86136. # endif
  86137. # else
  86138. # ifdef HAS_vsnprintf_void
  86139. flags += 1L << 26;
  86140. # endif
  86141. # endif
  86142. #else
  86143. flags += 1L << 24;
  86144. # ifdef NO_snprintf
  86145. flags += 1L << 25;
  86146. # ifdef HAS_sprintf_void
  86147. flags += 1L << 26;
  86148. # endif
  86149. # else
  86150. # ifdef HAS_snprintf_void
  86151. flags += 1L << 26;
  86152. # endif
  86153. # endif
  86154. #endif
  86155. return flags;
  86156. }*/
  86157. #ifdef DEBUG
  86158. # ifndef verbose
  86159. # define verbose 0
  86160. # endif
  86161. int z_verbose = verbose;
  86162. void z_error (const char *m)
  86163. {
  86164. fprintf(stderr, "%s\n", m);
  86165. exit(1);
  86166. }
  86167. #endif
  86168. /* exported to allow conversion of error code to string for compress() and
  86169. * uncompress()
  86170. */
  86171. const char * ZEXPORT zError(int err)
  86172. {
  86173. return ERR_MSG(err);
  86174. }
  86175. #if defined(_WIN32_WCE)
  86176. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86177. * errno. We define it as a global variable to simplify porting.
  86178. * Its value is always 0 and should not be used.
  86179. */
  86180. int errno = 0;
  86181. #endif
  86182. #ifndef HAVE_MEMCPY
  86183. void zmemcpy(dest, source, len)
  86184. Bytef* dest;
  86185. const Bytef* source;
  86186. uInt len;
  86187. {
  86188. if (len == 0) return;
  86189. do {
  86190. *dest++ = *source++; /* ??? to be unrolled */
  86191. } while (--len != 0);
  86192. }
  86193. int zmemcmp(s1, s2, len)
  86194. const Bytef* s1;
  86195. const Bytef* s2;
  86196. uInt len;
  86197. {
  86198. uInt j;
  86199. for (j = 0; j < len; j++) {
  86200. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86201. }
  86202. return 0;
  86203. }
  86204. void zmemzero(dest, len)
  86205. Bytef* dest;
  86206. uInt len;
  86207. {
  86208. if (len == 0) return;
  86209. do {
  86210. *dest++ = 0; /* ??? to be unrolled */
  86211. } while (--len != 0);
  86212. }
  86213. #endif
  86214. #ifdef SYS16BIT
  86215. #ifdef __TURBOC__
  86216. /* Turbo C in 16-bit mode */
  86217. # define MY_ZCALLOC
  86218. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86219. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86220. * must fix the pointer. Warning: the pointer must be put back to its
  86221. * original form in order to free it, use zcfree().
  86222. */
  86223. #define MAX_PTR 10
  86224. /* 10*64K = 640K */
  86225. local int next_ptr = 0;
  86226. typedef struct ptr_table_s {
  86227. voidpf org_ptr;
  86228. voidpf new_ptr;
  86229. } ptr_table;
  86230. local ptr_table table[MAX_PTR];
  86231. /* This table is used to remember the original form of pointers
  86232. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86233. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86234. * protected from concurrent access. This hack doesn't work anyway on
  86235. * a protected system like OS/2. Use Microsoft C instead.
  86236. */
  86237. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86238. {
  86239. voidpf buf = opaque; /* just to make some compilers happy */
  86240. ulg bsize = (ulg)items*size;
  86241. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86242. * will return a usable pointer which doesn't have to be normalized.
  86243. */
  86244. if (bsize < 65520L) {
  86245. buf = farmalloc(bsize);
  86246. if (*(ush*)&buf != 0) return buf;
  86247. } else {
  86248. buf = farmalloc(bsize + 16L);
  86249. }
  86250. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86251. table[next_ptr].org_ptr = buf;
  86252. /* Normalize the pointer to seg:0 */
  86253. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86254. *(ush*)&buf = 0;
  86255. table[next_ptr++].new_ptr = buf;
  86256. return buf;
  86257. }
  86258. void zcfree (voidpf opaque, voidpf ptr)
  86259. {
  86260. int n;
  86261. if (*(ush*)&ptr != 0) { /* object < 64K */
  86262. farfree(ptr);
  86263. return;
  86264. }
  86265. /* Find the original pointer */
  86266. for (n = 0; n < next_ptr; n++) {
  86267. if (ptr != table[n].new_ptr) continue;
  86268. farfree(table[n].org_ptr);
  86269. while (++n < next_ptr) {
  86270. table[n-1] = table[n];
  86271. }
  86272. next_ptr--;
  86273. return;
  86274. }
  86275. ptr = opaque; /* just to make some compilers happy */
  86276. Assert(0, "zcfree: ptr not found");
  86277. }
  86278. #endif /* __TURBOC__ */
  86279. #ifdef M_I86
  86280. /* Microsoft C in 16-bit mode */
  86281. # define MY_ZCALLOC
  86282. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86283. # define _halloc halloc
  86284. # define _hfree hfree
  86285. #endif
  86286. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86287. {
  86288. if (opaque) opaque = 0; /* to make compiler happy */
  86289. return _halloc((long)items, size);
  86290. }
  86291. void zcfree (voidpf opaque, voidpf ptr)
  86292. {
  86293. if (opaque) opaque = 0; /* to make compiler happy */
  86294. _hfree(ptr);
  86295. }
  86296. #endif /* M_I86 */
  86297. #endif /* SYS16BIT */
  86298. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86299. #ifndef STDC
  86300. extern voidp malloc OF((uInt size));
  86301. extern voidp calloc OF((uInt items, uInt size));
  86302. extern void free OF((voidpf ptr));
  86303. #endif
  86304. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86305. {
  86306. if (opaque) items += size - size; /* make compiler happy */
  86307. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86308. (voidpf)calloc(items, size);
  86309. }
  86310. void zcfree (voidpf opaque, voidpf ptr)
  86311. {
  86312. free(ptr);
  86313. if (opaque) return; /* make compiler happy */
  86314. }
  86315. #endif /* MY_ZCALLOC */
  86316. /*** End of inlined file: zutil.c ***/
  86317. #undef Byte
  86318. #else
  86319. #include <zlib.h>
  86320. #endif
  86321. }
  86322. #if JUCE_MSVC
  86323. #pragma warning (pop)
  86324. #endif
  86325. BEGIN_JUCE_NAMESPACE
  86326. // internal helper object that holds the zlib structures so they don't have to be
  86327. // included publicly.
  86328. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86329. {
  86330. public:
  86331. GZIPDecompressHelper (const bool noWrap)
  86332. : finished (true),
  86333. needsDictionary (false),
  86334. error (true),
  86335. streamIsValid (false),
  86336. data (0),
  86337. dataSize (0)
  86338. {
  86339. using namespace zlibNamespace;
  86340. zerostruct (stream);
  86341. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86342. finished = error = ! streamIsValid;
  86343. }
  86344. ~GZIPDecompressHelper()
  86345. {
  86346. using namespace zlibNamespace;
  86347. if (streamIsValid)
  86348. inflateEnd (&stream);
  86349. }
  86350. bool needsInput() const throw() { return dataSize <= 0; }
  86351. void setInput (uint8* const data_, const int size) throw()
  86352. {
  86353. data = data_;
  86354. dataSize = size;
  86355. }
  86356. int doNextBlock (uint8* const dest, const int destSize)
  86357. {
  86358. using namespace zlibNamespace;
  86359. if (streamIsValid && data != 0 && ! finished)
  86360. {
  86361. stream.next_in = data;
  86362. stream.next_out = dest;
  86363. stream.avail_in = dataSize;
  86364. stream.avail_out = destSize;
  86365. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86366. {
  86367. case Z_STREAM_END:
  86368. finished = true;
  86369. // deliberate fall-through
  86370. case Z_OK:
  86371. data += dataSize - stream.avail_in;
  86372. dataSize = stream.avail_in;
  86373. return destSize - stream.avail_out;
  86374. case Z_NEED_DICT:
  86375. needsDictionary = true;
  86376. data += dataSize - stream.avail_in;
  86377. dataSize = stream.avail_in;
  86378. break;
  86379. case Z_DATA_ERROR:
  86380. case Z_MEM_ERROR:
  86381. error = true;
  86382. default:
  86383. break;
  86384. }
  86385. }
  86386. return 0;
  86387. }
  86388. bool finished, needsDictionary, error, streamIsValid;
  86389. enum { gzipDecompBufferSize = 32768 };
  86390. private:
  86391. zlibNamespace::z_stream stream;
  86392. uint8* data;
  86393. int dataSize;
  86394. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86395. };
  86396. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86397. const bool deleteSourceWhenDestroyed,
  86398. const bool noWrap_,
  86399. const int64 uncompressedStreamLength_)
  86400. : sourceStream (sourceStream_, deleteSourceWhenDestroyed),
  86401. uncompressedStreamLength (uncompressedStreamLength_),
  86402. noWrap (noWrap_),
  86403. isEof (false),
  86404. activeBufferSize (0),
  86405. originalSourcePos (sourceStream_->getPosition()),
  86406. currentPos (0),
  86407. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86408. helper (new GZIPDecompressHelper (noWrap_))
  86409. {
  86410. }
  86411. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86412. : sourceStream (&sourceStream_, false),
  86413. uncompressedStreamLength (-1),
  86414. noWrap (false),
  86415. isEof (false),
  86416. activeBufferSize (0),
  86417. originalSourcePos (sourceStream_.getPosition()),
  86418. currentPos (0),
  86419. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86420. helper (new GZIPDecompressHelper (false))
  86421. {
  86422. }
  86423. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86424. {
  86425. }
  86426. int64 GZIPDecompressorInputStream::getTotalLength()
  86427. {
  86428. return uncompressedStreamLength;
  86429. }
  86430. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86431. {
  86432. if ((howMany > 0) && ! isEof)
  86433. {
  86434. jassert (destBuffer != 0);
  86435. if (destBuffer != 0)
  86436. {
  86437. int numRead = 0;
  86438. uint8* d = static_cast <uint8*> (destBuffer);
  86439. while (! helper->error)
  86440. {
  86441. const int n = helper->doNextBlock (d, howMany);
  86442. currentPos += n;
  86443. if (n == 0)
  86444. {
  86445. if (helper->finished || helper->needsDictionary)
  86446. {
  86447. isEof = true;
  86448. return numRead;
  86449. }
  86450. if (helper->needsInput())
  86451. {
  86452. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86453. if (activeBufferSize > 0)
  86454. {
  86455. helper->setInput (buffer, activeBufferSize);
  86456. }
  86457. else
  86458. {
  86459. isEof = true;
  86460. return numRead;
  86461. }
  86462. }
  86463. }
  86464. else
  86465. {
  86466. numRead += n;
  86467. howMany -= n;
  86468. d += n;
  86469. if (howMany <= 0)
  86470. return numRead;
  86471. }
  86472. }
  86473. }
  86474. }
  86475. return 0;
  86476. }
  86477. bool GZIPDecompressorInputStream::isExhausted()
  86478. {
  86479. return helper->error || isEof;
  86480. }
  86481. int64 GZIPDecompressorInputStream::getPosition()
  86482. {
  86483. return currentPos;
  86484. }
  86485. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86486. {
  86487. if (newPos < currentPos)
  86488. {
  86489. // to go backwards, reset the stream and start again..
  86490. isEof = false;
  86491. activeBufferSize = 0;
  86492. currentPos = 0;
  86493. helper = new GZIPDecompressHelper (noWrap);
  86494. sourceStream->setPosition (originalSourcePos);
  86495. }
  86496. skipNextBytes (newPos - currentPos);
  86497. return true;
  86498. }
  86499. END_JUCE_NAMESPACE
  86500. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86501. #endif
  86502. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86503. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86504. #if JUCE_USE_FLAC
  86505. #if JUCE_WINDOWS
  86506. #include <windows.h>
  86507. #endif
  86508. namespace FlacNamespace
  86509. {
  86510. #if JUCE_INCLUDE_FLAC_CODE
  86511. #if JUCE_MSVC
  86512. #pragma warning (disable: 4505 181 111)
  86513. #endif
  86514. #define FLAC__NO_DLL 1
  86515. #if ! defined (SIZE_MAX)
  86516. #define SIZE_MAX 0xffffffff
  86517. #endif
  86518. #define __STDC_LIMIT_MACROS 1
  86519. /*** Start of inlined file: all.h ***/
  86520. #ifndef FLAC__ALL_H
  86521. #define FLAC__ALL_H
  86522. /*** Start of inlined file: export.h ***/
  86523. #ifndef FLAC__EXPORT_H
  86524. #define FLAC__EXPORT_H
  86525. /** \file include/FLAC/export.h
  86526. *
  86527. * \brief
  86528. * This module contains #defines and symbols for exporting function
  86529. * calls, and providing version information and compiled-in features.
  86530. *
  86531. * See the \link flac_export export \endlink module.
  86532. */
  86533. /** \defgroup flac_export FLAC/export.h: export symbols
  86534. * \ingroup flac
  86535. *
  86536. * \brief
  86537. * This module contains #defines and symbols for exporting function
  86538. * calls, and providing version information and compiled-in features.
  86539. *
  86540. * If you are compiling with MSVC and will link to the static library
  86541. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86542. * make sure the symbols are exported properly.
  86543. *
  86544. * \{
  86545. */
  86546. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86547. #define FLAC_API
  86548. #else
  86549. #ifdef FLAC_API_EXPORTS
  86550. #define FLAC_API _declspec(dllexport)
  86551. #else
  86552. #define FLAC_API _declspec(dllimport)
  86553. #endif
  86554. #endif
  86555. /** These #defines will mirror the libtool-based library version number, see
  86556. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86557. */
  86558. #define FLAC_API_VERSION_CURRENT 10
  86559. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86560. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86561. #ifdef __cplusplus
  86562. extern "C" {
  86563. #endif
  86564. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86565. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86566. #ifdef __cplusplus
  86567. }
  86568. #endif
  86569. /* \} */
  86570. #endif
  86571. /*** End of inlined file: export.h ***/
  86572. /*** Start of inlined file: assert.h ***/
  86573. #ifndef FLAC__ASSERT_H
  86574. #define FLAC__ASSERT_H
  86575. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86576. #ifdef DEBUG
  86577. #include <assert.h>
  86578. #define FLAC__ASSERT(x) assert(x)
  86579. #define FLAC__ASSERT_DECLARATION(x) x
  86580. #else
  86581. #define FLAC__ASSERT(x)
  86582. #define FLAC__ASSERT_DECLARATION(x)
  86583. #endif
  86584. #endif
  86585. /*** End of inlined file: assert.h ***/
  86586. /*** Start of inlined file: callback.h ***/
  86587. #ifndef FLAC__CALLBACK_H
  86588. #define FLAC__CALLBACK_H
  86589. /*** Start of inlined file: ordinals.h ***/
  86590. #ifndef FLAC__ORDINALS_H
  86591. #define FLAC__ORDINALS_H
  86592. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86593. #include <inttypes.h>
  86594. #endif
  86595. typedef signed char FLAC__int8;
  86596. typedef unsigned char FLAC__uint8;
  86597. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86598. typedef __int16 FLAC__int16;
  86599. typedef __int32 FLAC__int32;
  86600. typedef __int64 FLAC__int64;
  86601. typedef unsigned __int16 FLAC__uint16;
  86602. typedef unsigned __int32 FLAC__uint32;
  86603. typedef unsigned __int64 FLAC__uint64;
  86604. #elif defined(__EMX__)
  86605. typedef short FLAC__int16;
  86606. typedef long FLAC__int32;
  86607. typedef long long FLAC__int64;
  86608. typedef unsigned short FLAC__uint16;
  86609. typedef unsigned long FLAC__uint32;
  86610. typedef unsigned long long FLAC__uint64;
  86611. #else
  86612. typedef int16_t FLAC__int16;
  86613. typedef int32_t FLAC__int32;
  86614. typedef int64_t FLAC__int64;
  86615. typedef uint16_t FLAC__uint16;
  86616. typedef uint32_t FLAC__uint32;
  86617. typedef uint64_t FLAC__uint64;
  86618. #endif
  86619. typedef int FLAC__bool;
  86620. typedef FLAC__uint8 FLAC__byte;
  86621. #ifdef true
  86622. #undef true
  86623. #endif
  86624. #ifdef false
  86625. #undef false
  86626. #endif
  86627. #ifndef __cplusplus
  86628. #define true 1
  86629. #define false 0
  86630. #endif
  86631. #endif
  86632. /*** End of inlined file: ordinals.h ***/
  86633. #include <stdlib.h> /* for size_t */
  86634. /** \file include/FLAC/callback.h
  86635. *
  86636. * \brief
  86637. * This module defines the structures for describing I/O callbacks
  86638. * to the other FLAC interfaces.
  86639. *
  86640. * See the detailed documentation for callbacks in the
  86641. * \link flac_callbacks callbacks \endlink module.
  86642. */
  86643. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86644. * \ingroup flac
  86645. *
  86646. * \brief
  86647. * This module defines the structures for describing I/O callbacks
  86648. * to the other FLAC interfaces.
  86649. *
  86650. * The purpose of the I/O callback functions is to create a common way
  86651. * for the metadata interfaces to handle I/O.
  86652. *
  86653. * Originally the metadata interfaces required filenames as the way of
  86654. * specifying FLAC files to operate on. This is problematic in some
  86655. * environments so there is an additional option to specify a set of
  86656. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86657. *
  86658. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86659. * opaque structure for a data source.
  86660. *
  86661. * The callback function prototypes are similar (but not identical) to the
  86662. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86663. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86664. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86665. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86666. * is required. \warning You generally CANNOT directly use fseek or ftell
  86667. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86668. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86669. * large files. You will have to find an equivalent function (e.g. ftello),
  86670. * or write a wrapper. The same is true for feof() since this is usually
  86671. * implemented as a macro, not as a function whose address can be taken.
  86672. *
  86673. * \{
  86674. */
  86675. #ifdef __cplusplus
  86676. extern "C" {
  86677. #endif
  86678. /** This is the opaque handle type used by the callbacks. Typically
  86679. * this is a \c FILE* or address of a file descriptor.
  86680. */
  86681. typedef void* FLAC__IOHandle;
  86682. /** Signature for the read callback.
  86683. * The signature and semantics match POSIX fread() implementations
  86684. * and can generally be used interchangeably.
  86685. *
  86686. * \param ptr The address of the read buffer.
  86687. * \param size The size of the records to be read.
  86688. * \param nmemb The number of records to be read.
  86689. * \param handle The handle to the data source.
  86690. * \retval size_t
  86691. * The number of records read.
  86692. */
  86693. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86694. /** Signature for the write callback.
  86695. * The signature and semantics match POSIX fwrite() implementations
  86696. * and can generally be used interchangeably.
  86697. *
  86698. * \param ptr The address of the write buffer.
  86699. * \param size The size of the records to be written.
  86700. * \param nmemb The number of records to be written.
  86701. * \param handle The handle to the data source.
  86702. * \retval size_t
  86703. * The number of records written.
  86704. */
  86705. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86706. /** Signature for the seek callback.
  86707. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86708. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86709. * and 32-bits wide.
  86710. *
  86711. * \param handle The handle to the data source.
  86712. * \param offset The new position, relative to \a whence
  86713. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86714. * \retval int
  86715. * \c 0 on success, \c -1 on error.
  86716. */
  86717. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86718. /** Signature for the tell callback.
  86719. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86720. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86721. * and 32-bits wide.
  86722. *
  86723. * \param handle The handle to the data source.
  86724. * \retval FLAC__int64
  86725. * The current position on success, \c -1 on error.
  86726. */
  86727. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86728. /** Signature for the EOF callback.
  86729. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86730. * on many systems, feof() is a macro, so in this case a wrapper function
  86731. * must be provided instead.
  86732. *
  86733. * \param handle The handle to the data source.
  86734. * \retval int
  86735. * \c 0 if not at end of file, nonzero if at end of file.
  86736. */
  86737. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86738. /** Signature for the close callback.
  86739. * The signature and semantics match POSIX fclose() implementations
  86740. * and can generally be used interchangeably.
  86741. *
  86742. * \param handle The handle to the data source.
  86743. * \retval int
  86744. * \c 0 on success, \c EOF on error.
  86745. */
  86746. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86747. /** A structure for holding a set of callbacks.
  86748. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86749. * describe which of the callbacks are required. The ones that are not
  86750. * required may be set to NULL.
  86751. *
  86752. * If the seek requirement for an interface is optional, you can signify that
  86753. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86754. */
  86755. typedef struct {
  86756. FLAC__IOCallback_Read read;
  86757. FLAC__IOCallback_Write write;
  86758. FLAC__IOCallback_Seek seek;
  86759. FLAC__IOCallback_Tell tell;
  86760. FLAC__IOCallback_Eof eof;
  86761. FLAC__IOCallback_Close close;
  86762. } FLAC__IOCallbacks;
  86763. /* \} */
  86764. #ifdef __cplusplus
  86765. }
  86766. #endif
  86767. #endif
  86768. /*** End of inlined file: callback.h ***/
  86769. /*** Start of inlined file: format.h ***/
  86770. #ifndef FLAC__FORMAT_H
  86771. #define FLAC__FORMAT_H
  86772. #ifdef __cplusplus
  86773. extern "C" {
  86774. #endif
  86775. /** \file include/FLAC/format.h
  86776. *
  86777. * \brief
  86778. * This module contains structure definitions for the representation
  86779. * of FLAC format components in memory. These are the basic
  86780. * structures used by the rest of the interfaces.
  86781. *
  86782. * See the detailed documentation in the
  86783. * \link flac_format format \endlink module.
  86784. */
  86785. /** \defgroup flac_format FLAC/format.h: format components
  86786. * \ingroup flac
  86787. *
  86788. * \brief
  86789. * This module contains structure definitions for the representation
  86790. * of FLAC format components in memory. These are the basic
  86791. * structures used by the rest of the interfaces.
  86792. *
  86793. * First, you should be familiar with the
  86794. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86795. * follow directly from the specification. As a user of libFLAC, the
  86796. * interesting parts really are the structures that describe the frame
  86797. * header and metadata blocks.
  86798. *
  86799. * The format structures here are very primitive, designed to store
  86800. * information in an efficient way. Reading information from the
  86801. * structures is easy but creating or modifying them directly is
  86802. * more complex. For the most part, as a user of a library, editing
  86803. * is not necessary; however, for metadata blocks it is, so there are
  86804. * convenience functions provided in the \link flac_metadata metadata
  86805. * module \endlink to simplify the manipulation of metadata blocks.
  86806. *
  86807. * \note
  86808. * It's not the best convention, but symbols ending in _LEN are in bits
  86809. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86810. * global variables because they are usually used when declaring byte
  86811. * arrays and some compilers require compile-time knowledge of array
  86812. * sizes when declared on the stack.
  86813. *
  86814. * \{
  86815. */
  86816. /*
  86817. Most of the values described in this file are defined by the FLAC
  86818. format specification. There is nothing to tune here.
  86819. */
  86820. /** The largest legal metadata type code. */
  86821. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86822. /** The minimum block size, in samples, permitted by the format. */
  86823. #define FLAC__MIN_BLOCK_SIZE (16u)
  86824. /** The maximum block size, in samples, permitted by the format. */
  86825. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86826. /** The maximum block size, in samples, permitted by the FLAC subset for
  86827. * sample rates up to 48kHz. */
  86828. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86829. /** The maximum number of channels permitted by the format. */
  86830. #define FLAC__MAX_CHANNELS (8u)
  86831. /** The minimum sample resolution permitted by the format. */
  86832. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86833. /** The maximum sample resolution permitted by the format. */
  86834. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86835. /** The maximum sample resolution permitted by libFLAC.
  86836. *
  86837. * \warning
  86838. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86839. * the reference encoder/decoder is currently limited to 24 bits because
  86840. * of prevalent 32-bit math, so make sure and use this value when
  86841. * appropriate.
  86842. */
  86843. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86844. /** The maximum sample rate permitted by the format. The value is
  86845. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86846. * as to why.
  86847. */
  86848. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86849. /** The maximum LPC order permitted by the format. */
  86850. #define FLAC__MAX_LPC_ORDER (32u)
  86851. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86852. * up to 48kHz. */
  86853. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86854. /** The minimum quantized linear predictor coefficient precision
  86855. * permitted by the format.
  86856. */
  86857. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86858. /** The maximum quantized linear predictor coefficient precision
  86859. * permitted by the format.
  86860. */
  86861. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86862. /** The maximum order of the fixed predictors permitted by the format. */
  86863. #define FLAC__MAX_FIXED_ORDER (4u)
  86864. /** The maximum Rice partition order permitted by the format. */
  86865. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86866. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86867. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86868. /** The version string of the release, stamped onto the libraries and binaries.
  86869. *
  86870. * \note
  86871. * This does not correspond to the shared library version number, which
  86872. * is used to determine binary compatibility.
  86873. */
  86874. extern FLAC_API const char *FLAC__VERSION_STRING;
  86875. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86876. * This is a NUL-terminated ASCII string; when inserted into the
  86877. * VORBIS_COMMENT the trailing null is stripped.
  86878. */
  86879. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86880. /** The byte string representation of the beginning of a FLAC stream. */
  86881. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86882. /** The 32-bit integer big-endian representation of the beginning of
  86883. * a FLAC stream.
  86884. */
  86885. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86886. /** The length of the FLAC signature in bits. */
  86887. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86888. /** The length of the FLAC signature in bytes. */
  86889. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86890. /*****************************************************************************
  86891. *
  86892. * Subframe structures
  86893. *
  86894. *****************************************************************************/
  86895. /*****************************************************************************/
  86896. /** An enumeration of the available entropy coding methods. */
  86897. typedef enum {
  86898. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86899. /**< Residual is coded by partitioning into contexts, each with it's own
  86900. * 4-bit Rice parameter. */
  86901. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86902. /**< Residual is coded by partitioning into contexts, each with it's own
  86903. * 5-bit Rice parameter. */
  86904. } FLAC__EntropyCodingMethodType;
  86905. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86906. *
  86907. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86908. * give the string equivalent. The contents should not be modified.
  86909. */
  86910. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86911. /** Contents of a Rice partitioned residual
  86912. */
  86913. typedef struct {
  86914. unsigned *parameters;
  86915. /**< The Rice parameters for each context. */
  86916. unsigned *raw_bits;
  86917. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86918. * partitions and zero for unescaped partitions.
  86919. */
  86920. unsigned capacity_by_order;
  86921. /**< The capacity of the \a parameters and \a raw_bits arrays
  86922. * specified as an order, i.e. the number of array elements
  86923. * allocated is 2 ^ \a capacity_by_order.
  86924. */
  86925. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86926. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86927. */
  86928. typedef struct {
  86929. unsigned order;
  86930. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86931. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86932. /**< The context's Rice parameters and/or raw bits. */
  86933. } FLAC__EntropyCodingMethod_PartitionedRice;
  86934. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86935. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86936. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86937. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86938. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86939. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86940. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86941. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86942. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86943. */
  86944. typedef struct {
  86945. FLAC__EntropyCodingMethodType type;
  86946. union {
  86947. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86948. } data;
  86949. } FLAC__EntropyCodingMethod;
  86950. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86951. /*****************************************************************************/
  86952. /** An enumeration of the available subframe types. */
  86953. typedef enum {
  86954. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86955. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86956. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86957. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86958. } FLAC__SubframeType;
  86959. /** Maps a FLAC__SubframeType to a C string.
  86960. *
  86961. * Using a FLAC__SubframeType as the index to this array will
  86962. * give the string equivalent. The contents should not be modified.
  86963. */
  86964. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86965. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86966. */
  86967. typedef struct {
  86968. FLAC__int32 value; /**< The constant signal value. */
  86969. } FLAC__Subframe_Constant;
  86970. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86971. */
  86972. typedef struct {
  86973. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86974. } FLAC__Subframe_Verbatim;
  86975. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86976. */
  86977. typedef struct {
  86978. FLAC__EntropyCodingMethod entropy_coding_method;
  86979. /**< The residual coding method. */
  86980. unsigned order;
  86981. /**< The polynomial order. */
  86982. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86983. /**< Warmup samples to prime the predictor, length == order. */
  86984. const FLAC__int32 *residual;
  86985. /**< The residual signal, length == (blocksize minus order) samples. */
  86986. } FLAC__Subframe_Fixed;
  86987. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86988. */
  86989. typedef struct {
  86990. FLAC__EntropyCodingMethod entropy_coding_method;
  86991. /**< The residual coding method. */
  86992. unsigned order;
  86993. /**< The FIR order. */
  86994. unsigned qlp_coeff_precision;
  86995. /**< Quantized FIR filter coefficient precision in bits. */
  86996. int quantization_level;
  86997. /**< The qlp coeff shift needed. */
  86998. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86999. /**< FIR filter coefficients. */
  87000. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87001. /**< Warmup samples to prime the predictor, length == order. */
  87002. const FLAC__int32 *residual;
  87003. /**< The residual signal, length == (blocksize minus order) samples. */
  87004. } FLAC__Subframe_LPC;
  87005. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87006. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87007. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87008. */
  87009. typedef struct {
  87010. FLAC__SubframeType type;
  87011. union {
  87012. FLAC__Subframe_Constant constant;
  87013. FLAC__Subframe_Fixed fixed;
  87014. FLAC__Subframe_LPC lpc;
  87015. FLAC__Subframe_Verbatim verbatim;
  87016. } data;
  87017. unsigned wasted_bits;
  87018. } FLAC__Subframe;
  87019. /** == 1 (bit)
  87020. *
  87021. * This used to be a zero-padding bit (hence the name
  87022. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87023. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87024. * to mean something else.
  87025. */
  87026. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87027. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87028. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87029. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87030. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87031. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87032. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87033. /*****************************************************************************/
  87034. /*****************************************************************************
  87035. *
  87036. * Frame structures
  87037. *
  87038. *****************************************************************************/
  87039. /** An enumeration of the available channel assignments. */
  87040. typedef enum {
  87041. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87042. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87043. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87044. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87045. } FLAC__ChannelAssignment;
  87046. /** Maps a FLAC__ChannelAssignment to a C string.
  87047. *
  87048. * Using a FLAC__ChannelAssignment as the index to this array will
  87049. * give the string equivalent. The contents should not be modified.
  87050. */
  87051. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87052. /** An enumeration of the possible frame numbering methods. */
  87053. typedef enum {
  87054. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87055. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87056. } FLAC__FrameNumberType;
  87057. /** Maps a FLAC__FrameNumberType to a C string.
  87058. *
  87059. * Using a FLAC__FrameNumberType as the index to this array will
  87060. * give the string equivalent. The contents should not be modified.
  87061. */
  87062. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87063. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87064. */
  87065. typedef struct {
  87066. unsigned blocksize;
  87067. /**< The number of samples per subframe. */
  87068. unsigned sample_rate;
  87069. /**< The sample rate in Hz. */
  87070. unsigned channels;
  87071. /**< The number of channels (== number of subframes). */
  87072. FLAC__ChannelAssignment channel_assignment;
  87073. /**< The channel assignment for the frame. */
  87074. unsigned bits_per_sample;
  87075. /**< The sample resolution. */
  87076. FLAC__FrameNumberType number_type;
  87077. /**< The numbering scheme used for the frame. As a convenience, the
  87078. * decoder will always convert a frame number to a sample number because
  87079. * the rules are complex. */
  87080. union {
  87081. FLAC__uint32 frame_number;
  87082. FLAC__uint64 sample_number;
  87083. } number;
  87084. /**< The frame number or sample number of first sample in frame;
  87085. * use the \a number_type value to determine which to use. */
  87086. FLAC__uint8 crc;
  87087. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87088. * of the raw frame header bytes, meaning everything before the CRC byte
  87089. * including the sync code.
  87090. */
  87091. } FLAC__FrameHeader;
  87092. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87093. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87094. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87095. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87096. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87097. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87098. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87099. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87100. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87101. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87102. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87103. */
  87104. typedef struct {
  87105. FLAC__uint16 crc;
  87106. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87107. * 0) of the bytes before the crc, back to and including the frame header
  87108. * sync code.
  87109. */
  87110. } FLAC__FrameFooter;
  87111. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87112. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87113. */
  87114. typedef struct {
  87115. FLAC__FrameHeader header;
  87116. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87117. FLAC__FrameFooter footer;
  87118. } FLAC__Frame;
  87119. /*****************************************************************************/
  87120. /*****************************************************************************
  87121. *
  87122. * Meta-data structures
  87123. *
  87124. *****************************************************************************/
  87125. /** An enumeration of the available metadata block types. */
  87126. typedef enum {
  87127. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87128. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87129. FLAC__METADATA_TYPE_PADDING = 1,
  87130. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87131. FLAC__METADATA_TYPE_APPLICATION = 2,
  87132. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87133. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87134. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87135. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87136. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87137. FLAC__METADATA_TYPE_CUESHEET = 5,
  87138. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87139. FLAC__METADATA_TYPE_PICTURE = 6,
  87140. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87141. FLAC__METADATA_TYPE_UNDEFINED = 7
  87142. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87143. } FLAC__MetadataType;
  87144. /** Maps a FLAC__MetadataType to a C string.
  87145. *
  87146. * Using a FLAC__MetadataType as the index to this array will
  87147. * give the string equivalent. The contents should not be modified.
  87148. */
  87149. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87150. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87151. */
  87152. typedef struct {
  87153. unsigned min_blocksize, max_blocksize;
  87154. unsigned min_framesize, max_framesize;
  87155. unsigned sample_rate;
  87156. unsigned channels;
  87157. unsigned bits_per_sample;
  87158. FLAC__uint64 total_samples;
  87159. FLAC__byte md5sum[16];
  87160. } FLAC__StreamMetadata_StreamInfo;
  87161. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87162. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87163. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87164. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87165. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87166. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87167. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87168. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87170. /** The total stream length of the STREAMINFO block in bytes. */
  87171. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87172. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87173. */
  87174. typedef struct {
  87175. int dummy;
  87176. /**< Conceptually this is an empty struct since we don't store the
  87177. * padding bytes. Empty structs are not allowed by some C compilers,
  87178. * hence the dummy.
  87179. */
  87180. } FLAC__StreamMetadata_Padding;
  87181. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87182. */
  87183. typedef struct {
  87184. FLAC__byte id[4];
  87185. FLAC__byte *data;
  87186. } FLAC__StreamMetadata_Application;
  87187. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87188. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87189. */
  87190. typedef struct {
  87191. FLAC__uint64 sample_number;
  87192. /**< The sample number of the target frame. */
  87193. FLAC__uint64 stream_offset;
  87194. /**< The offset, in bytes, of the target frame with respect to
  87195. * beginning of the first frame. */
  87196. unsigned frame_samples;
  87197. /**< The number of samples in the target frame. */
  87198. } FLAC__StreamMetadata_SeekPoint;
  87199. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87200. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87201. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87202. /** The total stream length of a seek point in bytes. */
  87203. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87204. /** The value used in the \a sample_number field of
  87205. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87206. * point (== 0xffffffffffffffff).
  87207. */
  87208. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87209. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87210. *
  87211. * \note From the format specification:
  87212. * - The seek points must be sorted by ascending sample number.
  87213. * - Each seek point's sample number must be the first sample of the
  87214. * target frame.
  87215. * - Each seek point's sample number must be unique within the table.
  87216. * - Existence of a SEEKTABLE block implies a correct setting of
  87217. * total_samples in the stream_info block.
  87218. * - Behavior is undefined when more than one SEEKTABLE block is
  87219. * present in a stream.
  87220. */
  87221. typedef struct {
  87222. unsigned num_points;
  87223. FLAC__StreamMetadata_SeekPoint *points;
  87224. } FLAC__StreamMetadata_SeekTable;
  87225. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87226. *
  87227. * For convenience, the APIs maintain a trailing NUL character at the end of
  87228. * \a entry which is not counted toward \a length, i.e.
  87229. * \code strlen(entry) == length \endcode
  87230. */
  87231. typedef struct {
  87232. FLAC__uint32 length;
  87233. FLAC__byte *entry;
  87234. } FLAC__StreamMetadata_VorbisComment_Entry;
  87235. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87236. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87237. */
  87238. typedef struct {
  87239. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87240. FLAC__uint32 num_comments;
  87241. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87242. } FLAC__StreamMetadata_VorbisComment;
  87243. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87244. /** FLAC CUESHEET track index structure. (See the
  87245. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87246. * the full description of each field.)
  87247. */
  87248. typedef struct {
  87249. FLAC__uint64 offset;
  87250. /**< Offset in samples, relative to the track offset, of the index
  87251. * point.
  87252. */
  87253. FLAC__byte number;
  87254. /**< The index point number. */
  87255. } FLAC__StreamMetadata_CueSheet_Index;
  87256. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87257. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87258. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87259. /** FLAC CUESHEET track structure. (See the
  87260. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87261. * the full description of each field.)
  87262. */
  87263. typedef struct {
  87264. FLAC__uint64 offset;
  87265. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87266. FLAC__byte number;
  87267. /**< The track number. */
  87268. char isrc[13];
  87269. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87270. unsigned type:1;
  87271. /**< The track type: 0 for audio, 1 for non-audio. */
  87272. unsigned pre_emphasis:1;
  87273. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87274. FLAC__byte num_indices;
  87275. /**< The number of track index points. */
  87276. FLAC__StreamMetadata_CueSheet_Index *indices;
  87277. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87278. } FLAC__StreamMetadata_CueSheet_Track;
  87279. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87280. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87281. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87282. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87283. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87284. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87285. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87286. /** FLAC CUESHEET structure. (See the
  87287. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87288. * for the full description of each field.)
  87289. */
  87290. typedef struct {
  87291. char media_catalog_number[129];
  87292. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87293. * general, the media catalog number may be 0 to 128 bytes long; any
  87294. * unused characters should be right-padded with NUL characters.
  87295. */
  87296. FLAC__uint64 lead_in;
  87297. /**< The number of lead-in samples. */
  87298. FLAC__bool is_cd;
  87299. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87300. unsigned num_tracks;
  87301. /**< The number of tracks. */
  87302. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87303. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87304. } FLAC__StreamMetadata_CueSheet;
  87305. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87306. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87307. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87308. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87309. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87310. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87311. typedef enum {
  87312. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87313. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87314. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87315. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87316. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87317. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87318. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87319. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87320. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87321. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87322. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87323. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87324. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87325. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87326. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87327. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87328. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87329. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87330. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87331. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87332. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87333. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87334. } FLAC__StreamMetadata_Picture_Type;
  87335. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87336. *
  87337. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87338. * will give the string equivalent. The contents should not be
  87339. * modified.
  87340. */
  87341. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87342. /** FLAC PICTURE structure. (See the
  87343. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87344. * for the full description of each field.)
  87345. */
  87346. typedef struct {
  87347. FLAC__StreamMetadata_Picture_Type type;
  87348. /**< The kind of picture stored. */
  87349. char *mime_type;
  87350. /**< Picture data's MIME type, in ASCII printable characters
  87351. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87352. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87353. * MIME type of '-->' is also allowed, in which case the picture
  87354. * data should be a complete URL. In file storage, the MIME type is
  87355. * stored as a 32-bit length followed by the ASCII string with no NUL
  87356. * terminator, but is converted to a plain C string in this structure
  87357. * for convenience.
  87358. */
  87359. FLAC__byte *description;
  87360. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87361. * the description is stored as a 32-bit length followed by the UTF-8
  87362. * string with no NUL terminator, but is converted to a plain C string
  87363. * in this structure for convenience.
  87364. */
  87365. FLAC__uint32 width;
  87366. /**< Picture's width in pixels. */
  87367. FLAC__uint32 height;
  87368. /**< Picture's height in pixels. */
  87369. FLAC__uint32 depth;
  87370. /**< Picture's color depth in bits-per-pixel. */
  87371. FLAC__uint32 colors;
  87372. /**< For indexed palettes (like GIF), picture's number of colors (the
  87373. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87374. */
  87375. FLAC__uint32 data_length;
  87376. /**< Length of binary picture data in bytes. */
  87377. FLAC__byte *data;
  87378. /**< Binary picture data. */
  87379. } FLAC__StreamMetadata_Picture;
  87380. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87381. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87382. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87383. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87384. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87385. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87386. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87387. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87388. /** Structure that is used when a metadata block of unknown type is loaded.
  87389. * The contents are opaque. The structure is used only internally to
  87390. * correctly handle unknown metadata.
  87391. */
  87392. typedef struct {
  87393. FLAC__byte *data;
  87394. } FLAC__StreamMetadata_Unknown;
  87395. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87396. */
  87397. typedef struct {
  87398. FLAC__MetadataType type;
  87399. /**< The type of the metadata block; used determine which member of the
  87400. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87401. * then \a data.unknown must be used. */
  87402. FLAC__bool is_last;
  87403. /**< \c true if this metadata block is the last, else \a false */
  87404. unsigned length;
  87405. /**< Length, in bytes, of the block data as it appears in the stream. */
  87406. union {
  87407. FLAC__StreamMetadata_StreamInfo stream_info;
  87408. FLAC__StreamMetadata_Padding padding;
  87409. FLAC__StreamMetadata_Application application;
  87410. FLAC__StreamMetadata_SeekTable seek_table;
  87411. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87412. FLAC__StreamMetadata_CueSheet cue_sheet;
  87413. FLAC__StreamMetadata_Picture picture;
  87414. FLAC__StreamMetadata_Unknown unknown;
  87415. } data;
  87416. /**< Polymorphic block data; use the \a type value to determine which
  87417. * to use. */
  87418. } FLAC__StreamMetadata;
  87419. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87420. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87421. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87422. /** The total stream length of a metadata block header in bytes. */
  87423. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87424. /*****************************************************************************/
  87425. /*****************************************************************************
  87426. *
  87427. * Utility functions
  87428. *
  87429. *****************************************************************************/
  87430. /** Tests that a sample rate is valid for FLAC.
  87431. *
  87432. * \param sample_rate The sample rate to test for compliance.
  87433. * \retval FLAC__bool
  87434. * \c true if the given sample rate conforms to the specification, else
  87435. * \c false.
  87436. */
  87437. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87438. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87439. * for valid sample rates are slightly more complex since the rate has to
  87440. * be expressible completely in the frame header.
  87441. *
  87442. * \param sample_rate The sample rate to test for compliance.
  87443. * \retval FLAC__bool
  87444. * \c true if the given sample rate conforms to the specification for the
  87445. * subset, else \c false.
  87446. */
  87447. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87448. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87449. * comment specification.
  87450. *
  87451. * Vorbis comment names must be composed only of characters from
  87452. * [0x20-0x3C,0x3E-0x7D].
  87453. *
  87454. * \param name A NUL-terminated string to be checked.
  87455. * \assert
  87456. * \code name != NULL \endcode
  87457. * \retval FLAC__bool
  87458. * \c false if entry name is illegal, else \c true.
  87459. */
  87460. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87461. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87462. * comment specification.
  87463. *
  87464. * Vorbis comment values must be valid UTF-8 sequences.
  87465. *
  87466. * \param value A string to be checked.
  87467. * \param length A the length of \a value in bytes. May be
  87468. * \c (unsigned)(-1) to indicate that \a value is a plain
  87469. * UTF-8 NUL-terminated string.
  87470. * \assert
  87471. * \code value != NULL \endcode
  87472. * \retval FLAC__bool
  87473. * \c false if entry name is illegal, else \c true.
  87474. */
  87475. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87476. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87477. * comment specification.
  87478. *
  87479. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87480. * 'value' must be legal according to
  87481. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87482. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87483. *
  87484. * \param entry An entry to be checked.
  87485. * \param length The length of \a entry in bytes.
  87486. * \assert
  87487. * \code value != NULL \endcode
  87488. * \retval FLAC__bool
  87489. * \c false if entry name is illegal, else \c true.
  87490. */
  87491. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87492. /** Check a seek table to see if it conforms to the FLAC specification.
  87493. * See the format specification for limits on the contents of the
  87494. * seek table.
  87495. *
  87496. * \param seek_table A pointer to a seek table to be checked.
  87497. * \assert
  87498. * \code seek_table != NULL \endcode
  87499. * \retval FLAC__bool
  87500. * \c false if seek table is illegal, else \c true.
  87501. */
  87502. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87503. /** Sort a seek table's seek points according to the format specification.
  87504. * This includes a "unique-ification" step to remove duplicates, i.e.
  87505. * seek points with identical \a sample_number values. Duplicate seek
  87506. * points are converted into placeholder points and sorted to the end of
  87507. * the table.
  87508. *
  87509. * \param seek_table A pointer to a seek table to be sorted.
  87510. * \assert
  87511. * \code seek_table != NULL \endcode
  87512. * \retval unsigned
  87513. * The number of duplicate seek points converted into placeholders.
  87514. */
  87515. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87516. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87517. * See the format specification for limits on the contents of the
  87518. * cue sheet.
  87519. *
  87520. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87521. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87522. * stringent requirements for a CD-DA (audio) disc.
  87523. * \param violation Address of a pointer to a string. If there is a
  87524. * violation, a pointer to a string explanation of the
  87525. * violation will be returned here. \a violation may be
  87526. * \c NULL if you don't need the returned string. Do not
  87527. * free the returned string; it will always point to static
  87528. * data.
  87529. * \assert
  87530. * \code cue_sheet != NULL \endcode
  87531. * \retval FLAC__bool
  87532. * \c false if cue sheet is illegal, else \c true.
  87533. */
  87534. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87535. /** Check picture data to see if it conforms to the FLAC specification.
  87536. * See the format specification for limits on the contents of the
  87537. * PICTURE block.
  87538. *
  87539. * \param picture A pointer to existing picture data to be checked.
  87540. * \param violation Address of a pointer to a string. If there is a
  87541. * violation, a pointer to a string explanation of the
  87542. * violation will be returned here. \a violation may be
  87543. * \c NULL if you don't need the returned string. Do not
  87544. * free the returned string; it will always point to static
  87545. * data.
  87546. * \assert
  87547. * \code picture != NULL \endcode
  87548. * \retval FLAC__bool
  87549. * \c false if picture data is illegal, else \c true.
  87550. */
  87551. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87552. /* \} */
  87553. #ifdef __cplusplus
  87554. }
  87555. #endif
  87556. #endif
  87557. /*** End of inlined file: format.h ***/
  87558. /*** Start of inlined file: metadata.h ***/
  87559. #ifndef FLAC__METADATA_H
  87560. #define FLAC__METADATA_H
  87561. #include <sys/types.h> /* for off_t */
  87562. /* --------------------------------------------------------------------
  87563. (For an example of how all these routines are used, see the source
  87564. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87565. metaflac in src/metaflac/)
  87566. ------------------------------------------------------------------*/
  87567. /** \file include/FLAC/metadata.h
  87568. *
  87569. * \brief
  87570. * This module provides functions for creating and manipulating FLAC
  87571. * metadata blocks in memory, and three progressively more powerful
  87572. * interfaces for traversing and editing metadata in FLAC files.
  87573. *
  87574. * See the detailed documentation for each interface in the
  87575. * \link flac_metadata metadata \endlink module.
  87576. */
  87577. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87578. * \ingroup flac
  87579. *
  87580. * \brief
  87581. * This module provides functions for creating and manipulating FLAC
  87582. * metadata blocks in memory, and three progressively more powerful
  87583. * interfaces for traversing and editing metadata in native FLAC files.
  87584. * Note that currently only the Chain interface (level 2) supports Ogg
  87585. * FLAC files, and it is read-only i.e. no writing back changed
  87586. * metadata to file.
  87587. *
  87588. * There are three metadata interfaces of increasing complexity:
  87589. *
  87590. * Level 0:
  87591. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87592. * PICTURE blocks.
  87593. *
  87594. * Level 1:
  87595. * Read-write access to all metadata blocks. This level is write-
  87596. * efficient in most cases (more on this below), and uses less memory
  87597. * than level 2.
  87598. *
  87599. * Level 2:
  87600. * Read-write access to all metadata blocks. This level is write-
  87601. * efficient in all cases, but uses more memory since all metadata for
  87602. * the whole file is read into memory and manipulated before writing
  87603. * out again.
  87604. *
  87605. * What do we mean by efficient? Since FLAC metadata appears at the
  87606. * beginning of the file, when writing metadata back to a FLAC file
  87607. * it is possible to grow or shrink the metadata such that the entire
  87608. * file must be rewritten. However, if the size remains the same during
  87609. * changes or PADDING blocks are utilized, only the metadata needs to be
  87610. * overwritten, which is much faster.
  87611. *
  87612. * Efficient means the whole file is rewritten at most one time, and only
  87613. * when necessary. Level 1 is not efficient only in the case that you
  87614. * cause more than one metadata block to grow or shrink beyond what can
  87615. * be accomodated by padding. In this case you should probably use level
  87616. * 2, which allows you to edit all the metadata for a file in memory and
  87617. * write it out all at once.
  87618. *
  87619. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87620. * front of the file.
  87621. *
  87622. * All levels access files via their filenames. In addition, level 2
  87623. * has additional alternative read and write functions that take an I/O
  87624. * handle and callbacks, for situations where access by filename is not
  87625. * possible.
  87626. *
  87627. * In addition to the three interfaces, this module defines functions for
  87628. * creating and manipulating various metadata objects in memory. As we see
  87629. * from the Format module, FLAC metadata blocks in memory are very primitive
  87630. * structures for storing information in an efficient way. Reading
  87631. * information from the structures is easy but creating or modifying them
  87632. * directly is more complex. The metadata object routines here facilitate
  87633. * this by taking care of the consistency and memory management drudgery.
  87634. *
  87635. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87636. * metadata however, you will not probably not need these.
  87637. *
  87638. * From a dependency standpoint, none of the encoders or decoders require
  87639. * the metadata module. This is so that embedded users can strip out the
  87640. * metadata module from libFLAC to reduce the size and complexity.
  87641. */
  87642. #ifdef __cplusplus
  87643. extern "C" {
  87644. #endif
  87645. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87646. * \ingroup flac_metadata
  87647. *
  87648. * \brief
  87649. * The level 0 interface consists of individual routines to read the
  87650. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87651. * only a filename.
  87652. *
  87653. * They try to skip any ID3v2 tag at the head of the file.
  87654. *
  87655. * \{
  87656. */
  87657. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87658. * will try to skip any ID3v2 tag at the head of the file.
  87659. *
  87660. * \param filename The path to the FLAC file to read.
  87661. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87662. * FLAC__StreamMetadata is a simple structure with no
  87663. * memory allocation involved, you pass the address of
  87664. * an existing structure. It need not be initialized.
  87665. * \assert
  87666. * \code filename != NULL \endcode
  87667. * \code streaminfo != NULL \endcode
  87668. * \retval FLAC__bool
  87669. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87670. * \c false if there was a memory allocation error, a file decoder error,
  87671. * or the file contained no STREAMINFO block. (A memory allocation error
  87672. * is possible because this function must set up a file decoder.)
  87673. */
  87674. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87675. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87676. * function will try to skip any ID3v2 tag at the head of the file.
  87677. *
  87678. * \param filename The path to the FLAC file to read.
  87679. * \param tags The address where the returned pointer will be
  87680. * stored. The \a tags object must be deleted by
  87681. * the caller using FLAC__metadata_object_delete().
  87682. * \assert
  87683. * \code filename != NULL \endcode
  87684. * \code tags != NULL \endcode
  87685. * \retval FLAC__bool
  87686. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87687. * and \a *tags will be set to the address of the metadata structure.
  87688. * Returns \c false if there was a memory allocation error, a file
  87689. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87690. * \a *tags will be set to \c NULL.
  87691. */
  87692. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87693. /** Read the CUESHEET metadata block of the given FLAC file. This
  87694. * function will try to skip any ID3v2 tag at the head of the file.
  87695. *
  87696. * \param filename The path to the FLAC file to read.
  87697. * \param cuesheet The address where the returned pointer will be
  87698. * stored. The \a cuesheet object must be deleted by
  87699. * the caller using FLAC__metadata_object_delete().
  87700. * \assert
  87701. * \code filename != NULL \endcode
  87702. * \code cuesheet != NULL \endcode
  87703. * \retval FLAC__bool
  87704. * \c true if a valid CUESHEET block was read from \a filename,
  87705. * and \a *cuesheet will be set to the address of the metadata
  87706. * structure. Returns \c false if there was a memory allocation
  87707. * error, a file decoder error, or the file contained no CUESHEET
  87708. * block, and \a *cuesheet will be set to \c NULL.
  87709. */
  87710. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87711. /** Read a PICTURE metadata block of the given FLAC file. This
  87712. * function will try to skip any ID3v2 tag at the head of the file.
  87713. * Since there can be more than one PICTURE block in a file, this
  87714. * function takes a number of parameters that act as constraints to
  87715. * the search. The PICTURE block with the largest area matching all
  87716. * the constraints will be returned, or \a *picture will be set to
  87717. * \c NULL if there was no such block.
  87718. *
  87719. * \param filename The path to the FLAC file to read.
  87720. * \param picture The address where the returned pointer will be
  87721. * stored. The \a picture object must be deleted by
  87722. * the caller using FLAC__metadata_object_delete().
  87723. * \param type The desired picture type. Use \c -1 to mean
  87724. * "any type".
  87725. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87726. * string will be matched exactly. Use \c NULL to
  87727. * mean "any MIME type".
  87728. * \param description The desired description. The string will be
  87729. * matched exactly. Use \c NULL to mean "any
  87730. * description".
  87731. * \param max_width The maximum width in pixels desired. Use
  87732. * \c (unsigned)(-1) to mean "any width".
  87733. * \param max_height The maximum height in pixels desired. Use
  87734. * \c (unsigned)(-1) to mean "any height".
  87735. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87736. * Use \c (unsigned)(-1) to mean "any depth".
  87737. * \param max_colors The maximum number of colors desired. Use
  87738. * \c (unsigned)(-1) to mean "any number of colors".
  87739. * \assert
  87740. * \code filename != NULL \endcode
  87741. * \code picture != NULL \endcode
  87742. * \retval FLAC__bool
  87743. * \c true if a valid PICTURE block was read from \a filename,
  87744. * and \a *picture will be set to the address of the metadata
  87745. * structure. Returns \c false if there was a memory allocation
  87746. * error, a file decoder error, or the file contained no PICTURE
  87747. * block, and \a *picture will be set to \c NULL.
  87748. */
  87749. 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);
  87750. /* \} */
  87751. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87752. * \ingroup flac_metadata
  87753. *
  87754. * \brief
  87755. * The level 1 interface provides read-write access to FLAC file metadata and
  87756. * operates directly on the FLAC file.
  87757. *
  87758. * The general usage of this interface is:
  87759. *
  87760. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87761. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87762. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87763. * see if the file is writable, or only read access is allowed.
  87764. * - Use FLAC__metadata_simple_iterator_next() and
  87765. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87766. * This is does not read the actual blocks themselves.
  87767. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87768. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87769. * forward from the front of the file.
  87770. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87771. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87772. * the current iterator position. The returned object is yours to modify
  87773. * and free.
  87774. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87775. * back. You must have write permission to the original file. Make sure to
  87776. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87777. * below.
  87778. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87779. * Use the object creation functions from
  87780. * \link flac_metadata_object here \endlink to generate new objects.
  87781. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87782. * currently referred to by the iterator, or replace it with padding.
  87783. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87784. * finished.
  87785. *
  87786. * \note
  87787. * The FLAC file remains open the whole time between
  87788. * FLAC__metadata_simple_iterator_init() and
  87789. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87790. * the file during this time.
  87791. *
  87792. * \note
  87793. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87794. * FLAC__StreamMetadata objects. These are managed automatically.
  87795. *
  87796. * \note
  87797. * If any of the modification functions
  87798. * (FLAC__metadata_simple_iterator_set_block(),
  87799. * FLAC__metadata_simple_iterator_delete_block(),
  87800. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87801. * you should delete the iterator as it may no longer be valid.
  87802. *
  87803. * \{
  87804. */
  87805. struct FLAC__Metadata_SimpleIterator;
  87806. /** The opaque structure definition for the level 1 iterator type.
  87807. * See the
  87808. * \link flac_metadata_level1 metadata level 1 module \endlink
  87809. * for a detailed description.
  87810. */
  87811. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87812. /** Status type for FLAC__Metadata_SimpleIterator.
  87813. *
  87814. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87815. */
  87816. typedef enum {
  87817. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87818. /**< The iterator is in the normal OK state */
  87819. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87820. /**< The data passed into a function violated the function's usage criteria */
  87821. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87822. /**< The iterator could not open the target file */
  87823. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87824. /**< The iterator could not find the FLAC signature at the start of the file */
  87825. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87826. /**< The iterator tried to write to a file that was not writable */
  87827. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87828. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87829. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87830. /**< The iterator encountered an error while reading the FLAC file */
  87831. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87832. /**< The iterator encountered an error while seeking in the FLAC file */
  87833. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87834. /**< The iterator encountered an error while writing the FLAC file */
  87835. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87836. /**< The iterator encountered an error renaming the FLAC file */
  87837. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87838. /**< The iterator encountered an error removing the temporary file */
  87839. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87840. /**< Memory allocation failed */
  87841. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87842. /**< The caller violated an assertion or an unexpected error occurred */
  87843. } FLAC__Metadata_SimpleIteratorStatus;
  87844. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87845. *
  87846. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87847. * will give the string equivalent. The contents should not be modified.
  87848. */
  87849. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87850. /** Create a new iterator instance.
  87851. *
  87852. * \retval FLAC__Metadata_SimpleIterator*
  87853. * \c NULL if there was an error allocating memory, else the new instance.
  87854. */
  87855. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87856. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87857. *
  87858. * \param iterator A pointer to an existing iterator.
  87859. * \assert
  87860. * \code iterator != NULL \endcode
  87861. */
  87862. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87863. /** Get the current status of the iterator. Call this after a function
  87864. * returns \c false to get the reason for the error. Also resets the status
  87865. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87866. *
  87867. * \param iterator A pointer to an existing iterator.
  87868. * \assert
  87869. * \code iterator != NULL \endcode
  87870. * \retval FLAC__Metadata_SimpleIteratorStatus
  87871. * The current status of the iterator.
  87872. */
  87873. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87874. /** Initialize the iterator to point to the first metadata block in the
  87875. * given FLAC file.
  87876. *
  87877. * \param iterator A pointer to an existing iterator.
  87878. * \param filename The path to the FLAC file.
  87879. * \param read_only If \c true, the FLAC file will be opened
  87880. * in read-only mode; if \c false, the FLAC
  87881. * file will be opened for edit even if no
  87882. * edits are performed.
  87883. * \param preserve_file_stats If \c true, the owner and modification
  87884. * time will be preserved even if the FLAC
  87885. * file is written to.
  87886. * \assert
  87887. * \code iterator != NULL \endcode
  87888. * \code filename != NULL \endcode
  87889. * \retval FLAC__bool
  87890. * \c false if a memory allocation error occurs, the file can't be
  87891. * opened, or another error occurs, else \c true.
  87892. */
  87893. 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);
  87894. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87895. * FLAC__metadata_simple_iterator_set_block() and
  87896. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87897. *
  87898. * \param iterator A pointer to an existing iterator.
  87899. * \assert
  87900. * \code iterator != NULL \endcode
  87901. * \retval FLAC__bool
  87902. * See above.
  87903. */
  87904. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87905. /** Moves the iterator forward one metadata block, returning \c false if
  87906. * already at the end.
  87907. *
  87908. * \param iterator A pointer to an existing initialized iterator.
  87909. * \assert
  87910. * \code iterator != NULL \endcode
  87911. * \a iterator has been successfully initialized with
  87912. * FLAC__metadata_simple_iterator_init()
  87913. * \retval FLAC__bool
  87914. * \c false if already at the last metadata block of the chain, else
  87915. * \c true.
  87916. */
  87917. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87918. /** Moves the iterator backward one metadata block, returning \c false if
  87919. * already at the beginning.
  87920. *
  87921. * \param iterator A pointer to an existing initialized iterator.
  87922. * \assert
  87923. * \code iterator != NULL \endcode
  87924. * \a iterator has been successfully initialized with
  87925. * FLAC__metadata_simple_iterator_init()
  87926. * \retval FLAC__bool
  87927. * \c false if already at the first metadata block of the chain, else
  87928. * \c true.
  87929. */
  87930. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87931. /** Returns a flag telling if the current metadata block is the last.
  87932. *
  87933. * \param iterator A pointer to an existing initialized iterator.
  87934. * \assert
  87935. * \code iterator != NULL \endcode
  87936. * \a iterator has been successfully initialized with
  87937. * FLAC__metadata_simple_iterator_init()
  87938. * \retval FLAC__bool
  87939. * \c true if the current metadata block is the last in the file,
  87940. * else \c false.
  87941. */
  87942. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87943. /** Get the offset of the metadata block at the current position. This
  87944. * avoids reading the actual block data which can save time for large
  87945. * blocks.
  87946. *
  87947. * \param iterator A pointer to an existing initialized iterator.
  87948. * \assert
  87949. * \code iterator != NULL \endcode
  87950. * \a iterator has been successfully initialized with
  87951. * FLAC__metadata_simple_iterator_init()
  87952. * \retval off_t
  87953. * The offset of the metadata block at the current iterator position.
  87954. * This is the byte offset relative to the beginning of the file of
  87955. * the current metadata block's header.
  87956. */
  87957. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87958. /** Get the type of the metadata block at the current position. This
  87959. * avoids reading the actual block data which can save time for large
  87960. * blocks.
  87961. *
  87962. * \param iterator A pointer to an existing initialized iterator.
  87963. * \assert
  87964. * \code iterator != NULL \endcode
  87965. * \a iterator has been successfully initialized with
  87966. * FLAC__metadata_simple_iterator_init()
  87967. * \retval FLAC__MetadataType
  87968. * The type of the metadata block at the current iterator position.
  87969. */
  87970. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87971. /** Get the length of the metadata block at the current position. This
  87972. * avoids reading the actual block data which can save time for large
  87973. * blocks.
  87974. *
  87975. * \param iterator A pointer to an existing initialized iterator.
  87976. * \assert
  87977. * \code iterator != NULL \endcode
  87978. * \a iterator has been successfully initialized with
  87979. * FLAC__metadata_simple_iterator_init()
  87980. * \retval unsigned
  87981. * The length of the metadata block at the current iterator position.
  87982. * The is same length as that in the
  87983. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87984. * i.e. the length of the metadata body that follows the header.
  87985. */
  87986. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87987. /** Get the application ID of the \c APPLICATION block at the current
  87988. * position. This avoids reading the actual block data which can save
  87989. * time for large blocks.
  87990. *
  87991. * \param iterator A pointer to an existing initialized iterator.
  87992. * \param id A pointer to a buffer of at least \c 4 bytes where
  87993. * the ID will be stored.
  87994. * \assert
  87995. * \code iterator != NULL \endcode
  87996. * \code id != NULL \endcode
  87997. * \a iterator has been successfully initialized with
  87998. * FLAC__metadata_simple_iterator_init()
  87999. * \retval FLAC__bool
  88000. * \c true if the ID was successfully read, else \c false, in which
  88001. * case you should check FLAC__metadata_simple_iterator_status() to
  88002. * find out why. If the status is
  88003. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88004. * current metadata block is not an \c APPLICATION block. Otherwise
  88005. * if the status is
  88006. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88007. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88008. * occurred and the iterator can no longer be used.
  88009. */
  88010. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88011. /** Get the metadata block at the current position. You can modify the
  88012. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88013. * write it back to the FLAC file.
  88014. *
  88015. * You must call FLAC__metadata_object_delete() on the returned object
  88016. * when you are finished with it.
  88017. *
  88018. * \param iterator A pointer to an existing initialized iterator.
  88019. * \assert
  88020. * \code iterator != NULL \endcode
  88021. * \a iterator has been successfully initialized with
  88022. * FLAC__metadata_simple_iterator_init()
  88023. * \retval FLAC__StreamMetadata*
  88024. * The current metadata block, or \c NULL if there was a memory
  88025. * allocation error.
  88026. */
  88027. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88028. /** Write a block back to the FLAC file. This function tries to be
  88029. * as efficient as possible; how the block is actually written is
  88030. * shown by the following:
  88031. *
  88032. * Existing block is a STREAMINFO block and the new block is a
  88033. * STREAMINFO block: the new block is written in place. Make sure
  88034. * you know what you're doing when changing the values of a
  88035. * STREAMINFO block.
  88036. *
  88037. * Existing block is a STREAMINFO block and the new block is a
  88038. * not a STREAMINFO block: this is an error since the first block
  88039. * must be a STREAMINFO block. Returns \c false without altering the
  88040. * file.
  88041. *
  88042. * Existing block is not a STREAMINFO block and the new block is a
  88043. * STREAMINFO block: this is an error since there may be only one
  88044. * STREAMINFO block. Returns \c false without altering the file.
  88045. *
  88046. * Existing block and new block are the same length: the existing
  88047. * block will be replaced by the new block, written in place.
  88048. *
  88049. * Existing block is longer than new block: if use_padding is \c true,
  88050. * the existing block will be overwritten in place with the new
  88051. * block followed by a PADDING block, if possible, to make the total
  88052. * size the same as the existing block. Remember that a padding
  88053. * block requires at least four bytes so if the difference in size
  88054. * between the new block and existing block is less than that, the
  88055. * entire file will have to be rewritten, using the new block's
  88056. * exact size. If use_padding is \c false, the entire file will be
  88057. * rewritten, replacing the existing block by the new block.
  88058. *
  88059. * Existing block is shorter than new block: if use_padding is \c true,
  88060. * the function will try and expand the new block into the following
  88061. * PADDING block, if it exists and doing so won't shrink the PADDING
  88062. * block to less than 4 bytes. If there is no following PADDING
  88063. * block, or it will shrink to less than 4 bytes, or use_padding is
  88064. * \c false, the entire file is rewritten, replacing the existing block
  88065. * with the new block. Note that in this case any following PADDING
  88066. * block is preserved as is.
  88067. *
  88068. * After writing the block, the iterator will remain in the same
  88069. * place, i.e. pointing to the new block.
  88070. *
  88071. * \param iterator A pointer to an existing initialized iterator.
  88072. * \param block The block to set.
  88073. * \param use_padding See above.
  88074. * \assert
  88075. * \code iterator != NULL \endcode
  88076. * \a iterator has been successfully initialized with
  88077. * FLAC__metadata_simple_iterator_init()
  88078. * \code block != NULL \endcode
  88079. * \retval FLAC__bool
  88080. * \c true if successful, else \c false.
  88081. */
  88082. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88083. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88084. * except that instead of writing over an existing block, it appends
  88085. * a block after the existing block. \a use_padding is again used to
  88086. * tell the function to try an expand into following padding in an
  88087. * attempt to avoid rewriting the entire file.
  88088. *
  88089. * This function will fail and return \c false if given a STREAMINFO
  88090. * block.
  88091. *
  88092. * After writing the block, the iterator will be pointing to the
  88093. * new block.
  88094. *
  88095. * \param iterator A pointer to an existing initialized iterator.
  88096. * \param block The block to set.
  88097. * \param use_padding See above.
  88098. * \assert
  88099. * \code iterator != NULL \endcode
  88100. * \a iterator has been successfully initialized with
  88101. * FLAC__metadata_simple_iterator_init()
  88102. * \code block != NULL \endcode
  88103. * \retval FLAC__bool
  88104. * \c true if successful, else \c false.
  88105. */
  88106. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88107. /** Deletes the block at the current position. This will cause the
  88108. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88109. * in which case the block will be replaced by an equal-sized PADDING
  88110. * block. The iterator will be left pointing to the block before the
  88111. * one just deleted.
  88112. *
  88113. * You may not delete the STREAMINFO block.
  88114. *
  88115. * \param iterator A pointer to an existing initialized iterator.
  88116. * \param use_padding See above.
  88117. * \assert
  88118. * \code iterator != NULL \endcode
  88119. * \a iterator has been successfully initialized with
  88120. * FLAC__metadata_simple_iterator_init()
  88121. * \retval FLAC__bool
  88122. * \c true if successful, else \c false.
  88123. */
  88124. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88125. /* \} */
  88126. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88127. * \ingroup flac_metadata
  88128. *
  88129. * \brief
  88130. * The level 2 interface provides read-write access to FLAC file metadata;
  88131. * all metadata is read into memory, operated on in memory, and then written
  88132. * to file, which is more efficient than level 1 when editing multiple blocks.
  88133. *
  88134. * Currently Ogg FLAC is supported for read only, via
  88135. * FLAC__metadata_chain_read_ogg() but a subsequent
  88136. * FLAC__metadata_chain_write() will fail.
  88137. *
  88138. * The general usage of this interface is:
  88139. *
  88140. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88141. * linked list of FLAC metadata blocks.
  88142. * - Read all metadata into the the chain from a FLAC file using
  88143. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88144. * check the status.
  88145. * - Optionally, consolidate the padding using
  88146. * FLAC__metadata_chain_merge_padding() or
  88147. * FLAC__metadata_chain_sort_padding().
  88148. * - Create a new iterator using FLAC__metadata_iterator_new()
  88149. * - Initialize the iterator to point to the first element in the chain
  88150. * using FLAC__metadata_iterator_init()
  88151. * - Traverse the chain using FLAC__metadata_iterator_next and
  88152. * FLAC__metadata_iterator_prev().
  88153. * - Get a block for reading or modification using
  88154. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88155. * inside the chain is returned, so the block is yours to modify.
  88156. * Changes will be reflected in the FLAC file when you write the
  88157. * chain. You can also add and delete blocks (see functions below).
  88158. * - When done, write out the chain using FLAC__metadata_chain_write().
  88159. * Make sure to read the whole comment to the function below.
  88160. * - Delete the chain using FLAC__metadata_chain_delete().
  88161. *
  88162. * \note
  88163. * Even though the FLAC file is not open while the chain is being
  88164. * manipulated, you must not alter the file externally during
  88165. * this time. The chain assumes the FLAC file will not change
  88166. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88167. * and FLAC__metadata_chain_write().
  88168. *
  88169. * \note
  88170. * Do not modify the is_last, length, or type fields of returned
  88171. * FLAC__StreamMetadata objects. These are managed automatically.
  88172. *
  88173. * \note
  88174. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88175. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88176. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88177. * become owned by the chain and they will be deleted when the chain is
  88178. * deleted.
  88179. *
  88180. * \{
  88181. */
  88182. struct FLAC__Metadata_Chain;
  88183. /** The opaque structure definition for the level 2 chain type.
  88184. */
  88185. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88186. struct FLAC__Metadata_Iterator;
  88187. /** The opaque structure definition for the level 2 iterator type.
  88188. */
  88189. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88190. typedef enum {
  88191. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88192. /**< The chain is in the normal OK state */
  88193. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88194. /**< The data passed into a function violated the function's usage criteria */
  88195. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88196. /**< The chain could not open the target file */
  88197. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88198. /**< The chain could not find the FLAC signature at the start of the file */
  88199. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88200. /**< The chain tried to write to a file that was not writable */
  88201. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88202. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88203. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88204. /**< The chain encountered an error while reading the FLAC file */
  88205. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88206. /**< The chain encountered an error while seeking in the FLAC file */
  88207. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88208. /**< The chain encountered an error while writing the FLAC file */
  88209. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88210. /**< The chain encountered an error renaming the FLAC file */
  88211. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88212. /**< The chain encountered an error removing the temporary file */
  88213. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88214. /**< Memory allocation failed */
  88215. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88216. /**< The caller violated an assertion or an unexpected error occurred */
  88217. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88218. /**< One or more of the required callbacks was NULL */
  88219. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88220. /**< FLAC__metadata_chain_write() was called on a chain read by
  88221. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88222. * or
  88223. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88224. * was called on a chain read by
  88225. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88226. * Matching read/write methods must always be used. */
  88227. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88228. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88229. * chain write requires a tempfile; use
  88230. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88231. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88232. * called when the chain write does not require a tempfile; use
  88233. * FLAC__metadata_chain_write_with_callbacks() instead.
  88234. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88235. * before writing via callbacks. */
  88236. } FLAC__Metadata_ChainStatus;
  88237. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88238. *
  88239. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88240. * will give the string equivalent. The contents should not be modified.
  88241. */
  88242. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88243. /*********** FLAC__Metadata_Chain ***********/
  88244. /** Create a new chain instance.
  88245. *
  88246. * \retval FLAC__Metadata_Chain*
  88247. * \c NULL if there was an error allocating memory, else the new instance.
  88248. */
  88249. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88250. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88251. *
  88252. * \param chain A pointer to an existing chain.
  88253. * \assert
  88254. * \code chain != NULL \endcode
  88255. */
  88256. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88257. /** Get the current status of the chain. Call this after a function
  88258. * returns \c false to get the reason for the error. Also resets the
  88259. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88260. *
  88261. * \param chain A pointer to an existing chain.
  88262. * \assert
  88263. * \code chain != NULL \endcode
  88264. * \retval FLAC__Metadata_ChainStatus
  88265. * The current status of the chain.
  88266. */
  88267. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88268. /** Read all metadata from a FLAC file into the chain.
  88269. *
  88270. * \param chain A pointer to an existing chain.
  88271. * \param filename The path to the FLAC file to read.
  88272. * \assert
  88273. * \code chain != NULL \endcode
  88274. * \code filename != NULL \endcode
  88275. * \retval FLAC__bool
  88276. * \c true if a valid list of metadata blocks was read from
  88277. * \a filename, else \c false. On failure, check the status with
  88278. * FLAC__metadata_chain_status().
  88279. */
  88280. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88281. /** Read all metadata from an Ogg FLAC file into the chain.
  88282. *
  88283. * \note Ogg FLAC metadata data writing is not supported yet and
  88284. * FLAC__metadata_chain_write() will fail.
  88285. *
  88286. * \param chain A pointer to an existing chain.
  88287. * \param filename The path to the Ogg FLAC file to read.
  88288. * \assert
  88289. * \code chain != NULL \endcode
  88290. * \code filename != NULL \endcode
  88291. * \retval FLAC__bool
  88292. * \c true if a valid list of metadata blocks was read from
  88293. * \a filename, else \c false. On failure, check the status with
  88294. * FLAC__metadata_chain_status().
  88295. */
  88296. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88297. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88298. *
  88299. * The \a handle need only be open for reading, but must be seekable.
  88300. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88301. * for Windows).
  88302. *
  88303. * \param chain A pointer to an existing chain.
  88304. * \param handle The I/O handle of the FLAC stream to read. The
  88305. * handle will NOT be closed after the metadata is read;
  88306. * that is the duty of the caller.
  88307. * \param callbacks
  88308. * A set of callbacks to use for I/O. The mandatory
  88309. * callbacks are \a read, \a seek, and \a tell.
  88310. * \assert
  88311. * \code chain != NULL \endcode
  88312. * \retval FLAC__bool
  88313. * \c true if a valid list of metadata blocks was read from
  88314. * \a handle, else \c false. On failure, check the status with
  88315. * FLAC__metadata_chain_status().
  88316. */
  88317. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88318. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88319. *
  88320. * The \a handle need only be open for reading, but must be seekable.
  88321. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88322. * for Windows).
  88323. *
  88324. * \note Ogg FLAC metadata data writing is not supported yet and
  88325. * FLAC__metadata_chain_write() will fail.
  88326. *
  88327. * \param chain A pointer to an existing chain.
  88328. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88329. * handle will NOT be closed after the metadata is read;
  88330. * that is the duty of the caller.
  88331. * \param callbacks
  88332. * A set of callbacks to use for I/O. The mandatory
  88333. * callbacks are \a read, \a seek, and \a tell.
  88334. * \assert
  88335. * \code chain != NULL \endcode
  88336. * \retval FLAC__bool
  88337. * \c true if a valid list of metadata blocks was read from
  88338. * \a handle, else \c false. On failure, check the status with
  88339. * FLAC__metadata_chain_status().
  88340. */
  88341. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88342. /** Checks if writing the given chain would require the use of a
  88343. * temporary file, or if it could be written in place.
  88344. *
  88345. * Under certain conditions, padding can be utilized so that writing
  88346. * edited metadata back to the FLAC file does not require rewriting the
  88347. * entire file. If rewriting is required, then a temporary workfile is
  88348. * required. When writing metadata using callbacks, you must check
  88349. * this function to know whether to call
  88350. * FLAC__metadata_chain_write_with_callbacks() or
  88351. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88352. * writing with FLAC__metadata_chain_write(), the temporary file is
  88353. * handled internally.
  88354. *
  88355. * \param chain A pointer to an existing chain.
  88356. * \param use_padding
  88357. * Whether or not padding will be allowed to be used
  88358. * during the write. The value of \a use_padding given
  88359. * here must match the value later passed to
  88360. * FLAC__metadata_chain_write_with_callbacks() or
  88361. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88362. * \assert
  88363. * \code chain != NULL \endcode
  88364. * \retval FLAC__bool
  88365. * \c true if writing the current chain would require a tempfile, or
  88366. * \c false if metadata can be written in place.
  88367. */
  88368. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88369. /** Write all metadata out to the FLAC file. This function tries to be as
  88370. * efficient as possible; how the metadata is actually written is shown by
  88371. * the following:
  88372. *
  88373. * If the current chain is the same size as the existing metadata, the new
  88374. * data is written in place.
  88375. *
  88376. * If the current chain is longer than the existing metadata, and
  88377. * \a use_padding is \c true, and the last block is a PADDING block of
  88378. * sufficient length, the function will truncate the final padding block
  88379. * so that the overall size of the metadata is the same as the existing
  88380. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88381. * the above conditions are met, the entire FLAC file must be rewritten.
  88382. * If you want to use padding this way it is a good idea to call
  88383. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88384. * amount of padding to work with, unless you need to preserve ordering
  88385. * of the PADDING blocks for some reason.
  88386. *
  88387. * If the current chain is shorter than the existing metadata, and
  88388. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88389. * is extended to make the overall size the same as the existing data. If
  88390. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88391. * PADDING block is added to the end of the new data to make it the same
  88392. * size as the existing data (if possible, see the note to
  88393. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88394. * and the new data is written in place. If none of the above apply or
  88395. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88396. *
  88397. * If \a preserve_file_stats is \c true, the owner and modification time will
  88398. * be preserved even if the FLAC file is written.
  88399. *
  88400. * For this write function to be used, the chain must have been read with
  88401. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88402. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88403. *
  88404. * \param chain A pointer to an existing chain.
  88405. * \param use_padding See above.
  88406. * \param preserve_file_stats See above.
  88407. * \assert
  88408. * \code chain != NULL \endcode
  88409. * \retval FLAC__bool
  88410. * \c true if the write succeeded, else \c false. On failure,
  88411. * check the status with FLAC__metadata_chain_status().
  88412. */
  88413. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88414. /** Write all metadata out to a FLAC stream via callbacks.
  88415. *
  88416. * (See FLAC__metadata_chain_write() for the details on how padding is
  88417. * used to write metadata in place if possible.)
  88418. *
  88419. * The \a handle must be open for updating and be seekable. The
  88420. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88421. * for Windows).
  88422. *
  88423. * For this write function to be used, the chain must have been read with
  88424. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88425. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88426. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88427. * \c false.
  88428. *
  88429. * \param chain A pointer to an existing chain.
  88430. * \param use_padding See FLAC__metadata_chain_write()
  88431. * \param handle The I/O handle of the FLAC stream to write. The
  88432. * handle will NOT be closed after the metadata is
  88433. * written; that is the duty of the caller.
  88434. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88435. * callbacks are \a write and \a seek.
  88436. * \assert
  88437. * \code chain != NULL \endcode
  88438. * \retval FLAC__bool
  88439. * \c true if the write succeeded, else \c false. On failure,
  88440. * check the status with FLAC__metadata_chain_status().
  88441. */
  88442. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88443. /** Write all metadata out to a FLAC stream via callbacks.
  88444. *
  88445. * (See FLAC__metadata_chain_write() for the details on how padding is
  88446. * used to write metadata in place if possible.)
  88447. *
  88448. * This version of the write-with-callbacks function must be used when
  88449. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88450. * this function, you must supply an I/O handle corresponding to the
  88451. * FLAC file to edit, and a temporary handle to which the new FLAC
  88452. * file will be written. It is the caller's job to move this temporary
  88453. * FLAC file on top of the original FLAC file to complete the metadata
  88454. * edit.
  88455. *
  88456. * The \a handle must be open for reading and be seekable. The
  88457. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88458. * for Windows).
  88459. *
  88460. * The \a temp_handle must be open for writing. The
  88461. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88462. * for Windows). It should be an empty stream, or at least positioned
  88463. * at the start-of-file (in which case it is the caller's duty to
  88464. * truncate it on return).
  88465. *
  88466. * For this write function to be used, the chain must have been read with
  88467. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88468. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88469. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88470. * \c true.
  88471. *
  88472. * \param chain A pointer to an existing chain.
  88473. * \param use_padding See FLAC__metadata_chain_write()
  88474. * \param handle The I/O handle of the original FLAC stream to read.
  88475. * The handle will NOT be closed after the metadata is
  88476. * written; that is the duty of the caller.
  88477. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88478. * The mandatory callbacks are \a read, \a seek, and
  88479. * \a eof.
  88480. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88481. * handle will NOT be closed after the metadata is
  88482. * written; that is the duty of the caller.
  88483. * \param temp_callbacks
  88484. * A set of callbacks to use for I/O on temp_handle.
  88485. * The only mandatory callback is \a write.
  88486. * \assert
  88487. * \code chain != NULL \endcode
  88488. * \retval FLAC__bool
  88489. * \c true if the write succeeded, else \c false. On failure,
  88490. * check the status with FLAC__metadata_chain_status().
  88491. */
  88492. 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);
  88493. /** Merge adjacent PADDING blocks into a single block.
  88494. *
  88495. * \note This function does not write to the FLAC file, it only
  88496. * modifies the chain.
  88497. *
  88498. * \warning Any iterator on the current chain will become invalid after this
  88499. * call. You should delete the iterator and get a new one.
  88500. *
  88501. * \param chain A pointer to an existing chain.
  88502. * \assert
  88503. * \code chain != NULL \endcode
  88504. */
  88505. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88506. /** This function will move all PADDING blocks to the end on the metadata,
  88507. * then merge them into a single block.
  88508. *
  88509. * \note This function does not write to the FLAC file, it only
  88510. * modifies the chain.
  88511. *
  88512. * \warning Any iterator on the current chain will become invalid after this
  88513. * call. You should delete the iterator and get a new one.
  88514. *
  88515. * \param chain A pointer to an existing chain.
  88516. * \assert
  88517. * \code chain != NULL \endcode
  88518. */
  88519. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88520. /*********** FLAC__Metadata_Iterator ***********/
  88521. /** Create a new iterator instance.
  88522. *
  88523. * \retval FLAC__Metadata_Iterator*
  88524. * \c NULL if there was an error allocating memory, else the new instance.
  88525. */
  88526. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88527. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88528. *
  88529. * \param iterator A pointer to an existing iterator.
  88530. * \assert
  88531. * \code iterator != NULL \endcode
  88532. */
  88533. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88534. /** Initialize the iterator to point to the first metadata block in the
  88535. * given chain.
  88536. *
  88537. * \param iterator A pointer to an existing iterator.
  88538. * \param chain A pointer to an existing and initialized (read) chain.
  88539. * \assert
  88540. * \code iterator != NULL \endcode
  88541. * \code chain != NULL \endcode
  88542. */
  88543. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88544. /** Moves the iterator forward one metadata block, returning \c false if
  88545. * already at the end.
  88546. *
  88547. * \param iterator A pointer to an existing initialized iterator.
  88548. * \assert
  88549. * \code iterator != NULL \endcode
  88550. * \a iterator has been successfully initialized with
  88551. * FLAC__metadata_iterator_init()
  88552. * \retval FLAC__bool
  88553. * \c false if already at the last metadata block of the chain, else
  88554. * \c true.
  88555. */
  88556. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88557. /** Moves the iterator backward one metadata block, returning \c false if
  88558. * already at the beginning.
  88559. *
  88560. * \param iterator A pointer to an existing initialized iterator.
  88561. * \assert
  88562. * \code iterator != NULL \endcode
  88563. * \a iterator has been successfully initialized with
  88564. * FLAC__metadata_iterator_init()
  88565. * \retval FLAC__bool
  88566. * \c false if already at the first metadata block of the chain, else
  88567. * \c true.
  88568. */
  88569. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88570. /** Get the type of the metadata block at the current position.
  88571. *
  88572. * \param iterator A pointer to an existing initialized iterator.
  88573. * \assert
  88574. * \code iterator != NULL \endcode
  88575. * \a iterator has been successfully initialized with
  88576. * FLAC__metadata_iterator_init()
  88577. * \retval FLAC__MetadataType
  88578. * The type of the metadata block at the current iterator position.
  88579. */
  88580. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88581. /** Get the metadata block at the current position. You can modify
  88582. * the block in place but must write the chain before the changes
  88583. * are reflected to the FLAC file. You do not need to call
  88584. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88585. * the pointer returned by FLAC__metadata_iterator_get_block()
  88586. * points directly into the chain.
  88587. *
  88588. * \warning
  88589. * Do not call FLAC__metadata_object_delete() on the returned object;
  88590. * to delete a block use FLAC__metadata_iterator_delete_block().
  88591. *
  88592. * \param iterator A pointer to an existing initialized iterator.
  88593. * \assert
  88594. * \code iterator != NULL \endcode
  88595. * \a iterator has been successfully initialized with
  88596. * FLAC__metadata_iterator_init()
  88597. * \retval FLAC__StreamMetadata*
  88598. * The current metadata block.
  88599. */
  88600. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88601. /** Set the metadata block at the current position, replacing the existing
  88602. * block. The new block passed in becomes owned by the chain and it will be
  88603. * deleted when the chain is deleted.
  88604. *
  88605. * \param iterator A pointer to an existing initialized iterator.
  88606. * \param block A pointer to a metadata block.
  88607. * \assert
  88608. * \code iterator != NULL \endcode
  88609. * \a iterator has been successfully initialized with
  88610. * FLAC__metadata_iterator_init()
  88611. * \code block != NULL \endcode
  88612. * \retval FLAC__bool
  88613. * \c false if the conditions in the above description are not met, or
  88614. * a memory allocation error occurs, otherwise \c true.
  88615. */
  88616. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88617. /** Removes the current block from the chain. If \a replace_with_padding is
  88618. * \c true, the block will instead be replaced with a padding block of equal
  88619. * size. You can not delete the STREAMINFO block. The iterator will be
  88620. * left pointing to the block before the one just "deleted", even if
  88621. * \a replace_with_padding is \c true.
  88622. *
  88623. * \param iterator A pointer to an existing initialized iterator.
  88624. * \param replace_with_padding See above.
  88625. * \assert
  88626. * \code iterator != NULL \endcode
  88627. * \a iterator has been successfully initialized with
  88628. * FLAC__metadata_iterator_init()
  88629. * \retval FLAC__bool
  88630. * \c false if the conditions in the above description are not met,
  88631. * otherwise \c true.
  88632. */
  88633. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88634. /** Insert a new block before the current block. You cannot insert a block
  88635. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88636. * as there can be only one, the one that already exists at the head when you
  88637. * read in a chain. The chain takes ownership of the new block and it will be
  88638. * deleted when the chain is deleted. The iterator will be left pointing to
  88639. * the new block.
  88640. *
  88641. * \param iterator A pointer to an existing initialized iterator.
  88642. * \param block A pointer to a metadata block to insert.
  88643. * \assert
  88644. * \code iterator != NULL \endcode
  88645. * \a iterator has been successfully initialized with
  88646. * FLAC__metadata_iterator_init()
  88647. * \retval FLAC__bool
  88648. * \c false if the conditions in the above description are not met, or
  88649. * a memory allocation error occurs, otherwise \c true.
  88650. */
  88651. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88652. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88653. * block as there can be only one, the one that already exists at the head when
  88654. * you read in a chain. The chain takes ownership of the new block and it will
  88655. * be deleted when the chain is deleted. The iterator will be left pointing to
  88656. * the new block.
  88657. *
  88658. * \param iterator A pointer to an existing initialized iterator.
  88659. * \param block A pointer to a metadata block to insert.
  88660. * \assert
  88661. * \code iterator != NULL \endcode
  88662. * \a iterator has been successfully initialized with
  88663. * FLAC__metadata_iterator_init()
  88664. * \retval FLAC__bool
  88665. * \c false if the conditions in the above description are not met, or
  88666. * a memory allocation error occurs, otherwise \c true.
  88667. */
  88668. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88669. /* \} */
  88670. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88671. * \ingroup flac_metadata
  88672. *
  88673. * \brief
  88674. * This module contains methods for manipulating FLAC metadata objects.
  88675. *
  88676. * Since many are variable length we have to be careful about the memory
  88677. * management. We decree that all pointers to data in the object are
  88678. * owned by the object and memory-managed by the object.
  88679. *
  88680. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88681. * functions to create all instances. When using the
  88682. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88683. * \a copy to \c true to have the function make it's own copy of the data, or
  88684. * to \c false to give the object ownership of your data. In the latter case
  88685. * your pointer must be freeable by free() and will be free()d when the object
  88686. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88687. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88688. * the length argument is 0 and the \a copy argument is \c false.
  88689. *
  88690. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88691. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88692. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88693. * case of a memory allocation error.
  88694. *
  88695. * We don't have the convenience of C++ here, so note that the library relies
  88696. * on you to keep the types straight. In other words, if you pass, for
  88697. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88698. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88699. * failure.
  88700. *
  88701. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88702. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88703. * toward the length or stored in the stream, but it can make working with plain
  88704. * comments (those that don't contain embedded-NULs in the value) easier.
  88705. * Entries passed into these functions have trailing NULs added if missing, and
  88706. * returned entries are guaranteed to have a trailing NUL.
  88707. *
  88708. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88709. * comment entry/name/value will first validate that it complies with the Vorbis
  88710. * comment specification and return false if it does not.
  88711. *
  88712. * There is no need to recalculate the length field on metadata blocks you
  88713. * have modified. They will be calculated automatically before they are
  88714. * written back to a file.
  88715. *
  88716. * \{
  88717. */
  88718. /** Create a new metadata object instance of the given type.
  88719. *
  88720. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88721. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88722. * the vendor string set (but zero comments).
  88723. *
  88724. * Do not pass in a value greater than or equal to
  88725. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88726. * doing.
  88727. *
  88728. * \param type Type of object to create
  88729. * \retval FLAC__StreamMetadata*
  88730. * \c NULL if there was an error allocating memory or the type code is
  88731. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88732. */
  88733. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88734. /** Create a copy of an existing metadata object.
  88735. *
  88736. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88737. * object is also copied. The caller takes ownership of the new block and
  88738. * is responsible for freeing it with FLAC__metadata_object_delete().
  88739. *
  88740. * \param object Pointer to object to copy.
  88741. * \assert
  88742. * \code object != NULL \endcode
  88743. * \retval FLAC__StreamMetadata*
  88744. * \c NULL if there was an error allocating memory, else the new instance.
  88745. */
  88746. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88747. /** Free a metadata object. Deletes the object pointed to by \a object.
  88748. *
  88749. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88750. * object is also deleted.
  88751. *
  88752. * \param object A pointer to an existing object.
  88753. * \assert
  88754. * \code object != NULL \endcode
  88755. */
  88756. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88757. /** Compares two metadata objects.
  88758. *
  88759. * The compare is "deep", i.e. dynamically allocated data within the
  88760. * object is also compared.
  88761. *
  88762. * \param block1 A pointer to an existing object.
  88763. * \param block2 A pointer to an existing object.
  88764. * \assert
  88765. * \code block1 != NULL \endcode
  88766. * \code block2 != NULL \endcode
  88767. * \retval FLAC__bool
  88768. * \c true if objects are identical, else \c false.
  88769. */
  88770. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88771. /** Sets the application data of an APPLICATION block.
  88772. *
  88773. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88774. * takes ownership of the pointer. The existing data will be freed if this
  88775. * function is successful, otherwise the original data will remain if \a copy
  88776. * is \c true and malloc() fails.
  88777. *
  88778. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88779. *
  88780. * \param object A pointer to an existing APPLICATION object.
  88781. * \param data A pointer to the data to set.
  88782. * \param length The length of \a data in bytes.
  88783. * \param copy See above.
  88784. * \assert
  88785. * \code object != NULL \endcode
  88786. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88787. * \code (data != NULL && length > 0) ||
  88788. * (data == NULL && length == 0 && copy == false) \endcode
  88789. * \retval FLAC__bool
  88790. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88791. */
  88792. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88793. /** Resize the seekpoint array.
  88794. *
  88795. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88796. * points will be added to the end.
  88797. *
  88798. * \param object A pointer to an existing SEEKTABLE object.
  88799. * \param new_num_points The desired length of the array; may be \c 0.
  88800. * \assert
  88801. * \code object != NULL \endcode
  88802. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88803. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88804. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88805. * \retval FLAC__bool
  88806. * \c false if memory allocation error, else \c true.
  88807. */
  88808. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88809. /** Set a seekpoint in a seektable.
  88810. *
  88811. * \param object A pointer to an existing SEEKTABLE object.
  88812. * \param point_num Index into seekpoint array to set.
  88813. * \param point The point to set.
  88814. * \assert
  88815. * \code object != NULL \endcode
  88816. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88817. * \code object->data.seek_table.num_points > point_num \endcode
  88818. */
  88819. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88820. /** Insert a seekpoint into a seektable.
  88821. *
  88822. * \param object A pointer to an existing SEEKTABLE object.
  88823. * \param point_num Index into seekpoint array to set.
  88824. * \param point The point to set.
  88825. * \assert
  88826. * \code object != NULL \endcode
  88827. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88828. * \code object->data.seek_table.num_points >= point_num \endcode
  88829. * \retval FLAC__bool
  88830. * \c false if memory allocation error, else \c true.
  88831. */
  88832. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88833. /** Delete a seekpoint from a seektable.
  88834. *
  88835. * \param object A pointer to an existing SEEKTABLE object.
  88836. * \param point_num Index into seekpoint array to set.
  88837. * \assert
  88838. * \code object != NULL \endcode
  88839. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88840. * \code object->data.seek_table.num_points > point_num \endcode
  88841. * \retval FLAC__bool
  88842. * \c false if memory allocation error, else \c true.
  88843. */
  88844. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88845. /** Check a seektable to see if it conforms to the FLAC specification.
  88846. * See the format specification for limits on the contents of the
  88847. * seektable.
  88848. *
  88849. * \param object A pointer to an existing SEEKTABLE object.
  88850. * \assert
  88851. * \code object != NULL \endcode
  88852. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88853. * \retval FLAC__bool
  88854. * \c false if seek table is illegal, else \c true.
  88855. */
  88856. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88857. /** Append a number of placeholder points to the end of a seek table.
  88858. *
  88859. * \note
  88860. * As with the other ..._seektable_template_... functions, you should
  88861. * call FLAC__metadata_object_seektable_template_sort() when finished
  88862. * to make the seek table legal.
  88863. *
  88864. * \param object A pointer to an existing SEEKTABLE object.
  88865. * \param num The number of placeholder points to append.
  88866. * \assert
  88867. * \code object != NULL \endcode
  88868. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88869. * \retval FLAC__bool
  88870. * \c false if memory allocation fails, else \c true.
  88871. */
  88872. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88873. /** Append a specific seek point template to the end of a seek table.
  88874. *
  88875. * \note
  88876. * As with the other ..._seektable_template_... functions, you should
  88877. * call FLAC__metadata_object_seektable_template_sort() when finished
  88878. * to make the seek table legal.
  88879. *
  88880. * \param object A pointer to an existing SEEKTABLE object.
  88881. * \param sample_number The sample number of the seek point template.
  88882. * \assert
  88883. * \code object != NULL \endcode
  88884. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88885. * \retval FLAC__bool
  88886. * \c false if memory allocation fails, else \c true.
  88887. */
  88888. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88889. /** Append specific seek point templates to the end of a seek table.
  88890. *
  88891. * \note
  88892. * As with the other ..._seektable_template_... functions, you should
  88893. * call FLAC__metadata_object_seektable_template_sort() when finished
  88894. * to make the seek table legal.
  88895. *
  88896. * \param object A pointer to an existing SEEKTABLE object.
  88897. * \param sample_numbers An array of sample numbers for the seek points.
  88898. * \param num The number of seek point templates to append.
  88899. * \assert
  88900. * \code object != NULL \endcode
  88901. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88902. * \retval FLAC__bool
  88903. * \c false if memory allocation fails, else \c true.
  88904. */
  88905. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88906. /** Append a set of evenly-spaced seek point templates to the end of a
  88907. * seek table.
  88908. *
  88909. * \note
  88910. * As with the other ..._seektable_template_... functions, you should
  88911. * call FLAC__metadata_object_seektable_template_sort() when finished
  88912. * to make the seek table legal.
  88913. *
  88914. * \param object A pointer to an existing SEEKTABLE object.
  88915. * \param num The number of placeholder points to append.
  88916. * \param total_samples The total number of samples to be encoded;
  88917. * the seekpoints will be spaced approximately
  88918. * \a total_samples / \a num samples apart.
  88919. * \assert
  88920. * \code object != NULL \endcode
  88921. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88922. * \code total_samples > 0 \endcode
  88923. * \retval FLAC__bool
  88924. * \c false if memory allocation fails, else \c true.
  88925. */
  88926. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88927. /** Append a set of evenly-spaced seek point templates to the end of a
  88928. * seek table.
  88929. *
  88930. * \note
  88931. * As with the other ..._seektable_template_... functions, you should
  88932. * call FLAC__metadata_object_seektable_template_sort() when finished
  88933. * to make the seek table legal.
  88934. *
  88935. * \param object A pointer to an existing SEEKTABLE object.
  88936. * \param samples The number of samples apart to space the placeholder
  88937. * points. The first point will be at sample \c 0, the
  88938. * second at sample \a samples, then 2*\a samples, and
  88939. * so on. As long as \a samples and \a total_samples
  88940. * are greater than \c 0, there will always be at least
  88941. * one seekpoint at sample \c 0.
  88942. * \param total_samples The total number of samples to be encoded;
  88943. * the seekpoints will be spaced
  88944. * \a samples samples apart.
  88945. * \assert
  88946. * \code object != NULL \endcode
  88947. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88948. * \code samples > 0 \endcode
  88949. * \code total_samples > 0 \endcode
  88950. * \retval FLAC__bool
  88951. * \c false if memory allocation fails, else \c true.
  88952. */
  88953. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88954. /** Sort a seek table's seek points according to the format specification,
  88955. * removing duplicates.
  88956. *
  88957. * \param object A pointer to a seek table to be sorted.
  88958. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88959. * If \c true, duplicates are deleted and the seek table is
  88960. * shrunk appropriately; the number of placeholder points
  88961. * present in the seek table will be the same after the call
  88962. * as before.
  88963. * \assert
  88964. * \code object != NULL \endcode
  88965. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88966. * \retval FLAC__bool
  88967. * \c false if realloc() fails, else \c true.
  88968. */
  88969. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88970. /** Sets the vendor string in a VORBIS_COMMENT block.
  88971. *
  88972. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88973. * one already.
  88974. *
  88975. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88976. * takes ownership of the \c entry.entry pointer.
  88977. *
  88978. * \note If this function returns \c false, the caller still owns the
  88979. * pointer.
  88980. *
  88981. * \param object A pointer to an existing VORBIS_COMMENT object.
  88982. * \param entry The entry to set the vendor string to.
  88983. * \param copy See above.
  88984. * \assert
  88985. * \code object != NULL \endcode
  88986. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88987. * \code (entry.entry != NULL && entry.length > 0) ||
  88988. * (entry.entry == NULL && entry.length == 0) \endcode
  88989. * \retval FLAC__bool
  88990. * \c false if memory allocation fails or \a entry does not comply with the
  88991. * Vorbis comment specification, else \c true.
  88992. */
  88993. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88994. /** Resize the comment array.
  88995. *
  88996. * If the size shrinks, elements will truncated; if it grows, new empty
  88997. * fields will be added to the end.
  88998. *
  88999. * \param object A pointer to an existing VORBIS_COMMENT object.
  89000. * \param new_num_comments The desired length of the array; may be \c 0.
  89001. * \assert
  89002. * \code object != NULL \endcode
  89003. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89004. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89005. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89006. * \retval FLAC__bool
  89007. * \c false if memory allocation fails, else \c true.
  89008. */
  89009. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89010. /** Sets a comment in a VORBIS_COMMENT block.
  89011. *
  89012. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89013. * one already.
  89014. *
  89015. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89016. * takes ownership of the \c entry.entry pointer.
  89017. *
  89018. * \note If this function returns \c false, the caller still owns the
  89019. * pointer.
  89020. *
  89021. * \param object A pointer to an existing VORBIS_COMMENT object.
  89022. * \param comment_num Index into comment array to set.
  89023. * \param entry The entry to set the comment to.
  89024. * \param copy See above.
  89025. * \assert
  89026. * \code object != NULL \endcode
  89027. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89028. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89029. * \code (entry.entry != NULL && entry.length > 0) ||
  89030. * (entry.entry == NULL && entry.length == 0) \endcode
  89031. * \retval FLAC__bool
  89032. * \c false if memory allocation fails or \a entry does not comply with the
  89033. * Vorbis comment specification, else \c true.
  89034. */
  89035. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89036. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89037. *
  89038. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89039. * one already.
  89040. *
  89041. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89042. * takes ownership of the \c entry.entry pointer.
  89043. *
  89044. * \note If this function returns \c false, the caller still owns the
  89045. * pointer.
  89046. *
  89047. * \param object A pointer to an existing VORBIS_COMMENT object.
  89048. * \param comment_num The index at which to insert the comment. The comments
  89049. * at and after \a comment_num move right one position.
  89050. * To append a comment to the end, set \a comment_num to
  89051. * \c object->data.vorbis_comment.num_comments .
  89052. * \param entry The comment to insert.
  89053. * \param copy See above.
  89054. * \assert
  89055. * \code object != NULL \endcode
  89056. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89057. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89058. * \code (entry.entry != NULL && entry.length > 0) ||
  89059. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89060. * \retval FLAC__bool
  89061. * \c false if memory allocation fails or \a entry does not comply with the
  89062. * Vorbis comment specification, else \c true.
  89063. */
  89064. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89065. /** Appends a comment to a VORBIS_COMMENT block.
  89066. *
  89067. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89068. * one already.
  89069. *
  89070. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89071. * takes ownership of the \c entry.entry pointer.
  89072. *
  89073. * \note If this function returns \c false, the caller still owns the
  89074. * pointer.
  89075. *
  89076. * \param object A pointer to an existing VORBIS_COMMENT object.
  89077. * \param entry The comment to insert.
  89078. * \param copy See above.
  89079. * \assert
  89080. * \code object != NULL \endcode
  89081. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89082. * \code (entry.entry != NULL && entry.length > 0) ||
  89083. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89084. * \retval FLAC__bool
  89085. * \c false if memory allocation fails or \a entry does not comply with the
  89086. * Vorbis comment specification, else \c true.
  89087. */
  89088. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89089. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89090. *
  89091. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89092. * one already.
  89093. *
  89094. * Depending on the the value of \a all, either all or just the first comment
  89095. * whose field name(s) match the given entry's name will be replaced by the
  89096. * given entry. If no comments match, \a entry will simply be appended.
  89097. *
  89098. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89099. * takes ownership of the \c entry.entry pointer.
  89100. *
  89101. * \note If this function returns \c false, the caller still owns the
  89102. * pointer.
  89103. *
  89104. * \param object A pointer to an existing VORBIS_COMMENT object.
  89105. * \param entry The comment to insert.
  89106. * \param all If \c true, all comments whose field name matches
  89107. * \a entry's field name will be removed, and \a entry will
  89108. * be inserted at the position of the first matching
  89109. * comment. If \c false, only the first comment whose
  89110. * field name matches \a entry's field name will be
  89111. * replaced with \a entry.
  89112. * \param copy See above.
  89113. * \assert
  89114. * \code object != NULL \endcode
  89115. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89116. * \code (entry.entry != NULL && entry.length > 0) ||
  89117. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89118. * \retval FLAC__bool
  89119. * \c false if memory allocation fails or \a entry does not comply with the
  89120. * Vorbis comment specification, else \c true.
  89121. */
  89122. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89123. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89124. *
  89125. * \param object A pointer to an existing VORBIS_COMMENT object.
  89126. * \param comment_num The index of the comment to delete.
  89127. * \assert
  89128. * \code object != NULL \endcode
  89129. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89130. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89131. * \retval FLAC__bool
  89132. * \c false if realloc() fails, else \c true.
  89133. */
  89134. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89135. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89136. *
  89137. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89138. * memory and shall be owned by the caller. For convenience the entry will
  89139. * have a terminating NUL.
  89140. *
  89141. * \param entry A pointer to a Vorbis comment entry. The entry's
  89142. * \c entry pointer should not point to allocated
  89143. * memory as it will be overwritten.
  89144. * \param field_name The field name in ASCII, \c NUL terminated.
  89145. * \param field_value The field value in UTF-8, \c NUL terminated.
  89146. * \assert
  89147. * \code entry != NULL \endcode
  89148. * \code field_name != NULL \endcode
  89149. * \code field_value != NULL \endcode
  89150. * \retval FLAC__bool
  89151. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89152. * not comply with the Vorbis comment specification, else \c true.
  89153. */
  89154. 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);
  89155. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89156. *
  89157. * The returned pointers to name and value will be allocated by malloc()
  89158. * and shall be owned by the caller.
  89159. *
  89160. * \param entry An existing Vorbis comment entry.
  89161. * \param field_name The address of where the returned pointer to the
  89162. * field name will be stored.
  89163. * \param field_value The address of where the returned pointer to the
  89164. * field value will be stored.
  89165. * \assert
  89166. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89167. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89168. * \code field_name != NULL \endcode
  89169. * \code field_value != NULL \endcode
  89170. * \retval FLAC__bool
  89171. * \c false if memory allocation fails or \a entry does not comply with the
  89172. * Vorbis comment specification, else \c true.
  89173. */
  89174. 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);
  89175. /** Check if the given Vorbis comment entry's field name matches the given
  89176. * field name.
  89177. *
  89178. * \param entry An existing Vorbis comment entry.
  89179. * \param field_name The field name to check.
  89180. * \param field_name_length The length of \a field_name, not including the
  89181. * terminating \c NUL.
  89182. * \assert
  89183. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89184. * \retval FLAC__bool
  89185. * \c true if the field names match, else \c false
  89186. */
  89187. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89188. /** Find a Vorbis comment with the given field name.
  89189. *
  89190. * The search begins at entry number \a offset; use an offset of 0 to
  89191. * search from the beginning of the comment array.
  89192. *
  89193. * \param object A pointer to an existing VORBIS_COMMENT object.
  89194. * \param offset The offset into the comment array from where to start
  89195. * the search.
  89196. * \param field_name The field name of the comment to find.
  89197. * \assert
  89198. * \code object != NULL \endcode
  89199. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89200. * \code field_name != NULL \endcode
  89201. * \retval int
  89202. * The offset in the comment array of the first comment whose field
  89203. * name matches \a field_name, or \c -1 if no match was found.
  89204. */
  89205. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89206. /** Remove first Vorbis comment matching the given field name.
  89207. *
  89208. * \param object A pointer to an existing VORBIS_COMMENT object.
  89209. * \param field_name The field name of comment to delete.
  89210. * \assert
  89211. * \code object != NULL \endcode
  89212. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89213. * \retval int
  89214. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89215. * \c 1 for one matching entry deleted.
  89216. */
  89217. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89218. /** Remove all Vorbis comments matching the given field name.
  89219. *
  89220. * \param object A pointer to an existing VORBIS_COMMENT object.
  89221. * \param field_name The field name of comments to delete.
  89222. * \assert
  89223. * \code object != NULL \endcode
  89224. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89225. * \retval int
  89226. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89227. * else the number of matching entries deleted.
  89228. */
  89229. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89230. /** Create a new CUESHEET track instance.
  89231. *
  89232. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89233. *
  89234. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89235. * \c NULL if there was an error allocating memory, else the new instance.
  89236. */
  89237. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89238. /** Create a copy of an existing CUESHEET track object.
  89239. *
  89240. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89241. * object is also copied. The caller takes ownership of the new object and
  89242. * is responsible for freeing it with
  89243. * FLAC__metadata_object_cuesheet_track_delete().
  89244. *
  89245. * \param object Pointer to object to copy.
  89246. * \assert
  89247. * \code object != NULL \endcode
  89248. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89249. * \c NULL if there was an error allocating memory, else the new instance.
  89250. */
  89251. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89252. /** Delete a CUESHEET track object
  89253. *
  89254. * \param object A pointer to an existing CUESHEET track object.
  89255. * \assert
  89256. * \code object != NULL \endcode
  89257. */
  89258. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89259. /** Resize a track's index point array.
  89260. *
  89261. * If the size shrinks, elements will truncated; if it grows, new blank
  89262. * indices will be added to the end.
  89263. *
  89264. * \param object A pointer to an existing CUESHEET object.
  89265. * \param track_num The index of the track to modify. NOTE: this is not
  89266. * necessarily the same as the track's \a number field.
  89267. * \param new_num_indices The desired length of the array; may be \c 0.
  89268. * \assert
  89269. * \code object != NULL \endcode
  89270. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89271. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89272. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89273. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89274. * \retval FLAC__bool
  89275. * \c false if memory allocation error, else \c true.
  89276. */
  89277. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89278. /** Insert an index point in a CUESHEET track at the given index.
  89279. *
  89280. * \param object A pointer to an existing CUESHEET object.
  89281. * \param track_num The index of the track to modify. NOTE: this is not
  89282. * necessarily the same as the track's \a number field.
  89283. * \param index_num The index into the track's index array at which to
  89284. * insert the index point. NOTE: this is not necessarily
  89285. * the same as the index point's \a number field. The
  89286. * indices at and after \a index_num move right one
  89287. * position. To append an index point to the end, set
  89288. * \a index_num to
  89289. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89290. * \param index The index point to insert.
  89291. * \assert
  89292. * \code object != NULL \endcode
  89293. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89294. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89295. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89296. * \retval FLAC__bool
  89297. * \c false if realloc() fails, else \c true.
  89298. */
  89299. 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);
  89300. /** Insert a blank index point in a CUESHEET track at the given index.
  89301. *
  89302. * A blank index point is one in which all field values are zero.
  89303. *
  89304. * \param object A pointer to an existing CUESHEET object.
  89305. * \param track_num The index of the track to modify. NOTE: this is not
  89306. * necessarily the same as the track's \a number field.
  89307. * \param index_num The index into the track's index array at which to
  89308. * insert the index point. NOTE: this is not necessarily
  89309. * the same as the index point's \a number field. The
  89310. * indices at and after \a index_num move right one
  89311. * position. To append an index point to the end, set
  89312. * \a index_num to
  89313. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89314. * \assert
  89315. * \code object != NULL \endcode
  89316. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89317. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89318. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89319. * \retval FLAC__bool
  89320. * \c false if realloc() fails, else \c true.
  89321. */
  89322. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89323. /** Delete an index point in a CUESHEET track at the given index.
  89324. *
  89325. * \param object A pointer to an existing CUESHEET object.
  89326. * \param track_num The index into the track array of the track to
  89327. * modify. NOTE: this is not necessarily the same
  89328. * as the track's \a number field.
  89329. * \param index_num The index into the track's index array of the index
  89330. * to delete. NOTE: this is not necessarily the same
  89331. * as the index's \a number field.
  89332. * \assert
  89333. * \code object != NULL \endcode
  89334. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89335. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89336. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89337. * \retval FLAC__bool
  89338. * \c false if realloc() fails, else \c true.
  89339. */
  89340. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89341. /** Resize the track array.
  89342. *
  89343. * If the size shrinks, elements will truncated; if it grows, new blank
  89344. * tracks will be added to the end.
  89345. *
  89346. * \param object A pointer to an existing CUESHEET object.
  89347. * \param new_num_tracks The desired length of the array; may be \c 0.
  89348. * \assert
  89349. * \code object != NULL \endcode
  89350. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89351. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89352. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89353. * \retval FLAC__bool
  89354. * \c false if memory allocation error, else \c true.
  89355. */
  89356. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89357. /** Sets a track in a CUESHEET block.
  89358. *
  89359. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89360. * takes ownership of the \a track pointer.
  89361. *
  89362. * \param object A pointer to an existing CUESHEET object.
  89363. * \param track_num Index into track array to set. NOTE: this is not
  89364. * necessarily the same as the track's \a number field.
  89365. * \param track The track to set the track to. You may safely pass in
  89366. * a const pointer if \a copy is \c true.
  89367. * \param copy See above.
  89368. * \assert
  89369. * \code object != NULL \endcode
  89370. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89371. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89372. * \code (track->indices != NULL && track->num_indices > 0) ||
  89373. * (track->indices == NULL && track->num_indices == 0)
  89374. * \retval FLAC__bool
  89375. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89376. */
  89377. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89378. /** Insert a track in a CUESHEET block at the given index.
  89379. *
  89380. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89381. * takes ownership of the \a track pointer.
  89382. *
  89383. * \param object A pointer to an existing CUESHEET object.
  89384. * \param track_num The index at which to insert the track. NOTE: this
  89385. * is not necessarily the same as the track's \a number
  89386. * field. The tracks at and after \a track_num move right
  89387. * one position. To append a track to the end, set
  89388. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89389. * \param track The track to insert. You may safely pass in a const
  89390. * pointer if \a copy is \c true.
  89391. * \param copy See above.
  89392. * \assert
  89393. * \code object != NULL \endcode
  89394. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89395. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89396. * \retval FLAC__bool
  89397. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89398. */
  89399. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89400. /** Insert a blank track in a CUESHEET block at the given index.
  89401. *
  89402. * A blank track is one in which all field values are zero.
  89403. *
  89404. * \param object A pointer to an existing CUESHEET object.
  89405. * \param track_num The index at which to insert the track. NOTE: this
  89406. * is not necessarily the same as the track's \a number
  89407. * field. The tracks at and after \a track_num move right
  89408. * one position. To append a track to the end, set
  89409. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89410. * \assert
  89411. * \code object != NULL \endcode
  89412. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89413. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89414. * \retval FLAC__bool
  89415. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89416. */
  89417. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89418. /** Delete a track in a CUESHEET block at the given index.
  89419. *
  89420. * \param object A pointer to an existing CUESHEET object.
  89421. * \param track_num The index into the track array of the track to
  89422. * delete. NOTE: this is not necessarily the same
  89423. * as the track's \a number field.
  89424. * \assert
  89425. * \code object != NULL \endcode
  89426. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89427. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89428. * \retval FLAC__bool
  89429. * \c false if realloc() fails, else \c true.
  89430. */
  89431. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89432. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89433. * See the format specification for limits on the contents of the
  89434. * cue sheet.
  89435. *
  89436. * \param object A pointer to an existing CUESHEET object.
  89437. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89438. * stringent requirements for a CD-DA (audio) disc.
  89439. * \param violation Address of a pointer to a string. If there is a
  89440. * violation, a pointer to a string explanation of the
  89441. * violation will be returned here. \a violation may be
  89442. * \c NULL if you don't need the returned string. Do not
  89443. * free the returned string; it will always point to static
  89444. * data.
  89445. * \assert
  89446. * \code object != NULL \endcode
  89447. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89448. * \retval FLAC__bool
  89449. * \c false if cue sheet is illegal, else \c true.
  89450. */
  89451. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89452. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89453. * assumes the cue sheet corresponds to a CD; the result is undefined
  89454. * if the cuesheet's is_cd bit is not set.
  89455. *
  89456. * \param object A pointer to an existing CUESHEET object.
  89457. * \assert
  89458. * \code object != NULL \endcode
  89459. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89460. * \retval FLAC__uint32
  89461. * The unsigned integer representation of the CDDB/freedb ID
  89462. */
  89463. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89464. /** Sets the MIME type of a PICTURE block.
  89465. *
  89466. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89467. * takes ownership of the pointer. The existing string will be freed if this
  89468. * function is successful, otherwise the original string will remain if \a copy
  89469. * is \c true and malloc() fails.
  89470. *
  89471. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89472. *
  89473. * \param object A pointer to an existing PICTURE object.
  89474. * \param mime_type A pointer to the MIME type string. The string must be
  89475. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89476. * is done.
  89477. * \param copy See above.
  89478. * \assert
  89479. * \code object != NULL \endcode
  89480. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89481. * \code (mime_type != NULL) \endcode
  89482. * \retval FLAC__bool
  89483. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89484. */
  89485. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89486. /** Sets the description of a PICTURE block.
  89487. *
  89488. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89489. * takes ownership of the pointer. The existing string will be freed if this
  89490. * function is successful, otherwise the original string will remain if \a copy
  89491. * is \c true and malloc() fails.
  89492. *
  89493. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89494. *
  89495. * \param object A pointer to an existing PICTURE object.
  89496. * \param description A pointer to the description string. The string must be
  89497. * valid UTF-8, NUL-terminated. No validation is done.
  89498. * \param copy See above.
  89499. * \assert
  89500. * \code object != NULL \endcode
  89501. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89502. * \code (description != NULL) \endcode
  89503. * \retval FLAC__bool
  89504. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89505. */
  89506. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89507. /** Sets the picture data of a PICTURE block.
  89508. *
  89509. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89510. * takes ownership of the pointer. Also sets the \a data_length field of the
  89511. * metadata object to what is passed in as the \a length parameter. The
  89512. * existing data will be freed if this function is successful, otherwise the
  89513. * original data and data_length will remain if \a copy is \c true and
  89514. * malloc() fails.
  89515. *
  89516. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89517. *
  89518. * \param object A pointer to an existing PICTURE object.
  89519. * \param data A pointer to the data to set.
  89520. * \param length The length of \a data in bytes.
  89521. * \param copy See above.
  89522. * \assert
  89523. * \code object != NULL \endcode
  89524. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89525. * \code (data != NULL && length > 0) ||
  89526. * (data == NULL && length == 0 && copy == false) \endcode
  89527. * \retval FLAC__bool
  89528. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89529. */
  89530. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89531. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89532. * See the format specification for limits on the contents of the
  89533. * PICTURE block.
  89534. *
  89535. * \param object A pointer to existing PICTURE block to be checked.
  89536. * \param violation Address of a pointer to a string. If there is a
  89537. * violation, a pointer to a string explanation of the
  89538. * violation will be returned here. \a violation may be
  89539. * \c NULL if you don't need the returned string. Do not
  89540. * free the returned string; it will always point to static
  89541. * data.
  89542. * \assert
  89543. * \code object != NULL \endcode
  89544. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89545. * \retval FLAC__bool
  89546. * \c false if PICTURE block is illegal, else \c true.
  89547. */
  89548. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89549. /* \} */
  89550. #ifdef __cplusplus
  89551. }
  89552. #endif
  89553. #endif
  89554. /*** End of inlined file: metadata.h ***/
  89555. /*** Start of inlined file: stream_decoder.h ***/
  89556. #ifndef FLAC__STREAM_DECODER_H
  89557. #define FLAC__STREAM_DECODER_H
  89558. #include <stdio.h> /* for FILE */
  89559. #ifdef __cplusplus
  89560. extern "C" {
  89561. #endif
  89562. /** \file include/FLAC/stream_decoder.h
  89563. *
  89564. * \brief
  89565. * This module contains the functions which implement the stream
  89566. * decoder.
  89567. *
  89568. * See the detailed documentation in the
  89569. * \link flac_stream_decoder stream decoder \endlink module.
  89570. */
  89571. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89572. * \ingroup flac
  89573. *
  89574. * \brief
  89575. * This module describes the decoder layers provided by libFLAC.
  89576. *
  89577. * The stream decoder can be used to decode complete streams either from
  89578. * the client via callbacks, or directly from a file, depending on how
  89579. * it is initialized. When decoding via callbacks, the client provides
  89580. * callbacks for reading FLAC data and writing decoded samples, and
  89581. * handling metadata and errors. If the client also supplies seek-related
  89582. * callback, the decoder function for sample-accurate seeking within the
  89583. * FLAC input is also available. When decoding from a file, the client
  89584. * needs only supply a filename or open \c FILE* and write/metadata/error
  89585. * callbacks; the rest of the callbacks are supplied internally. For more
  89586. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89587. */
  89588. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89589. * \ingroup flac_decoder
  89590. *
  89591. * \brief
  89592. * This module contains the functions which implement the stream
  89593. * decoder.
  89594. *
  89595. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89596. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89597. *
  89598. * The basic usage of this decoder is as follows:
  89599. * - The program creates an instance of a decoder using
  89600. * FLAC__stream_decoder_new().
  89601. * - The program overrides the default settings using
  89602. * FLAC__stream_decoder_set_*() functions.
  89603. * - The program initializes the instance to validate the settings and
  89604. * prepare for decoding using
  89605. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89606. * or FLAC__stream_decoder_init_file() for native FLAC,
  89607. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89608. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89609. * - The program calls the FLAC__stream_decoder_process_*() functions
  89610. * to decode data, which subsequently calls the callbacks.
  89611. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89612. * which flushes the input and output and resets the decoder to the
  89613. * uninitialized state.
  89614. * - The instance may be used again or deleted with
  89615. * FLAC__stream_decoder_delete().
  89616. *
  89617. * In more detail, the program will create a new instance by calling
  89618. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89619. * functions to override the default decoder options, and call
  89620. * one of the FLAC__stream_decoder_init_*() functions.
  89621. *
  89622. * There are three initialization functions for native FLAC, one for
  89623. * setting up the decoder to decode FLAC data from the client via
  89624. * callbacks, and two for decoding directly from a FLAC file.
  89625. *
  89626. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89627. * You must also supply several callbacks for handling I/O. Some (like
  89628. * seeking) are optional, depending on the capabilities of the input.
  89629. *
  89630. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89631. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89632. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89633. * the other callbacks internally.
  89634. *
  89635. * There are three similarly-named init functions for decoding from Ogg
  89636. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89637. * library has been built with Ogg support.
  89638. *
  89639. * Once the decoder is initialized, your program will call one of several
  89640. * functions to start the decoding process:
  89641. *
  89642. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89643. * most one metadata block or audio frame and return, calling either the
  89644. * metadata callback or write callback, respectively, once. If the decoder
  89645. * loses sync it will return with only the error callback being called.
  89646. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89647. * to process the stream from the current location and stop upon reaching
  89648. * the first audio frame. The client will get one metadata, write, or error
  89649. * callback per metadata block, audio frame, or sync error, respectively.
  89650. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89651. * to process the stream from the current location until the read callback
  89652. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89653. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89654. * write, or error callback per metadata block, audio frame, or sync error,
  89655. * respectively.
  89656. *
  89657. * When the decoder has finished decoding (normally or through an abort),
  89658. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89659. * ensures the decoder is in the correct state and frees memory. Then the
  89660. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89661. * again to decode another stream.
  89662. *
  89663. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89664. * At any point after the stream decoder has been initialized, the client can
  89665. * call this function to seek to an exact sample within the stream.
  89666. * Subsequently, the first time the write callback is called it will be
  89667. * passed a (possibly partial) block starting at that sample.
  89668. *
  89669. * If the client cannot seek via the callback interface provided, but still
  89670. * has another way of seeking, it can flush the decoder using
  89671. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89672. * through the read callback.
  89673. *
  89674. * The stream decoder also provides MD5 signature checking. If this is
  89675. * turned on before initialization, FLAC__stream_decoder_finish() will
  89676. * report when the decoded MD5 signature does not match the one stored
  89677. * in the STREAMINFO block. MD5 checking is automatically turned off
  89678. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89679. * in the STREAMINFO block or when a seek is attempted.
  89680. *
  89681. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89682. * attention. By default, the decoder only calls the metadata_callback for
  89683. * the STREAMINFO block. These functions allow you to tell the decoder
  89684. * explicitly which blocks to parse and return via the metadata_callback
  89685. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89686. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89687. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89688. * which blocks to return. Remember that metadata blocks can potentially
  89689. * be big (for example, cover art) so filtering out the ones you don't
  89690. * use can reduce the memory requirements of the decoder. Also note the
  89691. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89692. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89693. * filtering APPLICATION blocks based on the application ID.
  89694. *
  89695. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89696. * they still can legally be filtered from the metadata_callback.
  89697. *
  89698. * \note
  89699. * The "set" functions may only be called when the decoder is in the
  89700. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89701. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89702. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89703. * return \c true, otherwise \c false.
  89704. *
  89705. * \note
  89706. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89707. * defaults, including the callbacks.
  89708. *
  89709. * \{
  89710. */
  89711. /** State values for a FLAC__StreamDecoder
  89712. *
  89713. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89714. */
  89715. typedef enum {
  89716. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89717. /**< The decoder is ready to search for metadata. */
  89718. FLAC__STREAM_DECODER_READ_METADATA,
  89719. /**< The decoder is ready to or is in the process of reading metadata. */
  89720. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89721. /**< The decoder is ready to or is in the process of searching for the
  89722. * frame sync code.
  89723. */
  89724. FLAC__STREAM_DECODER_READ_FRAME,
  89725. /**< The decoder is ready to or is in the process of reading a frame. */
  89726. FLAC__STREAM_DECODER_END_OF_STREAM,
  89727. /**< The decoder has reached the end of the stream. */
  89728. FLAC__STREAM_DECODER_OGG_ERROR,
  89729. /**< An error occurred in the underlying Ogg layer. */
  89730. FLAC__STREAM_DECODER_SEEK_ERROR,
  89731. /**< An error occurred while seeking. The decoder must be flushed
  89732. * with FLAC__stream_decoder_flush() or reset with
  89733. * FLAC__stream_decoder_reset() before decoding can continue.
  89734. */
  89735. FLAC__STREAM_DECODER_ABORTED,
  89736. /**< The decoder was aborted by the read callback. */
  89737. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89738. /**< An error occurred allocating memory. The decoder is in an invalid
  89739. * state and can no longer be used.
  89740. */
  89741. FLAC__STREAM_DECODER_UNINITIALIZED
  89742. /**< The decoder is in the uninitialized state; one of the
  89743. * FLAC__stream_decoder_init_*() functions must be called before samples
  89744. * can be processed.
  89745. */
  89746. } FLAC__StreamDecoderState;
  89747. /** Maps a FLAC__StreamDecoderState to a C string.
  89748. *
  89749. * Using a FLAC__StreamDecoderState as the index to this array
  89750. * will give the string equivalent. The contents should not be modified.
  89751. */
  89752. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89753. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89754. */
  89755. typedef enum {
  89756. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89757. /**< Initialization was successful. */
  89758. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89759. /**< The library was not compiled with support for the given container
  89760. * format.
  89761. */
  89762. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89763. /**< A required callback was not supplied. */
  89764. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89765. /**< An error occurred allocating memory. */
  89766. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89767. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89768. * FLAC__stream_decoder_init_ogg_file(). */
  89769. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89770. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89771. * already initialized, usually because
  89772. * FLAC__stream_decoder_finish() was not called.
  89773. */
  89774. } FLAC__StreamDecoderInitStatus;
  89775. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89776. *
  89777. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89778. * will give the string equivalent. The contents should not be modified.
  89779. */
  89780. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89781. /** Return values for the FLAC__StreamDecoder read callback.
  89782. */
  89783. typedef enum {
  89784. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89785. /**< The read was OK and decoding can continue. */
  89786. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89787. /**< The read was attempted while at the end of the stream. Note that
  89788. * the client must only return this value when the read callback was
  89789. * called when already at the end of the stream. Otherwise, if the read
  89790. * itself moves to the end of the stream, the client should still return
  89791. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89792. * the next read callback it should return
  89793. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89794. * of \c 0.
  89795. */
  89796. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89797. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89798. } FLAC__StreamDecoderReadStatus;
  89799. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89800. *
  89801. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89802. * will give the string equivalent. The contents should not be modified.
  89803. */
  89804. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89805. /** Return values for the FLAC__StreamDecoder seek callback.
  89806. */
  89807. typedef enum {
  89808. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89809. /**< The seek was OK and decoding can continue. */
  89810. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89811. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89812. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89813. /**< Client does not support seeking. */
  89814. } FLAC__StreamDecoderSeekStatus;
  89815. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89816. *
  89817. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89818. * will give the string equivalent. The contents should not be modified.
  89819. */
  89820. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89821. /** Return values for the FLAC__StreamDecoder tell callback.
  89822. */
  89823. typedef enum {
  89824. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89825. /**< The tell was OK and decoding can continue. */
  89826. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89827. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89828. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89829. /**< Client does not support telling the position. */
  89830. } FLAC__StreamDecoderTellStatus;
  89831. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89832. *
  89833. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89834. * will give the string equivalent. The contents should not be modified.
  89835. */
  89836. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89837. /** Return values for the FLAC__StreamDecoder length callback.
  89838. */
  89839. typedef enum {
  89840. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89841. /**< The length call was OK and decoding can continue. */
  89842. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89843. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89844. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89845. /**< Client does not support reporting the length. */
  89846. } FLAC__StreamDecoderLengthStatus;
  89847. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89848. *
  89849. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89850. * will give the string equivalent. The contents should not be modified.
  89851. */
  89852. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89853. /** Return values for the FLAC__StreamDecoder write callback.
  89854. */
  89855. typedef enum {
  89856. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89857. /**< The write was OK and decoding can continue. */
  89858. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89859. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89860. } FLAC__StreamDecoderWriteStatus;
  89861. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89862. *
  89863. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89864. * will give the string equivalent. The contents should not be modified.
  89865. */
  89866. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89867. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89868. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89869. * all. The rest could be caused by bad sync (false synchronization on
  89870. * data that is not the start of a frame) or corrupted data. The error
  89871. * itself is the decoder's best guess at what happened assuming a correct
  89872. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89873. * could be caused by a correct sync on the start of a frame, but some
  89874. * data in the frame header was corrupted. Or it could be the result of
  89875. * syncing on a point the stream that looked like the starting of a frame
  89876. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89877. * could be because the decoder encountered a valid frame made by a future
  89878. * version of the encoder which it cannot parse, or because of a false
  89879. * sync making it appear as though an encountered frame was generated by
  89880. * a future encoder.
  89881. */
  89882. typedef enum {
  89883. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89884. /**< An error in the stream caused the decoder to lose synchronization. */
  89885. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89886. /**< The decoder encountered a corrupted frame header. */
  89887. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89888. /**< The frame's data did not match the CRC in the footer. */
  89889. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89890. /**< The decoder encountered reserved fields in use in the stream. */
  89891. } FLAC__StreamDecoderErrorStatus;
  89892. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89893. *
  89894. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89895. * will give the string equivalent. The contents should not be modified.
  89896. */
  89897. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89898. /***********************************************************************
  89899. *
  89900. * class FLAC__StreamDecoder
  89901. *
  89902. ***********************************************************************/
  89903. struct FLAC__StreamDecoderProtected;
  89904. struct FLAC__StreamDecoderPrivate;
  89905. /** The opaque structure definition for the stream decoder type.
  89906. * See the \link flac_stream_decoder stream decoder module \endlink
  89907. * for a detailed description.
  89908. */
  89909. typedef struct {
  89910. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89911. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89912. } FLAC__StreamDecoder;
  89913. /** Signature for the read callback.
  89914. *
  89915. * A function pointer matching this signature must be passed to
  89916. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89917. * called when the decoder needs more input data. The address of the
  89918. * buffer to be filled is supplied, along with the number of bytes the
  89919. * buffer can hold. The callback may choose to supply less data and
  89920. * modify the byte count but must be careful not to overflow the buffer.
  89921. * The callback then returns a status code chosen from
  89922. * FLAC__StreamDecoderReadStatus.
  89923. *
  89924. * Here is an example of a read callback for stdio streams:
  89925. * \code
  89926. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89927. * {
  89928. * FILE *file = ((MyClientData*)client_data)->file;
  89929. * if(*bytes > 0) {
  89930. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89931. * if(ferror(file))
  89932. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89933. * else if(*bytes == 0)
  89934. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89935. * else
  89936. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89937. * }
  89938. * else
  89939. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89940. * }
  89941. * \endcode
  89942. *
  89943. * \note In general, FLAC__StreamDecoder functions which change the
  89944. * state should not be called on the \a decoder while in the callback.
  89945. *
  89946. * \param decoder The decoder instance calling the callback.
  89947. * \param buffer A pointer to a location for the callee to store
  89948. * data to be decoded.
  89949. * \param bytes A pointer to the size of the buffer. On entry
  89950. * to the callback, it contains the maximum number
  89951. * of bytes that may be stored in \a buffer. The
  89952. * callee must set it to the actual number of bytes
  89953. * stored (0 in case of error or end-of-stream) before
  89954. * returning.
  89955. * \param client_data The callee's client data set through
  89956. * FLAC__stream_decoder_init_*().
  89957. * \retval FLAC__StreamDecoderReadStatus
  89958. * The callee's return status. Note that the callback should return
  89959. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89960. * zero bytes were read and there is no more data to be read.
  89961. */
  89962. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89963. /** Signature for the seek callback.
  89964. *
  89965. * A function pointer matching this signature may be passed to
  89966. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89967. * called when the decoder needs to seek the input stream. The decoder
  89968. * will pass the absolute byte offset to seek to, 0 meaning the
  89969. * beginning of the stream.
  89970. *
  89971. * Here is an example of a seek callback for stdio streams:
  89972. * \code
  89973. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89974. * {
  89975. * FILE *file = ((MyClientData*)client_data)->file;
  89976. * if(file == stdin)
  89977. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89978. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89979. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89980. * else
  89981. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89982. * }
  89983. * \endcode
  89984. *
  89985. * \note In general, FLAC__StreamDecoder functions which change the
  89986. * state should not be called on the \a decoder while in the callback.
  89987. *
  89988. * \param decoder The decoder instance calling the callback.
  89989. * \param absolute_byte_offset The offset from the beginning of the stream
  89990. * to seek to.
  89991. * \param client_data The callee's client data set through
  89992. * FLAC__stream_decoder_init_*().
  89993. * \retval FLAC__StreamDecoderSeekStatus
  89994. * The callee's return status.
  89995. */
  89996. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89997. /** Signature for the tell callback.
  89998. *
  89999. * A function pointer matching this signature may be passed to
  90000. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90001. * called when the decoder wants to know the current position of the
  90002. * stream. The callback should return the byte offset from the
  90003. * beginning of the stream.
  90004. *
  90005. * Here is an example of a tell callback for stdio streams:
  90006. * \code
  90007. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90008. * {
  90009. * FILE *file = ((MyClientData*)client_data)->file;
  90010. * off_t pos;
  90011. * if(file == stdin)
  90012. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90013. * else if((pos = ftello(file)) < 0)
  90014. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90015. * else {
  90016. * *absolute_byte_offset = (FLAC__uint64)pos;
  90017. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90018. * }
  90019. * }
  90020. * \endcode
  90021. *
  90022. * \note In general, FLAC__StreamDecoder functions which change the
  90023. * state should not be called on the \a decoder while in the callback.
  90024. *
  90025. * \param decoder The decoder instance calling the callback.
  90026. * \param absolute_byte_offset A pointer to storage for the current offset
  90027. * from the beginning of the stream.
  90028. * \param client_data The callee's client data set through
  90029. * FLAC__stream_decoder_init_*().
  90030. * \retval FLAC__StreamDecoderTellStatus
  90031. * The callee's return status.
  90032. */
  90033. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90034. /** Signature for the length callback.
  90035. *
  90036. * A function pointer matching this signature may be passed to
  90037. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90038. * called when the decoder wants to know the total length of the stream
  90039. * in bytes.
  90040. *
  90041. * Here is an example of a length callback for stdio streams:
  90042. * \code
  90043. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90044. * {
  90045. * FILE *file = ((MyClientData*)client_data)->file;
  90046. * struct stat filestats;
  90047. *
  90048. * if(file == stdin)
  90049. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90050. * else if(fstat(fileno(file), &filestats) != 0)
  90051. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90052. * else {
  90053. * *stream_length = (FLAC__uint64)filestats.st_size;
  90054. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90055. * }
  90056. * }
  90057. * \endcode
  90058. *
  90059. * \note In general, FLAC__StreamDecoder functions which change the
  90060. * state should not be called on the \a decoder while in the callback.
  90061. *
  90062. * \param decoder The decoder instance calling the callback.
  90063. * \param stream_length A pointer to storage for the length of the stream
  90064. * in bytes.
  90065. * \param client_data The callee's client data set through
  90066. * FLAC__stream_decoder_init_*().
  90067. * \retval FLAC__StreamDecoderLengthStatus
  90068. * The callee's return status.
  90069. */
  90070. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90071. /** Signature for the EOF callback.
  90072. *
  90073. * A function pointer matching this signature may be passed to
  90074. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90075. * called when the decoder needs to know if the end of the stream has
  90076. * been reached.
  90077. *
  90078. * Here is an example of a EOF callback for stdio streams:
  90079. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90080. * \code
  90081. * {
  90082. * FILE *file = ((MyClientData*)client_data)->file;
  90083. * return feof(file)? true : false;
  90084. * }
  90085. * \endcode
  90086. *
  90087. * \note In general, FLAC__StreamDecoder functions which change the
  90088. * state should not be called on the \a decoder while in the callback.
  90089. *
  90090. * \param decoder The decoder instance calling the callback.
  90091. * \param client_data The callee's client data set through
  90092. * FLAC__stream_decoder_init_*().
  90093. * \retval FLAC__bool
  90094. * \c true if the currently at the end of the stream, else \c false.
  90095. */
  90096. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90097. /** Signature for the write callback.
  90098. *
  90099. * A function pointer matching this signature must be passed to one of
  90100. * the FLAC__stream_decoder_init_*() functions.
  90101. * The supplied function will be called when the decoder has decoded a
  90102. * single audio frame. The decoder will pass the frame metadata as well
  90103. * as an array of pointers (one for each channel) pointing to the
  90104. * decoded audio.
  90105. *
  90106. * \note In general, FLAC__StreamDecoder functions which change the
  90107. * state should not be called on the \a decoder while in the callback.
  90108. *
  90109. * \param decoder The decoder instance calling the callback.
  90110. * \param frame The description of the decoded frame. See
  90111. * FLAC__Frame.
  90112. * \param buffer An array of pointers to decoded channels of data.
  90113. * Each pointer will point to an array of signed
  90114. * samples of length \a frame->header.blocksize.
  90115. * Channels will be ordered according to the FLAC
  90116. * specification; see the documentation for the
  90117. * <A HREF="../format.html#frame_header">frame header</A>.
  90118. * \param client_data The callee's client data set through
  90119. * FLAC__stream_decoder_init_*().
  90120. * \retval FLAC__StreamDecoderWriteStatus
  90121. * The callee's return status.
  90122. */
  90123. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90124. /** Signature for the metadata callback.
  90125. *
  90126. * A function pointer matching this signature must be passed to one of
  90127. * the FLAC__stream_decoder_init_*() functions.
  90128. * The supplied function will be called when the decoder has decoded a
  90129. * metadata block. In a valid FLAC file there will always be one
  90130. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90131. * These will be supplied by the decoder in the same order as they
  90132. * appear in the stream and always before the first audio frame (i.e.
  90133. * write callback). The metadata block that is passed in must not be
  90134. * modified, and it doesn't live beyond the callback, so you should make
  90135. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90136. * elsewhere. Since metadata blocks can potentially be large, by
  90137. * default the decoder only calls the metadata callback for the
  90138. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90139. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90140. *
  90141. * \note In general, FLAC__StreamDecoder functions which change the
  90142. * state should not be called on the \a decoder while in the callback.
  90143. *
  90144. * \param decoder The decoder instance calling the callback.
  90145. * \param metadata The decoded metadata block.
  90146. * \param client_data The callee's client data set through
  90147. * FLAC__stream_decoder_init_*().
  90148. */
  90149. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90150. /** Signature for the error callback.
  90151. *
  90152. * A function pointer matching this signature must be passed to one of
  90153. * the FLAC__stream_decoder_init_*() functions.
  90154. * The supplied function will be called whenever an error occurs during
  90155. * decoding.
  90156. *
  90157. * \note In general, FLAC__StreamDecoder functions which change the
  90158. * state should not be called on the \a decoder while in the callback.
  90159. *
  90160. * \param decoder The decoder instance calling the callback.
  90161. * \param status The error encountered by the decoder.
  90162. * \param client_data The callee's client data set through
  90163. * FLAC__stream_decoder_init_*().
  90164. */
  90165. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90166. /***********************************************************************
  90167. *
  90168. * Class constructor/destructor
  90169. *
  90170. ***********************************************************************/
  90171. /** Create a new stream decoder instance. The instance is created with
  90172. * default settings; see the individual FLAC__stream_decoder_set_*()
  90173. * functions for each setting's default.
  90174. *
  90175. * \retval FLAC__StreamDecoder*
  90176. * \c NULL if there was an error allocating memory, else the new instance.
  90177. */
  90178. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90179. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90180. *
  90181. * \param decoder A pointer to an existing decoder.
  90182. * \assert
  90183. * \code decoder != NULL \endcode
  90184. */
  90185. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90186. /***********************************************************************
  90187. *
  90188. * Public class method prototypes
  90189. *
  90190. ***********************************************************************/
  90191. /** Set the serial number for the FLAC stream within the Ogg container.
  90192. * The default behavior is to use the serial number of the first Ogg
  90193. * page. Setting a serial number here will explicitly specify which
  90194. * stream is to be decoded.
  90195. *
  90196. * \note
  90197. * This does not need to be set for native FLAC decoding.
  90198. *
  90199. * \default \c use serial number of first page
  90200. * \param decoder A decoder instance to set.
  90201. * \param serial_number See above.
  90202. * \assert
  90203. * \code decoder != NULL \endcode
  90204. * \retval FLAC__bool
  90205. * \c false if the decoder is already initialized, else \c true.
  90206. */
  90207. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90208. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90209. * compute the MD5 signature of the unencoded audio data while decoding
  90210. * and compare it to the signature from the STREAMINFO block, if it
  90211. * exists, during FLAC__stream_decoder_finish().
  90212. *
  90213. * MD5 signature checking will be turned off (until the next
  90214. * FLAC__stream_decoder_reset()) if there is no signature in the
  90215. * STREAMINFO block or when a seek is attempted.
  90216. *
  90217. * Clients that do not use the MD5 check should leave this off to speed
  90218. * up decoding.
  90219. *
  90220. * \default \c false
  90221. * \param decoder A decoder instance to set.
  90222. * \param value Flag value (see above).
  90223. * \assert
  90224. * \code decoder != NULL \endcode
  90225. * \retval FLAC__bool
  90226. * \c false if the decoder is already initialized, else \c true.
  90227. */
  90228. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90229. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90230. *
  90231. * \default By default, only the \c STREAMINFO block is returned via the
  90232. * metadata callback.
  90233. * \param decoder A decoder instance to set.
  90234. * \param type See above.
  90235. * \assert
  90236. * \code decoder != NULL \endcode
  90237. * \a type is valid
  90238. * \retval FLAC__bool
  90239. * \c false if the decoder is already initialized, else \c true.
  90240. */
  90241. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90242. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90243. * given \a id.
  90244. *
  90245. * \default By default, only the \c STREAMINFO block is returned via the
  90246. * metadata callback.
  90247. * \param decoder A decoder instance to set.
  90248. * \param id See above.
  90249. * \assert
  90250. * \code decoder != NULL \endcode
  90251. * \code id != NULL \endcode
  90252. * \retval FLAC__bool
  90253. * \c false if the decoder is already initialized, else \c true.
  90254. */
  90255. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90256. /** Direct the decoder to pass on all metadata blocks of any type.
  90257. *
  90258. * \default By default, only the \c STREAMINFO block is returned via the
  90259. * metadata callback.
  90260. * \param decoder A decoder instance to set.
  90261. * \assert
  90262. * \code decoder != NULL \endcode
  90263. * \retval FLAC__bool
  90264. * \c false if the decoder is already initialized, else \c true.
  90265. */
  90266. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90267. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90268. *
  90269. * \default By default, only the \c STREAMINFO block is returned via the
  90270. * metadata callback.
  90271. * \param decoder A decoder instance to set.
  90272. * \param type See above.
  90273. * \assert
  90274. * \code decoder != NULL \endcode
  90275. * \a type is valid
  90276. * \retval FLAC__bool
  90277. * \c false if the decoder is already initialized, else \c true.
  90278. */
  90279. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90280. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90281. * the given \a id.
  90282. *
  90283. * \default By default, only the \c STREAMINFO block is returned via the
  90284. * metadata callback.
  90285. * \param decoder A decoder instance to set.
  90286. * \param id See above.
  90287. * \assert
  90288. * \code decoder != NULL \endcode
  90289. * \code id != NULL \endcode
  90290. * \retval FLAC__bool
  90291. * \c false if the decoder is already initialized, else \c true.
  90292. */
  90293. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90294. /** Direct the decoder to filter out all metadata blocks of any type.
  90295. *
  90296. * \default By default, only the \c STREAMINFO block is returned via the
  90297. * metadata callback.
  90298. * \param decoder A decoder instance to set.
  90299. * \assert
  90300. * \code decoder != NULL \endcode
  90301. * \retval FLAC__bool
  90302. * \c false if the decoder is already initialized, else \c true.
  90303. */
  90304. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90305. /** Get the current decoder state.
  90306. *
  90307. * \param decoder A decoder instance to query.
  90308. * \assert
  90309. * \code decoder != NULL \endcode
  90310. * \retval FLAC__StreamDecoderState
  90311. * The current decoder state.
  90312. */
  90313. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90314. /** Get the current decoder state as a C string.
  90315. *
  90316. * \param decoder A decoder instance to query.
  90317. * \assert
  90318. * \code decoder != NULL \endcode
  90319. * \retval const char *
  90320. * The decoder state as a C string. Do not modify the contents.
  90321. */
  90322. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90323. /** Get the "MD5 signature checking" flag.
  90324. * This is the value of the setting, not whether or not the decoder is
  90325. * currently checking the MD5 (remember, it can be turned off automatically
  90326. * by a seek). When the decoder is reset the flag will be restored to the
  90327. * value returned by this function.
  90328. *
  90329. * \param decoder A decoder instance to query.
  90330. * \assert
  90331. * \code decoder != NULL \endcode
  90332. * \retval FLAC__bool
  90333. * See above.
  90334. */
  90335. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90336. /** Get the total number of samples in the stream being decoded.
  90337. * Will only be valid after decoding has started and will contain the
  90338. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90339. *
  90340. * \param decoder A decoder instance to query.
  90341. * \assert
  90342. * \code decoder != NULL \endcode
  90343. * \retval unsigned
  90344. * See above.
  90345. */
  90346. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90347. /** Get the current number of channels in the stream being decoded.
  90348. * Will only be valid after decoding has started and will contain the
  90349. * value from the most recently decoded frame header.
  90350. *
  90351. * \param decoder A decoder instance to query.
  90352. * \assert
  90353. * \code decoder != NULL \endcode
  90354. * \retval unsigned
  90355. * See above.
  90356. */
  90357. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90358. /** Get the current channel assignment in the stream being decoded.
  90359. * Will only be valid after decoding has started and will contain the
  90360. * value from the most recently decoded frame header.
  90361. *
  90362. * \param decoder A decoder instance to query.
  90363. * \assert
  90364. * \code decoder != NULL \endcode
  90365. * \retval FLAC__ChannelAssignment
  90366. * See above.
  90367. */
  90368. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90369. /** Get the current sample resolution in the stream being decoded.
  90370. * Will only be valid after decoding has started and will contain the
  90371. * value from the most recently decoded frame header.
  90372. *
  90373. * \param decoder A decoder instance to query.
  90374. * \assert
  90375. * \code decoder != NULL \endcode
  90376. * \retval unsigned
  90377. * See above.
  90378. */
  90379. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90380. /** Get the current sample rate in Hz of the stream being decoded.
  90381. * Will only be valid after decoding has started and will contain the
  90382. * value from the most recently decoded frame header.
  90383. *
  90384. * \param decoder A decoder instance to query.
  90385. * \assert
  90386. * \code decoder != NULL \endcode
  90387. * \retval unsigned
  90388. * See above.
  90389. */
  90390. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90391. /** Get the current blocksize of the stream being decoded.
  90392. * Will only be valid after decoding has started and will contain the
  90393. * value from the most recently decoded frame header.
  90394. *
  90395. * \param decoder A decoder instance to query.
  90396. * \assert
  90397. * \code decoder != NULL \endcode
  90398. * \retval unsigned
  90399. * See above.
  90400. */
  90401. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90402. /** Returns the decoder's current read position within the stream.
  90403. * The position is the byte offset from the start of the stream.
  90404. * Bytes before this position have been fully decoded. Note that
  90405. * there may still be undecoded bytes in the decoder's read FIFO.
  90406. * The returned position is correct even after a seek.
  90407. *
  90408. * \warning This function currently only works for native FLAC,
  90409. * not Ogg FLAC streams.
  90410. *
  90411. * \param decoder A decoder instance to query.
  90412. * \param position Address at which to return the desired position.
  90413. * \assert
  90414. * \code decoder != NULL \endcode
  90415. * \code position != NULL \endcode
  90416. * \retval FLAC__bool
  90417. * \c true if successful, \c false if the stream is not native FLAC,
  90418. * or there was an error from the 'tell' callback or it returned
  90419. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90420. */
  90421. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90422. /** Initialize the decoder instance to decode native FLAC streams.
  90423. *
  90424. * This flavor of initialization sets up the decoder to decode from a
  90425. * native FLAC stream. I/O is performed via callbacks to the client.
  90426. * For decoding from a plain file via filename or open FILE*,
  90427. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90428. * provide a simpler interface.
  90429. *
  90430. * This function should be called after FLAC__stream_decoder_new() and
  90431. * FLAC__stream_decoder_set_*() but before any of the
  90432. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90433. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90434. * if initialization succeeded.
  90435. *
  90436. * \param decoder An uninitialized decoder instance.
  90437. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90438. * pointer must not be \c NULL.
  90439. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90440. * pointer may be \c NULL if seeking is not
  90441. * supported. If \a seek_callback is not \c NULL then a
  90442. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90443. * Alternatively, a dummy seek callback that just
  90444. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90445. * may also be supplied, all though this is slightly
  90446. * less efficient for the decoder.
  90447. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90448. * pointer may be \c NULL if not supported by the client. If
  90449. * \a seek_callback is not \c NULL then a
  90450. * \a tell_callback must also be supplied.
  90451. * Alternatively, a dummy tell callback that just
  90452. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90453. * may also be supplied, all though this is slightly
  90454. * less efficient for the decoder.
  90455. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90456. * pointer may be \c NULL if not supported by the client. If
  90457. * \a seek_callback is not \c NULL then a
  90458. * \a length_callback must also be supplied.
  90459. * Alternatively, a dummy length callback that just
  90460. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90461. * may also be supplied, all though this is slightly
  90462. * less efficient for the decoder.
  90463. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90464. * pointer may be \c NULL if not supported by the client. If
  90465. * \a seek_callback is not \c NULL then a
  90466. * \a eof_callback must also be supplied.
  90467. * Alternatively, a dummy length callback that just
  90468. * returns \c false
  90469. * may also be supplied, all though this is slightly
  90470. * less efficient for the decoder.
  90471. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90472. * pointer must not be \c NULL.
  90473. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90474. * pointer may be \c NULL if the callback is not
  90475. * desired.
  90476. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90477. * pointer must not be \c NULL.
  90478. * \param client_data This value will be supplied to callbacks in their
  90479. * \a client_data argument.
  90480. * \assert
  90481. * \code decoder != NULL \endcode
  90482. * \retval FLAC__StreamDecoderInitStatus
  90483. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90484. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90485. */
  90486. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90487. FLAC__StreamDecoder *decoder,
  90488. FLAC__StreamDecoderReadCallback read_callback,
  90489. FLAC__StreamDecoderSeekCallback seek_callback,
  90490. FLAC__StreamDecoderTellCallback tell_callback,
  90491. FLAC__StreamDecoderLengthCallback length_callback,
  90492. FLAC__StreamDecoderEofCallback eof_callback,
  90493. FLAC__StreamDecoderWriteCallback write_callback,
  90494. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90495. FLAC__StreamDecoderErrorCallback error_callback,
  90496. void *client_data
  90497. );
  90498. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90499. *
  90500. * This flavor of initialization sets up the decoder to decode from a
  90501. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90502. * client. For decoding from a plain file via filename or open FILE*,
  90503. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90504. * provide a simpler interface.
  90505. *
  90506. * This function should be called after FLAC__stream_decoder_new() and
  90507. * FLAC__stream_decoder_set_*() but before any of the
  90508. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90509. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90510. * if initialization succeeded.
  90511. *
  90512. * \note Support for Ogg FLAC in the library is optional. If this
  90513. * library has been built without support for Ogg FLAC, this function
  90514. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90515. *
  90516. * \param decoder An uninitialized decoder instance.
  90517. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90518. * pointer must not be \c NULL.
  90519. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90520. * pointer may be \c NULL if seeking is not
  90521. * supported. If \a seek_callback is not \c NULL then a
  90522. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90523. * Alternatively, a dummy seek callback that just
  90524. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90525. * may also be supplied, all though this is slightly
  90526. * less efficient for the decoder.
  90527. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90528. * pointer may be \c NULL if not supported by the client. If
  90529. * \a seek_callback is not \c NULL then a
  90530. * \a tell_callback must also be supplied.
  90531. * Alternatively, a dummy tell callback that just
  90532. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90533. * may also be supplied, all though this is slightly
  90534. * less efficient for the decoder.
  90535. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90536. * pointer may be \c NULL if not supported by the client. If
  90537. * \a seek_callback is not \c NULL then a
  90538. * \a length_callback must also be supplied.
  90539. * Alternatively, a dummy length callback that just
  90540. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90541. * may also be supplied, all though this is slightly
  90542. * less efficient for the decoder.
  90543. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90544. * pointer may be \c NULL if not supported by the client. If
  90545. * \a seek_callback is not \c NULL then a
  90546. * \a eof_callback must also be supplied.
  90547. * Alternatively, a dummy length callback that just
  90548. * returns \c false
  90549. * may also be supplied, all though this is slightly
  90550. * less efficient for the decoder.
  90551. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90552. * pointer must not be \c NULL.
  90553. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90554. * pointer may be \c NULL if the callback is not
  90555. * desired.
  90556. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90557. * pointer must not be \c NULL.
  90558. * \param client_data This value will be supplied to callbacks in their
  90559. * \a client_data argument.
  90560. * \assert
  90561. * \code decoder != NULL \endcode
  90562. * \retval FLAC__StreamDecoderInitStatus
  90563. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90564. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90565. */
  90566. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90567. FLAC__StreamDecoder *decoder,
  90568. FLAC__StreamDecoderReadCallback read_callback,
  90569. FLAC__StreamDecoderSeekCallback seek_callback,
  90570. FLAC__StreamDecoderTellCallback tell_callback,
  90571. FLAC__StreamDecoderLengthCallback length_callback,
  90572. FLAC__StreamDecoderEofCallback eof_callback,
  90573. FLAC__StreamDecoderWriteCallback write_callback,
  90574. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90575. FLAC__StreamDecoderErrorCallback error_callback,
  90576. void *client_data
  90577. );
  90578. /** Initialize the decoder instance to decode native FLAC files.
  90579. *
  90580. * This flavor of initialization sets up the decoder to decode from a
  90581. * plain native FLAC file. For non-stdio streams, you must use
  90582. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90583. *
  90584. * This function should be called after FLAC__stream_decoder_new() and
  90585. * FLAC__stream_decoder_set_*() but before any of the
  90586. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90587. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90588. * if initialization succeeded.
  90589. *
  90590. * \param decoder An uninitialized decoder instance.
  90591. * \param file An open FLAC file. The file should have been
  90592. * opened with mode \c "rb" and rewound. The file
  90593. * becomes owned by the decoder and should not be
  90594. * manipulated by the client while decoding.
  90595. * Unless \a file is \c stdin, it will be closed
  90596. * when FLAC__stream_decoder_finish() is called.
  90597. * Note however that seeking will not work when
  90598. * decoding from \c stdout since it is not seekable.
  90599. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90600. * pointer must not be \c NULL.
  90601. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90602. * pointer may be \c NULL if the callback is not
  90603. * desired.
  90604. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90605. * pointer must not be \c NULL.
  90606. * \param client_data This value will be supplied to callbacks in their
  90607. * \a client_data argument.
  90608. * \assert
  90609. * \code decoder != NULL \endcode
  90610. * \code file != NULL \endcode
  90611. * \retval FLAC__StreamDecoderInitStatus
  90612. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90613. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90614. */
  90615. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90616. FLAC__StreamDecoder *decoder,
  90617. FILE *file,
  90618. FLAC__StreamDecoderWriteCallback write_callback,
  90619. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90620. FLAC__StreamDecoderErrorCallback error_callback,
  90621. void *client_data
  90622. );
  90623. /** Initialize the decoder instance to decode Ogg FLAC files.
  90624. *
  90625. * This flavor of initialization sets up the decoder to decode from a
  90626. * plain Ogg FLAC file. For non-stdio streams, you must use
  90627. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90628. *
  90629. * This function should be called after FLAC__stream_decoder_new() and
  90630. * FLAC__stream_decoder_set_*() but before any of the
  90631. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90632. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90633. * if initialization succeeded.
  90634. *
  90635. * \note Support for Ogg FLAC in the library is optional. If this
  90636. * library has been built without support for Ogg FLAC, this function
  90637. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90638. *
  90639. * \param decoder An uninitialized decoder instance.
  90640. * \param file An open FLAC file. The file should have been
  90641. * opened with mode \c "rb" and rewound. The file
  90642. * becomes owned by the decoder and should not be
  90643. * manipulated by the client while decoding.
  90644. * Unless \a file is \c stdin, it will be closed
  90645. * when FLAC__stream_decoder_finish() is called.
  90646. * Note however that seeking will not work when
  90647. * decoding from \c stdout since it is not seekable.
  90648. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90649. * pointer must not be \c NULL.
  90650. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90651. * pointer may be \c NULL if the callback is not
  90652. * desired.
  90653. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90654. * pointer must not be \c NULL.
  90655. * \param client_data This value will be supplied to callbacks in their
  90656. * \a client_data argument.
  90657. * \assert
  90658. * \code decoder != NULL \endcode
  90659. * \code file != NULL \endcode
  90660. * \retval FLAC__StreamDecoderInitStatus
  90661. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90662. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90663. */
  90664. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90665. FLAC__StreamDecoder *decoder,
  90666. FILE *file,
  90667. FLAC__StreamDecoderWriteCallback write_callback,
  90668. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90669. FLAC__StreamDecoderErrorCallback error_callback,
  90670. void *client_data
  90671. );
  90672. /** Initialize the decoder instance to decode native FLAC files.
  90673. *
  90674. * This flavor of initialization sets up the decoder to decode from a plain
  90675. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90676. * example, with Unicode filenames on Windows), you must use
  90677. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90678. * and provide callbacks for the I/O.
  90679. *
  90680. * This function should be called after FLAC__stream_decoder_new() and
  90681. * FLAC__stream_decoder_set_*() but before any of the
  90682. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90683. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90684. * if initialization succeeded.
  90685. *
  90686. * \param decoder An uninitialized decoder instance.
  90687. * \param filename The name of the file to decode from. The file will
  90688. * be opened with fopen(). Use \c NULL to decode from
  90689. * \c stdin. Note that \c stdin is not seekable.
  90690. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90691. * pointer must not be \c NULL.
  90692. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90693. * pointer may be \c NULL if the callback is not
  90694. * desired.
  90695. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90696. * pointer must not be \c NULL.
  90697. * \param client_data This value will be supplied to callbacks in their
  90698. * \a client_data argument.
  90699. * \assert
  90700. * \code decoder != NULL \endcode
  90701. * \retval FLAC__StreamDecoderInitStatus
  90702. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90703. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90704. */
  90705. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90706. FLAC__StreamDecoder *decoder,
  90707. const char *filename,
  90708. FLAC__StreamDecoderWriteCallback write_callback,
  90709. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90710. FLAC__StreamDecoderErrorCallback error_callback,
  90711. void *client_data
  90712. );
  90713. /** Initialize the decoder instance to decode Ogg FLAC files.
  90714. *
  90715. * This flavor of initialization sets up the decoder to decode from a plain
  90716. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90717. * example, with Unicode filenames on Windows), you must use
  90718. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90719. * and provide callbacks for the I/O.
  90720. *
  90721. * This function should be called after FLAC__stream_decoder_new() and
  90722. * FLAC__stream_decoder_set_*() but before any of the
  90723. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90724. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90725. * if initialization succeeded.
  90726. *
  90727. * \note Support for Ogg FLAC in the library is optional. If this
  90728. * library has been built without support for Ogg FLAC, this function
  90729. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90730. *
  90731. * \param decoder An uninitialized decoder instance.
  90732. * \param filename The name of the file to decode from. The file will
  90733. * be opened with fopen(). Use \c NULL to decode from
  90734. * \c stdin. Note that \c stdin is not seekable.
  90735. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90736. * pointer must not be \c NULL.
  90737. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90738. * pointer may be \c NULL if the callback is not
  90739. * desired.
  90740. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90741. * pointer must not be \c NULL.
  90742. * \param client_data This value will be supplied to callbacks in their
  90743. * \a client_data argument.
  90744. * \assert
  90745. * \code decoder != NULL \endcode
  90746. * \retval FLAC__StreamDecoderInitStatus
  90747. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90748. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90749. */
  90750. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90751. FLAC__StreamDecoder *decoder,
  90752. const char *filename,
  90753. FLAC__StreamDecoderWriteCallback write_callback,
  90754. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90755. FLAC__StreamDecoderErrorCallback error_callback,
  90756. void *client_data
  90757. );
  90758. /** Finish the decoding process.
  90759. * Flushes the decoding buffer, releases resources, resets the decoder
  90760. * settings to their defaults, and returns the decoder state to
  90761. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90762. *
  90763. * In the event of a prematurely-terminated decode, it is not strictly
  90764. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90765. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90766. * with a FLAC__stream_decoder_finish().
  90767. *
  90768. * \param decoder An uninitialized decoder instance.
  90769. * \assert
  90770. * \code decoder != NULL \endcode
  90771. * \retval FLAC__bool
  90772. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90773. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90774. * signature does not match the one computed by the decoder; else
  90775. * \c true.
  90776. */
  90777. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90778. /** Flush the stream input.
  90779. * The decoder's input buffer will be cleared and the state set to
  90780. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90781. * off MD5 checking.
  90782. *
  90783. * \param decoder A decoder instance.
  90784. * \assert
  90785. * \code decoder != NULL \endcode
  90786. * \retval FLAC__bool
  90787. * \c true if successful, else \c false if a memory allocation
  90788. * error occurs (in which case the state will be set to
  90789. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90790. */
  90791. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90792. /** Reset the decoding process.
  90793. * The decoder's input buffer will be cleared and the state set to
  90794. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90795. * FLAC__stream_decoder_finish() except that the settings are
  90796. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90797. * before decoding again. MD5 checking will be restored to its original
  90798. * setting.
  90799. *
  90800. * If the decoder is seekable, or was initialized with
  90801. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90802. * the decoder will also attempt to seek to the beginning of the file.
  90803. * If this rewind fails, this function will return \c false. It follows
  90804. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90805. * \c stdin.
  90806. *
  90807. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90808. * and is not seekable (i.e. no seek callback was provided or the seek
  90809. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90810. * is the duty of the client to start feeding data from the beginning of
  90811. * the stream on the next FLAC__stream_decoder_process() or
  90812. * FLAC__stream_decoder_process_interleaved() call.
  90813. *
  90814. * \param decoder A decoder instance.
  90815. * \assert
  90816. * \code decoder != NULL \endcode
  90817. * \retval FLAC__bool
  90818. * \c true if successful, else \c false if a memory allocation occurs
  90819. * (in which case the state will be set to
  90820. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90821. * occurs (the state will be unchanged).
  90822. */
  90823. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90824. /** Decode one metadata block or audio frame.
  90825. * This version instructs the decoder to decode a either a single metadata
  90826. * block or a single frame and stop, unless the callbacks return a fatal
  90827. * error or the read callback returns
  90828. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90829. *
  90830. * As the decoder needs more input it will call the read callback.
  90831. * Depending on what was decoded, the metadata or write callback will be
  90832. * called with the decoded metadata block or audio frame.
  90833. *
  90834. * Unless there is a fatal read error or end of stream, this function
  90835. * will return once one whole frame is decoded. In other words, if the
  90836. * stream is not synchronized or points to a corrupt frame header, the
  90837. * decoder will continue to try and resync until it gets to a valid
  90838. * frame, then decode one frame, then return. If the decoder points to
  90839. * a frame whose frame CRC in the frame footer does not match the
  90840. * computed frame CRC, this function will issue a
  90841. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90842. * error callback, and return, having decoded one complete, although
  90843. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90844. * correct length to the write callback.)
  90845. *
  90846. * \param decoder An initialized decoder instance.
  90847. * \assert
  90848. * \code decoder != NULL \endcode
  90849. * \retval FLAC__bool
  90850. * \c false if any fatal read, write, or memory allocation error
  90851. * occurred (meaning decoding must stop), else \c true; for more
  90852. * information about the decoder, check the decoder state with
  90853. * FLAC__stream_decoder_get_state().
  90854. */
  90855. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90856. /** Decode until the end of the metadata.
  90857. * This version instructs the decoder to decode from the current position
  90858. * and continue until all the metadata has been read, or until the
  90859. * callbacks return a fatal error or the read callback returns
  90860. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90861. *
  90862. * As the decoder needs more input it will call the read callback.
  90863. * As each metadata block is decoded, the metadata callback will be called
  90864. * with the decoded metadata.
  90865. *
  90866. * \param decoder An initialized decoder instance.
  90867. * \assert
  90868. * \code decoder != NULL \endcode
  90869. * \retval FLAC__bool
  90870. * \c false if any fatal read, write, or memory allocation error
  90871. * occurred (meaning decoding must stop), else \c true; for more
  90872. * information about the decoder, check the decoder state with
  90873. * FLAC__stream_decoder_get_state().
  90874. */
  90875. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90876. /** Decode until the end of the stream.
  90877. * This version instructs the decoder to decode from the current position
  90878. * and continue until the end of stream (the read callback returns
  90879. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90880. * callbacks return a fatal error.
  90881. *
  90882. * As the decoder needs more input it will call the read callback.
  90883. * As each metadata block and frame is decoded, the metadata or write
  90884. * callback will be called with the decoded metadata or frame.
  90885. *
  90886. * \param decoder An initialized decoder instance.
  90887. * \assert
  90888. * \code decoder != NULL \endcode
  90889. * \retval FLAC__bool
  90890. * \c false if any fatal read, write, or memory allocation error
  90891. * occurred (meaning decoding must stop), else \c true; for more
  90892. * information about the decoder, check the decoder state with
  90893. * FLAC__stream_decoder_get_state().
  90894. */
  90895. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90896. /** Skip one audio frame.
  90897. * This version instructs the decoder to 'skip' a single frame and stop,
  90898. * unless the callbacks return a fatal error or the read callback returns
  90899. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90900. *
  90901. * The decoding flow is the same as what occurs when
  90902. * FLAC__stream_decoder_process_single() is called to process an audio
  90903. * frame, except that this function does not decode the parsed data into
  90904. * PCM or call the write callback. The integrity of the frame is still
  90905. * checked the same way as in the other process functions.
  90906. *
  90907. * This function will return once one whole frame is skipped, in the
  90908. * same way that FLAC__stream_decoder_process_single() will return once
  90909. * one whole frame is decoded.
  90910. *
  90911. * This function can be used in more quickly determining FLAC frame
  90912. * boundaries when decoding of the actual data is not needed, for
  90913. * example when an application is separating a FLAC stream into frames
  90914. * for editing or storing in a container. To do this, the application
  90915. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90916. * to the next frame, then use
  90917. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90918. * boundary.
  90919. *
  90920. * This function should only be called when the stream has advanced
  90921. * past all the metadata, otherwise it will return \c false.
  90922. *
  90923. * \param decoder An initialized decoder instance not in a metadata
  90924. * state.
  90925. * \assert
  90926. * \code decoder != NULL \endcode
  90927. * \retval FLAC__bool
  90928. * \c false if any fatal read, write, or memory allocation error
  90929. * occurred (meaning decoding must stop), or if the decoder
  90930. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90931. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90932. * information about the decoder, check the decoder state with
  90933. * FLAC__stream_decoder_get_state().
  90934. */
  90935. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90936. /** Flush the input and seek to an absolute sample.
  90937. * Decoding will resume at the given sample. Note that because of
  90938. * this, the next write callback may contain a partial block. The
  90939. * client must support seeking the input or this function will fail
  90940. * and return \c false. Furthermore, if the decoder state is
  90941. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90942. * with FLAC__stream_decoder_flush() or reset with
  90943. * FLAC__stream_decoder_reset() before decoding can continue.
  90944. *
  90945. * \param decoder A decoder instance.
  90946. * \param sample The target sample number to seek to.
  90947. * \assert
  90948. * \code decoder != NULL \endcode
  90949. * \retval FLAC__bool
  90950. * \c true if successful, else \c false.
  90951. */
  90952. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90953. /* \} */
  90954. #ifdef __cplusplus
  90955. }
  90956. #endif
  90957. #endif
  90958. /*** End of inlined file: stream_decoder.h ***/
  90959. /*** Start of inlined file: stream_encoder.h ***/
  90960. #ifndef FLAC__STREAM_ENCODER_H
  90961. #define FLAC__STREAM_ENCODER_H
  90962. #include <stdio.h> /* for FILE */
  90963. #ifdef __cplusplus
  90964. extern "C" {
  90965. #endif
  90966. /** \file include/FLAC/stream_encoder.h
  90967. *
  90968. * \brief
  90969. * This module contains the functions which implement the stream
  90970. * encoder.
  90971. *
  90972. * See the detailed documentation in the
  90973. * \link flac_stream_encoder stream encoder \endlink module.
  90974. */
  90975. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90976. * \ingroup flac
  90977. *
  90978. * \brief
  90979. * This module describes the encoder layers provided by libFLAC.
  90980. *
  90981. * The stream encoder can be used to encode complete streams either to the
  90982. * client via callbacks, or directly to a file, depending on how it is
  90983. * initialized. When encoding via callbacks, the client provides a write
  90984. * callback which will be called whenever FLAC data is ready to be written.
  90985. * If the client also supplies a seek callback, the encoder will also
  90986. * automatically handle the writing back of metadata discovered while
  90987. * encoding, like stream info, seek points offsets, etc. When encoding to
  90988. * a file, the client needs only supply a filename or open \c FILE* and an
  90989. * optional progress callback for periodic notification of progress; the
  90990. * write and seek callbacks are supplied internally. For more info see the
  90991. * \link flac_stream_encoder stream encoder \endlink module.
  90992. */
  90993. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90994. * \ingroup flac_encoder
  90995. *
  90996. * \brief
  90997. * This module contains the functions which implement the stream
  90998. * encoder.
  90999. *
  91000. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91001. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91002. *
  91003. * The basic usage of this encoder is as follows:
  91004. * - The program creates an instance of an encoder using
  91005. * FLAC__stream_encoder_new().
  91006. * - The program overrides the default settings using
  91007. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91008. * functions should be called:
  91009. * - FLAC__stream_encoder_set_channels()
  91010. * - FLAC__stream_encoder_set_bits_per_sample()
  91011. * - FLAC__stream_encoder_set_sample_rate()
  91012. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91013. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91014. * - If the application wants to control the compression level or set its own
  91015. * metadata, then the following should also be called:
  91016. * - FLAC__stream_encoder_set_compression_level()
  91017. * - FLAC__stream_encoder_set_verify()
  91018. * - FLAC__stream_encoder_set_metadata()
  91019. * - The rest of the set functions should only be called if the client needs
  91020. * exact control over how the audio is compressed; thorough understanding
  91021. * of the FLAC format is necessary to achieve good results.
  91022. * - The program initializes the instance to validate the settings and
  91023. * prepare for encoding using
  91024. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91025. * or FLAC__stream_encoder_init_file() for native FLAC
  91026. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91027. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91028. * - The program calls FLAC__stream_encoder_process() or
  91029. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91030. * subsequently calls the callbacks when there is encoder data ready
  91031. * to be written.
  91032. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91033. * which causes the encoder to encode any data still in its input pipe,
  91034. * update the metadata with the final encoding statistics if output
  91035. * seeking is possible, and finally reset the encoder to the
  91036. * uninitialized state.
  91037. * - The instance may be used again or deleted with
  91038. * FLAC__stream_encoder_delete().
  91039. *
  91040. * In more detail, the stream encoder functions similarly to the
  91041. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91042. * callbacks and more options. Typically the client will create a new
  91043. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91044. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91045. * calling one of the FLAC__stream_encoder_init_*() functions.
  91046. *
  91047. * Unlike the decoders, the stream encoder has many options that can
  91048. * affect the speed and compression ratio. When setting these parameters
  91049. * you should have some basic knowledge of the format (see the
  91050. * <A HREF="../documentation.html#format">user-level documentation</A>
  91051. * or the <A HREF="../format.html">formal description</A>). The
  91052. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91053. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91054. * functions will do this, so make sure to pay attention to the state
  91055. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91056. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91057. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91058. * the constructor.
  91059. *
  91060. * There are three initialization functions for native FLAC, one for
  91061. * setting up the encoder to encode FLAC data to the client via
  91062. * callbacks, and two for encoding directly to a file.
  91063. *
  91064. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91065. * You must also supply a write callback which will be called anytime
  91066. * there is raw encoded data to write. If the client can seek the output
  91067. * it is best to also supply seek and tell callbacks, as this allows the
  91068. * encoder to go back after encoding is finished to write back
  91069. * information that was collected while encoding, like seek point offsets,
  91070. * frame sizes, etc.
  91071. *
  91072. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91073. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91074. * filename or open \c FILE*; the encoder will handle all the callbacks
  91075. * internally. You may also supply a progress callback for periodic
  91076. * notification of the encoding progress.
  91077. *
  91078. * There are three similarly-named init functions for encoding to Ogg
  91079. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91080. * library has been built with Ogg support.
  91081. *
  91082. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91083. * call the write callback several times, once with the \c fLaC signature,
  91084. * and once for each encoded metadata block. Note that for Ogg FLAC
  91085. * encoding you will usually get at least twice the number of callbacks than
  91086. * with native FLAC, one for the Ogg page header and one for the page body.
  91087. *
  91088. * After initializing the instance, the client may feed audio data to the
  91089. * encoder in one of two ways:
  91090. *
  91091. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91092. * will pass an array of pointers to buffers, one for each channel, to
  91093. * the encoder, each of the same length. The samples need not be
  91094. * block-aligned, but each channel should have the same number of samples.
  91095. * - Channel interleaved, through
  91096. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91097. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91098. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91099. * Again, the samples need not be block-aligned but they must be
  91100. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91101. * the last value channelN_sampleM.
  91102. *
  91103. * Note that for either process call, each sample in the buffers should be a
  91104. * signed integer, right-justified to the resolution set by
  91105. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91106. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91107. *
  91108. * When the client is finished encoding data, it calls
  91109. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91110. * data still in its input pipe, and call the metadata callback with the
  91111. * final encoding statistics. Then the instance may be deleted with
  91112. * FLAC__stream_encoder_delete() or initialized again to encode another
  91113. * stream.
  91114. *
  91115. * For programs that write their own metadata, but that do not know the
  91116. * actual metadata until after encoding, it is advantageous to instruct
  91117. * the encoder to write a PADDING block of the correct size, so that
  91118. * instead of rewriting the whole stream after encoding, the program can
  91119. * just overwrite the PADDING block. If only the maximum size of the
  91120. * metadata is known, the program can write a slightly larger padding
  91121. * block, then split it after encoding.
  91122. *
  91123. * Make sure you understand how lengths are calculated. All FLAC metadata
  91124. * blocks have a 4 byte header which contains the type and length. This
  91125. * length does not include the 4 bytes of the header. See the format page
  91126. * for the specification of metadata blocks and their lengths.
  91127. *
  91128. * \note
  91129. * If you are writing the FLAC data to a file via callbacks, make sure it
  91130. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91131. * after the first encoding pass, the encoder will try to seek back to the
  91132. * beginning of the stream, to the STREAMINFO block, to write some data
  91133. * there. (If using FLAC__stream_encoder_init*_file() or
  91134. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91135. *
  91136. * \note
  91137. * The "set" functions may only be called when the encoder is in the
  91138. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91139. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91140. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91141. * return \c true, otherwise \c false.
  91142. *
  91143. * \note
  91144. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91145. * defaults.
  91146. *
  91147. * \{
  91148. */
  91149. /** State values for a FLAC__StreamEncoder.
  91150. *
  91151. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91152. *
  91153. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91154. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91155. * must be deleted with FLAC__stream_encoder_delete().
  91156. */
  91157. typedef enum {
  91158. FLAC__STREAM_ENCODER_OK = 0,
  91159. /**< The encoder is in the normal OK state and samples can be processed. */
  91160. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91161. /**< The encoder is in the uninitialized state; one of the
  91162. * FLAC__stream_encoder_init_*() functions must be called before samples
  91163. * can be processed.
  91164. */
  91165. FLAC__STREAM_ENCODER_OGG_ERROR,
  91166. /**< An error occurred in the underlying Ogg layer. */
  91167. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91168. /**< An error occurred in the underlying verify stream decoder;
  91169. * check FLAC__stream_encoder_get_verify_decoder_state().
  91170. */
  91171. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91172. /**< The verify decoder detected a mismatch between the original
  91173. * audio signal and the decoded audio signal.
  91174. */
  91175. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91176. /**< One of the callbacks returned a fatal error. */
  91177. FLAC__STREAM_ENCODER_IO_ERROR,
  91178. /**< An I/O error occurred while opening/reading/writing a file.
  91179. * Check \c errno.
  91180. */
  91181. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91182. /**< An error occurred while writing the stream; usually, the
  91183. * write_callback returned an error.
  91184. */
  91185. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91186. /**< Memory allocation failed. */
  91187. } FLAC__StreamEncoderState;
  91188. /** Maps a FLAC__StreamEncoderState to a C string.
  91189. *
  91190. * Using a FLAC__StreamEncoderState as the index to this array
  91191. * will give the string equivalent. The contents should not be modified.
  91192. */
  91193. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91194. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91195. */
  91196. typedef enum {
  91197. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91198. /**< Initialization was successful. */
  91199. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91200. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91201. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91202. /**< The library was not compiled with support for the given container
  91203. * format.
  91204. */
  91205. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91206. /**< A required callback was not supplied. */
  91207. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91208. /**< The encoder has an invalid setting for number of channels. */
  91209. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91210. /**< The encoder has an invalid setting for bits-per-sample.
  91211. * FLAC supports 4-32 bps but the reference encoder currently supports
  91212. * only up to 24 bps.
  91213. */
  91214. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91215. /**< The encoder has an invalid setting for the input sample rate. */
  91216. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91217. /**< The encoder has an invalid setting for the block size. */
  91218. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91219. /**< The encoder has an invalid setting for the maximum LPC order. */
  91220. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91221. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91222. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91223. /**< The specified block size is less than the maximum LPC order. */
  91224. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91225. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91226. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91227. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91228. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91229. * - One of the metadata blocks contains an undefined type
  91230. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91231. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91232. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91233. */
  91234. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91235. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91236. * already initialized, usually because
  91237. * FLAC__stream_encoder_finish() was not called.
  91238. */
  91239. } FLAC__StreamEncoderInitStatus;
  91240. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91241. *
  91242. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91243. * will give the string equivalent. The contents should not be modified.
  91244. */
  91245. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91246. /** Return values for the FLAC__StreamEncoder read callback.
  91247. */
  91248. typedef enum {
  91249. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91250. /**< The read was OK and decoding can continue. */
  91251. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91252. /**< The read was attempted at the end of the stream. */
  91253. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91254. /**< An unrecoverable error occurred. */
  91255. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91256. /**< Client does not support reading back from the output. */
  91257. } FLAC__StreamEncoderReadStatus;
  91258. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91259. *
  91260. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91261. * will give the string equivalent. The contents should not be modified.
  91262. */
  91263. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91264. /** Return values for the FLAC__StreamEncoder write callback.
  91265. */
  91266. typedef enum {
  91267. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91268. /**< The write was OK and encoding can continue. */
  91269. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91270. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91271. } FLAC__StreamEncoderWriteStatus;
  91272. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91273. *
  91274. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91275. * will give the string equivalent. The contents should not be modified.
  91276. */
  91277. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91278. /** Return values for the FLAC__StreamEncoder seek callback.
  91279. */
  91280. typedef enum {
  91281. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91282. /**< The seek was OK and encoding can continue. */
  91283. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91284. /**< An unrecoverable error occurred. */
  91285. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91286. /**< Client does not support seeking. */
  91287. } FLAC__StreamEncoderSeekStatus;
  91288. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91289. *
  91290. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91291. * will give the string equivalent. The contents should not be modified.
  91292. */
  91293. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91294. /** Return values for the FLAC__StreamEncoder tell callback.
  91295. */
  91296. typedef enum {
  91297. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91298. /**< The tell was OK and encoding can continue. */
  91299. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91300. /**< An unrecoverable error occurred. */
  91301. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91302. /**< Client does not support seeking. */
  91303. } FLAC__StreamEncoderTellStatus;
  91304. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91305. *
  91306. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91307. * will give the string equivalent. The contents should not be modified.
  91308. */
  91309. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91310. /***********************************************************************
  91311. *
  91312. * class FLAC__StreamEncoder
  91313. *
  91314. ***********************************************************************/
  91315. struct FLAC__StreamEncoderProtected;
  91316. struct FLAC__StreamEncoderPrivate;
  91317. /** The opaque structure definition for the stream encoder type.
  91318. * See the \link flac_stream_encoder stream encoder module \endlink
  91319. * for a detailed description.
  91320. */
  91321. typedef struct {
  91322. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91323. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91324. } FLAC__StreamEncoder;
  91325. /** Signature for the read callback.
  91326. *
  91327. * A function pointer matching this signature must be passed to
  91328. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91329. * The supplied function will be called when the encoder needs to read back
  91330. * encoded data. This happens during the metadata callback, when the encoder
  91331. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91332. * while encoding. The address of the buffer to be filled is supplied, along
  91333. * with the number of bytes the buffer can hold. The callback may choose to
  91334. * supply less data and modify the byte count but must be careful not to
  91335. * overflow the buffer. The callback then returns a status code chosen from
  91336. * FLAC__StreamEncoderReadStatus.
  91337. *
  91338. * Here is an example of a read callback for stdio streams:
  91339. * \code
  91340. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91341. * {
  91342. * FILE *file = ((MyClientData*)client_data)->file;
  91343. * if(*bytes > 0) {
  91344. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91345. * if(ferror(file))
  91346. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91347. * else if(*bytes == 0)
  91348. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91349. * else
  91350. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91351. * }
  91352. * else
  91353. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91354. * }
  91355. * \endcode
  91356. *
  91357. * \note In general, FLAC__StreamEncoder functions which change the
  91358. * state should not be called on the \a encoder while in the callback.
  91359. *
  91360. * \param encoder The encoder instance calling the callback.
  91361. * \param buffer A pointer to a location for the callee to store
  91362. * data to be encoded.
  91363. * \param bytes A pointer to the size of the buffer. On entry
  91364. * to the callback, it contains the maximum number
  91365. * of bytes that may be stored in \a buffer. The
  91366. * callee must set it to the actual number of bytes
  91367. * stored (0 in case of error or end-of-stream) before
  91368. * returning.
  91369. * \param client_data The callee's client data set through
  91370. * FLAC__stream_encoder_set_client_data().
  91371. * \retval FLAC__StreamEncoderReadStatus
  91372. * The callee's return status.
  91373. */
  91374. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91375. /** Signature for the write callback.
  91376. *
  91377. * A function pointer matching this signature must be passed to
  91378. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91379. * by the encoder anytime there is raw encoded data ready to write. It may
  91380. * include metadata mixed with encoded audio frames and the data is not
  91381. * guaranteed to be aligned on frame or metadata block boundaries.
  91382. *
  91383. * The only duty of the callback is to write out the \a bytes worth of data
  91384. * in \a buffer to the current position in the output stream. The arguments
  91385. * \a samples and \a current_frame are purely informational. If \a samples
  91386. * is greater than \c 0, then \a current_frame will hold the current frame
  91387. * number that is being written; otherwise it indicates that the write
  91388. * callback is being called to write metadata.
  91389. *
  91390. * \note
  91391. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91392. * write callback will be called twice when writing each audio
  91393. * frame; once for the page header, and once for the page body.
  91394. * When writing the page header, the \a samples argument to the
  91395. * write callback will be \c 0.
  91396. *
  91397. * \note In general, FLAC__StreamEncoder functions which change the
  91398. * state should not be called on the \a encoder while in the callback.
  91399. *
  91400. * \param encoder The encoder instance calling the callback.
  91401. * \param buffer An array of encoded data of length \a bytes.
  91402. * \param bytes The byte length of \a buffer.
  91403. * \param samples The number of samples encoded by \a buffer.
  91404. * \c 0 has a special meaning; see above.
  91405. * \param current_frame The number of the current frame being encoded.
  91406. * \param client_data The callee's client data set through
  91407. * FLAC__stream_encoder_init_*().
  91408. * \retval FLAC__StreamEncoderWriteStatus
  91409. * The callee's return status.
  91410. */
  91411. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91412. /** Signature for the seek callback.
  91413. *
  91414. * A function pointer matching this signature may be passed to
  91415. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91416. * when the encoder needs to seek the output stream. The encoder will pass
  91417. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91418. *
  91419. * Here is an example of a seek callback for stdio streams:
  91420. * \code
  91421. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91422. * {
  91423. * FILE *file = ((MyClientData*)client_data)->file;
  91424. * if(file == stdin)
  91425. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91426. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91427. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91428. * else
  91429. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91430. * }
  91431. * \endcode
  91432. *
  91433. * \note In general, FLAC__StreamEncoder functions which change the
  91434. * state should not be called on the \a encoder while in the callback.
  91435. *
  91436. * \param encoder The encoder instance calling the callback.
  91437. * \param absolute_byte_offset The offset from the beginning of the stream
  91438. * to seek to.
  91439. * \param client_data The callee's client data set through
  91440. * FLAC__stream_encoder_init_*().
  91441. * \retval FLAC__StreamEncoderSeekStatus
  91442. * The callee's return status.
  91443. */
  91444. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91445. /** Signature for the tell callback.
  91446. *
  91447. * A function pointer matching this signature may be passed to
  91448. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91449. * when the encoder needs to know the current position of the output stream.
  91450. *
  91451. * \warning
  91452. * The callback must return the true current byte offset of the output to
  91453. * which the encoder is writing. If you are buffering the output, make
  91454. * sure and take this into account. If you are writing directly to a
  91455. * FILE* from your write callback, ftell() is sufficient. If you are
  91456. * writing directly to a file descriptor from your write callback, you
  91457. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91458. * these points to rewrite metadata after encoding.
  91459. *
  91460. * Here is an example of a tell callback for stdio streams:
  91461. * \code
  91462. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91463. * {
  91464. * FILE *file = ((MyClientData*)client_data)->file;
  91465. * off_t pos;
  91466. * if(file == stdin)
  91467. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91468. * else if((pos = ftello(file)) < 0)
  91469. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91470. * else {
  91471. * *absolute_byte_offset = (FLAC__uint64)pos;
  91472. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91473. * }
  91474. * }
  91475. * \endcode
  91476. *
  91477. * \note In general, FLAC__StreamEncoder functions which change the
  91478. * state should not be called on the \a encoder while in the callback.
  91479. *
  91480. * \param encoder The encoder instance calling the callback.
  91481. * \param absolute_byte_offset The address at which to store the current
  91482. * position of the output.
  91483. * \param client_data The callee's client data set through
  91484. * FLAC__stream_encoder_init_*().
  91485. * \retval FLAC__StreamEncoderTellStatus
  91486. * The callee's return status.
  91487. */
  91488. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91489. /** Signature for the metadata callback.
  91490. *
  91491. * A function pointer matching this signature may be passed to
  91492. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91493. * once at the end of encoding with the populated STREAMINFO structure. This
  91494. * is so the client can seek back to the beginning of the file and write the
  91495. * STREAMINFO block with the correct statistics after encoding (like
  91496. * minimum/maximum frame size and total samples).
  91497. *
  91498. * \note In general, FLAC__StreamEncoder functions which change the
  91499. * state should not be called on the \a encoder while in the callback.
  91500. *
  91501. * \param encoder The encoder instance calling the callback.
  91502. * \param metadata The final populated STREAMINFO block.
  91503. * \param client_data The callee's client data set through
  91504. * FLAC__stream_encoder_init_*().
  91505. */
  91506. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91507. /** Signature for the progress callback.
  91508. *
  91509. * A function pointer matching this signature may be passed to
  91510. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91511. * The supplied function will be called when the encoder has finished
  91512. * writing a frame. The \c total_frames_estimate argument to the
  91513. * callback will be based on the value from
  91514. * FLAC__stream_encoder_set_total_samples_estimate().
  91515. *
  91516. * \note In general, FLAC__StreamEncoder functions which change the
  91517. * state should not be called on the \a encoder while in the callback.
  91518. *
  91519. * \param encoder The encoder instance calling the callback.
  91520. * \param bytes_written Bytes written so far.
  91521. * \param samples_written Samples written so far.
  91522. * \param frames_written Frames written so far.
  91523. * \param total_frames_estimate The estimate of the total number of
  91524. * frames to be written.
  91525. * \param client_data The callee's client data set through
  91526. * FLAC__stream_encoder_init_*().
  91527. */
  91528. 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);
  91529. /***********************************************************************
  91530. *
  91531. * Class constructor/destructor
  91532. *
  91533. ***********************************************************************/
  91534. /** Create a new stream encoder instance. The instance is created with
  91535. * default settings; see the individual FLAC__stream_encoder_set_*()
  91536. * functions for each setting's default.
  91537. *
  91538. * \retval FLAC__StreamEncoder*
  91539. * \c NULL if there was an error allocating memory, else the new instance.
  91540. */
  91541. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91542. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91543. *
  91544. * \param encoder A pointer to an existing encoder.
  91545. * \assert
  91546. * \code encoder != NULL \endcode
  91547. */
  91548. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91549. /***********************************************************************
  91550. *
  91551. * Public class method prototypes
  91552. *
  91553. ***********************************************************************/
  91554. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91555. *
  91556. * \note
  91557. * This does not need to be set for native FLAC encoding.
  91558. *
  91559. * \note
  91560. * It is recommended to set a serial number explicitly as the default of '0'
  91561. * may collide with other streams.
  91562. *
  91563. * \default \c 0
  91564. * \param encoder An encoder instance to set.
  91565. * \param serial_number See above.
  91566. * \assert
  91567. * \code encoder != NULL \endcode
  91568. * \retval FLAC__bool
  91569. * \c false if the encoder is already initialized, else \c true.
  91570. */
  91571. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91572. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91573. * encoded output by feeding it through an internal decoder and comparing
  91574. * the original signal against the decoded signal. If a mismatch occurs,
  91575. * the process call will return \c false. Note that this will slow the
  91576. * encoding process by the extra time required for decoding and comparison.
  91577. *
  91578. * \default \c false
  91579. * \param encoder An encoder instance to set.
  91580. * \param value Flag value (see above).
  91581. * \assert
  91582. * \code encoder != NULL \endcode
  91583. * \retval FLAC__bool
  91584. * \c false if the encoder is already initialized, else \c true.
  91585. */
  91586. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91587. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91588. * the encoder will comply with the Subset and will check the
  91589. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91590. * comply. If \c false, the settings may take advantage of the full
  91591. * range that the format allows.
  91592. *
  91593. * Make sure you know what it entails before setting this to \c false.
  91594. *
  91595. * \default \c true
  91596. * \param encoder An encoder instance to set.
  91597. * \param value Flag value (see above).
  91598. * \assert
  91599. * \code encoder != NULL \endcode
  91600. * \retval FLAC__bool
  91601. * \c false if the encoder is already initialized, else \c true.
  91602. */
  91603. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91604. /** Set the number of channels to be encoded.
  91605. *
  91606. * \default \c 2
  91607. * \param encoder An encoder instance to set.
  91608. * \param value See above.
  91609. * \assert
  91610. * \code encoder != NULL \endcode
  91611. * \retval FLAC__bool
  91612. * \c false if the encoder is already initialized, else \c true.
  91613. */
  91614. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91615. /** Set the sample resolution of the input to be encoded.
  91616. *
  91617. * \warning
  91618. * Do not feed the encoder data that is wider than the value you
  91619. * set here or you will generate an invalid stream.
  91620. *
  91621. * \default \c 16
  91622. * \param encoder An encoder instance to set.
  91623. * \param value See above.
  91624. * \assert
  91625. * \code encoder != NULL \endcode
  91626. * \retval FLAC__bool
  91627. * \c false if the encoder is already initialized, else \c true.
  91628. */
  91629. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91630. /** Set the sample rate (in Hz) of the input to be encoded.
  91631. *
  91632. * \default \c 44100
  91633. * \param encoder An encoder instance to set.
  91634. * \param value See above.
  91635. * \assert
  91636. * \code encoder != NULL \endcode
  91637. * \retval FLAC__bool
  91638. * \c false if the encoder is already initialized, else \c true.
  91639. */
  91640. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91641. /** Set the compression level
  91642. *
  91643. * The compression level is roughly proportional to the amount of effort
  91644. * the encoder expends to compress the file. A higher level usually
  91645. * means more computation but higher compression. The default level is
  91646. * suitable for most applications.
  91647. *
  91648. * Currently the levels range from \c 0 (fastest, least compression) to
  91649. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91650. * treated as \c 8.
  91651. *
  91652. * This function automatically calls the following other \c _set_
  91653. * functions with appropriate values, so the client does not need to
  91654. * unless it specifically wants to override them:
  91655. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91656. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91657. * - FLAC__stream_encoder_set_apodization()
  91658. * - FLAC__stream_encoder_set_max_lpc_order()
  91659. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91660. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91661. * - FLAC__stream_encoder_set_do_escape_coding()
  91662. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91663. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91664. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91665. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91666. *
  91667. * The actual values set for each level are:
  91668. * <table>
  91669. * <tr>
  91670. * <td><b>level</b><td>
  91671. * <td>do mid-side stereo<td>
  91672. * <td>loose mid-side stereo<td>
  91673. * <td>apodization<td>
  91674. * <td>max lpc order<td>
  91675. * <td>qlp coeff precision<td>
  91676. * <td>qlp coeff prec search<td>
  91677. * <td>escape coding<td>
  91678. * <td>exhaustive model search<td>
  91679. * <td>min residual partition order<td>
  91680. * <td>max residual partition order<td>
  91681. * <td>rice parameter search dist<td>
  91682. * </tr>
  91683. * <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>
  91684. * <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>
  91685. * <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>
  91686. * <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>
  91687. * <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>
  91688. * <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>
  91689. * <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>
  91690. * <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>
  91691. * <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>
  91692. * </table>
  91693. *
  91694. * \default \c 5
  91695. * \param encoder An encoder instance to set.
  91696. * \param value See above.
  91697. * \assert
  91698. * \code encoder != NULL \endcode
  91699. * \retval FLAC__bool
  91700. * \c false if the encoder is already initialized, else \c true.
  91701. */
  91702. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91703. /** Set the blocksize to use while encoding.
  91704. *
  91705. * The number of samples to use per frame. Use \c 0 to let the encoder
  91706. * estimate a blocksize; this is usually best.
  91707. *
  91708. * \default \c 0
  91709. * \param encoder An encoder instance to set.
  91710. * \param value See above.
  91711. * \assert
  91712. * \code encoder != NULL \endcode
  91713. * \retval FLAC__bool
  91714. * \c false if the encoder is already initialized, else \c true.
  91715. */
  91716. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91717. /** Set to \c true to enable mid-side encoding on stereo input. The
  91718. * number of channels must be 2 for this to have any effect. Set to
  91719. * \c false to use only independent channel coding.
  91720. *
  91721. * \default \c false
  91722. * \param encoder An encoder instance to set.
  91723. * \param value Flag value (see above).
  91724. * \assert
  91725. * \code encoder != NULL \endcode
  91726. * \retval FLAC__bool
  91727. * \c false if the encoder is already initialized, else \c true.
  91728. */
  91729. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91730. /** Set to \c true to enable adaptive switching between mid-side and
  91731. * left-right encoding on stereo input. Set to \c false to use
  91732. * exhaustive searching. Setting this to \c true requires
  91733. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91734. * \c true in order to have any effect.
  91735. *
  91736. * \default \c false
  91737. * \param encoder An encoder instance to set.
  91738. * \param value Flag value (see above).
  91739. * \assert
  91740. * \code encoder != NULL \endcode
  91741. * \retval FLAC__bool
  91742. * \c false if the encoder is already initialized, else \c true.
  91743. */
  91744. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91745. /** Sets the apodization function(s) the encoder will use when windowing
  91746. * audio data for LPC analysis.
  91747. *
  91748. * The \a specification is a plain ASCII string which specifies exactly
  91749. * which functions to use. There may be more than one (up to 32),
  91750. * separated by \c ';' characters. Some functions take one or more
  91751. * comma-separated arguments in parentheses.
  91752. *
  91753. * The available functions are \c bartlett, \c bartlett_hann,
  91754. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91755. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91756. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91757. *
  91758. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91759. * (0<STDDEV<=0.5).
  91760. *
  91761. * For \c tukey(P), P specifies the fraction of the window that is
  91762. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91763. * corresponds to \c hann.
  91764. *
  91765. * Example specifications are \c "blackman" or
  91766. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91767. *
  91768. * Any function that is specified erroneously is silently dropped. Up
  91769. * to 32 functions are kept, the rest are dropped. If the specification
  91770. * is empty the encoder defaults to \c "tukey(0.5)".
  91771. *
  91772. * When more than one function is specified, then for every subframe the
  91773. * encoder will try each of them separately and choose the window that
  91774. * results in the smallest compressed subframe.
  91775. *
  91776. * Note that each function specified causes the encoder to occupy a
  91777. * floating point array in which to store the window.
  91778. *
  91779. * \default \c "tukey(0.5)"
  91780. * \param encoder An encoder instance to set.
  91781. * \param specification See above.
  91782. * \assert
  91783. * \code encoder != NULL \endcode
  91784. * \code specification != NULL \endcode
  91785. * \retval FLAC__bool
  91786. * \c false if the encoder is already initialized, else \c true.
  91787. */
  91788. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91789. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91790. *
  91791. * \default \c 0
  91792. * \param encoder An encoder instance to set.
  91793. * \param value See above.
  91794. * \assert
  91795. * \code encoder != NULL \endcode
  91796. * \retval FLAC__bool
  91797. * \c false if the encoder is already initialized, else \c true.
  91798. */
  91799. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91800. /** Set the precision, in bits, of the quantized linear predictor
  91801. * coefficients, or \c 0 to let the encoder select it based on the
  91802. * blocksize.
  91803. *
  91804. * \note
  91805. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91806. * be less than 32.
  91807. *
  91808. * \default \c 0
  91809. * \param encoder An encoder instance to set.
  91810. * \param value See above.
  91811. * \assert
  91812. * \code encoder != NULL \endcode
  91813. * \retval FLAC__bool
  91814. * \c false if the encoder is already initialized, else \c true.
  91815. */
  91816. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91817. /** Set to \c false to use only the specified quantized linear predictor
  91818. * coefficient precision, or \c true to search neighboring precision
  91819. * values and use the best one.
  91820. *
  91821. * \default \c false
  91822. * \param encoder An encoder instance to set.
  91823. * \param value See above.
  91824. * \assert
  91825. * \code encoder != NULL \endcode
  91826. * \retval FLAC__bool
  91827. * \c false if the encoder is already initialized, else \c true.
  91828. */
  91829. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91830. /** Deprecated. Setting this value has no effect.
  91831. *
  91832. * \default \c false
  91833. * \param encoder An encoder instance to set.
  91834. * \param value See above.
  91835. * \assert
  91836. * \code encoder != NULL \endcode
  91837. * \retval FLAC__bool
  91838. * \c false if the encoder is already initialized, else \c true.
  91839. */
  91840. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91841. /** Set to \c false to let the encoder estimate the best model order
  91842. * based on the residual signal energy, or \c true to force the
  91843. * encoder to evaluate all order models and select the best.
  91844. *
  91845. * \default \c false
  91846. * \param encoder An encoder instance to set.
  91847. * \param value See above.
  91848. * \assert
  91849. * \code encoder != NULL \endcode
  91850. * \retval FLAC__bool
  91851. * \c false if the encoder is already initialized, else \c true.
  91852. */
  91853. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91854. /** Set the minimum partition order to search when coding the residual.
  91855. * This is used in tandem with
  91856. * FLAC__stream_encoder_set_max_residual_partition_order().
  91857. *
  91858. * The partition order determines the context size in the residual.
  91859. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91860. *
  91861. * Set both min and max values to \c 0 to force a single context,
  91862. * whose Rice parameter is based on the residual signal variance.
  91863. * Otherwise, set a min and max order, and the encoder will search
  91864. * all orders, using the mean of each context for its Rice parameter,
  91865. * and use the best.
  91866. *
  91867. * \default \c 0
  91868. * \param encoder An encoder instance to set.
  91869. * \param value See above.
  91870. * \assert
  91871. * \code encoder != NULL \endcode
  91872. * \retval FLAC__bool
  91873. * \c false if the encoder is already initialized, else \c true.
  91874. */
  91875. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91876. /** Set the maximum partition order to search when coding the residual.
  91877. * This is used in tandem with
  91878. * FLAC__stream_encoder_set_min_residual_partition_order().
  91879. *
  91880. * The partition order determines the context size in the residual.
  91881. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91882. *
  91883. * Set both min and max values to \c 0 to force a single context,
  91884. * whose Rice parameter is based on the residual signal variance.
  91885. * Otherwise, set a min and max order, and the encoder will search
  91886. * all orders, using the mean of each context for its Rice parameter,
  91887. * and use the best.
  91888. *
  91889. * \default \c 0
  91890. * \param encoder An encoder instance to set.
  91891. * \param value See above.
  91892. * \assert
  91893. * \code encoder != NULL \endcode
  91894. * \retval FLAC__bool
  91895. * \c false if the encoder is already initialized, else \c true.
  91896. */
  91897. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91898. /** Deprecated. Setting this value has no effect.
  91899. *
  91900. * \default \c 0
  91901. * \param encoder An encoder instance to set.
  91902. * \param value See above.
  91903. * \assert
  91904. * \code encoder != NULL \endcode
  91905. * \retval FLAC__bool
  91906. * \c false if the encoder is already initialized, else \c true.
  91907. */
  91908. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91909. /** Set an estimate of the total samples that will be encoded.
  91910. * This is merely an estimate and may be set to \c 0 if unknown.
  91911. * This value will be written to the STREAMINFO block before encoding,
  91912. * and can remove the need for the caller to rewrite the value later
  91913. * if the value is known before encoding.
  91914. *
  91915. * \default \c 0
  91916. * \param encoder An encoder instance to set.
  91917. * \param value See above.
  91918. * \assert
  91919. * \code encoder != NULL \endcode
  91920. * \retval FLAC__bool
  91921. * \c false if the encoder is already initialized, else \c true.
  91922. */
  91923. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91924. /** Set the metadata blocks to be emitted to the stream before encoding.
  91925. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91926. * array of pointers to metadata blocks. The array is non-const since
  91927. * the encoder may need to change the \a is_last flag inside them, and
  91928. * in some cases update seek point offsets. Otherwise, the encoder will
  91929. * not modify or free the blocks. It is up to the caller to free the
  91930. * metadata blocks after encoding finishes.
  91931. *
  91932. * \note
  91933. * The encoder stores only copies of the pointers in the \a metadata array;
  91934. * the metadata blocks themselves must survive at least until after
  91935. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91936. *
  91937. * \note
  91938. * The STREAMINFO block is always written and no STREAMINFO block may
  91939. * occur in the supplied array.
  91940. *
  91941. * \note
  91942. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91943. * in the \a metadata array, but the client has specified that it does not
  91944. * support seeking, then the SEEKTABLE will be written verbatim. However
  91945. * by itself this is not very useful as the client will not know the stream
  91946. * offsets for the seekpoints ahead of time. In order to get a proper
  91947. * seektable the client must support seeking. See next note.
  91948. *
  91949. * \note
  91950. * SEEKTABLE blocks are handled specially. Since you will not know
  91951. * the values for the seek point stream offsets, you should pass in
  91952. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91953. * required sample numbers (or placeholder points), with \c 0 for the
  91954. * \a frame_samples and \a stream_offset fields for each point. If the
  91955. * client has specified that it supports seeking by providing a seek
  91956. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91957. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91958. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91959. * then while it is encoding the encoder will fill the stream offsets in
  91960. * for you and when encoding is finished, it will seek back and write the
  91961. * real values into the SEEKTABLE block in the stream. There are helper
  91962. * routines for manipulating seektable template blocks; see metadata.h:
  91963. * FLAC__metadata_object_seektable_template_*(). If the client does
  91964. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91965. * will slow down or remove the ability to seek in the FLAC stream.
  91966. *
  91967. * \note
  91968. * The encoder instance \b will modify the first \c SEEKTABLE block
  91969. * as it transforms the template to a valid seektable while encoding,
  91970. * but it is still up to the caller to free all metadata blocks after
  91971. * encoding.
  91972. *
  91973. * \note
  91974. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91975. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91976. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91977. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91978. * block is present in the \a metadata array, libFLAC will write an
  91979. * empty one, containing only the vendor string.
  91980. *
  91981. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91982. * the second metadata block of the stream. The encoder already supplies
  91983. * the STREAMINFO block automatically. If \a metadata does not contain a
  91984. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91985. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91986. * first, the init function will reorder \a metadata by moving the
  91987. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91988. * blocks will remain as they were.
  91989. *
  91990. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91991. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91992. * return \c false.
  91993. *
  91994. * \default \c NULL, 0
  91995. * \param encoder An encoder instance to set.
  91996. * \param metadata See above.
  91997. * \param num_blocks See above.
  91998. * \assert
  91999. * \code encoder != NULL \endcode
  92000. * \retval FLAC__bool
  92001. * \c false if the encoder is already initialized, else \c true.
  92002. * \c false if the encoder is already initialized, or if
  92003. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92004. */
  92005. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92006. /** Get the current encoder state.
  92007. *
  92008. * \param encoder An encoder instance to query.
  92009. * \assert
  92010. * \code encoder != NULL \endcode
  92011. * \retval FLAC__StreamEncoderState
  92012. * The current encoder state.
  92013. */
  92014. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92015. /** Get the state of the verify stream decoder.
  92016. * Useful when the stream encoder state is
  92017. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92018. *
  92019. * \param encoder An encoder instance to query.
  92020. * \assert
  92021. * \code encoder != NULL \endcode
  92022. * \retval FLAC__StreamDecoderState
  92023. * The verify stream decoder state.
  92024. */
  92025. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92026. /** Get the current encoder state as a C string.
  92027. * This version automatically resolves
  92028. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92029. * verify decoder's state.
  92030. *
  92031. * \param encoder A encoder instance to query.
  92032. * \assert
  92033. * \code encoder != NULL \endcode
  92034. * \retval const char *
  92035. * The encoder state as a C string. Do not modify the contents.
  92036. */
  92037. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92038. /** Get relevant values about the nature of a verify decoder error.
  92039. * Useful when the stream encoder state is
  92040. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92041. * be addresses in which the stats will be returned, or NULL if value
  92042. * is not desired.
  92043. *
  92044. * \param encoder An encoder instance to query.
  92045. * \param absolute_sample The absolute sample number of the mismatch.
  92046. * \param frame_number The number of the frame in which the mismatch occurred.
  92047. * \param channel The channel in which the mismatch occurred.
  92048. * \param sample The number of the sample (relative to the frame) in
  92049. * which the mismatch occurred.
  92050. * \param expected The expected value for the sample in question.
  92051. * \param got The actual value returned by the decoder.
  92052. * \assert
  92053. * \code encoder != NULL \endcode
  92054. */
  92055. 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);
  92056. /** Get the "verify" flag.
  92057. *
  92058. * \param encoder An encoder instance to query.
  92059. * \assert
  92060. * \code encoder != NULL \endcode
  92061. * \retval FLAC__bool
  92062. * See FLAC__stream_encoder_set_verify().
  92063. */
  92064. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92065. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92066. *
  92067. * \param encoder An encoder instance to query.
  92068. * \assert
  92069. * \code encoder != NULL \endcode
  92070. * \retval FLAC__bool
  92071. * See FLAC__stream_encoder_set_streamable_subset().
  92072. */
  92073. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92074. /** Get the number of input channels being processed.
  92075. *
  92076. * \param encoder An encoder instance to query.
  92077. * \assert
  92078. * \code encoder != NULL \endcode
  92079. * \retval unsigned
  92080. * See FLAC__stream_encoder_set_channels().
  92081. */
  92082. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92083. /** Get the input sample resolution setting.
  92084. *
  92085. * \param encoder An encoder instance to query.
  92086. * \assert
  92087. * \code encoder != NULL \endcode
  92088. * \retval unsigned
  92089. * See FLAC__stream_encoder_set_bits_per_sample().
  92090. */
  92091. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92092. /** Get the input sample rate setting.
  92093. *
  92094. * \param encoder An encoder instance to query.
  92095. * \assert
  92096. * \code encoder != NULL \endcode
  92097. * \retval unsigned
  92098. * See FLAC__stream_encoder_set_sample_rate().
  92099. */
  92100. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92101. /** Get the blocksize setting.
  92102. *
  92103. * \param encoder An encoder instance to query.
  92104. * \assert
  92105. * \code encoder != NULL \endcode
  92106. * \retval unsigned
  92107. * See FLAC__stream_encoder_set_blocksize().
  92108. */
  92109. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92110. /** Get the "mid/side stereo coding" flag.
  92111. *
  92112. * \param encoder An encoder instance to query.
  92113. * \assert
  92114. * \code encoder != NULL \endcode
  92115. * \retval FLAC__bool
  92116. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92117. */
  92118. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92119. /** Get the "adaptive mid/side switching" flag.
  92120. *
  92121. * \param encoder An encoder instance to query.
  92122. * \assert
  92123. * \code encoder != NULL \endcode
  92124. * \retval FLAC__bool
  92125. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92126. */
  92127. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92128. /** Get the maximum LPC order setting.
  92129. *
  92130. * \param encoder An encoder instance to query.
  92131. * \assert
  92132. * \code encoder != NULL \endcode
  92133. * \retval unsigned
  92134. * See FLAC__stream_encoder_set_max_lpc_order().
  92135. */
  92136. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92137. /** Get the quantized linear predictor coefficient precision setting.
  92138. *
  92139. * \param encoder An encoder instance to query.
  92140. * \assert
  92141. * \code encoder != NULL \endcode
  92142. * \retval unsigned
  92143. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92144. */
  92145. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92146. /** Get the qlp coefficient precision search flag.
  92147. *
  92148. * \param encoder An encoder instance to query.
  92149. * \assert
  92150. * \code encoder != NULL \endcode
  92151. * \retval FLAC__bool
  92152. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92153. */
  92154. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92155. /** Get the "escape coding" flag.
  92156. *
  92157. * \param encoder An encoder instance to query.
  92158. * \assert
  92159. * \code encoder != NULL \endcode
  92160. * \retval FLAC__bool
  92161. * See FLAC__stream_encoder_set_do_escape_coding().
  92162. */
  92163. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92164. /** Get the exhaustive model search flag.
  92165. *
  92166. * \param encoder An encoder instance to query.
  92167. * \assert
  92168. * \code encoder != NULL \endcode
  92169. * \retval FLAC__bool
  92170. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92171. */
  92172. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92173. /** Get the minimum residual partition order setting.
  92174. *
  92175. * \param encoder An encoder instance to query.
  92176. * \assert
  92177. * \code encoder != NULL \endcode
  92178. * \retval unsigned
  92179. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92180. */
  92181. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92182. /** Get maximum residual partition order setting.
  92183. *
  92184. * \param encoder An encoder instance to query.
  92185. * \assert
  92186. * \code encoder != NULL \endcode
  92187. * \retval unsigned
  92188. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92189. */
  92190. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92191. /** Get the Rice parameter search distance setting.
  92192. *
  92193. * \param encoder An encoder instance to query.
  92194. * \assert
  92195. * \code encoder != NULL \endcode
  92196. * \retval unsigned
  92197. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92198. */
  92199. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92200. /** Get the previously set estimate of the total samples to be encoded.
  92201. * The encoder merely mimics back the value given to
  92202. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92203. * other way of knowing how many samples the client will encode.
  92204. *
  92205. * \param encoder An encoder instance to set.
  92206. * \assert
  92207. * \code encoder != NULL \endcode
  92208. * \retval FLAC__uint64
  92209. * See FLAC__stream_encoder_get_total_samples_estimate().
  92210. */
  92211. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92212. /** Initialize the encoder instance to encode native FLAC streams.
  92213. *
  92214. * This flavor of initialization sets up the encoder to encode to a
  92215. * native FLAC stream. I/O is performed via callbacks to the client.
  92216. * For encoding to a plain file via filename or open \c FILE*,
  92217. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92218. * provide a simpler interface.
  92219. *
  92220. * This function should be called after FLAC__stream_encoder_new() and
  92221. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92222. * or FLAC__stream_encoder_process_interleaved().
  92223. * initialization succeeded.
  92224. *
  92225. * The call to FLAC__stream_encoder_init_stream() currently will also
  92226. * immediately call the write callback several times, once with the \c fLaC
  92227. * signature, and once for each encoded metadata block.
  92228. *
  92229. * \param encoder An uninitialized encoder instance.
  92230. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92231. * pointer must not be \c NULL.
  92232. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92233. * pointer may be \c NULL if seeking is not
  92234. * supported. The encoder uses seeking to go back
  92235. * and write some some stream statistics to the
  92236. * STREAMINFO block; this is recommended but not
  92237. * necessary to create a valid FLAC stream. If
  92238. * \a seek_callback is not \c NULL then a
  92239. * \a tell_callback must also be supplied.
  92240. * Alternatively, a dummy seek callback that just
  92241. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92242. * may also be supplied, all though this is slightly
  92243. * less efficient for the encoder.
  92244. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92245. * pointer may be \c NULL if seeking is not
  92246. * supported. If \a seek_callback is \c NULL then
  92247. * this argument will be ignored. If
  92248. * \a seek_callback is not \c NULL then a
  92249. * \a tell_callback must also be supplied.
  92250. * Alternatively, a dummy tell callback that just
  92251. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92252. * may also be supplied, all though this is slightly
  92253. * less efficient for the encoder.
  92254. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92255. * pointer may be \c NULL if the callback is not
  92256. * desired. If the client provides a seek callback,
  92257. * this function is not necessary as the encoder
  92258. * will automatically seek back and update the
  92259. * STREAMINFO block. It may also be \c NULL if the
  92260. * client does not support seeking, since it will
  92261. * have no way of going back to update the
  92262. * STREAMINFO. However the client can still supply
  92263. * a callback if it would like to know the details
  92264. * from the STREAMINFO.
  92265. * \param client_data This value will be supplied to callbacks in their
  92266. * \a client_data argument.
  92267. * \assert
  92268. * \code encoder != NULL \endcode
  92269. * \retval FLAC__StreamEncoderInitStatus
  92270. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92271. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92272. */
  92273. 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);
  92274. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92275. *
  92276. * This flavor of initialization sets up the encoder to encode to a FLAC
  92277. * stream in an Ogg container. I/O is performed via callbacks to the
  92278. * client. For encoding to a plain file via filename or open \c FILE*,
  92279. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92280. * provide a simpler interface.
  92281. *
  92282. * This function should be called after FLAC__stream_encoder_new() and
  92283. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92284. * or FLAC__stream_encoder_process_interleaved().
  92285. * initialization succeeded.
  92286. *
  92287. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92288. * immediately call the write callback several times to write the metadata
  92289. * packets.
  92290. *
  92291. * \param encoder An uninitialized encoder instance.
  92292. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92293. * pointer must not be \c NULL if \a seek_callback
  92294. * is non-NULL since they are both needed to be
  92295. * able to write data back to the Ogg FLAC stream
  92296. * in the post-encode phase.
  92297. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92298. * pointer must not be \c NULL.
  92299. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92300. * pointer may be \c NULL if seeking is not
  92301. * supported. The encoder uses seeking to go back
  92302. * and write some some stream statistics to the
  92303. * STREAMINFO block; this is recommended but not
  92304. * necessary to create a valid FLAC stream. If
  92305. * \a seek_callback is not \c NULL then a
  92306. * \a tell_callback must also be supplied.
  92307. * Alternatively, a dummy seek callback that just
  92308. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92309. * may also be supplied, all though this is slightly
  92310. * less efficient for the encoder.
  92311. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92312. * pointer may be \c NULL if seeking is not
  92313. * supported. If \a seek_callback is \c NULL then
  92314. * this argument will be ignored. If
  92315. * \a seek_callback is not \c NULL then a
  92316. * \a tell_callback must also be supplied.
  92317. * Alternatively, a dummy tell callback that just
  92318. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92319. * may also be supplied, all though this is slightly
  92320. * less efficient for the encoder.
  92321. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92322. * pointer may be \c NULL if the callback is not
  92323. * desired. If the client provides a seek callback,
  92324. * this function is not necessary as the encoder
  92325. * will automatically seek back and update the
  92326. * STREAMINFO block. It may also be \c NULL if the
  92327. * client does not support seeking, since it will
  92328. * have no way of going back to update the
  92329. * STREAMINFO. However the client can still supply
  92330. * a callback if it would like to know the details
  92331. * from the STREAMINFO.
  92332. * \param client_data This value will be supplied to callbacks in their
  92333. * \a client_data argument.
  92334. * \assert
  92335. * \code encoder != NULL \endcode
  92336. * \retval FLAC__StreamEncoderInitStatus
  92337. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92338. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92339. */
  92340. 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);
  92341. /** Initialize the encoder instance to encode native FLAC files.
  92342. *
  92343. * This flavor of initialization sets up the encoder to encode to a
  92344. * plain native FLAC file. For non-stdio streams, you must use
  92345. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92346. *
  92347. * This function should be called after FLAC__stream_encoder_new() and
  92348. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92349. * or FLAC__stream_encoder_process_interleaved().
  92350. * initialization succeeded.
  92351. *
  92352. * \param encoder An uninitialized encoder instance.
  92353. * \param file An open file. The file should have been opened
  92354. * with mode \c "w+b" and rewound. The file
  92355. * becomes owned by the encoder and should not be
  92356. * manipulated by the client while encoding.
  92357. * Unless \a file is \c stdout, it will be closed
  92358. * when FLAC__stream_encoder_finish() is called.
  92359. * Note however that a proper SEEKTABLE cannot be
  92360. * created when encoding to \c stdout since it is
  92361. * not seekable.
  92362. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92363. * pointer may be \c NULL if the callback is not
  92364. * desired.
  92365. * \param client_data This value will be supplied to callbacks in their
  92366. * \a client_data argument.
  92367. * \assert
  92368. * \code encoder != NULL \endcode
  92369. * \code file != NULL \endcode
  92370. * \retval FLAC__StreamEncoderInitStatus
  92371. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92372. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92373. */
  92374. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92375. /** Initialize the encoder instance to encode Ogg FLAC files.
  92376. *
  92377. * This flavor of initialization sets up the encoder to encode to a
  92378. * plain Ogg FLAC file. For non-stdio streams, you must use
  92379. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92380. *
  92381. * This function should be called after FLAC__stream_encoder_new() and
  92382. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92383. * or FLAC__stream_encoder_process_interleaved().
  92384. * initialization succeeded.
  92385. *
  92386. * \param encoder An uninitialized encoder instance.
  92387. * \param file An open file. The file should have been opened
  92388. * with mode \c "w+b" and rewound. The file
  92389. * becomes owned by the encoder and should not be
  92390. * manipulated by the client while encoding.
  92391. * Unless \a file is \c stdout, it will be closed
  92392. * when FLAC__stream_encoder_finish() is called.
  92393. * Note however that a proper SEEKTABLE cannot be
  92394. * created when encoding to \c stdout since it is
  92395. * not seekable.
  92396. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92397. * pointer may be \c NULL if the callback is not
  92398. * desired.
  92399. * \param client_data This value will be supplied to callbacks in their
  92400. * \a client_data argument.
  92401. * \assert
  92402. * \code encoder != NULL \endcode
  92403. * \code file != NULL \endcode
  92404. * \retval FLAC__StreamEncoderInitStatus
  92405. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92406. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92407. */
  92408. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92409. /** Initialize the encoder instance to encode native FLAC files.
  92410. *
  92411. * This flavor of initialization sets up the encoder to encode to a plain
  92412. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92413. * with Unicode filenames on Windows), you must use
  92414. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92415. * and provide callbacks for the I/O.
  92416. *
  92417. * This function should be called after FLAC__stream_encoder_new() and
  92418. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92419. * or FLAC__stream_encoder_process_interleaved().
  92420. * initialization succeeded.
  92421. *
  92422. * \param encoder An uninitialized encoder instance.
  92423. * \param filename The name of the file to encode to. The file will
  92424. * be opened with fopen(). Use \c NULL to encode to
  92425. * \c stdout. Note however that a proper SEEKTABLE
  92426. * cannot be created when encoding to \c stdout since
  92427. * it is not seekable.
  92428. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92429. * pointer may be \c NULL if the callback is not
  92430. * desired.
  92431. * \param client_data This value will be supplied to callbacks in their
  92432. * \a client_data argument.
  92433. * \assert
  92434. * \code encoder != NULL \endcode
  92435. * \retval FLAC__StreamEncoderInitStatus
  92436. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92437. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92438. */
  92439. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92440. /** Initialize the encoder instance to encode Ogg FLAC files.
  92441. *
  92442. * This flavor of initialization sets up the encoder to encode to a plain
  92443. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92444. * with Unicode filenames on Windows), you must use
  92445. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92446. * and provide callbacks for the I/O.
  92447. *
  92448. * This function should be called after FLAC__stream_encoder_new() and
  92449. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92450. * or FLAC__stream_encoder_process_interleaved().
  92451. * initialization succeeded.
  92452. *
  92453. * \param encoder An uninitialized encoder instance.
  92454. * \param filename The name of the file to encode to. The file will
  92455. * be opened with fopen(). Use \c NULL to encode to
  92456. * \c stdout. Note however that a proper SEEKTABLE
  92457. * cannot be created when encoding to \c stdout since
  92458. * it is not seekable.
  92459. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92460. * pointer may be \c NULL if the callback is not
  92461. * desired.
  92462. * \param client_data This value will be supplied to callbacks in their
  92463. * \a client_data argument.
  92464. * \assert
  92465. * \code encoder != NULL \endcode
  92466. * \retval FLAC__StreamEncoderInitStatus
  92467. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92468. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92469. */
  92470. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92471. /** Finish the encoding process.
  92472. * Flushes the encoding buffer, releases resources, resets the encoder
  92473. * settings to their defaults, and returns the encoder state to
  92474. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92475. * one or more write callbacks before returning, and will generate
  92476. * a metadata callback.
  92477. *
  92478. * Note that in the course of processing the last frame, errors can
  92479. * occur, so the caller should be sure to check the return value to
  92480. * ensure the file was encoded properly.
  92481. *
  92482. * In the event of a prematurely-terminated encode, it is not strictly
  92483. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92484. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92485. * with a FLAC__stream_encoder_finish().
  92486. *
  92487. * \param encoder An uninitialized encoder instance.
  92488. * \assert
  92489. * \code encoder != NULL \endcode
  92490. * \retval FLAC__bool
  92491. * \c false if an error occurred processing the last frame; or if verify
  92492. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92493. * verify mismatch; else \c true. If \c false, caller should check the
  92494. * state with FLAC__stream_encoder_get_state() for more information
  92495. * about the error.
  92496. */
  92497. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92498. /** Submit data for encoding.
  92499. * This version allows you to supply the input data via an array of
  92500. * pointers, each pointer pointing to an array of \a samples samples
  92501. * representing one channel. The samples need not be block-aligned,
  92502. * but each channel should have the same number of samples. Each sample
  92503. * should be a signed integer, right-justified to the resolution set by
  92504. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92505. * resolution is 16 bits per sample, the samples should all be in the
  92506. * range [-32768,32767].
  92507. *
  92508. * For applications where channel order is important, channels must
  92509. * follow the order as described in the
  92510. * <A HREF="../format.html#frame_header">frame header</A>.
  92511. *
  92512. * \param encoder An initialized encoder instance in the OK state.
  92513. * \param buffer An array of pointers to each channel's signal.
  92514. * \param samples The number of samples in one channel.
  92515. * \assert
  92516. * \code encoder != NULL \endcode
  92517. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92518. * \retval FLAC__bool
  92519. * \c true if successful, else \c false; in this case, check the
  92520. * encoder state with FLAC__stream_encoder_get_state() to see what
  92521. * went wrong.
  92522. */
  92523. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92524. /** Submit data for encoding.
  92525. * This version allows you to supply the input data where the channels
  92526. * are interleaved into a single array (i.e. channel0_sample0,
  92527. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92528. * The samples need not be block-aligned but they must be
  92529. * sample-aligned, i.e. the first value should be channel0_sample0
  92530. * and the last value channelN_sampleM. Each sample should be a signed
  92531. * integer, right-justified to the resolution set by
  92532. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92533. * resolution is 16 bits per sample, the samples should all be in the
  92534. * range [-32768,32767].
  92535. *
  92536. * For applications where channel order is important, channels must
  92537. * follow the order as described in the
  92538. * <A HREF="../format.html#frame_header">frame header</A>.
  92539. *
  92540. * \param encoder An initialized encoder instance in the OK state.
  92541. * \param buffer An array of channel-interleaved data (see above).
  92542. * \param samples The number of samples in one channel, the same as for
  92543. * FLAC__stream_encoder_process(). For example, if
  92544. * encoding two channels, \c 1000 \a samples corresponds
  92545. * to a \a buffer of 2000 values.
  92546. * \assert
  92547. * \code encoder != NULL \endcode
  92548. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92549. * \retval FLAC__bool
  92550. * \c true if successful, else \c false; in this case, check the
  92551. * encoder state with FLAC__stream_encoder_get_state() to see what
  92552. * went wrong.
  92553. */
  92554. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92555. /* \} */
  92556. #ifdef __cplusplus
  92557. }
  92558. #endif
  92559. #endif
  92560. /*** End of inlined file: stream_encoder.h ***/
  92561. #ifdef _MSC_VER
  92562. /* OPT: an MSVC built-in would be better */
  92563. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92564. {
  92565. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92566. return (x>>16) | (x<<16);
  92567. }
  92568. #endif
  92569. #if defined(_MSC_VER) && defined(_X86_)
  92570. /* OPT: an MSVC built-in would be better */
  92571. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92572. {
  92573. __asm {
  92574. mov edx, start
  92575. mov ecx, len
  92576. test ecx, ecx
  92577. loop1:
  92578. jz done1
  92579. mov eax, [edx]
  92580. bswap eax
  92581. mov [edx], eax
  92582. add edx, 4
  92583. dec ecx
  92584. jmp short loop1
  92585. done1:
  92586. }
  92587. }
  92588. #endif
  92589. /** \mainpage
  92590. *
  92591. * \section intro Introduction
  92592. *
  92593. * This is the documentation for the FLAC C and C++ APIs. It is
  92594. * highly interconnected; this introduction should give you a top
  92595. * level idea of the structure and how to find the information you
  92596. * need. As a prerequisite you should have at least a basic
  92597. * knowledge of the FLAC format, documented
  92598. * <A HREF="../format.html">here</A>.
  92599. *
  92600. * \section c_api FLAC C API
  92601. *
  92602. * The FLAC C API is the interface to libFLAC, a set of structures
  92603. * describing the components of FLAC streams, and functions for
  92604. * encoding and decoding streams, as well as manipulating FLAC
  92605. * metadata in files. The public include files will be installed
  92606. * in your include area (for example /usr/include/FLAC/...).
  92607. *
  92608. * By writing a little code and linking against libFLAC, it is
  92609. * relatively easy to add FLAC support to another program. The
  92610. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92611. * Complete source code of libFLAC as well as the command-line
  92612. * encoder and plugins is available and is a useful source of
  92613. * examples.
  92614. *
  92615. * Aside from encoders and decoders, libFLAC provides a powerful
  92616. * metadata interface for manipulating metadata in FLAC files. It
  92617. * allows the user to add, delete, and modify FLAC metadata blocks
  92618. * and it can automatically take advantage of PADDING blocks to avoid
  92619. * rewriting the entire FLAC file when changing the size of the
  92620. * metadata.
  92621. *
  92622. * libFLAC usually only requires the standard C library and C math
  92623. * library. In particular, threading is not used so there is no
  92624. * dependency on a thread library. However, libFLAC does not use
  92625. * global variables and should be thread-safe.
  92626. *
  92627. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92628. * However the metadata editing interfaces currently have limited
  92629. * read-only support for Ogg FLAC files.
  92630. *
  92631. * \section cpp_api FLAC C++ API
  92632. *
  92633. * The FLAC C++ API is a set of classes that encapsulate the
  92634. * structures and functions in libFLAC. They provide slightly more
  92635. * functionality with respect to metadata but are otherwise
  92636. * equivalent. For the most part, they share the same usage as
  92637. * their counterparts in libFLAC, and the FLAC C API documentation
  92638. * can be used as a supplement. The public include files
  92639. * for the C++ API will be installed in your include area (for
  92640. * example /usr/include/FLAC++/...).
  92641. *
  92642. * libFLAC++ is also licensed under
  92643. * <A HREF="../license.html">Xiph's BSD license</A>.
  92644. *
  92645. * \section getting_started Getting Started
  92646. *
  92647. * A good starting point for learning the API is to browse through
  92648. * the <A HREF="modules.html">modules</A>. Modules are logical
  92649. * groupings of related functions or classes, which correspond roughly
  92650. * to header files or sections of header files. Each module includes a
  92651. * detailed description of the general usage of its functions or
  92652. * classes.
  92653. *
  92654. * From there you can go on to look at the documentation of
  92655. * individual functions. You can see different views of the individual
  92656. * functions through the links in top bar across this page.
  92657. *
  92658. * If you prefer a more hands-on approach, you can jump right to some
  92659. * <A HREF="../documentation_example_code.html">example code</A>.
  92660. *
  92661. * \section porting_guide Porting Guide
  92662. *
  92663. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92664. * has been introduced which gives detailed instructions on how to
  92665. * port your code to newer versions of FLAC.
  92666. *
  92667. * \section embedded_developers Embedded Developers
  92668. *
  92669. * libFLAC has grown larger over time as more functionality has been
  92670. * included, but much of it may be unnecessary for a particular embedded
  92671. * implementation. Unused parts may be pruned by some simple editing of
  92672. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92673. * metadata interface are all independent from each other.
  92674. *
  92675. * It is easiest to just describe the dependencies:
  92676. *
  92677. * - All modules depend on the \link flac_format Format \endlink module.
  92678. * - The decoders and encoders depend on the bitbuffer.
  92679. * - The decoder is independent of the encoder. The encoder uses the
  92680. * decoder because of the verify feature, but this can be removed if
  92681. * not needed.
  92682. * - Parts of the metadata interface require the stream decoder (but not
  92683. * the encoder).
  92684. * - Ogg support is selectable through the compile time macro
  92685. * \c FLAC__HAS_OGG.
  92686. *
  92687. * For example, if your application only requires the stream decoder, no
  92688. * encoder, and no metadata interface, you can remove the stream encoder
  92689. * and the metadata interface, which will greatly reduce the size of the
  92690. * library.
  92691. *
  92692. * Also, there are several places in the libFLAC code with comments marked
  92693. * with "OPT:" where a #define can be changed to enable code that might be
  92694. * faster on a specific platform. Experimenting with these can yield faster
  92695. * binaries.
  92696. */
  92697. /** \defgroup porting Porting Guide for New Versions
  92698. *
  92699. * This module describes differences in the library interfaces from
  92700. * version to version. It assists in the porting of code that uses
  92701. * the libraries to newer versions of FLAC.
  92702. *
  92703. * One simple facility for making porting easier that has been added
  92704. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92705. * library's includes (e.g. \c include/FLAC/export.h). The
  92706. * \c #defines mirror the libraries'
  92707. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92708. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92709. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92710. * These can be used to support multiple versions of an API during the
  92711. * transition phase, e.g.
  92712. *
  92713. * \code
  92714. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92715. * legacy code
  92716. * #else
  92717. * new code
  92718. * #endif
  92719. * \endcode
  92720. *
  92721. * The the source will work for multiple versions and the legacy code can
  92722. * easily be removed when the transition is complete.
  92723. *
  92724. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92725. * include/FLAC/export.h), which can be used to determine whether or not
  92726. * the library has been compiled with support for Ogg FLAC. This is
  92727. * simpler than trying to call an Ogg init function and catching the
  92728. * error.
  92729. */
  92730. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92731. * \ingroup porting
  92732. *
  92733. * \brief
  92734. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92735. *
  92736. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92737. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92738. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92739. * decoding layers and three encoding layers have been merged into a
  92740. * single stream decoder and stream encoder. That is, the functionality
  92741. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92742. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92743. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92744. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92745. * is there is now a single API that can be used to encode or decode
  92746. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92747. * on both seekable and non-seekable streams.
  92748. *
  92749. * Instead of creating an encoder or decoder of a certain layer, now the
  92750. * client will always create a FLAC__StreamEncoder or
  92751. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92752. * initialization function. For example, for the decoder,
  92753. * FLAC__stream_decoder_init() has been replaced by
  92754. * FLAC__stream_decoder_init_stream(). This init function takes
  92755. * callbacks for the I/O, and the seeking callbacks are optional. This
  92756. * allows the client to use the same object for seekable and
  92757. * non-seekable streams. For decoding a FLAC file directly, the client
  92758. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92759. * and fewer callbacks; most of the other callbacks are supplied
  92760. * internally. For situations where fopen()ing by filename is not
  92761. * possible (e.g. Unicode filenames on Windows) the client can instead
  92762. * open the file itself and supply the FILE* to
  92763. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92764. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92765. * Since the callbacks and client data are now passed to the init
  92766. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92767. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92768. * rest of the calls to the decoder are the same as before.
  92769. *
  92770. * There are counterpart init functions for Ogg FLAC, e.g.
  92771. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92772. * and callbacks are the same as for native FLAC.
  92773. *
  92774. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92775. * been set up like so:
  92776. *
  92777. * \code
  92778. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92779. * if(decoder == NULL) do_something;
  92780. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92781. * [... other settings ...]
  92782. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92783. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92784. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92785. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92786. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92787. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92788. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92789. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92790. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92791. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92792. * \endcode
  92793. *
  92794. * In FLAC 1.1.3 it is like this:
  92795. *
  92796. * \code
  92797. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92798. * if(decoder == NULL) do_something;
  92799. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92800. * [... other settings ...]
  92801. * if(FLAC__stream_decoder_init_stream(
  92802. * decoder,
  92803. * my_read_callback,
  92804. * my_seek_callback, // or NULL
  92805. * my_tell_callback, // or NULL
  92806. * my_length_callback, // or NULL
  92807. * my_eof_callback, // or NULL
  92808. * my_write_callback,
  92809. * my_metadata_callback, // or NULL
  92810. * my_error_callback,
  92811. * my_client_data
  92812. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92813. * \endcode
  92814. *
  92815. * or you could do;
  92816. *
  92817. * \code
  92818. * [...]
  92819. * FILE *file = fopen("somefile.flac","rb");
  92820. * if(file == NULL) do_somthing;
  92821. * if(FLAC__stream_decoder_init_FILE(
  92822. * decoder,
  92823. * file,
  92824. * my_write_callback,
  92825. * my_metadata_callback, // or NULL
  92826. * my_error_callback,
  92827. * my_client_data
  92828. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92829. * \endcode
  92830. *
  92831. * or just:
  92832. *
  92833. * \code
  92834. * [...]
  92835. * if(FLAC__stream_decoder_init_file(
  92836. * decoder,
  92837. * "somefile.flac",
  92838. * my_write_callback,
  92839. * my_metadata_callback, // or NULL
  92840. * my_error_callback,
  92841. * my_client_data
  92842. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92843. * \endcode
  92844. *
  92845. * Another small change to the decoder is in how it handles unparseable
  92846. * streams. Before, when the decoder found an unparseable stream
  92847. * (reserved for when the decoder encounters a stream from a future
  92848. * encoder that it can't parse), it changed the state to
  92849. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92850. * drops sync and calls the error callback with a new error code
  92851. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92852. * more robust. If your error callback does not discriminate on the the
  92853. * error state, your code does not need to be changed.
  92854. *
  92855. * The encoder now has a new setting:
  92856. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92857. * method used to window the data before LPC analysis. You only need to
  92858. * add a call to this function if the default is not suitable. There
  92859. * are also two new convenience functions that may be useful:
  92860. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92861. * FLAC__metadata_get_cuesheet().
  92862. *
  92863. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92864. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92865. * is now \c size_t instead of \c unsigned.
  92866. */
  92867. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92868. * \ingroup porting
  92869. *
  92870. * \brief
  92871. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92872. *
  92873. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92874. * There was a slight change in the implementation of
  92875. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92876. * of the \a metadata array of pointers so the client no longer needs
  92877. * to maintain it after the call. The objects themselves that are
  92878. * pointed to by the array are still not copied though and must be
  92879. * maintained until the call to FLAC__stream_encoder_finish().
  92880. */
  92881. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92882. * \ingroup porting
  92883. *
  92884. * \brief
  92885. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92886. *
  92887. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92888. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92889. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92890. *
  92891. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92892. * has changed to reflect the conversion of one of the reserved bits
  92893. * into active use. It used to be \c 2 and now is \c 1. However the
  92894. * FLAC frame header length has not changed, so to skip the proper
  92895. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92896. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92897. */
  92898. /** \defgroup flac FLAC C API
  92899. *
  92900. * The FLAC C API is the interface to libFLAC, a set of structures
  92901. * describing the components of FLAC streams, and functions for
  92902. * encoding and decoding streams, as well as manipulating FLAC
  92903. * metadata in files.
  92904. *
  92905. * You should start with the format components as all other modules
  92906. * are dependent on it.
  92907. */
  92908. #endif
  92909. /*** End of inlined file: all.h ***/
  92910. /*** Start of inlined file: bitmath.c ***/
  92911. /*** Start of inlined file: juce_FlacHeader.h ***/
  92912. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92913. // tasks..
  92914. #define VERSION "1.2.1"
  92915. #define FLAC__NO_DLL 1
  92916. #if JUCE_MSVC
  92917. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92918. #endif
  92919. #if JUCE_MAC
  92920. #define FLAC__SYS_DARWIN 1
  92921. #endif
  92922. /*** End of inlined file: juce_FlacHeader.h ***/
  92923. #if JUCE_USE_FLAC
  92924. #if HAVE_CONFIG_H
  92925. # include <config.h>
  92926. #endif
  92927. /*** Start of inlined file: bitmath.h ***/
  92928. #ifndef FLAC__PRIVATE__BITMATH_H
  92929. #define FLAC__PRIVATE__BITMATH_H
  92930. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92931. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92932. unsigned FLAC__bitmath_silog2(int v);
  92933. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92934. #endif
  92935. /*** End of inlined file: bitmath.h ***/
  92936. /* An example of what FLAC__bitmath_ilog2() computes:
  92937. *
  92938. * ilog2( 0) = assertion failure
  92939. * ilog2( 1) = 0
  92940. * ilog2( 2) = 1
  92941. * ilog2( 3) = 1
  92942. * ilog2( 4) = 2
  92943. * ilog2( 5) = 2
  92944. * ilog2( 6) = 2
  92945. * ilog2( 7) = 2
  92946. * ilog2( 8) = 3
  92947. * ilog2( 9) = 3
  92948. * ilog2(10) = 3
  92949. * ilog2(11) = 3
  92950. * ilog2(12) = 3
  92951. * ilog2(13) = 3
  92952. * ilog2(14) = 3
  92953. * ilog2(15) = 3
  92954. * ilog2(16) = 4
  92955. * ilog2(17) = 4
  92956. * ilog2(18) = 4
  92957. */
  92958. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92959. {
  92960. unsigned l = 0;
  92961. FLAC__ASSERT(v > 0);
  92962. while(v >>= 1)
  92963. l++;
  92964. return l;
  92965. }
  92966. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92967. {
  92968. unsigned l = 0;
  92969. FLAC__ASSERT(v > 0);
  92970. while(v >>= 1)
  92971. l++;
  92972. return l;
  92973. }
  92974. /* An example of what FLAC__bitmath_silog2() computes:
  92975. *
  92976. * silog2(-10) = 5
  92977. * silog2(- 9) = 5
  92978. * silog2(- 8) = 4
  92979. * silog2(- 7) = 4
  92980. * silog2(- 6) = 4
  92981. * silog2(- 5) = 4
  92982. * silog2(- 4) = 3
  92983. * silog2(- 3) = 3
  92984. * silog2(- 2) = 2
  92985. * silog2(- 1) = 2
  92986. * silog2( 0) = 0
  92987. * silog2( 1) = 2
  92988. * silog2( 2) = 3
  92989. * silog2( 3) = 3
  92990. * silog2( 4) = 4
  92991. * silog2( 5) = 4
  92992. * silog2( 6) = 4
  92993. * silog2( 7) = 4
  92994. * silog2( 8) = 5
  92995. * silog2( 9) = 5
  92996. * silog2( 10) = 5
  92997. */
  92998. unsigned FLAC__bitmath_silog2(int v)
  92999. {
  93000. while(1) {
  93001. if(v == 0) {
  93002. return 0;
  93003. }
  93004. else if(v > 0) {
  93005. unsigned l = 0;
  93006. while(v) {
  93007. l++;
  93008. v >>= 1;
  93009. }
  93010. return l+1;
  93011. }
  93012. else if(v == -1) {
  93013. return 2;
  93014. }
  93015. else {
  93016. v++;
  93017. v = -v;
  93018. }
  93019. }
  93020. }
  93021. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93022. {
  93023. while(1) {
  93024. if(v == 0) {
  93025. return 0;
  93026. }
  93027. else if(v > 0) {
  93028. unsigned l = 0;
  93029. while(v) {
  93030. l++;
  93031. v >>= 1;
  93032. }
  93033. return l+1;
  93034. }
  93035. else if(v == -1) {
  93036. return 2;
  93037. }
  93038. else {
  93039. v++;
  93040. v = -v;
  93041. }
  93042. }
  93043. }
  93044. #endif
  93045. /*** End of inlined file: bitmath.c ***/
  93046. /*** Start of inlined file: bitreader.c ***/
  93047. /*** Start of inlined file: juce_FlacHeader.h ***/
  93048. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93049. // tasks..
  93050. #define VERSION "1.2.1"
  93051. #define FLAC__NO_DLL 1
  93052. #if JUCE_MSVC
  93053. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93054. #endif
  93055. #if JUCE_MAC
  93056. #define FLAC__SYS_DARWIN 1
  93057. #endif
  93058. /*** End of inlined file: juce_FlacHeader.h ***/
  93059. #if JUCE_USE_FLAC
  93060. #if HAVE_CONFIG_H
  93061. # include <config.h>
  93062. #endif
  93063. #include <stdlib.h> /* for malloc() */
  93064. #include <string.h> /* for memcpy(), memset() */
  93065. #ifdef _MSC_VER
  93066. #include <winsock.h> /* for ntohl() */
  93067. #elif defined FLAC__SYS_DARWIN
  93068. #include <machine/endian.h> /* for ntohl() */
  93069. #elif defined __MINGW32__
  93070. #include <winsock.h> /* for ntohl() */
  93071. #else
  93072. #include <netinet/in.h> /* for ntohl() */
  93073. #endif
  93074. /*** Start of inlined file: bitreader.h ***/
  93075. #ifndef FLAC__PRIVATE__BITREADER_H
  93076. #define FLAC__PRIVATE__BITREADER_H
  93077. #include <stdio.h> /* for FILE */
  93078. /*** Start of inlined file: cpu.h ***/
  93079. #ifndef FLAC__PRIVATE__CPU_H
  93080. #define FLAC__PRIVATE__CPU_H
  93081. #ifdef HAVE_CONFIG_H
  93082. #include <config.h>
  93083. #endif
  93084. typedef enum {
  93085. FLAC__CPUINFO_TYPE_IA32,
  93086. FLAC__CPUINFO_TYPE_PPC,
  93087. FLAC__CPUINFO_TYPE_UNKNOWN
  93088. } FLAC__CPUInfo_Type;
  93089. typedef struct {
  93090. FLAC__bool cpuid;
  93091. FLAC__bool bswap;
  93092. FLAC__bool cmov;
  93093. FLAC__bool mmx;
  93094. FLAC__bool fxsr;
  93095. FLAC__bool sse;
  93096. FLAC__bool sse2;
  93097. FLAC__bool sse3;
  93098. FLAC__bool ssse3;
  93099. FLAC__bool _3dnow;
  93100. FLAC__bool ext3dnow;
  93101. FLAC__bool extmmx;
  93102. } FLAC__CPUInfo_IA32;
  93103. typedef struct {
  93104. FLAC__bool altivec;
  93105. FLAC__bool ppc64;
  93106. } FLAC__CPUInfo_PPC;
  93107. typedef struct {
  93108. FLAC__bool use_asm;
  93109. FLAC__CPUInfo_Type type;
  93110. union {
  93111. FLAC__CPUInfo_IA32 ia32;
  93112. FLAC__CPUInfo_PPC ppc;
  93113. } data;
  93114. } FLAC__CPUInfo;
  93115. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93116. #ifndef FLAC__NO_ASM
  93117. #ifdef FLAC__CPU_IA32
  93118. #ifdef FLAC__HAS_NASM
  93119. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93120. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93121. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93122. #endif
  93123. #endif
  93124. #endif
  93125. #endif
  93126. /*** End of inlined file: cpu.h ***/
  93127. /*
  93128. * opaque structure definition
  93129. */
  93130. struct FLAC__BitReader;
  93131. typedef struct FLAC__BitReader FLAC__BitReader;
  93132. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93133. /*
  93134. * construction, deletion, initialization, etc functions
  93135. */
  93136. FLAC__BitReader *FLAC__bitreader_new(void);
  93137. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93138. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93139. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93140. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93141. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93142. /*
  93143. * CRC functions
  93144. */
  93145. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93146. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93147. /*
  93148. * info functions
  93149. */
  93150. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93151. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93152. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93153. /*
  93154. * read functions
  93155. */
  93156. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93157. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93158. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93159. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93160. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93161. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93162. 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! */
  93163. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93164. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93165. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93166. #ifndef FLAC__NO_ASM
  93167. # ifdef FLAC__CPU_IA32
  93168. # ifdef FLAC__HAS_NASM
  93169. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93170. # endif
  93171. # endif
  93172. #endif
  93173. #if 0 /* UNUSED */
  93174. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93175. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93176. #endif
  93177. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93178. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93179. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93180. #endif
  93181. /*** End of inlined file: bitreader.h ***/
  93182. /*** Start of inlined file: crc.h ***/
  93183. #ifndef FLAC__PRIVATE__CRC_H
  93184. #define FLAC__PRIVATE__CRC_H
  93185. /* 8 bit CRC generator, MSB shifted first
  93186. ** polynomial = x^8 + x^2 + x^1 + x^0
  93187. ** init = 0
  93188. */
  93189. extern FLAC__byte const FLAC__crc8_table[256];
  93190. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93191. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93192. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93193. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93194. /* 16 bit CRC generator, MSB shifted first
  93195. ** polynomial = x^16 + x^15 + x^2 + x^0
  93196. ** init = 0
  93197. */
  93198. extern unsigned FLAC__crc16_table[256];
  93199. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93200. /* this alternate may be faster on some systems/compilers */
  93201. #if 0
  93202. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93203. #endif
  93204. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93205. #endif
  93206. /*** End of inlined file: crc.h ***/
  93207. /* Things should be fastest when this matches the machine word size */
  93208. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93209. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93210. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93211. typedef FLAC__uint32 brword;
  93212. #define FLAC__BYTES_PER_WORD 4
  93213. #define FLAC__BITS_PER_WORD 32
  93214. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93215. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93216. #if WORDS_BIGENDIAN
  93217. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93218. #else
  93219. #if defined (_MSC_VER) && defined (_X86_)
  93220. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93221. #else
  93222. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93223. #endif
  93224. #endif
  93225. /* counts the # of zero MSBs in a word */
  93226. #define COUNT_ZERO_MSBS(word) ( \
  93227. (word) <= 0xffff ? \
  93228. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93229. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93230. )
  93231. /* this alternate might be slightly faster on some systems/compilers: */
  93232. #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])) )
  93233. /*
  93234. * This should be at least twice as large as the largest number of words
  93235. * required to represent any 'number' (in any encoding) you are going to
  93236. * read. With FLAC this is on the order of maybe a few hundred bits.
  93237. * If the buffer is smaller than that, the decoder won't be able to read
  93238. * in a whole number that is in a variable length encoding (e.g. Rice).
  93239. * But to be practical it should be at least 1K bytes.
  93240. *
  93241. * Increase this number to decrease the number of read callbacks, at the
  93242. * expense of using more memory. Or decrease for the reverse effect,
  93243. * keeping in mind the limit from the first paragraph. The optimal size
  93244. * also depends on the CPU cache size and other factors; some twiddling
  93245. * may be necessary to squeeze out the best performance.
  93246. */
  93247. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93248. static const unsigned char byte_to_unary_table[] = {
  93249. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93250. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93251. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93252. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93253. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93254. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93255. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93256. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93265. };
  93266. #ifdef min
  93267. #undef min
  93268. #endif
  93269. #define min(x,y) ((x)<(y)?(x):(y))
  93270. #ifdef max
  93271. #undef max
  93272. #endif
  93273. #define max(x,y) ((x)>(y)?(x):(y))
  93274. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93275. #ifdef _MSC_VER
  93276. #define FLAC__U64L(x) x
  93277. #else
  93278. #define FLAC__U64L(x) x##LLU
  93279. #endif
  93280. #ifndef FLaC__INLINE
  93281. #define FLaC__INLINE
  93282. #endif
  93283. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93284. struct FLAC__BitReader {
  93285. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93286. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93287. brword *buffer;
  93288. unsigned capacity; /* in words */
  93289. unsigned words; /* # of completed words in buffer */
  93290. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93291. unsigned consumed_words; /* #words ... */
  93292. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93293. unsigned read_crc16; /* the running frame CRC */
  93294. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93295. FLAC__BitReaderReadCallback read_callback;
  93296. void *client_data;
  93297. FLAC__CPUInfo cpu_info;
  93298. };
  93299. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93300. {
  93301. register unsigned crc = br->read_crc16;
  93302. #if FLAC__BYTES_PER_WORD == 4
  93303. switch(br->crc16_align) {
  93304. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93305. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93306. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93307. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93308. }
  93309. #elif FLAC__BYTES_PER_WORD == 8
  93310. switch(br->crc16_align) {
  93311. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93312. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93313. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93314. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93315. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93316. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93317. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93318. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93319. }
  93320. #else
  93321. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93322. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93323. br->read_crc16 = crc;
  93324. #endif
  93325. br->crc16_align = 0;
  93326. }
  93327. /* would be static except it needs to be called by asm routines */
  93328. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93329. {
  93330. unsigned start, end;
  93331. size_t bytes;
  93332. FLAC__byte *target;
  93333. /* first shift the unconsumed buffer data toward the front as much as possible */
  93334. if(br->consumed_words > 0) {
  93335. start = br->consumed_words;
  93336. end = br->words + (br->bytes? 1:0);
  93337. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93338. br->words -= start;
  93339. br->consumed_words = 0;
  93340. }
  93341. /*
  93342. * set the target for reading, taking into account word alignment and endianness
  93343. */
  93344. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93345. if(bytes == 0)
  93346. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93347. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93348. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93349. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93350. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93351. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93352. * ^^-------target, bytes=3
  93353. * on LE machines, have to byteswap the odd tail word so nothing is
  93354. * overwritten:
  93355. */
  93356. #if WORDS_BIGENDIAN
  93357. #else
  93358. if(br->bytes)
  93359. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93360. #endif
  93361. /* now it looks like:
  93362. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93363. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93364. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93365. * ^^-------target, bytes=3
  93366. */
  93367. /* read in the data; note that the callback may return a smaller number of bytes */
  93368. if(!br->read_callback(target, &bytes, br->client_data))
  93369. return false;
  93370. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93371. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93372. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93373. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93374. * now have to byteswap on LE machines:
  93375. */
  93376. #if WORDS_BIGENDIAN
  93377. #else
  93378. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93379. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93380. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93381. start = br->words;
  93382. local_swap32_block_(br->buffer + start, end - start);
  93383. }
  93384. else
  93385. # endif
  93386. for(start = br->words; start < end; start++)
  93387. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93388. #endif
  93389. /* now it looks like:
  93390. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93391. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93392. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93393. * finally we'll update the reader values:
  93394. */
  93395. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93396. br->words = end / FLAC__BYTES_PER_WORD;
  93397. br->bytes = end % FLAC__BYTES_PER_WORD;
  93398. return true;
  93399. }
  93400. /***********************************************************************
  93401. *
  93402. * Class constructor/destructor
  93403. *
  93404. ***********************************************************************/
  93405. FLAC__BitReader *FLAC__bitreader_new(void)
  93406. {
  93407. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93408. /* calloc() implies:
  93409. memset(br, 0, sizeof(FLAC__BitReader));
  93410. br->buffer = 0;
  93411. br->capacity = 0;
  93412. br->words = br->bytes = 0;
  93413. br->consumed_words = br->consumed_bits = 0;
  93414. br->read_callback = 0;
  93415. br->client_data = 0;
  93416. */
  93417. return br;
  93418. }
  93419. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93420. {
  93421. FLAC__ASSERT(0 != br);
  93422. FLAC__bitreader_free(br);
  93423. free(br);
  93424. }
  93425. /***********************************************************************
  93426. *
  93427. * Public class methods
  93428. *
  93429. ***********************************************************************/
  93430. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93431. {
  93432. FLAC__ASSERT(0 != br);
  93433. br->words = br->bytes = 0;
  93434. br->consumed_words = br->consumed_bits = 0;
  93435. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93436. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93437. if(br->buffer == 0)
  93438. return false;
  93439. br->read_callback = rcb;
  93440. br->client_data = cd;
  93441. br->cpu_info = cpu;
  93442. return true;
  93443. }
  93444. void FLAC__bitreader_free(FLAC__BitReader *br)
  93445. {
  93446. FLAC__ASSERT(0 != br);
  93447. if(0 != br->buffer)
  93448. free(br->buffer);
  93449. br->buffer = 0;
  93450. br->capacity = 0;
  93451. br->words = br->bytes = 0;
  93452. br->consumed_words = br->consumed_bits = 0;
  93453. br->read_callback = 0;
  93454. br->client_data = 0;
  93455. }
  93456. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93457. {
  93458. br->words = br->bytes = 0;
  93459. br->consumed_words = br->consumed_bits = 0;
  93460. return true;
  93461. }
  93462. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93463. {
  93464. unsigned i, j;
  93465. if(br == 0) {
  93466. fprintf(out, "bitreader is NULL\n");
  93467. }
  93468. else {
  93469. 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);
  93470. for(i = 0; i < br->words; i++) {
  93471. fprintf(out, "%08X: ", i);
  93472. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93473. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93474. fprintf(out, ".");
  93475. else
  93476. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93477. fprintf(out, "\n");
  93478. }
  93479. if(br->bytes > 0) {
  93480. fprintf(out, "%08X: ", i);
  93481. for(j = 0; j < br->bytes*8; j++)
  93482. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93483. fprintf(out, ".");
  93484. else
  93485. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93486. fprintf(out, "\n");
  93487. }
  93488. }
  93489. }
  93490. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93491. {
  93492. FLAC__ASSERT(0 != br);
  93493. FLAC__ASSERT(0 != br->buffer);
  93494. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93495. br->read_crc16 = (unsigned)seed;
  93496. br->crc16_align = br->consumed_bits;
  93497. }
  93498. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93499. {
  93500. FLAC__ASSERT(0 != br);
  93501. FLAC__ASSERT(0 != br->buffer);
  93502. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93503. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93504. /* CRC any tail bytes in a partially-consumed word */
  93505. if(br->consumed_bits) {
  93506. const brword tail = br->buffer[br->consumed_words];
  93507. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93508. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93509. }
  93510. return br->read_crc16;
  93511. }
  93512. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93513. {
  93514. return ((br->consumed_bits & 7) == 0);
  93515. }
  93516. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93517. {
  93518. return 8 - (br->consumed_bits & 7);
  93519. }
  93520. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93521. {
  93522. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93523. }
  93524. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93525. {
  93526. FLAC__ASSERT(0 != br);
  93527. FLAC__ASSERT(0 != br->buffer);
  93528. FLAC__ASSERT(bits <= 32);
  93529. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93530. FLAC__ASSERT(br->consumed_words <= br->words);
  93531. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93532. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93533. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93534. *val = 0;
  93535. return true;
  93536. }
  93537. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93538. if(!bitreader_read_from_client_(br))
  93539. return false;
  93540. }
  93541. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93542. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93543. if(br->consumed_bits) {
  93544. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93545. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93546. const brword word = br->buffer[br->consumed_words];
  93547. if(bits < n) {
  93548. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93549. br->consumed_bits += bits;
  93550. return true;
  93551. }
  93552. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93553. bits -= n;
  93554. crc16_update_word_(br, word);
  93555. br->consumed_words++;
  93556. br->consumed_bits = 0;
  93557. 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 */
  93558. *val <<= bits;
  93559. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93560. br->consumed_bits = bits;
  93561. }
  93562. return true;
  93563. }
  93564. else {
  93565. const brword word = br->buffer[br->consumed_words];
  93566. if(bits < FLAC__BITS_PER_WORD) {
  93567. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93568. br->consumed_bits = bits;
  93569. return true;
  93570. }
  93571. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93572. *val = word;
  93573. crc16_update_word_(br, word);
  93574. br->consumed_words++;
  93575. return true;
  93576. }
  93577. }
  93578. else {
  93579. /* in this case we're starting our read at a partial tail word;
  93580. * the reader has guaranteed that we have at least 'bits' bits
  93581. * available to read, which makes this case simpler.
  93582. */
  93583. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93584. if(br->consumed_bits) {
  93585. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93586. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93587. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93588. br->consumed_bits += bits;
  93589. return true;
  93590. }
  93591. else {
  93592. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93593. br->consumed_bits += bits;
  93594. return true;
  93595. }
  93596. }
  93597. }
  93598. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93599. {
  93600. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93601. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93602. return false;
  93603. /* sign-extend: */
  93604. *val <<= (32-bits);
  93605. *val >>= (32-bits);
  93606. return true;
  93607. }
  93608. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93609. {
  93610. FLAC__uint32 hi, lo;
  93611. if(bits > 32) {
  93612. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93613. return false;
  93614. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93615. return false;
  93616. *val = hi;
  93617. *val <<= 32;
  93618. *val |= lo;
  93619. }
  93620. else {
  93621. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93622. return false;
  93623. *val = lo;
  93624. }
  93625. return true;
  93626. }
  93627. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93628. {
  93629. FLAC__uint32 x8, x32 = 0;
  93630. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93631. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93632. return false;
  93633. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93634. return false;
  93635. x32 |= (x8 << 8);
  93636. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93637. return false;
  93638. x32 |= (x8 << 16);
  93639. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93640. return false;
  93641. x32 |= (x8 << 24);
  93642. *val = x32;
  93643. return true;
  93644. }
  93645. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93646. {
  93647. /*
  93648. * OPT: a faster implementation is possible but probably not that useful
  93649. * since this is only called a couple of times in the metadata readers.
  93650. */
  93651. FLAC__ASSERT(0 != br);
  93652. FLAC__ASSERT(0 != br->buffer);
  93653. if(bits > 0) {
  93654. const unsigned n = br->consumed_bits & 7;
  93655. unsigned m;
  93656. FLAC__uint32 x;
  93657. if(n != 0) {
  93658. m = min(8-n, bits);
  93659. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93660. return false;
  93661. bits -= m;
  93662. }
  93663. m = bits / 8;
  93664. if(m > 0) {
  93665. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93666. return false;
  93667. bits %= 8;
  93668. }
  93669. if(bits > 0) {
  93670. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93671. return false;
  93672. }
  93673. }
  93674. return true;
  93675. }
  93676. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93677. {
  93678. FLAC__uint32 x;
  93679. FLAC__ASSERT(0 != br);
  93680. FLAC__ASSERT(0 != br->buffer);
  93681. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93682. /* step 1: skip over partial head word to get word aligned */
  93683. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93684. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93685. return false;
  93686. nvals--;
  93687. }
  93688. if(0 == nvals)
  93689. return true;
  93690. /* step 2: skip whole words in chunks */
  93691. while(nvals >= FLAC__BYTES_PER_WORD) {
  93692. if(br->consumed_words < br->words) {
  93693. br->consumed_words++;
  93694. nvals -= FLAC__BYTES_PER_WORD;
  93695. }
  93696. else if(!bitreader_read_from_client_(br))
  93697. return false;
  93698. }
  93699. /* step 3: skip any remainder from partial tail bytes */
  93700. while(nvals) {
  93701. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93702. return false;
  93703. nvals--;
  93704. }
  93705. return true;
  93706. }
  93707. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93708. {
  93709. FLAC__uint32 x;
  93710. FLAC__ASSERT(0 != br);
  93711. FLAC__ASSERT(0 != br->buffer);
  93712. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93713. /* step 1: read from partial head word to get word aligned */
  93714. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93715. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93716. return false;
  93717. *val++ = (FLAC__byte)x;
  93718. nvals--;
  93719. }
  93720. if(0 == nvals)
  93721. return true;
  93722. /* step 2: read whole words in chunks */
  93723. while(nvals >= FLAC__BYTES_PER_WORD) {
  93724. if(br->consumed_words < br->words) {
  93725. const brword word = br->buffer[br->consumed_words++];
  93726. #if FLAC__BYTES_PER_WORD == 4
  93727. val[0] = (FLAC__byte)(word >> 24);
  93728. val[1] = (FLAC__byte)(word >> 16);
  93729. val[2] = (FLAC__byte)(word >> 8);
  93730. val[3] = (FLAC__byte)word;
  93731. #elif FLAC__BYTES_PER_WORD == 8
  93732. val[0] = (FLAC__byte)(word >> 56);
  93733. val[1] = (FLAC__byte)(word >> 48);
  93734. val[2] = (FLAC__byte)(word >> 40);
  93735. val[3] = (FLAC__byte)(word >> 32);
  93736. val[4] = (FLAC__byte)(word >> 24);
  93737. val[5] = (FLAC__byte)(word >> 16);
  93738. val[6] = (FLAC__byte)(word >> 8);
  93739. val[7] = (FLAC__byte)word;
  93740. #else
  93741. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93742. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93743. #endif
  93744. val += FLAC__BYTES_PER_WORD;
  93745. nvals -= FLAC__BYTES_PER_WORD;
  93746. }
  93747. else if(!bitreader_read_from_client_(br))
  93748. return false;
  93749. }
  93750. /* step 3: read any remainder from partial tail bytes */
  93751. while(nvals) {
  93752. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93753. return false;
  93754. *val++ = (FLAC__byte)x;
  93755. nvals--;
  93756. }
  93757. return true;
  93758. }
  93759. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93760. #if 0 /* slow but readable version */
  93761. {
  93762. unsigned bit;
  93763. FLAC__ASSERT(0 != br);
  93764. FLAC__ASSERT(0 != br->buffer);
  93765. *val = 0;
  93766. while(1) {
  93767. if(!FLAC__bitreader_read_bit(br, &bit))
  93768. return false;
  93769. if(bit)
  93770. break;
  93771. else
  93772. *val++;
  93773. }
  93774. return true;
  93775. }
  93776. #else
  93777. {
  93778. unsigned i;
  93779. FLAC__ASSERT(0 != br);
  93780. FLAC__ASSERT(0 != br->buffer);
  93781. *val = 0;
  93782. while(1) {
  93783. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93784. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93785. if(b) {
  93786. i = COUNT_ZERO_MSBS(b);
  93787. *val += i;
  93788. i++;
  93789. br->consumed_bits += i;
  93790. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93791. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93792. br->consumed_words++;
  93793. br->consumed_bits = 0;
  93794. }
  93795. return true;
  93796. }
  93797. else {
  93798. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93799. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93800. br->consumed_words++;
  93801. br->consumed_bits = 0;
  93802. /* didn't find stop bit yet, have to keep going... */
  93803. }
  93804. }
  93805. /* at this point we've eaten up all the whole words; have to try
  93806. * reading through any tail bytes before calling the read callback.
  93807. * this is a repeat of the above logic adjusted for the fact we
  93808. * don't have a whole word. note though if the client is feeding
  93809. * us data a byte at a time (unlikely), br->consumed_bits may not
  93810. * be zero.
  93811. */
  93812. if(br->bytes) {
  93813. const unsigned end = br->bytes * 8;
  93814. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93815. if(b) {
  93816. i = COUNT_ZERO_MSBS(b);
  93817. *val += i;
  93818. i++;
  93819. br->consumed_bits += i;
  93820. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93821. return true;
  93822. }
  93823. else {
  93824. *val += end - br->consumed_bits;
  93825. br->consumed_bits += end;
  93826. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93827. /* didn't find stop bit yet, have to keep going... */
  93828. }
  93829. }
  93830. if(!bitreader_read_from_client_(br))
  93831. return false;
  93832. }
  93833. }
  93834. #endif
  93835. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93836. {
  93837. FLAC__uint32 lsbs = 0, msbs = 0;
  93838. unsigned uval;
  93839. FLAC__ASSERT(0 != br);
  93840. FLAC__ASSERT(0 != br->buffer);
  93841. FLAC__ASSERT(parameter <= 31);
  93842. /* read the unary MSBs and end bit */
  93843. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93844. return false;
  93845. /* read the binary LSBs */
  93846. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93847. return false;
  93848. /* compose the value */
  93849. uval = (msbs << parameter) | lsbs;
  93850. if(uval & 1)
  93851. *val = -((int)(uval >> 1)) - 1;
  93852. else
  93853. *val = (int)(uval >> 1);
  93854. return true;
  93855. }
  93856. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93857. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93858. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93859. /* OPT: possibly faster version for use with MSVC */
  93860. #ifdef _MSC_VER
  93861. {
  93862. unsigned i;
  93863. unsigned uval = 0;
  93864. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93865. /* try and get br->consumed_words and br->consumed_bits into register;
  93866. * must remember to flush them back to *br before calling other
  93867. * bitwriter functions that use them, and before returning */
  93868. register unsigned cwords;
  93869. register unsigned cbits;
  93870. FLAC__ASSERT(0 != br);
  93871. FLAC__ASSERT(0 != br->buffer);
  93872. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93873. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93874. FLAC__ASSERT(parameter < 32);
  93875. /* 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 */
  93876. if(nvals == 0)
  93877. return true;
  93878. cbits = br->consumed_bits;
  93879. cwords = br->consumed_words;
  93880. while(1) {
  93881. /* read unary part */
  93882. while(1) {
  93883. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93884. brword b = br->buffer[cwords] << cbits;
  93885. if(b) {
  93886. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93887. __asm {
  93888. bsr eax, b
  93889. not eax
  93890. and eax, 31
  93891. mov i, eax
  93892. }
  93893. #else
  93894. i = COUNT_ZERO_MSBS(b);
  93895. #endif
  93896. uval += i;
  93897. bits = parameter;
  93898. i++;
  93899. cbits += i;
  93900. if(cbits == FLAC__BITS_PER_WORD) {
  93901. crc16_update_word_(br, br->buffer[cwords]);
  93902. cwords++;
  93903. cbits = 0;
  93904. }
  93905. goto break1;
  93906. }
  93907. else {
  93908. uval += FLAC__BITS_PER_WORD - cbits;
  93909. crc16_update_word_(br, br->buffer[cwords]);
  93910. cwords++;
  93911. cbits = 0;
  93912. /* didn't find stop bit yet, have to keep going... */
  93913. }
  93914. }
  93915. /* at this point we've eaten up all the whole words; have to try
  93916. * reading through any tail bytes before calling the read callback.
  93917. * this is a repeat of the above logic adjusted for the fact we
  93918. * don't have a whole word. note though if the client is feeding
  93919. * us data a byte at a time (unlikely), br->consumed_bits may not
  93920. * be zero.
  93921. */
  93922. if(br->bytes) {
  93923. const unsigned end = br->bytes * 8;
  93924. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93925. if(b) {
  93926. i = COUNT_ZERO_MSBS(b);
  93927. uval += i;
  93928. bits = parameter;
  93929. i++;
  93930. cbits += i;
  93931. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93932. goto break1;
  93933. }
  93934. else {
  93935. uval += end - cbits;
  93936. cbits += end;
  93937. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93938. /* didn't find stop bit yet, have to keep going... */
  93939. }
  93940. }
  93941. /* flush registers and read; bitreader_read_from_client_() does
  93942. * not touch br->consumed_bits at all but we still need to set
  93943. * it in case it fails and we have to return false.
  93944. */
  93945. br->consumed_bits = cbits;
  93946. br->consumed_words = cwords;
  93947. if(!bitreader_read_from_client_(br))
  93948. return false;
  93949. cwords = br->consumed_words;
  93950. }
  93951. break1:
  93952. /* read binary part */
  93953. FLAC__ASSERT(cwords <= br->words);
  93954. if(bits) {
  93955. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93956. /* flush registers and read; bitreader_read_from_client_() does
  93957. * not touch br->consumed_bits at all but we still need to set
  93958. * it in case it fails and we have to return false.
  93959. */
  93960. br->consumed_bits = cbits;
  93961. br->consumed_words = cwords;
  93962. if(!bitreader_read_from_client_(br))
  93963. return false;
  93964. cwords = br->consumed_words;
  93965. }
  93966. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93967. if(cbits) {
  93968. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93969. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93970. const brword word = br->buffer[cwords];
  93971. if(bits < n) {
  93972. uval <<= bits;
  93973. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93974. cbits += bits;
  93975. goto break2;
  93976. }
  93977. uval <<= n;
  93978. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93979. bits -= n;
  93980. crc16_update_word_(br, word);
  93981. cwords++;
  93982. cbits = 0;
  93983. 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 */
  93984. uval <<= bits;
  93985. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93986. cbits = bits;
  93987. }
  93988. goto break2;
  93989. }
  93990. else {
  93991. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93992. uval <<= bits;
  93993. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93994. cbits = bits;
  93995. goto break2;
  93996. }
  93997. }
  93998. else {
  93999. /* in this case we're starting our read at a partial tail word;
  94000. * the reader has guaranteed that we have at least 'bits' bits
  94001. * available to read, which makes this case simpler.
  94002. */
  94003. uval <<= bits;
  94004. if(cbits) {
  94005. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94006. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94007. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94008. cbits += bits;
  94009. goto break2;
  94010. }
  94011. else {
  94012. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94013. cbits += bits;
  94014. goto break2;
  94015. }
  94016. }
  94017. }
  94018. break2:
  94019. /* compose the value */
  94020. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94021. /* are we done? */
  94022. --nvals;
  94023. if(nvals == 0) {
  94024. br->consumed_bits = cbits;
  94025. br->consumed_words = cwords;
  94026. return true;
  94027. }
  94028. uval = 0;
  94029. ++vals;
  94030. }
  94031. }
  94032. #else
  94033. {
  94034. unsigned i;
  94035. unsigned uval = 0;
  94036. /* try and get br->consumed_words and br->consumed_bits into register;
  94037. * must remember to flush them back to *br before calling other
  94038. * bitwriter functions that use them, and before returning */
  94039. register unsigned cwords;
  94040. register unsigned cbits;
  94041. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94042. FLAC__ASSERT(0 != br);
  94043. FLAC__ASSERT(0 != br->buffer);
  94044. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94045. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94046. FLAC__ASSERT(parameter < 32);
  94047. /* 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 */
  94048. if(nvals == 0)
  94049. return true;
  94050. cbits = br->consumed_bits;
  94051. cwords = br->consumed_words;
  94052. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94053. while(1) {
  94054. /* read unary part */
  94055. while(1) {
  94056. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94057. brword b = br->buffer[cwords] << cbits;
  94058. if(b) {
  94059. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94060. asm volatile (
  94061. "bsrl %1, %0;"
  94062. "notl %0;"
  94063. "andl $31, %0;"
  94064. : "=r"(i)
  94065. : "r"(b)
  94066. );
  94067. #else
  94068. i = COUNT_ZERO_MSBS(b);
  94069. #endif
  94070. uval += i;
  94071. cbits += i;
  94072. cbits++; /* skip over stop bit */
  94073. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94074. crc16_update_word_(br, br->buffer[cwords]);
  94075. cwords++;
  94076. cbits = 0;
  94077. }
  94078. goto break1;
  94079. }
  94080. else {
  94081. uval += FLAC__BITS_PER_WORD - cbits;
  94082. crc16_update_word_(br, br->buffer[cwords]);
  94083. cwords++;
  94084. cbits = 0;
  94085. /* didn't find stop bit yet, have to keep going... */
  94086. }
  94087. }
  94088. /* at this point we've eaten up all the whole words; have to try
  94089. * reading through any tail bytes before calling the read callback.
  94090. * this is a repeat of the above logic adjusted for the fact we
  94091. * don't have a whole word. note though if the client is feeding
  94092. * us data a byte at a time (unlikely), br->consumed_bits may not
  94093. * be zero.
  94094. */
  94095. if(br->bytes) {
  94096. const unsigned end = br->bytes * 8;
  94097. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94098. if(b) {
  94099. i = COUNT_ZERO_MSBS(b);
  94100. uval += i;
  94101. cbits += i;
  94102. cbits++; /* skip over stop bit */
  94103. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94104. goto break1;
  94105. }
  94106. else {
  94107. uval += end - cbits;
  94108. cbits += end;
  94109. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94110. /* didn't find stop bit yet, have to keep going... */
  94111. }
  94112. }
  94113. /* flush registers and read; bitreader_read_from_client_() does
  94114. * not touch br->consumed_bits at all but we still need to set
  94115. * it in case it fails and we have to return false.
  94116. */
  94117. br->consumed_bits = cbits;
  94118. br->consumed_words = cwords;
  94119. if(!bitreader_read_from_client_(br))
  94120. return false;
  94121. cwords = br->consumed_words;
  94122. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94123. /* + uval to offset our count by the # of unary bits already
  94124. * consumed before the read, because we will add these back
  94125. * in all at once at break1
  94126. */
  94127. }
  94128. break1:
  94129. ucbits -= uval;
  94130. ucbits--; /* account for stop bit */
  94131. /* read binary part */
  94132. FLAC__ASSERT(cwords <= br->words);
  94133. if(parameter) {
  94134. while(ucbits < parameter) {
  94135. /* flush registers and read; bitreader_read_from_client_() does
  94136. * not touch br->consumed_bits at all but we still need to set
  94137. * it in case it fails and we have to return false.
  94138. */
  94139. br->consumed_bits = cbits;
  94140. br->consumed_words = cwords;
  94141. if(!bitreader_read_from_client_(br))
  94142. return false;
  94143. cwords = br->consumed_words;
  94144. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94145. }
  94146. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94147. if(cbits) {
  94148. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94149. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94150. const brword word = br->buffer[cwords];
  94151. if(parameter < n) {
  94152. uval <<= parameter;
  94153. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94154. cbits += parameter;
  94155. }
  94156. else {
  94157. uval <<= n;
  94158. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94159. crc16_update_word_(br, word);
  94160. cwords++;
  94161. cbits = parameter - n;
  94162. 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 */
  94163. uval <<= cbits;
  94164. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94165. }
  94166. }
  94167. }
  94168. else {
  94169. cbits = parameter;
  94170. uval <<= parameter;
  94171. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94172. }
  94173. }
  94174. else {
  94175. /* in this case we're starting our read at a partial tail word;
  94176. * the reader has guaranteed that we have at least 'parameter'
  94177. * bits available to read, which makes this case simpler.
  94178. */
  94179. uval <<= parameter;
  94180. if(cbits) {
  94181. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94182. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94183. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94184. cbits += parameter;
  94185. }
  94186. else {
  94187. cbits = parameter;
  94188. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94189. }
  94190. }
  94191. }
  94192. ucbits -= parameter;
  94193. /* compose the value */
  94194. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94195. /* are we done? */
  94196. --nvals;
  94197. if(nvals == 0) {
  94198. br->consumed_bits = cbits;
  94199. br->consumed_words = cwords;
  94200. return true;
  94201. }
  94202. uval = 0;
  94203. ++vals;
  94204. }
  94205. }
  94206. #endif
  94207. #if 0 /* UNUSED */
  94208. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94209. {
  94210. FLAC__uint32 lsbs = 0, msbs = 0;
  94211. unsigned bit, uval, k;
  94212. FLAC__ASSERT(0 != br);
  94213. FLAC__ASSERT(0 != br->buffer);
  94214. k = FLAC__bitmath_ilog2(parameter);
  94215. /* read the unary MSBs and end bit */
  94216. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94217. return false;
  94218. /* read the binary LSBs */
  94219. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94220. return false;
  94221. if(parameter == 1u<<k) {
  94222. /* compose the value */
  94223. uval = (msbs << k) | lsbs;
  94224. }
  94225. else {
  94226. unsigned d = (1 << (k+1)) - parameter;
  94227. if(lsbs >= d) {
  94228. if(!FLAC__bitreader_read_bit(br, &bit))
  94229. return false;
  94230. lsbs <<= 1;
  94231. lsbs |= bit;
  94232. lsbs -= d;
  94233. }
  94234. /* compose the value */
  94235. uval = msbs * parameter + lsbs;
  94236. }
  94237. /* unfold unsigned to signed */
  94238. if(uval & 1)
  94239. *val = -((int)(uval >> 1)) - 1;
  94240. else
  94241. *val = (int)(uval >> 1);
  94242. return true;
  94243. }
  94244. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94245. {
  94246. FLAC__uint32 lsbs, msbs = 0;
  94247. unsigned bit, k;
  94248. FLAC__ASSERT(0 != br);
  94249. FLAC__ASSERT(0 != br->buffer);
  94250. k = FLAC__bitmath_ilog2(parameter);
  94251. /* read the unary MSBs and end bit */
  94252. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94253. return false;
  94254. /* read the binary LSBs */
  94255. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94256. return false;
  94257. if(parameter == 1u<<k) {
  94258. /* compose the value */
  94259. *val = (msbs << k) | lsbs;
  94260. }
  94261. else {
  94262. unsigned d = (1 << (k+1)) - parameter;
  94263. if(lsbs >= d) {
  94264. if(!FLAC__bitreader_read_bit(br, &bit))
  94265. return false;
  94266. lsbs <<= 1;
  94267. lsbs |= bit;
  94268. lsbs -= d;
  94269. }
  94270. /* compose the value */
  94271. *val = msbs * parameter + lsbs;
  94272. }
  94273. return true;
  94274. }
  94275. #endif /* UNUSED */
  94276. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94277. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94278. {
  94279. FLAC__uint32 v = 0;
  94280. FLAC__uint32 x;
  94281. unsigned i;
  94282. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94283. return false;
  94284. if(raw)
  94285. raw[(*rawlen)++] = (FLAC__byte)x;
  94286. if(!(x & 0x80)) { /* 0xxxxxxx */
  94287. v = x;
  94288. i = 0;
  94289. }
  94290. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94291. v = x & 0x1F;
  94292. i = 1;
  94293. }
  94294. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94295. v = x & 0x0F;
  94296. i = 2;
  94297. }
  94298. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94299. v = x & 0x07;
  94300. i = 3;
  94301. }
  94302. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94303. v = x & 0x03;
  94304. i = 4;
  94305. }
  94306. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94307. v = x & 0x01;
  94308. i = 5;
  94309. }
  94310. else {
  94311. *val = 0xffffffff;
  94312. return true;
  94313. }
  94314. for( ; i; i--) {
  94315. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94316. return false;
  94317. if(raw)
  94318. raw[(*rawlen)++] = (FLAC__byte)x;
  94319. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94320. *val = 0xffffffff;
  94321. return true;
  94322. }
  94323. v <<= 6;
  94324. v |= (x & 0x3F);
  94325. }
  94326. *val = v;
  94327. return true;
  94328. }
  94329. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94330. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94331. {
  94332. FLAC__uint64 v = 0;
  94333. FLAC__uint32 x;
  94334. unsigned i;
  94335. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94336. return false;
  94337. if(raw)
  94338. raw[(*rawlen)++] = (FLAC__byte)x;
  94339. if(!(x & 0x80)) { /* 0xxxxxxx */
  94340. v = x;
  94341. i = 0;
  94342. }
  94343. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94344. v = x & 0x1F;
  94345. i = 1;
  94346. }
  94347. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94348. v = x & 0x0F;
  94349. i = 2;
  94350. }
  94351. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94352. v = x & 0x07;
  94353. i = 3;
  94354. }
  94355. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94356. v = x & 0x03;
  94357. i = 4;
  94358. }
  94359. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94360. v = x & 0x01;
  94361. i = 5;
  94362. }
  94363. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94364. v = 0;
  94365. i = 6;
  94366. }
  94367. else {
  94368. *val = FLAC__U64L(0xffffffffffffffff);
  94369. return true;
  94370. }
  94371. for( ; i; i--) {
  94372. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94373. return false;
  94374. if(raw)
  94375. raw[(*rawlen)++] = (FLAC__byte)x;
  94376. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94377. *val = FLAC__U64L(0xffffffffffffffff);
  94378. return true;
  94379. }
  94380. v <<= 6;
  94381. v |= (x & 0x3F);
  94382. }
  94383. *val = v;
  94384. return true;
  94385. }
  94386. #endif
  94387. /*** End of inlined file: bitreader.c ***/
  94388. /*** Start of inlined file: bitwriter.c ***/
  94389. /*** Start of inlined file: juce_FlacHeader.h ***/
  94390. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94391. // tasks..
  94392. #define VERSION "1.2.1"
  94393. #define FLAC__NO_DLL 1
  94394. #if JUCE_MSVC
  94395. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94396. #endif
  94397. #if JUCE_MAC
  94398. #define FLAC__SYS_DARWIN 1
  94399. #endif
  94400. /*** End of inlined file: juce_FlacHeader.h ***/
  94401. #if JUCE_USE_FLAC
  94402. #if HAVE_CONFIG_H
  94403. # include <config.h>
  94404. #endif
  94405. #include <stdlib.h> /* for malloc() */
  94406. #include <string.h> /* for memcpy(), memset() */
  94407. #ifdef _MSC_VER
  94408. #include <winsock.h> /* for ntohl() */
  94409. #elif defined FLAC__SYS_DARWIN
  94410. #include <machine/endian.h> /* for ntohl() */
  94411. #elif defined __MINGW32__
  94412. #include <winsock.h> /* for ntohl() */
  94413. #else
  94414. #include <netinet/in.h> /* for ntohl() */
  94415. #endif
  94416. #if 0 /* UNUSED */
  94417. #endif
  94418. /*** Start of inlined file: bitwriter.h ***/
  94419. #ifndef FLAC__PRIVATE__BITWRITER_H
  94420. #define FLAC__PRIVATE__BITWRITER_H
  94421. #include <stdio.h> /* for FILE */
  94422. /*
  94423. * opaque structure definition
  94424. */
  94425. struct FLAC__BitWriter;
  94426. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94427. /*
  94428. * construction, deletion, initialization, etc functions
  94429. */
  94430. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94431. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94432. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94433. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94434. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94435. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94436. /*
  94437. * CRC functions
  94438. *
  94439. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94440. */
  94441. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94442. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94443. /*
  94444. * info functions
  94445. */
  94446. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94447. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94448. /*
  94449. * direct buffer access
  94450. *
  94451. * there may be no calls on the bitwriter between get and release.
  94452. * the bitwriter continues to own the returned buffer.
  94453. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94454. */
  94455. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94456. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94457. /*
  94458. * write functions
  94459. */
  94460. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94461. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94462. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94463. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94464. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94465. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94466. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94467. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94468. #if 0 /* UNUSED */
  94469. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94470. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94471. #endif
  94472. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94473. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94474. #if 0 /* UNUSED */
  94475. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94476. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94477. #endif
  94478. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94479. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94480. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94481. #endif
  94482. /*** End of inlined file: bitwriter.h ***/
  94483. /*** Start of inlined file: alloc.h ***/
  94484. #ifndef FLAC__SHARE__ALLOC_H
  94485. #define FLAC__SHARE__ALLOC_H
  94486. #if HAVE_CONFIG_H
  94487. # include <config.h>
  94488. #endif
  94489. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94490. * before #including this file, otherwise SIZE_MAX might not be defined
  94491. */
  94492. #include <limits.h> /* for SIZE_MAX */
  94493. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94494. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94495. #endif
  94496. #include <stdlib.h> /* for size_t, malloc(), etc */
  94497. #ifndef SIZE_MAX
  94498. # ifndef SIZE_T_MAX
  94499. # ifdef _MSC_VER
  94500. # define SIZE_T_MAX UINT_MAX
  94501. # else
  94502. # error
  94503. # endif
  94504. # endif
  94505. # define SIZE_MAX SIZE_T_MAX
  94506. #endif
  94507. #ifndef FLaC__INLINE
  94508. #define FLaC__INLINE
  94509. #endif
  94510. /* avoid malloc()ing 0 bytes, see:
  94511. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94512. */
  94513. static FLaC__INLINE void *safe_malloc_(size_t size)
  94514. {
  94515. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94516. if(!size)
  94517. size++;
  94518. return malloc(size);
  94519. }
  94520. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94521. {
  94522. if(!nmemb || !size)
  94523. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94524. return calloc(nmemb, size);
  94525. }
  94526. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94527. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94528. {
  94529. size2 += size1;
  94530. if(size2 < size1)
  94531. return 0;
  94532. return safe_malloc_(size2);
  94533. }
  94534. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94535. {
  94536. size2 += size1;
  94537. if(size2 < size1)
  94538. return 0;
  94539. size3 += size2;
  94540. if(size3 < size2)
  94541. return 0;
  94542. return safe_malloc_(size3);
  94543. }
  94544. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94545. {
  94546. size2 += size1;
  94547. if(size2 < size1)
  94548. return 0;
  94549. size3 += size2;
  94550. if(size3 < size2)
  94551. return 0;
  94552. size4 += size3;
  94553. if(size4 < size3)
  94554. return 0;
  94555. return safe_malloc_(size4);
  94556. }
  94557. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94558. #if 0
  94559. needs support for cases where sizeof(size_t) != 4
  94560. {
  94561. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94562. if(sizeof(size_t) == 4) {
  94563. if ((double)size1 * (double)size2 < 4294967296.0)
  94564. return malloc(size1*size2);
  94565. }
  94566. return 0;
  94567. }
  94568. #else
  94569. /* better? */
  94570. {
  94571. if(!size1 || !size2)
  94572. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94573. if(size1 > SIZE_MAX / size2)
  94574. return 0;
  94575. return malloc(size1*size2);
  94576. }
  94577. #endif
  94578. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94579. {
  94580. if(!size1 || !size2 || !size3)
  94581. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94582. if(size1 > SIZE_MAX / size2)
  94583. return 0;
  94584. size1 *= size2;
  94585. if(size1 > SIZE_MAX / size3)
  94586. return 0;
  94587. return malloc(size1*size3);
  94588. }
  94589. /* size1*size2 + size3 */
  94590. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94591. {
  94592. if(!size1 || !size2)
  94593. return safe_malloc_(size3);
  94594. if(size1 > SIZE_MAX / size2)
  94595. return 0;
  94596. return safe_malloc_add_2op_(size1*size2, size3);
  94597. }
  94598. /* size1 * (size2 + size3) */
  94599. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94600. {
  94601. if(!size1 || (!size2 && !size3))
  94602. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94603. size2 += size3;
  94604. if(size2 < size3)
  94605. return 0;
  94606. return safe_malloc_mul_2op_(size1, size2);
  94607. }
  94608. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94609. {
  94610. size2 += size1;
  94611. if(size2 < size1)
  94612. return 0;
  94613. return realloc(ptr, size2);
  94614. }
  94615. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94616. {
  94617. size2 += size1;
  94618. if(size2 < size1)
  94619. return 0;
  94620. size3 += size2;
  94621. if(size3 < size2)
  94622. return 0;
  94623. return realloc(ptr, size3);
  94624. }
  94625. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94626. {
  94627. size2 += size1;
  94628. if(size2 < size1)
  94629. return 0;
  94630. size3 += size2;
  94631. if(size3 < size2)
  94632. return 0;
  94633. size4 += size3;
  94634. if(size4 < size3)
  94635. return 0;
  94636. return realloc(ptr, size4);
  94637. }
  94638. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94639. {
  94640. if(!size1 || !size2)
  94641. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94642. if(size1 > SIZE_MAX / size2)
  94643. return 0;
  94644. return realloc(ptr, size1*size2);
  94645. }
  94646. /* size1 * (size2 + size3) */
  94647. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94648. {
  94649. if(!size1 || (!size2 && !size3))
  94650. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94651. size2 += size3;
  94652. if(size2 < size3)
  94653. return 0;
  94654. return safe_realloc_mul_2op_(ptr, size1, size2);
  94655. }
  94656. #endif
  94657. /*** End of inlined file: alloc.h ***/
  94658. /* Things should be fastest when this matches the machine word size */
  94659. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94660. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94661. typedef FLAC__uint32 bwword;
  94662. #define FLAC__BYTES_PER_WORD 4
  94663. #define FLAC__BITS_PER_WORD 32
  94664. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94665. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94666. #if WORDS_BIGENDIAN
  94667. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94668. #else
  94669. #ifdef _MSC_VER
  94670. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94671. #else
  94672. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94673. #endif
  94674. #endif
  94675. /*
  94676. * The default capacity here doesn't matter too much. The buffer always grows
  94677. * to hold whatever is written to it. Usually the encoder will stop adding at
  94678. * a frame or metadata block, then write that out and clear the buffer for the
  94679. * next one.
  94680. */
  94681. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94682. /* When growing, increment 4K at a time */
  94683. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94684. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94685. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94686. #ifdef min
  94687. #undef min
  94688. #endif
  94689. #define min(x,y) ((x)<(y)?(x):(y))
  94690. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94691. #ifdef _MSC_VER
  94692. #define FLAC__U64L(x) x
  94693. #else
  94694. #define FLAC__U64L(x) x##LLU
  94695. #endif
  94696. #ifndef FLaC__INLINE
  94697. #define FLaC__INLINE
  94698. #endif
  94699. struct FLAC__BitWriter {
  94700. bwword *buffer;
  94701. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94702. unsigned capacity; /* capacity of buffer in words */
  94703. unsigned words; /* # of complete words in buffer */
  94704. unsigned bits; /* # of used bits in accum */
  94705. };
  94706. /* * WATCHOUT: The current implementation only grows the buffer. */
  94707. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94708. {
  94709. unsigned new_capacity;
  94710. bwword *new_buffer;
  94711. FLAC__ASSERT(0 != bw);
  94712. FLAC__ASSERT(0 != bw->buffer);
  94713. /* calculate total words needed to store 'bits_to_add' additional bits */
  94714. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94715. /* it's possible (due to pessimism in the growth estimation that
  94716. * leads to this call) that we don't actually need to grow
  94717. */
  94718. if(bw->capacity >= new_capacity)
  94719. return true;
  94720. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94721. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94722. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94723. /* make sure we got everything right */
  94724. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94725. FLAC__ASSERT(new_capacity > bw->capacity);
  94726. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94727. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94728. if(new_buffer == 0)
  94729. return false;
  94730. bw->buffer = new_buffer;
  94731. bw->capacity = new_capacity;
  94732. return true;
  94733. }
  94734. /***********************************************************************
  94735. *
  94736. * Class constructor/destructor
  94737. *
  94738. ***********************************************************************/
  94739. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94740. {
  94741. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94742. /* note that calloc() sets all members to 0 for us */
  94743. return bw;
  94744. }
  94745. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94746. {
  94747. FLAC__ASSERT(0 != bw);
  94748. FLAC__bitwriter_free(bw);
  94749. free(bw);
  94750. }
  94751. /***********************************************************************
  94752. *
  94753. * Public class methods
  94754. *
  94755. ***********************************************************************/
  94756. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94757. {
  94758. FLAC__ASSERT(0 != bw);
  94759. bw->words = bw->bits = 0;
  94760. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94761. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94762. if(bw->buffer == 0)
  94763. return false;
  94764. return true;
  94765. }
  94766. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94767. {
  94768. FLAC__ASSERT(0 != bw);
  94769. if(0 != bw->buffer)
  94770. free(bw->buffer);
  94771. bw->buffer = 0;
  94772. bw->capacity = 0;
  94773. bw->words = bw->bits = 0;
  94774. }
  94775. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94776. {
  94777. bw->words = bw->bits = 0;
  94778. }
  94779. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94780. {
  94781. unsigned i, j;
  94782. if(bw == 0) {
  94783. fprintf(out, "bitwriter is NULL\n");
  94784. }
  94785. else {
  94786. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94787. for(i = 0; i < bw->words; i++) {
  94788. fprintf(out, "%08X: ", i);
  94789. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94790. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94791. fprintf(out, "\n");
  94792. }
  94793. if(bw->bits > 0) {
  94794. fprintf(out, "%08X: ", i);
  94795. for(j = 0; j < bw->bits; j++)
  94796. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94797. fprintf(out, "\n");
  94798. }
  94799. }
  94800. }
  94801. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94802. {
  94803. const FLAC__byte *buffer;
  94804. size_t bytes;
  94805. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94806. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94807. return false;
  94808. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94809. FLAC__bitwriter_release_buffer(bw);
  94810. return true;
  94811. }
  94812. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94813. {
  94814. const FLAC__byte *buffer;
  94815. size_t bytes;
  94816. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94817. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94818. return false;
  94819. *crc = FLAC__crc8(buffer, bytes);
  94820. FLAC__bitwriter_release_buffer(bw);
  94821. return true;
  94822. }
  94823. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94824. {
  94825. return ((bw->bits & 7) == 0);
  94826. }
  94827. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94828. {
  94829. return FLAC__TOTAL_BITS(bw);
  94830. }
  94831. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94832. {
  94833. FLAC__ASSERT((bw->bits & 7) == 0);
  94834. /* double protection */
  94835. if(bw->bits & 7)
  94836. return false;
  94837. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94838. if(bw->bits) {
  94839. FLAC__ASSERT(bw->words <= bw->capacity);
  94840. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94841. return false;
  94842. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94843. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94844. }
  94845. /* now we can just return what we have */
  94846. *buffer = (FLAC__byte*)bw->buffer;
  94847. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94848. return true;
  94849. }
  94850. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94851. {
  94852. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94853. * get-mode' flag could be added everywhere and then cleared here
  94854. */
  94855. (void)bw;
  94856. }
  94857. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94858. {
  94859. unsigned n;
  94860. FLAC__ASSERT(0 != bw);
  94861. FLAC__ASSERT(0 != bw->buffer);
  94862. if(bits == 0)
  94863. return true;
  94864. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94865. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94866. return false;
  94867. /* first part gets to word alignment */
  94868. if(bw->bits) {
  94869. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94870. bw->accum <<= n;
  94871. bits -= n;
  94872. bw->bits += n;
  94873. if(bw->bits == FLAC__BITS_PER_WORD) {
  94874. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94875. bw->bits = 0;
  94876. }
  94877. else
  94878. return true;
  94879. }
  94880. /* do whole words */
  94881. while(bits >= FLAC__BITS_PER_WORD) {
  94882. bw->buffer[bw->words++] = 0;
  94883. bits -= FLAC__BITS_PER_WORD;
  94884. }
  94885. /* do any leftovers */
  94886. if(bits > 0) {
  94887. bw->accum = 0;
  94888. bw->bits = bits;
  94889. }
  94890. return true;
  94891. }
  94892. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94893. {
  94894. register unsigned left;
  94895. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94896. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94897. FLAC__ASSERT(0 != bw);
  94898. FLAC__ASSERT(0 != bw->buffer);
  94899. FLAC__ASSERT(bits <= 32);
  94900. if(bits == 0)
  94901. return true;
  94902. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94903. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94904. return false;
  94905. left = FLAC__BITS_PER_WORD - bw->bits;
  94906. if(bits < left) {
  94907. bw->accum <<= bits;
  94908. bw->accum |= val;
  94909. bw->bits += bits;
  94910. }
  94911. 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 */
  94912. bw->accum <<= left;
  94913. bw->accum |= val >> (bw->bits = bits - left);
  94914. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94915. bw->accum = val;
  94916. }
  94917. else {
  94918. bw->accum = val;
  94919. bw->bits = 0;
  94920. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94921. }
  94922. return true;
  94923. }
  94924. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94925. {
  94926. /* zero-out unused bits */
  94927. if(bits < 32)
  94928. val &= (~(0xffffffff << bits));
  94929. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94930. }
  94931. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94932. {
  94933. /* this could be a little faster but it's not used for much */
  94934. if(bits > 32) {
  94935. return
  94936. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94937. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94938. }
  94939. else
  94940. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94941. }
  94942. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94943. {
  94944. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94945. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94946. return false;
  94947. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94948. return false;
  94949. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94950. return false;
  94951. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94952. return false;
  94953. return true;
  94954. }
  94955. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94956. {
  94957. unsigned i;
  94958. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94959. for(i = 0; i < nvals; i++) {
  94960. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94961. return false;
  94962. }
  94963. return true;
  94964. }
  94965. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94966. {
  94967. if(val < 32)
  94968. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94969. else
  94970. return
  94971. FLAC__bitwriter_write_zeroes(bw, val) &&
  94972. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94973. }
  94974. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94975. {
  94976. FLAC__uint32 uval;
  94977. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94978. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94979. uval = (val<<1) ^ (val>>31);
  94980. return 1 + parameter + (uval >> parameter);
  94981. }
  94982. #if 0 /* UNUSED */
  94983. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94984. {
  94985. unsigned bits, msbs, uval;
  94986. unsigned k;
  94987. FLAC__ASSERT(parameter > 0);
  94988. /* fold signed to unsigned */
  94989. if(val < 0)
  94990. uval = (unsigned)(((-(++val)) << 1) + 1);
  94991. else
  94992. uval = (unsigned)(val << 1);
  94993. k = FLAC__bitmath_ilog2(parameter);
  94994. if(parameter == 1u<<k) {
  94995. FLAC__ASSERT(k <= 30);
  94996. msbs = uval >> k;
  94997. bits = 1 + k + msbs;
  94998. }
  94999. else {
  95000. unsigned q, r, d;
  95001. d = (1 << (k+1)) - parameter;
  95002. q = uval / parameter;
  95003. r = uval - (q * parameter);
  95004. bits = 1 + q + k;
  95005. if(r >= d)
  95006. bits++;
  95007. }
  95008. return bits;
  95009. }
  95010. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95011. {
  95012. unsigned bits, msbs;
  95013. unsigned k;
  95014. FLAC__ASSERT(parameter > 0);
  95015. k = FLAC__bitmath_ilog2(parameter);
  95016. if(parameter == 1u<<k) {
  95017. FLAC__ASSERT(k <= 30);
  95018. msbs = uval >> k;
  95019. bits = 1 + k + msbs;
  95020. }
  95021. else {
  95022. unsigned q, r, d;
  95023. d = (1 << (k+1)) - parameter;
  95024. q = uval / parameter;
  95025. r = uval - (q * parameter);
  95026. bits = 1 + q + k;
  95027. if(r >= d)
  95028. bits++;
  95029. }
  95030. return bits;
  95031. }
  95032. #endif /* UNUSED */
  95033. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95034. {
  95035. unsigned total_bits, interesting_bits, msbs;
  95036. FLAC__uint32 uval, pattern;
  95037. FLAC__ASSERT(0 != bw);
  95038. FLAC__ASSERT(0 != bw->buffer);
  95039. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95040. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95041. uval = (val<<1) ^ (val>>31);
  95042. msbs = uval >> parameter;
  95043. interesting_bits = 1 + parameter;
  95044. total_bits = interesting_bits + msbs;
  95045. pattern = 1 << parameter; /* the unary end bit */
  95046. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95047. if(total_bits <= 32)
  95048. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95049. else
  95050. return
  95051. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95052. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95053. }
  95054. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95055. {
  95056. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95057. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95058. FLAC__uint32 uval;
  95059. unsigned left;
  95060. const unsigned lsbits = 1 + parameter;
  95061. unsigned msbits;
  95062. FLAC__ASSERT(0 != bw);
  95063. FLAC__ASSERT(0 != bw->buffer);
  95064. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95065. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95066. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95067. while(nvals) {
  95068. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95069. uval = (*vals<<1) ^ (*vals>>31);
  95070. msbits = uval >> parameter;
  95071. #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) */
  95072. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95073. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95074. bw->bits = bw->bits + msbits + lsbits;
  95075. uval |= mask1; /* set stop bit */
  95076. uval &= mask2; /* mask off unused top bits */
  95077. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95078. bw->accum <<= msbits;
  95079. bw->accum <<= lsbits;
  95080. bw->accum |= uval;
  95081. if(bw->bits == FLAC__BITS_PER_WORD) {
  95082. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95083. bw->bits = 0;
  95084. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95085. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95086. FLAC__ASSERT(bw->capacity == bw->words);
  95087. return false;
  95088. }
  95089. }
  95090. }
  95091. else {
  95092. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95093. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95094. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95095. bw->bits = bw->bits + msbits + lsbits;
  95096. uval |= mask1; /* set stop bit */
  95097. uval &= mask2; /* mask off unused top bits */
  95098. bw->accum <<= msbits + lsbits;
  95099. bw->accum |= uval;
  95100. }
  95101. else {
  95102. #endif
  95103. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95104. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95105. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95106. return false;
  95107. if(msbits) {
  95108. /* first part gets to word alignment */
  95109. if(bw->bits) {
  95110. left = FLAC__BITS_PER_WORD - bw->bits;
  95111. if(msbits < left) {
  95112. bw->accum <<= msbits;
  95113. bw->bits += msbits;
  95114. goto break1;
  95115. }
  95116. else {
  95117. bw->accum <<= left;
  95118. msbits -= left;
  95119. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95120. bw->bits = 0;
  95121. }
  95122. }
  95123. /* do whole words */
  95124. while(msbits >= FLAC__BITS_PER_WORD) {
  95125. bw->buffer[bw->words++] = 0;
  95126. msbits -= FLAC__BITS_PER_WORD;
  95127. }
  95128. /* do any leftovers */
  95129. if(msbits > 0) {
  95130. bw->accum = 0;
  95131. bw->bits = msbits;
  95132. }
  95133. }
  95134. break1:
  95135. uval |= mask1; /* set stop bit */
  95136. uval &= mask2; /* mask off unused top bits */
  95137. left = FLAC__BITS_PER_WORD - bw->bits;
  95138. if(lsbits < left) {
  95139. bw->accum <<= lsbits;
  95140. bw->accum |= uval;
  95141. bw->bits += lsbits;
  95142. }
  95143. else {
  95144. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95145. * be > lsbits (because of previous assertions) so it would have
  95146. * triggered the (lsbits<left) case above.
  95147. */
  95148. FLAC__ASSERT(bw->bits);
  95149. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95150. bw->accum <<= left;
  95151. bw->accum |= uval >> (bw->bits = lsbits - left);
  95152. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95153. bw->accum = uval;
  95154. }
  95155. #if 1
  95156. }
  95157. #endif
  95158. vals++;
  95159. nvals--;
  95160. }
  95161. return true;
  95162. }
  95163. #if 0 /* UNUSED */
  95164. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95165. {
  95166. unsigned total_bits, msbs, uval;
  95167. unsigned k;
  95168. FLAC__ASSERT(0 != bw);
  95169. FLAC__ASSERT(0 != bw->buffer);
  95170. FLAC__ASSERT(parameter > 0);
  95171. /* fold signed to unsigned */
  95172. if(val < 0)
  95173. uval = (unsigned)(((-(++val)) << 1) + 1);
  95174. else
  95175. uval = (unsigned)(val << 1);
  95176. k = FLAC__bitmath_ilog2(parameter);
  95177. if(parameter == 1u<<k) {
  95178. unsigned pattern;
  95179. FLAC__ASSERT(k <= 30);
  95180. msbs = uval >> k;
  95181. total_bits = 1 + k + msbs;
  95182. pattern = 1 << k; /* the unary end bit */
  95183. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95184. if(total_bits <= 32) {
  95185. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95186. return false;
  95187. }
  95188. else {
  95189. /* write the unary MSBs */
  95190. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95191. return false;
  95192. /* write the unary end bit and binary LSBs */
  95193. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95194. return false;
  95195. }
  95196. }
  95197. else {
  95198. unsigned q, r, d;
  95199. d = (1 << (k+1)) - parameter;
  95200. q = uval / parameter;
  95201. r = uval - (q * parameter);
  95202. /* write the unary MSBs */
  95203. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95204. return false;
  95205. /* write the unary end bit */
  95206. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95207. return false;
  95208. /* write the binary LSBs */
  95209. if(r >= d) {
  95210. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95211. return false;
  95212. }
  95213. else {
  95214. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95215. return false;
  95216. }
  95217. }
  95218. return true;
  95219. }
  95220. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95221. {
  95222. unsigned total_bits, msbs;
  95223. unsigned k;
  95224. FLAC__ASSERT(0 != bw);
  95225. FLAC__ASSERT(0 != bw->buffer);
  95226. FLAC__ASSERT(parameter > 0);
  95227. k = FLAC__bitmath_ilog2(parameter);
  95228. if(parameter == 1u<<k) {
  95229. unsigned pattern;
  95230. FLAC__ASSERT(k <= 30);
  95231. msbs = uval >> k;
  95232. total_bits = 1 + k + msbs;
  95233. pattern = 1 << k; /* the unary end bit */
  95234. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95235. if(total_bits <= 32) {
  95236. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95237. return false;
  95238. }
  95239. else {
  95240. /* write the unary MSBs */
  95241. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95242. return false;
  95243. /* write the unary end bit and binary LSBs */
  95244. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95245. return false;
  95246. }
  95247. }
  95248. else {
  95249. unsigned q, r, d;
  95250. d = (1 << (k+1)) - parameter;
  95251. q = uval / parameter;
  95252. r = uval - (q * parameter);
  95253. /* write the unary MSBs */
  95254. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95255. return false;
  95256. /* write the unary end bit */
  95257. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95258. return false;
  95259. /* write the binary LSBs */
  95260. if(r >= d) {
  95261. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95262. return false;
  95263. }
  95264. else {
  95265. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95266. return false;
  95267. }
  95268. }
  95269. return true;
  95270. }
  95271. #endif /* UNUSED */
  95272. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95273. {
  95274. FLAC__bool ok = 1;
  95275. FLAC__ASSERT(0 != bw);
  95276. FLAC__ASSERT(0 != bw->buffer);
  95277. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95278. if(val < 0x80) {
  95279. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95280. }
  95281. else if(val < 0x800) {
  95282. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95283. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95284. }
  95285. else if(val < 0x10000) {
  95286. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95287. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95288. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95289. }
  95290. else if(val < 0x200000) {
  95291. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95292. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95293. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95294. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95295. }
  95296. else if(val < 0x4000000) {
  95297. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95298. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95299. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95300. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95301. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95302. }
  95303. else {
  95304. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95305. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95306. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95307. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95308. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95309. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95310. }
  95311. return ok;
  95312. }
  95313. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95314. {
  95315. FLAC__bool ok = 1;
  95316. FLAC__ASSERT(0 != bw);
  95317. FLAC__ASSERT(0 != bw->buffer);
  95318. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95319. if(val < 0x80) {
  95320. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95321. }
  95322. else if(val < 0x800) {
  95323. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95324. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95325. }
  95326. else if(val < 0x10000) {
  95327. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95328. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95329. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95330. }
  95331. else if(val < 0x200000) {
  95332. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95333. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95334. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95335. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95336. }
  95337. else if(val < 0x4000000) {
  95338. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95339. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95341. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95342. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95343. }
  95344. else if(val < 0x80000000) {
  95345. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95346. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95347. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95348. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95349. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95351. }
  95352. else {
  95353. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95354. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95355. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95356. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95357. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95358. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95359. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95360. }
  95361. return ok;
  95362. }
  95363. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95364. {
  95365. /* 0-pad to byte boundary */
  95366. if(bw->bits & 7u)
  95367. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95368. else
  95369. return true;
  95370. }
  95371. #endif
  95372. /*** End of inlined file: bitwriter.c ***/
  95373. /*** Start of inlined file: cpu.c ***/
  95374. /*** Start of inlined file: juce_FlacHeader.h ***/
  95375. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95376. // tasks..
  95377. #define VERSION "1.2.1"
  95378. #define FLAC__NO_DLL 1
  95379. #if JUCE_MSVC
  95380. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95381. #endif
  95382. #if JUCE_MAC
  95383. #define FLAC__SYS_DARWIN 1
  95384. #endif
  95385. /*** End of inlined file: juce_FlacHeader.h ***/
  95386. #if JUCE_USE_FLAC
  95387. #if HAVE_CONFIG_H
  95388. # include <config.h>
  95389. #endif
  95390. #include <stdlib.h>
  95391. #include <stdio.h>
  95392. #if defined FLAC__CPU_IA32
  95393. # include <signal.h>
  95394. #elif defined FLAC__CPU_PPC
  95395. # if !defined FLAC__NO_ASM
  95396. # if defined FLAC__SYS_DARWIN
  95397. # include <sys/sysctl.h>
  95398. # include <mach/mach.h>
  95399. # include <mach/mach_host.h>
  95400. # include <mach/host_info.h>
  95401. # include <mach/machine.h>
  95402. # ifndef CPU_SUBTYPE_POWERPC_970
  95403. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95404. # endif
  95405. # else /* FLAC__SYS_DARWIN */
  95406. # include <signal.h>
  95407. # include <setjmp.h>
  95408. static sigjmp_buf jmpbuf;
  95409. static volatile sig_atomic_t canjump = 0;
  95410. static void sigill_handler (int sig)
  95411. {
  95412. if (!canjump) {
  95413. signal (sig, SIG_DFL);
  95414. raise (sig);
  95415. }
  95416. canjump = 0;
  95417. siglongjmp (jmpbuf, 1);
  95418. }
  95419. # endif /* FLAC__SYS_DARWIN */
  95420. # endif /* FLAC__NO_ASM */
  95421. #endif /* FLAC__CPU_PPC */
  95422. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95423. #include <sys/param.h>
  95424. #include <sys/sysctl.h>
  95425. #include <machine/cpu.h>
  95426. #endif
  95427. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95428. #include <sys/types.h>
  95429. #include <sys/sysctl.h>
  95430. #endif
  95431. #if defined(__APPLE__)
  95432. /* how to get sysctlbyname()? */
  95433. #endif
  95434. /* these are flags in EDX of CPUID AX=00000001 */
  95435. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95436. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95437. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95438. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95439. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95440. /* these are flags in ECX of CPUID AX=00000001 */
  95441. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95442. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95443. /* these are flags in EDX of CPUID AX=80000001 */
  95444. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95445. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95446. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95447. /*
  95448. * Extra stuff needed for detection of OS support for SSE on IA-32
  95449. */
  95450. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95451. # if defined(__linux__)
  95452. /*
  95453. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95454. * modify the return address to jump over the offending SSE instruction
  95455. * and also the operation following it that indicates the instruction
  95456. * executed successfully. In this way we use no global variables and
  95457. * stay thread-safe.
  95458. *
  95459. * 3 + 3 + 6:
  95460. * 3 bytes for "xorps xmm0,xmm0"
  95461. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95462. * 6 bytes extra in case our estimate is wrong
  95463. * 12 bytes puts us in the NOP "landing zone"
  95464. */
  95465. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95466. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95467. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95468. {
  95469. (void)signal;
  95470. sc.eip += 3 + 3 + 6;
  95471. }
  95472. # else
  95473. # include <sys/ucontext.h>
  95474. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95475. {
  95476. (void)signal, (void)si;
  95477. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95478. }
  95479. # endif
  95480. # elif defined(_MSC_VER)
  95481. # include <windows.h>
  95482. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95483. # ifdef USE_TRY_CATCH_FLAVOR
  95484. # else
  95485. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95486. {
  95487. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95488. ep->ContextRecord->Eip += 3 + 3 + 6;
  95489. return EXCEPTION_CONTINUE_EXECUTION;
  95490. }
  95491. return EXCEPTION_CONTINUE_SEARCH;
  95492. }
  95493. # endif
  95494. # endif
  95495. #endif
  95496. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95497. {
  95498. /*
  95499. * IA32-specific
  95500. */
  95501. #ifdef FLAC__CPU_IA32
  95502. info->type = FLAC__CPUINFO_TYPE_IA32;
  95503. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95504. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95505. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95506. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95507. info->data.ia32.cmov = false;
  95508. info->data.ia32.mmx = false;
  95509. info->data.ia32.fxsr = false;
  95510. info->data.ia32.sse = false;
  95511. info->data.ia32.sse2 = false;
  95512. info->data.ia32.sse3 = false;
  95513. info->data.ia32.ssse3 = false;
  95514. info->data.ia32._3dnow = false;
  95515. info->data.ia32.ext3dnow = false;
  95516. info->data.ia32.extmmx = false;
  95517. if(info->data.ia32.cpuid) {
  95518. /* http://www.sandpile.org/ia32/cpuid.htm */
  95519. FLAC__uint32 flags_edx, flags_ecx;
  95520. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95521. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95522. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95523. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95524. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95525. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95526. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95527. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95528. #ifdef FLAC__USE_3DNOW
  95529. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95530. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95531. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95532. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95533. #else
  95534. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95535. #endif
  95536. #ifdef DEBUG
  95537. fprintf(stderr, "CPU info (IA-32):\n");
  95538. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95539. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95540. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95541. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95542. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95543. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95544. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95545. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95546. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95547. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95548. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95549. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95550. #endif
  95551. /*
  95552. * now have to check for OS support of SSE/SSE2
  95553. */
  95554. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95555. #if defined FLAC__NO_SSE_OS
  95556. /* assume user knows better than us; turn it off */
  95557. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95558. #elif defined FLAC__SSE_OS
  95559. /* assume user knows better than us; leave as detected above */
  95560. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95561. int sse = 0;
  95562. size_t len;
  95563. /* at least one of these must work: */
  95564. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95565. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95566. if(!sse)
  95567. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95568. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95569. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95570. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95571. size_t len = sizeof(val);
  95572. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95573. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95574. else { /* double-check SSE2 */
  95575. mib[1] = CPU_SSE2;
  95576. len = sizeof(val);
  95577. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95578. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95579. }
  95580. # else
  95581. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95582. # endif
  95583. #elif defined(__linux__)
  95584. int sse = 0;
  95585. struct sigaction sigill_save;
  95586. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95587. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95588. #else
  95589. struct sigaction sigill_sse;
  95590. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95591. __sigemptyset(&sigill_sse.sa_mask);
  95592. 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 */
  95593. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95594. #endif
  95595. {
  95596. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95597. /* see sigill_handler_sse_os() for an explanation of the following: */
  95598. asm volatile (
  95599. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95600. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95601. "incl %0\n\t" /* SIGILL handler will jump over this */
  95602. /* landing zone */
  95603. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95604. "nop\n\t"
  95605. "nop\n\t"
  95606. "nop\n\t"
  95607. "nop\n\t"
  95608. "nop\n\t"
  95609. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95610. "nop\n\t"
  95611. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95612. : "=r"(sse)
  95613. : "r"(sse)
  95614. );
  95615. sigaction(SIGILL, &sigill_save, NULL);
  95616. }
  95617. if(!sse)
  95618. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95619. #elif defined(_MSC_VER)
  95620. # ifdef USE_TRY_CATCH_FLAVOR
  95621. _try {
  95622. __asm {
  95623. # if _MSC_VER <= 1200
  95624. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95625. _emit 0x0F
  95626. _emit 0x57
  95627. _emit 0xC0
  95628. # else
  95629. xorps xmm0,xmm0
  95630. # endif
  95631. }
  95632. }
  95633. _except(EXCEPTION_EXECUTE_HANDLER) {
  95634. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95635. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95636. }
  95637. # else
  95638. int sse = 0;
  95639. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95640. /* see GCC version above for explanation */
  95641. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95642. /* http://www.codeproject.com/cpp/gccasm.asp */
  95643. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95644. __asm {
  95645. # if _MSC_VER <= 1200
  95646. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95647. _emit 0x0F
  95648. _emit 0x57
  95649. _emit 0xC0
  95650. # else
  95651. xorps xmm0,xmm0
  95652. # endif
  95653. inc sse
  95654. nop
  95655. nop
  95656. nop
  95657. nop
  95658. nop
  95659. nop
  95660. nop
  95661. nop
  95662. nop
  95663. }
  95664. SetUnhandledExceptionFilter(save);
  95665. if(!sse)
  95666. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95667. # endif
  95668. #else
  95669. /* no way to test, disable to be safe */
  95670. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95671. #endif
  95672. #ifdef DEBUG
  95673. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95674. #endif
  95675. }
  95676. }
  95677. #else
  95678. info->use_asm = false;
  95679. #endif
  95680. /*
  95681. * PPC-specific
  95682. */
  95683. #elif defined FLAC__CPU_PPC
  95684. info->type = FLAC__CPUINFO_TYPE_PPC;
  95685. # if !defined FLAC__NO_ASM
  95686. info->use_asm = true;
  95687. # ifdef FLAC__USE_ALTIVEC
  95688. # if defined FLAC__SYS_DARWIN
  95689. {
  95690. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95691. size_t len = sizeof(val);
  95692. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95693. }
  95694. {
  95695. host_basic_info_data_t hostInfo;
  95696. mach_msg_type_number_t infoCount;
  95697. infoCount = HOST_BASIC_INFO_COUNT;
  95698. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95699. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95700. }
  95701. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95702. {
  95703. /* no Darwin, do it the brute-force way */
  95704. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95705. info->data.ppc.altivec = 0;
  95706. info->data.ppc.ppc64 = 0;
  95707. signal (SIGILL, sigill_handler);
  95708. canjump = 0;
  95709. if (!sigsetjmp (jmpbuf, 1)) {
  95710. canjump = 1;
  95711. asm volatile (
  95712. "mtspr 256, %0\n\t"
  95713. "vand %%v0, %%v0, %%v0"
  95714. :
  95715. : "r" (-1)
  95716. );
  95717. info->data.ppc.altivec = 1;
  95718. }
  95719. canjump = 0;
  95720. if (!sigsetjmp (jmpbuf, 1)) {
  95721. int x = 0;
  95722. canjump = 1;
  95723. /* PPC64 hardware implements the cntlzd instruction */
  95724. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95725. info->data.ppc.ppc64 = 1;
  95726. }
  95727. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95728. }
  95729. # endif
  95730. # else /* !FLAC__USE_ALTIVEC */
  95731. info->data.ppc.altivec = 0;
  95732. info->data.ppc.ppc64 = 0;
  95733. # endif
  95734. # else
  95735. info->use_asm = false;
  95736. # endif
  95737. /*
  95738. * unknown CPI
  95739. */
  95740. #else
  95741. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95742. info->use_asm = false;
  95743. #endif
  95744. }
  95745. #endif
  95746. /*** End of inlined file: cpu.c ***/
  95747. /*** Start of inlined file: crc.c ***/
  95748. /*** Start of inlined file: juce_FlacHeader.h ***/
  95749. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95750. // tasks..
  95751. #define VERSION "1.2.1"
  95752. #define FLAC__NO_DLL 1
  95753. #if JUCE_MSVC
  95754. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95755. #endif
  95756. #if JUCE_MAC
  95757. #define FLAC__SYS_DARWIN 1
  95758. #endif
  95759. /*** End of inlined file: juce_FlacHeader.h ***/
  95760. #if JUCE_USE_FLAC
  95761. #if HAVE_CONFIG_H
  95762. # include <config.h>
  95763. #endif
  95764. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95765. FLAC__byte const FLAC__crc8_table[256] = {
  95766. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95767. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95768. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95769. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95770. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95771. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95772. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95773. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95774. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95775. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95776. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95777. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95778. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95779. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95780. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95781. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95782. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95783. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95784. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95785. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95786. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95787. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95788. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95789. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95790. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95791. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95792. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95793. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95794. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95795. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95796. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95797. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95798. };
  95799. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95800. unsigned FLAC__crc16_table[256] = {
  95801. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95802. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95803. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95804. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95805. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95806. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95807. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95808. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95809. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95810. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95811. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95812. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95813. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95814. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95815. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95816. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95817. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95818. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95819. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95820. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95821. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95822. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95823. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95824. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95825. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95826. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95827. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95828. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95829. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95830. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95831. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95832. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95833. };
  95834. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95835. {
  95836. *crc = FLAC__crc8_table[*crc ^ data];
  95837. }
  95838. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95839. {
  95840. while(len--)
  95841. *crc = FLAC__crc8_table[*crc ^ *data++];
  95842. }
  95843. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95844. {
  95845. FLAC__uint8 crc = 0;
  95846. while(len--)
  95847. crc = FLAC__crc8_table[crc ^ *data++];
  95848. return crc;
  95849. }
  95850. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95851. {
  95852. unsigned crc = 0;
  95853. while(len--)
  95854. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95855. return crc;
  95856. }
  95857. #endif
  95858. /*** End of inlined file: crc.c ***/
  95859. /*** Start of inlined file: fixed.c ***/
  95860. /*** Start of inlined file: juce_FlacHeader.h ***/
  95861. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95862. // tasks..
  95863. #define VERSION "1.2.1"
  95864. #define FLAC__NO_DLL 1
  95865. #if JUCE_MSVC
  95866. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95867. #endif
  95868. #if JUCE_MAC
  95869. #define FLAC__SYS_DARWIN 1
  95870. #endif
  95871. /*** End of inlined file: juce_FlacHeader.h ***/
  95872. #if JUCE_USE_FLAC
  95873. #if HAVE_CONFIG_H
  95874. # include <config.h>
  95875. #endif
  95876. #include <math.h>
  95877. #include <string.h>
  95878. /*** Start of inlined file: fixed.h ***/
  95879. #ifndef FLAC__PRIVATE__FIXED_H
  95880. #define FLAC__PRIVATE__FIXED_H
  95881. #ifdef HAVE_CONFIG_H
  95882. #include <config.h>
  95883. #endif
  95884. /*** Start of inlined file: float.h ***/
  95885. #ifndef FLAC__PRIVATE__FLOAT_H
  95886. #define FLAC__PRIVATE__FLOAT_H
  95887. #ifdef HAVE_CONFIG_H
  95888. #include <config.h>
  95889. #endif
  95890. /*
  95891. * These typedefs make it easier to ensure that integer versions of
  95892. * the library really only contain integer operations. All the code
  95893. * in libFLAC should use FLAC__float and FLAC__double in place of
  95894. * float and double, and be protected by checks of the macro
  95895. * FLAC__INTEGER_ONLY_LIBRARY.
  95896. *
  95897. * FLAC__real is the basic floating point type used in LPC analysis.
  95898. */
  95899. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95900. typedef double FLAC__double;
  95901. typedef float FLAC__float;
  95902. /*
  95903. * WATCHOUT: changing FLAC__real will change the signatures of many
  95904. * functions that have assembly language equivalents and break them.
  95905. */
  95906. typedef float FLAC__real;
  95907. #else
  95908. /*
  95909. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95910. * for the integer part and lower 16 bits for the fractional part.
  95911. */
  95912. typedef FLAC__int32 FLAC__fixedpoint;
  95913. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95914. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95915. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95916. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95917. extern const FLAC__fixedpoint FLAC__FP_E;
  95918. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95919. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95920. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95921. /*
  95922. * FLAC__fixedpoint_log2()
  95923. * --------------------------------------------------------------------
  95924. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95925. * algorithm by Knuth for x >= 1.0
  95926. *
  95927. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95928. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95929. *
  95930. * 'precision' roughly limits the number of iterations that are done;
  95931. * use (unsigned)(-1) for maximum precision.
  95932. *
  95933. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95934. * function will punt and return 0.
  95935. *
  95936. * The return value will also have 'fracbits' fractional bits.
  95937. */
  95938. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95939. #endif
  95940. #endif
  95941. /*** End of inlined file: float.h ***/
  95942. /*** Start of inlined file: format.h ***/
  95943. #ifndef FLAC__PRIVATE__FORMAT_H
  95944. #define FLAC__PRIVATE__FORMAT_H
  95945. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95946. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95947. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95948. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95949. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95950. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95951. #endif
  95952. /*** End of inlined file: format.h ***/
  95953. /*
  95954. * FLAC__fixed_compute_best_predictor()
  95955. * --------------------------------------------------------------------
  95956. * Compute the best fixed predictor and the expected bits-per-sample
  95957. * of the residual signal for each order. The _wide() version uses
  95958. * 64-bit integers which is statistically necessary when bits-per-
  95959. * sample + log2(blocksize) > 30
  95960. *
  95961. * IN data[0,data_len-1]
  95962. * IN data_len
  95963. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95964. */
  95965. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95966. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95967. # ifndef FLAC__NO_ASM
  95968. # ifdef FLAC__CPU_IA32
  95969. # ifdef FLAC__HAS_NASM
  95970. 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]);
  95971. # endif
  95972. # endif
  95973. # endif
  95974. 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]);
  95975. #else
  95976. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95977. 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]);
  95978. #endif
  95979. /*
  95980. * FLAC__fixed_compute_residual()
  95981. * --------------------------------------------------------------------
  95982. * Compute the residual signal obtained from sutracting the predicted
  95983. * signal from the original.
  95984. *
  95985. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95986. * IN data_len length of original signal
  95987. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95988. * OUT residual[0,data_len-1] residual signal
  95989. */
  95990. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95991. /*
  95992. * FLAC__fixed_restore_signal()
  95993. * --------------------------------------------------------------------
  95994. * Restore the original signal by summing the residual and the
  95995. * predictor.
  95996. *
  95997. * IN residual[0,data_len-1] residual signal
  95998. * IN data_len length of original signal
  95999. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96000. * *** IMPORTANT: the caller must pass in the historical samples:
  96001. * IN data[-order,-1] previously-reconstructed historical samples
  96002. * OUT data[0,data_len-1] original signal
  96003. */
  96004. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96005. #endif
  96006. /*** End of inlined file: fixed.h ***/
  96007. #ifndef M_LN2
  96008. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96009. #define M_LN2 0.69314718055994530942
  96010. #endif
  96011. #ifdef min
  96012. #undef min
  96013. #endif
  96014. #define min(x,y) ((x) < (y)? (x) : (y))
  96015. #ifdef local_abs
  96016. #undef local_abs
  96017. #endif
  96018. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96019. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96020. /* rbps stands for residual bits per sample
  96021. *
  96022. * (ln(2) * err)
  96023. * rbps = log (-----------)
  96024. * 2 ( n )
  96025. */
  96026. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96027. {
  96028. FLAC__uint32 rbps;
  96029. unsigned bits; /* the number of bits required to represent a number */
  96030. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96031. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96032. FLAC__ASSERT(err > 0);
  96033. FLAC__ASSERT(n > 0);
  96034. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96035. if(err <= n)
  96036. return 0;
  96037. /*
  96038. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96039. * These allow us later to know we won't lose too much precision in the
  96040. * fixed-point division (err<<fracbits)/n.
  96041. */
  96042. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96043. err <<= fracbits;
  96044. err /= n;
  96045. /* err now holds err/n with fracbits fractional bits */
  96046. /*
  96047. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96048. * our purposes.
  96049. */
  96050. FLAC__ASSERT(err > 0);
  96051. bits = FLAC__bitmath_ilog2(err)+1;
  96052. if(bits > 16) {
  96053. err >>= (bits-16);
  96054. fracbits -= (bits-16);
  96055. }
  96056. rbps = (FLAC__uint32)err;
  96057. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96058. rbps *= FLAC__FP_LN2;
  96059. fracbits += 16;
  96060. FLAC__ASSERT(fracbits >= 0);
  96061. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96062. {
  96063. const int f = fracbits & 3;
  96064. if(f) {
  96065. rbps >>= f;
  96066. fracbits -= f;
  96067. }
  96068. }
  96069. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96070. if(rbps == 0)
  96071. return 0;
  96072. /*
  96073. * The return value must have 16 fractional bits. Since the whole part
  96074. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96075. * must be >= -3, these assertion allows us to be able to shift rbps
  96076. * left if necessary to get 16 fracbits without losing any bits of the
  96077. * whole part of rbps.
  96078. *
  96079. * There is a slight chance due to accumulated error that the whole part
  96080. * will require 6 bits, so we use 6 in the assertion. Really though as
  96081. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96082. */
  96083. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96084. FLAC__ASSERT(fracbits >= -3);
  96085. /* now shift the decimal point into place */
  96086. if(fracbits < 16)
  96087. return rbps << (16-fracbits);
  96088. else if(fracbits > 16)
  96089. return rbps >> (fracbits-16);
  96090. else
  96091. return rbps;
  96092. }
  96093. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96094. {
  96095. FLAC__uint32 rbps;
  96096. unsigned bits; /* the number of bits required to represent a number */
  96097. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96098. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96099. FLAC__ASSERT(err > 0);
  96100. FLAC__ASSERT(n > 0);
  96101. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96102. if(err <= n)
  96103. return 0;
  96104. /*
  96105. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96106. * These allow us later to know we won't lose too much precision in the
  96107. * fixed-point division (err<<fracbits)/n.
  96108. */
  96109. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96110. err <<= fracbits;
  96111. err /= n;
  96112. /* err now holds err/n with fracbits fractional bits */
  96113. /*
  96114. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96115. * our purposes.
  96116. */
  96117. FLAC__ASSERT(err > 0);
  96118. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96119. if(bits > 16) {
  96120. err >>= (bits-16);
  96121. fracbits -= (bits-16);
  96122. }
  96123. rbps = (FLAC__uint32)err;
  96124. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96125. rbps *= FLAC__FP_LN2;
  96126. fracbits += 16;
  96127. FLAC__ASSERT(fracbits >= 0);
  96128. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96129. {
  96130. const int f = fracbits & 3;
  96131. if(f) {
  96132. rbps >>= f;
  96133. fracbits -= f;
  96134. }
  96135. }
  96136. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96137. if(rbps == 0)
  96138. return 0;
  96139. /*
  96140. * The return value must have 16 fractional bits. Since the whole part
  96141. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96142. * must be >= -3, these assertion allows us to be able to shift rbps
  96143. * left if necessary to get 16 fracbits without losing any bits of the
  96144. * whole part of rbps.
  96145. *
  96146. * There is a slight chance due to accumulated error that the whole part
  96147. * will require 6 bits, so we use 6 in the assertion. Really though as
  96148. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96149. */
  96150. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96151. FLAC__ASSERT(fracbits >= -3);
  96152. /* now shift the decimal point into place */
  96153. if(fracbits < 16)
  96154. return rbps << (16-fracbits);
  96155. else if(fracbits > 16)
  96156. return rbps >> (fracbits-16);
  96157. else
  96158. return rbps;
  96159. }
  96160. #endif
  96161. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96162. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96163. #else
  96164. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96165. #endif
  96166. {
  96167. FLAC__int32 last_error_0 = data[-1];
  96168. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96169. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96170. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96171. FLAC__int32 error, save;
  96172. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96173. unsigned i, order;
  96174. for(i = 0; i < data_len; i++) {
  96175. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96176. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96177. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96178. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96179. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96180. }
  96181. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96182. order = 0;
  96183. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96184. order = 1;
  96185. else if(total_error_2 < min(total_error_3, total_error_4))
  96186. order = 2;
  96187. else if(total_error_3 < total_error_4)
  96188. order = 3;
  96189. else
  96190. order = 4;
  96191. /* Estimate the expected number of bits per residual signal sample. */
  96192. /* 'total_error*' is linearly related to the variance of the residual */
  96193. /* signal, so we use it directly to compute E(|x|) */
  96194. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96195. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96196. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96197. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96198. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96199. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96200. 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);
  96201. 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);
  96202. 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);
  96203. 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);
  96204. 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);
  96205. #else
  96206. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96207. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96208. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96209. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96210. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96211. #endif
  96212. return order;
  96213. }
  96214. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96215. 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])
  96216. #else
  96217. 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])
  96218. #endif
  96219. {
  96220. FLAC__int32 last_error_0 = data[-1];
  96221. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96222. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96223. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96224. FLAC__int32 error, save;
  96225. /* total_error_* are 64-bits to avoid overflow when encoding
  96226. * erratic signals when the bits-per-sample and blocksize are
  96227. * large.
  96228. */
  96229. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96230. unsigned i, order;
  96231. for(i = 0; i < data_len; i++) {
  96232. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96233. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96234. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96235. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96236. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96237. }
  96238. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96239. order = 0;
  96240. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96241. order = 1;
  96242. else if(total_error_2 < min(total_error_3, total_error_4))
  96243. order = 2;
  96244. else if(total_error_3 < total_error_4)
  96245. order = 3;
  96246. else
  96247. order = 4;
  96248. /* Estimate the expected number of bits per residual signal sample. */
  96249. /* 'total_error*' is linearly related to the variance of the residual */
  96250. /* signal, so we use it directly to compute E(|x|) */
  96251. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96252. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96253. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96254. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96255. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96256. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96257. #if defined _MSC_VER || defined __MINGW32__
  96258. /* with MSVC you have to spoon feed it the casting */
  96259. 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);
  96260. 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);
  96261. 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);
  96262. 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);
  96263. 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);
  96264. #else
  96265. 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);
  96266. 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);
  96267. 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);
  96268. 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);
  96269. 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);
  96270. #endif
  96271. #else
  96272. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96273. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96274. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96275. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96276. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96277. #endif
  96278. return order;
  96279. }
  96280. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96281. {
  96282. const int idata_len = (int)data_len;
  96283. int i;
  96284. switch(order) {
  96285. case 0:
  96286. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96287. memcpy(residual, data, sizeof(residual[0])*data_len);
  96288. break;
  96289. case 1:
  96290. for(i = 0; i < idata_len; i++)
  96291. residual[i] = data[i] - data[i-1];
  96292. break;
  96293. case 2:
  96294. for(i = 0; i < idata_len; i++)
  96295. #if 1 /* OPT: may be faster with some compilers on some systems */
  96296. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96297. #else
  96298. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96299. #endif
  96300. break;
  96301. case 3:
  96302. for(i = 0; i < idata_len; i++)
  96303. #if 1 /* OPT: may be faster with some compilers on some systems */
  96304. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96305. #else
  96306. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96307. #endif
  96308. break;
  96309. case 4:
  96310. for(i = 0; i < idata_len; i++)
  96311. #if 1 /* OPT: may be faster with some compilers on some systems */
  96312. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96313. #else
  96314. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96315. #endif
  96316. break;
  96317. default:
  96318. FLAC__ASSERT(0);
  96319. }
  96320. }
  96321. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96322. {
  96323. int i, idata_len = (int)data_len;
  96324. switch(order) {
  96325. case 0:
  96326. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96327. memcpy(data, residual, sizeof(residual[0])*data_len);
  96328. break;
  96329. case 1:
  96330. for(i = 0; i < idata_len; i++)
  96331. data[i] = residual[i] + data[i-1];
  96332. break;
  96333. case 2:
  96334. for(i = 0; i < idata_len; i++)
  96335. #if 1 /* OPT: may be faster with some compilers on some systems */
  96336. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96337. #else
  96338. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96339. #endif
  96340. break;
  96341. case 3:
  96342. for(i = 0; i < idata_len; i++)
  96343. #if 1 /* OPT: may be faster with some compilers on some systems */
  96344. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96345. #else
  96346. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96347. #endif
  96348. break;
  96349. case 4:
  96350. for(i = 0; i < idata_len; i++)
  96351. #if 1 /* OPT: may be faster with some compilers on some systems */
  96352. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96353. #else
  96354. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96355. #endif
  96356. break;
  96357. default:
  96358. FLAC__ASSERT(0);
  96359. }
  96360. }
  96361. #endif
  96362. /*** End of inlined file: fixed.c ***/
  96363. /*** Start of inlined file: float.c ***/
  96364. /*** Start of inlined file: juce_FlacHeader.h ***/
  96365. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96366. // tasks..
  96367. #define VERSION "1.2.1"
  96368. #define FLAC__NO_DLL 1
  96369. #if JUCE_MSVC
  96370. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96371. #endif
  96372. #if JUCE_MAC
  96373. #define FLAC__SYS_DARWIN 1
  96374. #endif
  96375. /*** End of inlined file: juce_FlacHeader.h ***/
  96376. #if JUCE_USE_FLAC
  96377. #if HAVE_CONFIG_H
  96378. # include <config.h>
  96379. #endif
  96380. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96381. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96382. #ifdef _MSC_VER
  96383. #define FLAC__U64L(x) x
  96384. #else
  96385. #define FLAC__U64L(x) x##LLU
  96386. #endif
  96387. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96388. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96389. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96390. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96391. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96392. /* Lookup tables for Knuth's logarithm algorithm */
  96393. #define LOG2_LOOKUP_PRECISION 16
  96394. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96395. {
  96396. /*
  96397. * 0 fraction bits
  96398. */
  96399. /* undefined */ 0x00000000,
  96400. /* lg(2/1) = */ 0x00000001,
  96401. /* lg(4/3) = */ 0x00000000,
  96402. /* lg(8/7) = */ 0x00000000,
  96403. /* lg(16/15) = */ 0x00000000,
  96404. /* lg(32/31) = */ 0x00000000,
  96405. /* lg(64/63) = */ 0x00000000,
  96406. /* lg(128/127) = */ 0x00000000,
  96407. /* lg(256/255) = */ 0x00000000,
  96408. /* lg(512/511) = */ 0x00000000,
  96409. /* lg(1024/1023) = */ 0x00000000,
  96410. /* lg(2048/2047) = */ 0x00000000,
  96411. /* lg(4096/4095) = */ 0x00000000,
  96412. /* lg(8192/8191) = */ 0x00000000,
  96413. /* lg(16384/16383) = */ 0x00000000,
  96414. /* lg(32768/32767) = */ 0x00000000
  96415. },
  96416. {
  96417. /*
  96418. * 4 fraction bits
  96419. */
  96420. /* undefined */ 0x00000000,
  96421. /* lg(2/1) = */ 0x00000010,
  96422. /* lg(4/3) = */ 0x00000007,
  96423. /* lg(8/7) = */ 0x00000003,
  96424. /* lg(16/15) = */ 0x00000001,
  96425. /* lg(32/31) = */ 0x00000001,
  96426. /* lg(64/63) = */ 0x00000000,
  96427. /* lg(128/127) = */ 0x00000000,
  96428. /* lg(256/255) = */ 0x00000000,
  96429. /* lg(512/511) = */ 0x00000000,
  96430. /* lg(1024/1023) = */ 0x00000000,
  96431. /* lg(2048/2047) = */ 0x00000000,
  96432. /* lg(4096/4095) = */ 0x00000000,
  96433. /* lg(8192/8191) = */ 0x00000000,
  96434. /* lg(16384/16383) = */ 0x00000000,
  96435. /* lg(32768/32767) = */ 0x00000000
  96436. },
  96437. {
  96438. /*
  96439. * 8 fraction bits
  96440. */
  96441. /* undefined */ 0x00000000,
  96442. /* lg(2/1) = */ 0x00000100,
  96443. /* lg(4/3) = */ 0x0000006a,
  96444. /* lg(8/7) = */ 0x00000031,
  96445. /* lg(16/15) = */ 0x00000018,
  96446. /* lg(32/31) = */ 0x0000000c,
  96447. /* lg(64/63) = */ 0x00000006,
  96448. /* lg(128/127) = */ 0x00000003,
  96449. /* lg(256/255) = */ 0x00000001,
  96450. /* lg(512/511) = */ 0x00000001,
  96451. /* lg(1024/1023) = */ 0x00000000,
  96452. /* lg(2048/2047) = */ 0x00000000,
  96453. /* lg(4096/4095) = */ 0x00000000,
  96454. /* lg(8192/8191) = */ 0x00000000,
  96455. /* lg(16384/16383) = */ 0x00000000,
  96456. /* lg(32768/32767) = */ 0x00000000
  96457. },
  96458. {
  96459. /*
  96460. * 12 fraction bits
  96461. */
  96462. /* undefined */ 0x00000000,
  96463. /* lg(2/1) = */ 0x00001000,
  96464. /* lg(4/3) = */ 0x000006a4,
  96465. /* lg(8/7) = */ 0x00000315,
  96466. /* lg(16/15) = */ 0x0000017d,
  96467. /* lg(32/31) = */ 0x000000bc,
  96468. /* lg(64/63) = */ 0x0000005d,
  96469. /* lg(128/127) = */ 0x0000002e,
  96470. /* lg(256/255) = */ 0x00000017,
  96471. /* lg(512/511) = */ 0x0000000c,
  96472. /* lg(1024/1023) = */ 0x00000006,
  96473. /* lg(2048/2047) = */ 0x00000003,
  96474. /* lg(4096/4095) = */ 0x00000001,
  96475. /* lg(8192/8191) = */ 0x00000001,
  96476. /* lg(16384/16383) = */ 0x00000000,
  96477. /* lg(32768/32767) = */ 0x00000000
  96478. },
  96479. {
  96480. /*
  96481. * 16 fraction bits
  96482. */
  96483. /* undefined */ 0x00000000,
  96484. /* lg(2/1) = */ 0x00010000,
  96485. /* lg(4/3) = */ 0x00006a40,
  96486. /* lg(8/7) = */ 0x00003151,
  96487. /* lg(16/15) = */ 0x000017d6,
  96488. /* lg(32/31) = */ 0x00000bba,
  96489. /* lg(64/63) = */ 0x000005d1,
  96490. /* lg(128/127) = */ 0x000002e6,
  96491. /* lg(256/255) = */ 0x00000172,
  96492. /* lg(512/511) = */ 0x000000b9,
  96493. /* lg(1024/1023) = */ 0x0000005c,
  96494. /* lg(2048/2047) = */ 0x0000002e,
  96495. /* lg(4096/4095) = */ 0x00000017,
  96496. /* lg(8192/8191) = */ 0x0000000c,
  96497. /* lg(16384/16383) = */ 0x00000006,
  96498. /* lg(32768/32767) = */ 0x00000003
  96499. },
  96500. {
  96501. /*
  96502. * 20 fraction bits
  96503. */
  96504. /* undefined */ 0x00000000,
  96505. /* lg(2/1) = */ 0x00100000,
  96506. /* lg(4/3) = */ 0x0006a3fe,
  96507. /* lg(8/7) = */ 0x00031513,
  96508. /* lg(16/15) = */ 0x00017d60,
  96509. /* lg(32/31) = */ 0x0000bb9d,
  96510. /* lg(64/63) = */ 0x00005d10,
  96511. /* lg(128/127) = */ 0x00002e59,
  96512. /* lg(256/255) = */ 0x00001721,
  96513. /* lg(512/511) = */ 0x00000b8e,
  96514. /* lg(1024/1023) = */ 0x000005c6,
  96515. /* lg(2048/2047) = */ 0x000002e3,
  96516. /* lg(4096/4095) = */ 0x00000171,
  96517. /* lg(8192/8191) = */ 0x000000b9,
  96518. /* lg(16384/16383) = */ 0x0000005c,
  96519. /* lg(32768/32767) = */ 0x0000002e
  96520. },
  96521. {
  96522. /*
  96523. * 24 fraction bits
  96524. */
  96525. /* undefined */ 0x00000000,
  96526. /* lg(2/1) = */ 0x01000000,
  96527. /* lg(4/3) = */ 0x006a3fe6,
  96528. /* lg(8/7) = */ 0x00315130,
  96529. /* lg(16/15) = */ 0x0017d605,
  96530. /* lg(32/31) = */ 0x000bb9ca,
  96531. /* lg(64/63) = */ 0x0005d0fc,
  96532. /* lg(128/127) = */ 0x0002e58f,
  96533. /* lg(256/255) = */ 0x0001720e,
  96534. /* lg(512/511) = */ 0x0000b8d8,
  96535. /* lg(1024/1023) = */ 0x00005c61,
  96536. /* lg(2048/2047) = */ 0x00002e2d,
  96537. /* lg(4096/4095) = */ 0x00001716,
  96538. /* lg(8192/8191) = */ 0x00000b8b,
  96539. /* lg(16384/16383) = */ 0x000005c5,
  96540. /* lg(32768/32767) = */ 0x000002e3
  96541. },
  96542. {
  96543. /*
  96544. * 28 fraction bits
  96545. */
  96546. /* undefined */ 0x00000000,
  96547. /* lg(2/1) = */ 0x10000000,
  96548. /* lg(4/3) = */ 0x06a3fe5c,
  96549. /* lg(8/7) = */ 0x03151301,
  96550. /* lg(16/15) = */ 0x017d6049,
  96551. /* lg(32/31) = */ 0x00bb9ca6,
  96552. /* lg(64/63) = */ 0x005d0fba,
  96553. /* lg(128/127) = */ 0x002e58f7,
  96554. /* lg(256/255) = */ 0x001720da,
  96555. /* lg(512/511) = */ 0x000b8d87,
  96556. /* lg(1024/1023) = */ 0x0005c60b,
  96557. /* lg(2048/2047) = */ 0x0002e2d7,
  96558. /* lg(4096/4095) = */ 0x00017160,
  96559. /* lg(8192/8191) = */ 0x0000b8ad,
  96560. /* lg(16384/16383) = */ 0x00005c56,
  96561. /* lg(32768/32767) = */ 0x00002e2b
  96562. }
  96563. };
  96564. #if 0
  96565. static const FLAC__uint64 log2_lookup_wide[] = {
  96566. {
  96567. /*
  96568. * 32 fraction bits
  96569. */
  96570. /* undefined */ 0x00000000,
  96571. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96572. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96573. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96574. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96575. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96576. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96577. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96578. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96579. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96580. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96581. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96582. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96583. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96584. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96585. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96586. },
  96587. {
  96588. /*
  96589. * 48 fraction bits
  96590. */
  96591. /* undefined */ 0x00000000,
  96592. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96593. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96594. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96595. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96596. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96597. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96598. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96599. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96600. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96601. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96602. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96603. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96604. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96605. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96606. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96607. }
  96608. };
  96609. #endif
  96610. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96611. {
  96612. const FLAC__uint32 ONE = (1u << fracbits);
  96613. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96614. FLAC__ASSERT(fracbits < 32);
  96615. FLAC__ASSERT((fracbits & 0x3) == 0);
  96616. if(x < ONE)
  96617. return 0;
  96618. if(precision > LOG2_LOOKUP_PRECISION)
  96619. precision = LOG2_LOOKUP_PRECISION;
  96620. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96621. {
  96622. FLAC__uint32 y = 0;
  96623. FLAC__uint32 z = x >> 1, k = 1;
  96624. while (x > ONE && k < precision) {
  96625. if (x - z >= ONE) {
  96626. x -= z;
  96627. z = x >> k;
  96628. y += table[k];
  96629. }
  96630. else {
  96631. z >>= 1;
  96632. k++;
  96633. }
  96634. }
  96635. return y;
  96636. }
  96637. }
  96638. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96639. #endif
  96640. /*** End of inlined file: float.c ***/
  96641. /*** Start of inlined file: format.c ***/
  96642. /*** Start of inlined file: juce_FlacHeader.h ***/
  96643. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96644. // tasks..
  96645. #define VERSION "1.2.1"
  96646. #define FLAC__NO_DLL 1
  96647. #if JUCE_MSVC
  96648. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96649. #endif
  96650. #if JUCE_MAC
  96651. #define FLAC__SYS_DARWIN 1
  96652. #endif
  96653. /*** End of inlined file: juce_FlacHeader.h ***/
  96654. #if JUCE_USE_FLAC
  96655. #if HAVE_CONFIG_H
  96656. # include <config.h>
  96657. #endif
  96658. #include <stdio.h>
  96659. #include <stdlib.h> /* for qsort() */
  96660. #include <string.h> /* for memset() */
  96661. #ifndef FLaC__INLINE
  96662. #define FLaC__INLINE
  96663. #endif
  96664. #ifdef min
  96665. #undef min
  96666. #endif
  96667. #define min(a,b) ((a)<(b)?(a):(b))
  96668. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96669. #ifdef _MSC_VER
  96670. #define FLAC__U64L(x) x
  96671. #else
  96672. #define FLAC__U64L(x) x##LLU
  96673. #endif
  96674. /* VERSION should come from configure */
  96675. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96676. ;
  96677. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96678. /* yet one more hack because of MSVC6: */
  96679. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96680. #else
  96681. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96682. #endif
  96683. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96684. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96685. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96686. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96687. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96688. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96689. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96690. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96691. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96692. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96693. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96694. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96695. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96696. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96697. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96698. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96699. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96700. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96701. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96702. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96703. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96704. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96705. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96706. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96707. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96708. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96709. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96710. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96711. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96712. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96713. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96714. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96715. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96716. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96717. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96718. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96719. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96720. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96721. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96722. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96723. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96724. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96725. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96726. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96727. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96728. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96729. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96730. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96731. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96732. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96733. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96734. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96735. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96736. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96737. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96738. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96739. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96740. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96741. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96742. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96743. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96744. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96745. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96746. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96747. "PARTITIONED_RICE",
  96748. "PARTITIONED_RICE2"
  96749. };
  96750. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96751. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96752. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96753. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96754. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96755. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96756. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96757. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96758. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96759. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96760. "CONSTANT",
  96761. "VERBATIM",
  96762. "FIXED",
  96763. "LPC"
  96764. };
  96765. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96766. "INDEPENDENT",
  96767. "LEFT_SIDE",
  96768. "RIGHT_SIDE",
  96769. "MID_SIDE"
  96770. };
  96771. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96772. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96773. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96774. };
  96775. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96776. "STREAMINFO",
  96777. "PADDING",
  96778. "APPLICATION",
  96779. "SEEKTABLE",
  96780. "VORBIS_COMMENT",
  96781. "CUESHEET",
  96782. "PICTURE"
  96783. };
  96784. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96785. "Other",
  96786. "32x32 pixels 'file icon' (PNG only)",
  96787. "Other file icon",
  96788. "Cover (front)",
  96789. "Cover (back)",
  96790. "Leaflet page",
  96791. "Media (e.g. label side of CD)",
  96792. "Lead artist/lead performer/soloist",
  96793. "Artist/performer",
  96794. "Conductor",
  96795. "Band/Orchestra",
  96796. "Composer",
  96797. "Lyricist/text writer",
  96798. "Recording Location",
  96799. "During recording",
  96800. "During performance",
  96801. "Movie/video screen capture",
  96802. "A bright coloured fish",
  96803. "Illustration",
  96804. "Band/artist logotype",
  96805. "Publisher/Studio logotype"
  96806. };
  96807. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96808. {
  96809. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96810. return false;
  96811. }
  96812. else
  96813. return true;
  96814. }
  96815. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96816. {
  96817. if(
  96818. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96819. (
  96820. sample_rate >= (1u << 16) &&
  96821. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96822. )
  96823. ) {
  96824. return false;
  96825. }
  96826. else
  96827. return true;
  96828. }
  96829. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96830. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96831. {
  96832. unsigned i;
  96833. FLAC__uint64 prev_sample_number = 0;
  96834. FLAC__bool got_prev = false;
  96835. FLAC__ASSERT(0 != seek_table);
  96836. for(i = 0; i < seek_table->num_points; i++) {
  96837. if(got_prev) {
  96838. if(
  96839. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96840. seek_table->points[i].sample_number <= prev_sample_number
  96841. )
  96842. return false;
  96843. }
  96844. prev_sample_number = seek_table->points[i].sample_number;
  96845. got_prev = true;
  96846. }
  96847. return true;
  96848. }
  96849. /* used as the sort predicate for qsort() */
  96850. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96851. {
  96852. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96853. if(l->sample_number == r->sample_number)
  96854. return 0;
  96855. else if(l->sample_number < r->sample_number)
  96856. return -1;
  96857. else
  96858. return 1;
  96859. }
  96860. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96861. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96862. {
  96863. unsigned i, j;
  96864. FLAC__bool first;
  96865. FLAC__ASSERT(0 != seek_table);
  96866. /* sort the seekpoints */
  96867. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96868. /* uniquify the seekpoints */
  96869. first = true;
  96870. for(i = j = 0; i < seek_table->num_points; i++) {
  96871. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96872. if(!first) {
  96873. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96874. continue;
  96875. }
  96876. }
  96877. first = false;
  96878. seek_table->points[j++] = seek_table->points[i];
  96879. }
  96880. for(i = j; i < seek_table->num_points; i++) {
  96881. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96882. seek_table->points[i].stream_offset = 0;
  96883. seek_table->points[i].frame_samples = 0;
  96884. }
  96885. return j;
  96886. }
  96887. /*
  96888. * also disallows non-shortest-form encodings, c.f.
  96889. * http://www.unicode.org/versions/corrigendum1.html
  96890. * and a more clear explanation at the end of this section:
  96891. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96892. */
  96893. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96894. {
  96895. FLAC__ASSERT(0 != utf8);
  96896. if ((utf8[0] & 0x80) == 0) {
  96897. return 1;
  96898. }
  96899. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96900. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96901. return 0;
  96902. return 2;
  96903. }
  96904. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96905. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96906. return 0;
  96907. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96908. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96909. return 0;
  96910. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96911. return 0;
  96912. return 3;
  96913. }
  96914. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96915. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96916. return 0;
  96917. return 4;
  96918. }
  96919. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96920. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96921. return 0;
  96922. return 5;
  96923. }
  96924. 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) {
  96925. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96926. return 0;
  96927. return 6;
  96928. }
  96929. else {
  96930. return 0;
  96931. }
  96932. }
  96933. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96934. {
  96935. char c;
  96936. for(c = *name; c; c = *(++name))
  96937. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96938. return false;
  96939. return true;
  96940. }
  96941. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96942. {
  96943. if(length == (unsigned)(-1)) {
  96944. while(*value) {
  96945. unsigned n = utf8len_(value);
  96946. if(n == 0)
  96947. return false;
  96948. value += n;
  96949. }
  96950. }
  96951. else {
  96952. const FLAC__byte *end = value + length;
  96953. while(value < end) {
  96954. unsigned n = utf8len_(value);
  96955. if(n == 0)
  96956. return false;
  96957. value += n;
  96958. }
  96959. if(value != end)
  96960. return false;
  96961. }
  96962. return true;
  96963. }
  96964. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96965. {
  96966. const FLAC__byte *s, *end;
  96967. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96968. if(*s < 0x20 || *s > 0x7D)
  96969. return false;
  96970. }
  96971. if(s == end)
  96972. return false;
  96973. s++; /* skip '=' */
  96974. while(s < end) {
  96975. unsigned n = utf8len_(s);
  96976. if(n == 0)
  96977. return false;
  96978. s += n;
  96979. }
  96980. if(s != end)
  96981. return false;
  96982. return true;
  96983. }
  96984. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96985. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96986. {
  96987. unsigned i, j;
  96988. if(check_cd_da_subset) {
  96989. if(cue_sheet->lead_in < 2 * 44100) {
  96990. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96991. return false;
  96992. }
  96993. if(cue_sheet->lead_in % 588 != 0) {
  96994. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96995. return false;
  96996. }
  96997. }
  96998. if(cue_sheet->num_tracks == 0) {
  96999. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97000. return false;
  97001. }
  97002. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97003. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97004. return false;
  97005. }
  97006. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97007. if(cue_sheet->tracks[i].number == 0) {
  97008. if(violation) *violation = "cue sheet may not have a track number 0";
  97009. return false;
  97010. }
  97011. if(check_cd_da_subset) {
  97012. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97013. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97014. return false;
  97015. }
  97016. }
  97017. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97018. if(violation) {
  97019. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97020. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97021. else
  97022. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97023. }
  97024. return false;
  97025. }
  97026. if(i < cue_sheet->num_tracks - 1) {
  97027. if(cue_sheet->tracks[i].num_indices == 0) {
  97028. if(violation) *violation = "cue sheet track must have at least one index point";
  97029. return false;
  97030. }
  97031. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97032. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97033. return false;
  97034. }
  97035. }
  97036. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97037. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97038. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97039. return false;
  97040. }
  97041. if(j > 0) {
  97042. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97043. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97044. return false;
  97045. }
  97046. }
  97047. }
  97048. }
  97049. return true;
  97050. }
  97051. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97052. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97053. {
  97054. char *p;
  97055. FLAC__byte *b;
  97056. for(p = picture->mime_type; *p; p++) {
  97057. if(*p < 0x20 || *p > 0x7e) {
  97058. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97059. return false;
  97060. }
  97061. }
  97062. for(b = picture->description; *b; ) {
  97063. unsigned n = utf8len_(b);
  97064. if(n == 0) {
  97065. if(violation) *violation = "description string must be valid UTF-8";
  97066. return false;
  97067. }
  97068. b += n;
  97069. }
  97070. return true;
  97071. }
  97072. /*
  97073. * These routines are private to libFLAC
  97074. */
  97075. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97076. {
  97077. return
  97078. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97079. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97080. blocksize,
  97081. predictor_order
  97082. );
  97083. }
  97084. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97085. {
  97086. unsigned max_rice_partition_order = 0;
  97087. while(!(blocksize & 1)) {
  97088. max_rice_partition_order++;
  97089. blocksize >>= 1;
  97090. }
  97091. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97092. }
  97093. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97094. {
  97095. unsigned max_rice_partition_order = limit;
  97096. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97097. max_rice_partition_order--;
  97098. FLAC__ASSERT(
  97099. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97100. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97101. );
  97102. return max_rice_partition_order;
  97103. }
  97104. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97105. {
  97106. FLAC__ASSERT(0 != object);
  97107. object->parameters = 0;
  97108. object->raw_bits = 0;
  97109. object->capacity_by_order = 0;
  97110. }
  97111. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97112. {
  97113. FLAC__ASSERT(0 != object);
  97114. if(0 != object->parameters)
  97115. free(object->parameters);
  97116. if(0 != object->raw_bits)
  97117. free(object->raw_bits);
  97118. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97119. }
  97120. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97121. {
  97122. FLAC__ASSERT(0 != object);
  97123. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97124. if(object->capacity_by_order < max_partition_order) {
  97125. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97126. return false;
  97127. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97128. return false;
  97129. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97130. object->capacity_by_order = max_partition_order;
  97131. }
  97132. return true;
  97133. }
  97134. #endif
  97135. /*** End of inlined file: format.c ***/
  97136. /*** Start of inlined file: lpc_flac.c ***/
  97137. /*** Start of inlined file: juce_FlacHeader.h ***/
  97138. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97139. // tasks..
  97140. #define VERSION "1.2.1"
  97141. #define FLAC__NO_DLL 1
  97142. #if JUCE_MSVC
  97143. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97144. #endif
  97145. #if JUCE_MAC
  97146. #define FLAC__SYS_DARWIN 1
  97147. #endif
  97148. /*** End of inlined file: juce_FlacHeader.h ***/
  97149. #if JUCE_USE_FLAC
  97150. #if HAVE_CONFIG_H
  97151. # include <config.h>
  97152. #endif
  97153. #include <math.h>
  97154. /*** Start of inlined file: lpc.h ***/
  97155. #ifndef FLAC__PRIVATE__LPC_H
  97156. #define FLAC__PRIVATE__LPC_H
  97157. #ifdef HAVE_CONFIG_H
  97158. #include <config.h>
  97159. #endif
  97160. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97161. /*
  97162. * FLAC__lpc_window_data()
  97163. * --------------------------------------------------------------------
  97164. * Applies the given window to the data.
  97165. * OPT: asm implementation
  97166. *
  97167. * IN in[0,data_len-1]
  97168. * IN window[0,data_len-1]
  97169. * OUT out[0,lag-1]
  97170. * IN data_len
  97171. */
  97172. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97173. /*
  97174. * FLAC__lpc_compute_autocorrelation()
  97175. * --------------------------------------------------------------------
  97176. * Compute the autocorrelation for lags between 0 and lag-1.
  97177. * Assumes data[] outside of [0,data_len-1] == 0.
  97178. * Asserts that lag > 0.
  97179. *
  97180. * IN data[0,data_len-1]
  97181. * IN data_len
  97182. * IN 0 < lag <= data_len
  97183. * OUT autoc[0,lag-1]
  97184. */
  97185. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97186. #ifndef FLAC__NO_ASM
  97187. # ifdef FLAC__CPU_IA32
  97188. # ifdef FLAC__HAS_NASM
  97189. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97190. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97191. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97192. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97193. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97194. # endif
  97195. # endif
  97196. #endif
  97197. /*
  97198. * FLAC__lpc_compute_lp_coefficients()
  97199. * --------------------------------------------------------------------
  97200. * Computes LP coefficients for orders 1..max_order.
  97201. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97202. * and there is no point in calculating a predictor.
  97203. *
  97204. * IN autoc[0,max_order] autocorrelation values
  97205. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97206. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97207. * *** IMPORTANT:
  97208. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97209. * OUT error[0,max_order-1] error for each order (more
  97210. * specifically, the variance of
  97211. * the error signal times # of
  97212. * samples in the signal)
  97213. *
  97214. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97215. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97216. * in lp_coeff[7][0,7], etc.
  97217. */
  97218. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97219. /*
  97220. * FLAC__lpc_quantize_coefficients()
  97221. * --------------------------------------------------------------------
  97222. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97223. * must be less than 32 (sizeof(FLAC__int32)*8).
  97224. *
  97225. * IN lp_coeff[0,order-1] LP coefficients
  97226. * IN order LP order
  97227. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97228. * desired precision (in bits, including sign
  97229. * bit) of largest coefficient
  97230. * OUT qlp_coeff[0,order-1] quantized coefficients
  97231. * OUT shift # of bits to shift right to get approximated
  97232. * LP coefficients. NOTE: could be negative.
  97233. * RETURN 0 => quantization OK
  97234. * 1 => coefficients require too much shifting for *shift to
  97235. * fit in the LPC subframe header. 'shift' is unset.
  97236. * 2 => coefficients are all zero, which is bad. 'shift' is
  97237. * unset.
  97238. */
  97239. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97240. /*
  97241. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97242. * --------------------------------------------------------------------
  97243. * Compute the residual signal obtained from sutracting the predicted
  97244. * signal from the original.
  97245. *
  97246. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97247. * IN data_len length of original signal
  97248. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97249. * IN order > 0 LP order
  97250. * IN lp_quantization quantization of LP coefficients in bits
  97251. * OUT residual[0,data_len-1] residual signal
  97252. */
  97253. 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[]);
  97254. 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[]);
  97255. #ifndef FLAC__NO_ASM
  97256. # ifdef FLAC__CPU_IA32
  97257. # ifdef FLAC__HAS_NASM
  97258. 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[]);
  97259. 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[]);
  97260. # endif
  97261. # endif
  97262. #endif
  97263. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97264. /*
  97265. * FLAC__lpc_restore_signal()
  97266. * --------------------------------------------------------------------
  97267. * Restore the original signal by summing the residual and the
  97268. * predictor.
  97269. *
  97270. * IN residual[0,data_len-1] residual signal
  97271. * IN data_len length of original signal
  97272. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97273. * IN order > 0 LP order
  97274. * IN lp_quantization quantization of LP coefficients in bits
  97275. * *** IMPORTANT: the caller must pass in the historical samples:
  97276. * IN data[-order,-1] previously-reconstructed historical samples
  97277. * OUT data[0,data_len-1] original signal
  97278. */
  97279. 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[]);
  97280. 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[]);
  97281. #ifndef FLAC__NO_ASM
  97282. # ifdef FLAC__CPU_IA32
  97283. # ifdef FLAC__HAS_NASM
  97284. 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[]);
  97285. 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[]);
  97286. # endif /* FLAC__HAS_NASM */
  97287. # elif defined FLAC__CPU_PPC
  97288. 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[]);
  97289. 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[]);
  97290. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97291. #endif /* FLAC__NO_ASM */
  97292. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97293. /*
  97294. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97295. * --------------------------------------------------------------------
  97296. * Compute the expected number of bits per residual signal sample
  97297. * based on the LP error (which is related to the residual variance).
  97298. *
  97299. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97300. * IN total_samples > 0 # of samples in residual signal
  97301. * RETURN expected bits per sample
  97302. */
  97303. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97304. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97305. /*
  97306. * FLAC__lpc_compute_best_order()
  97307. * --------------------------------------------------------------------
  97308. * Compute the best order from the array of signal errors returned
  97309. * during coefficient computation.
  97310. *
  97311. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97312. * IN max_order > 0 max LP order
  97313. * IN total_samples > 0 # of samples in residual signal
  97314. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97315. * (includes warmup sample size and quantized LP coefficient)
  97316. * RETURN [1,max_order] best order
  97317. */
  97318. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97319. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97320. #endif
  97321. /*** End of inlined file: lpc.h ***/
  97322. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97323. #include <stdio.h>
  97324. #endif
  97325. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97326. #ifndef M_LN2
  97327. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97328. #define M_LN2 0.69314718055994530942
  97329. #endif
  97330. /* OPT: #undef'ing this may improve the speed on some architectures */
  97331. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97332. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97333. {
  97334. unsigned i;
  97335. for(i = 0; i < data_len; i++)
  97336. out[i] = in[i] * window[i];
  97337. }
  97338. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97339. {
  97340. /* a readable, but slower, version */
  97341. #if 0
  97342. FLAC__real d;
  97343. unsigned i;
  97344. FLAC__ASSERT(lag > 0);
  97345. FLAC__ASSERT(lag <= data_len);
  97346. /*
  97347. * Technically we should subtract the mean first like so:
  97348. * for(i = 0; i < data_len; i++)
  97349. * data[i] -= mean;
  97350. * but it appears not to make enough of a difference to matter, and
  97351. * most signals are already closely centered around zero
  97352. */
  97353. while(lag--) {
  97354. for(i = lag, d = 0.0; i < data_len; i++)
  97355. d += data[i] * data[i - lag];
  97356. autoc[lag] = d;
  97357. }
  97358. #endif
  97359. /*
  97360. * this version tends to run faster because of better data locality
  97361. * ('data_len' is usually much larger than 'lag')
  97362. */
  97363. FLAC__real d;
  97364. unsigned sample, coeff;
  97365. const unsigned limit = data_len - lag;
  97366. FLAC__ASSERT(lag > 0);
  97367. FLAC__ASSERT(lag <= data_len);
  97368. for(coeff = 0; coeff < lag; coeff++)
  97369. autoc[coeff] = 0.0;
  97370. for(sample = 0; sample <= limit; sample++) {
  97371. d = data[sample];
  97372. for(coeff = 0; coeff < lag; coeff++)
  97373. autoc[coeff] += d * data[sample+coeff];
  97374. }
  97375. for(; sample < data_len; sample++) {
  97376. d = data[sample];
  97377. for(coeff = 0; coeff < data_len - sample; coeff++)
  97378. autoc[coeff] += d * data[sample+coeff];
  97379. }
  97380. }
  97381. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97382. {
  97383. unsigned i, j;
  97384. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97385. FLAC__ASSERT(0 != max_order);
  97386. FLAC__ASSERT(0 < *max_order);
  97387. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97388. FLAC__ASSERT(autoc[0] != 0.0);
  97389. err = autoc[0];
  97390. for(i = 0; i < *max_order; i++) {
  97391. /* Sum up this iteration's reflection coefficient. */
  97392. r = -autoc[i+1];
  97393. for(j = 0; j < i; j++)
  97394. r -= lpc[j] * autoc[i-j];
  97395. ref[i] = (r/=err);
  97396. /* Update LPC coefficients and total error. */
  97397. lpc[i]=r;
  97398. for(j = 0; j < (i>>1); j++) {
  97399. FLAC__double tmp = lpc[j];
  97400. lpc[j] += r * lpc[i-1-j];
  97401. lpc[i-1-j] += r * tmp;
  97402. }
  97403. if(i & 1)
  97404. lpc[j] += lpc[j] * r;
  97405. err *= (1.0 - r * r);
  97406. /* save this order */
  97407. for(j = 0; j <= i; j++)
  97408. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97409. error[i] = err;
  97410. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97411. if(err == 0.0) {
  97412. *max_order = i+1;
  97413. return;
  97414. }
  97415. }
  97416. }
  97417. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97418. {
  97419. unsigned i;
  97420. FLAC__double cmax;
  97421. FLAC__int32 qmax, qmin;
  97422. FLAC__ASSERT(precision > 0);
  97423. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97424. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97425. precision--;
  97426. qmax = 1 << precision;
  97427. qmin = -qmax;
  97428. qmax--;
  97429. /* calc cmax = max( |lp_coeff[i]| ) */
  97430. cmax = 0.0;
  97431. for(i = 0; i < order; i++) {
  97432. const FLAC__double d = fabs(lp_coeff[i]);
  97433. if(d > cmax)
  97434. cmax = d;
  97435. }
  97436. if(cmax <= 0.0) {
  97437. /* => coefficients are all 0, which means our constant-detect didn't work */
  97438. return 2;
  97439. }
  97440. else {
  97441. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97442. const int min_shiftlimit = -max_shiftlimit - 1;
  97443. int log2cmax;
  97444. (void)frexp(cmax, &log2cmax);
  97445. log2cmax--;
  97446. *shift = (int)precision - log2cmax - 1;
  97447. if(*shift > max_shiftlimit)
  97448. *shift = max_shiftlimit;
  97449. else if(*shift < min_shiftlimit)
  97450. return 1;
  97451. }
  97452. if(*shift >= 0) {
  97453. FLAC__double error = 0.0;
  97454. FLAC__int32 q;
  97455. for(i = 0; i < order; i++) {
  97456. error += lp_coeff[i] * (1 << *shift);
  97457. #if 1 /* unfortunately lround() is C99 */
  97458. if(error >= 0.0)
  97459. q = (FLAC__int32)(error + 0.5);
  97460. else
  97461. q = (FLAC__int32)(error - 0.5);
  97462. #else
  97463. q = lround(error);
  97464. #endif
  97465. #ifdef FLAC__OVERFLOW_DETECT
  97466. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97467. 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]);
  97468. else if(q < qmin)
  97469. 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]);
  97470. #endif
  97471. if(q > qmax)
  97472. q = qmax;
  97473. else if(q < qmin)
  97474. q = qmin;
  97475. error -= q;
  97476. qlp_coeff[i] = q;
  97477. }
  97478. }
  97479. /* negative shift is very rare but due to design flaw, negative shift is
  97480. * a NOP in the decoder, so it must be handled specially by scaling down
  97481. * coeffs
  97482. */
  97483. else {
  97484. const int nshift = -(*shift);
  97485. FLAC__double error = 0.0;
  97486. FLAC__int32 q;
  97487. #ifdef DEBUG
  97488. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97489. #endif
  97490. for(i = 0; i < order; i++) {
  97491. error += lp_coeff[i] / (1 << nshift);
  97492. #if 1 /* unfortunately lround() is C99 */
  97493. if(error >= 0.0)
  97494. q = (FLAC__int32)(error + 0.5);
  97495. else
  97496. q = (FLAC__int32)(error - 0.5);
  97497. #else
  97498. q = lround(error);
  97499. #endif
  97500. #ifdef FLAC__OVERFLOW_DETECT
  97501. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97502. 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]);
  97503. else if(q < qmin)
  97504. 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]);
  97505. #endif
  97506. if(q > qmax)
  97507. q = qmax;
  97508. else if(q < qmin)
  97509. q = qmin;
  97510. error -= q;
  97511. qlp_coeff[i] = q;
  97512. }
  97513. *shift = 0;
  97514. }
  97515. return 0;
  97516. }
  97517. 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[])
  97518. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97519. {
  97520. FLAC__int64 sumo;
  97521. unsigned i, j;
  97522. FLAC__int32 sum;
  97523. const FLAC__int32 *history;
  97524. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97525. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97526. for(i=0;i<order;i++)
  97527. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97528. fprintf(stderr,"\n");
  97529. #endif
  97530. FLAC__ASSERT(order > 0);
  97531. for(i = 0; i < data_len; i++) {
  97532. sumo = 0;
  97533. sum = 0;
  97534. history = data;
  97535. for(j = 0; j < order; j++) {
  97536. sum += qlp_coeff[j] * (*(--history));
  97537. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97538. #if defined _MSC_VER
  97539. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97540. 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);
  97541. #else
  97542. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97543. 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);
  97544. #endif
  97545. }
  97546. *(residual++) = *(data++) - (sum >> lp_quantization);
  97547. }
  97548. /* Here's a slower but clearer version:
  97549. for(i = 0; i < data_len; i++) {
  97550. sum = 0;
  97551. for(j = 0; j < order; j++)
  97552. sum += qlp_coeff[j] * data[i-j-1];
  97553. residual[i] = data[i] - (sum >> lp_quantization);
  97554. }
  97555. */
  97556. }
  97557. #else /* fully unrolled version for normal use */
  97558. {
  97559. int i;
  97560. FLAC__int32 sum;
  97561. FLAC__ASSERT(order > 0);
  97562. FLAC__ASSERT(order <= 32);
  97563. /*
  97564. * We do unique versions up to 12th order since that's the subset limit.
  97565. * Also they are roughly ordered to match frequency of occurrence to
  97566. * minimize branching.
  97567. */
  97568. if(order <= 12) {
  97569. if(order > 8) {
  97570. if(order > 10) {
  97571. if(order == 12) {
  97572. for(i = 0; i < (int)data_len; i++) {
  97573. sum = 0;
  97574. sum += qlp_coeff[11] * data[i-12];
  97575. sum += qlp_coeff[10] * data[i-11];
  97576. sum += qlp_coeff[9] * data[i-10];
  97577. sum += qlp_coeff[8] * data[i-9];
  97578. sum += qlp_coeff[7] * data[i-8];
  97579. sum += qlp_coeff[6] * data[i-7];
  97580. sum += qlp_coeff[5] * data[i-6];
  97581. sum += qlp_coeff[4] * data[i-5];
  97582. sum += qlp_coeff[3] * data[i-4];
  97583. sum += qlp_coeff[2] * data[i-3];
  97584. sum += qlp_coeff[1] * data[i-2];
  97585. sum += qlp_coeff[0] * data[i-1];
  97586. residual[i] = data[i] - (sum >> lp_quantization);
  97587. }
  97588. }
  97589. else { /* order == 11 */
  97590. for(i = 0; i < (int)data_len; i++) {
  97591. sum = 0;
  97592. sum += qlp_coeff[10] * data[i-11];
  97593. sum += qlp_coeff[9] * data[i-10];
  97594. sum += qlp_coeff[8] * data[i-9];
  97595. sum += qlp_coeff[7] * data[i-8];
  97596. sum += qlp_coeff[6] * data[i-7];
  97597. sum += qlp_coeff[5] * data[i-6];
  97598. sum += qlp_coeff[4] * data[i-5];
  97599. sum += qlp_coeff[3] * data[i-4];
  97600. sum += qlp_coeff[2] * data[i-3];
  97601. sum += qlp_coeff[1] * data[i-2];
  97602. sum += qlp_coeff[0] * data[i-1];
  97603. residual[i] = data[i] - (sum >> lp_quantization);
  97604. }
  97605. }
  97606. }
  97607. else {
  97608. if(order == 10) {
  97609. for(i = 0; i < (int)data_len; i++) {
  97610. sum = 0;
  97611. sum += qlp_coeff[9] * data[i-10];
  97612. sum += qlp_coeff[8] * data[i-9];
  97613. sum += qlp_coeff[7] * data[i-8];
  97614. sum += qlp_coeff[6] * data[i-7];
  97615. sum += qlp_coeff[5] * data[i-6];
  97616. sum += qlp_coeff[4] * data[i-5];
  97617. sum += qlp_coeff[3] * data[i-4];
  97618. sum += qlp_coeff[2] * data[i-3];
  97619. sum += qlp_coeff[1] * data[i-2];
  97620. sum += qlp_coeff[0] * data[i-1];
  97621. residual[i] = data[i] - (sum >> lp_quantization);
  97622. }
  97623. }
  97624. else { /* order == 9 */
  97625. for(i = 0; i < (int)data_len; i++) {
  97626. sum = 0;
  97627. sum += qlp_coeff[8] * data[i-9];
  97628. sum += qlp_coeff[7] * data[i-8];
  97629. sum += qlp_coeff[6] * data[i-7];
  97630. sum += qlp_coeff[5] * data[i-6];
  97631. sum += qlp_coeff[4] * data[i-5];
  97632. sum += qlp_coeff[3] * data[i-4];
  97633. sum += qlp_coeff[2] * data[i-3];
  97634. sum += qlp_coeff[1] * data[i-2];
  97635. sum += qlp_coeff[0] * data[i-1];
  97636. residual[i] = data[i] - (sum >> lp_quantization);
  97637. }
  97638. }
  97639. }
  97640. }
  97641. else if(order > 4) {
  97642. if(order > 6) {
  97643. if(order == 8) {
  97644. for(i = 0; i < (int)data_len; i++) {
  97645. sum = 0;
  97646. sum += qlp_coeff[7] * data[i-8];
  97647. sum += qlp_coeff[6] * data[i-7];
  97648. sum += qlp_coeff[5] * data[i-6];
  97649. sum += qlp_coeff[4] * data[i-5];
  97650. sum += qlp_coeff[3] * data[i-4];
  97651. sum += qlp_coeff[2] * data[i-3];
  97652. sum += qlp_coeff[1] * data[i-2];
  97653. sum += qlp_coeff[0] * data[i-1];
  97654. residual[i] = data[i] - (sum >> lp_quantization);
  97655. }
  97656. }
  97657. else { /* order == 7 */
  97658. for(i = 0; i < (int)data_len; i++) {
  97659. sum = 0;
  97660. sum += qlp_coeff[6] * data[i-7];
  97661. sum += qlp_coeff[5] * data[i-6];
  97662. sum += qlp_coeff[4] * data[i-5];
  97663. sum += qlp_coeff[3] * data[i-4];
  97664. sum += qlp_coeff[2] * data[i-3];
  97665. sum += qlp_coeff[1] * data[i-2];
  97666. sum += qlp_coeff[0] * data[i-1];
  97667. residual[i] = data[i] - (sum >> lp_quantization);
  97668. }
  97669. }
  97670. }
  97671. else {
  97672. if(order == 6) {
  97673. for(i = 0; i < (int)data_len; i++) {
  97674. sum = 0;
  97675. sum += qlp_coeff[5] * data[i-6];
  97676. sum += qlp_coeff[4] * data[i-5];
  97677. sum += qlp_coeff[3] * data[i-4];
  97678. sum += qlp_coeff[2] * data[i-3];
  97679. sum += qlp_coeff[1] * data[i-2];
  97680. sum += qlp_coeff[0] * data[i-1];
  97681. residual[i] = data[i] - (sum >> lp_quantization);
  97682. }
  97683. }
  97684. else { /* order == 5 */
  97685. for(i = 0; i < (int)data_len; i++) {
  97686. sum = 0;
  97687. sum += qlp_coeff[4] * data[i-5];
  97688. sum += qlp_coeff[3] * data[i-4];
  97689. sum += qlp_coeff[2] * data[i-3];
  97690. sum += qlp_coeff[1] * data[i-2];
  97691. sum += qlp_coeff[0] * data[i-1];
  97692. residual[i] = data[i] - (sum >> lp_quantization);
  97693. }
  97694. }
  97695. }
  97696. }
  97697. else {
  97698. if(order > 2) {
  97699. if(order == 4) {
  97700. for(i = 0; i < (int)data_len; i++) {
  97701. sum = 0;
  97702. sum += qlp_coeff[3] * data[i-4];
  97703. sum += qlp_coeff[2] * data[i-3];
  97704. sum += qlp_coeff[1] * data[i-2];
  97705. sum += qlp_coeff[0] * data[i-1];
  97706. residual[i] = data[i] - (sum >> lp_quantization);
  97707. }
  97708. }
  97709. else { /* order == 3 */
  97710. for(i = 0; i < (int)data_len; i++) {
  97711. sum = 0;
  97712. sum += qlp_coeff[2] * data[i-3];
  97713. sum += qlp_coeff[1] * data[i-2];
  97714. sum += qlp_coeff[0] * data[i-1];
  97715. residual[i] = data[i] - (sum >> lp_quantization);
  97716. }
  97717. }
  97718. }
  97719. else {
  97720. if(order == 2) {
  97721. for(i = 0; i < (int)data_len; i++) {
  97722. sum = 0;
  97723. sum += qlp_coeff[1] * data[i-2];
  97724. sum += qlp_coeff[0] * data[i-1];
  97725. residual[i] = data[i] - (sum >> lp_quantization);
  97726. }
  97727. }
  97728. else { /* order == 1 */
  97729. for(i = 0; i < (int)data_len; i++)
  97730. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97731. }
  97732. }
  97733. }
  97734. }
  97735. else { /* order > 12 */
  97736. for(i = 0; i < (int)data_len; i++) {
  97737. sum = 0;
  97738. switch(order) {
  97739. case 32: sum += qlp_coeff[31] * data[i-32];
  97740. case 31: sum += qlp_coeff[30] * data[i-31];
  97741. case 30: sum += qlp_coeff[29] * data[i-30];
  97742. case 29: sum += qlp_coeff[28] * data[i-29];
  97743. case 28: sum += qlp_coeff[27] * data[i-28];
  97744. case 27: sum += qlp_coeff[26] * data[i-27];
  97745. case 26: sum += qlp_coeff[25] * data[i-26];
  97746. case 25: sum += qlp_coeff[24] * data[i-25];
  97747. case 24: sum += qlp_coeff[23] * data[i-24];
  97748. case 23: sum += qlp_coeff[22] * data[i-23];
  97749. case 22: sum += qlp_coeff[21] * data[i-22];
  97750. case 21: sum += qlp_coeff[20] * data[i-21];
  97751. case 20: sum += qlp_coeff[19] * data[i-20];
  97752. case 19: sum += qlp_coeff[18] * data[i-19];
  97753. case 18: sum += qlp_coeff[17] * data[i-18];
  97754. case 17: sum += qlp_coeff[16] * data[i-17];
  97755. case 16: sum += qlp_coeff[15] * data[i-16];
  97756. case 15: sum += qlp_coeff[14] * data[i-15];
  97757. case 14: sum += qlp_coeff[13] * data[i-14];
  97758. case 13: sum += qlp_coeff[12] * data[i-13];
  97759. sum += qlp_coeff[11] * data[i-12];
  97760. sum += qlp_coeff[10] * data[i-11];
  97761. sum += qlp_coeff[ 9] * data[i-10];
  97762. sum += qlp_coeff[ 8] * data[i- 9];
  97763. sum += qlp_coeff[ 7] * data[i- 8];
  97764. sum += qlp_coeff[ 6] * data[i- 7];
  97765. sum += qlp_coeff[ 5] * data[i- 6];
  97766. sum += qlp_coeff[ 4] * data[i- 5];
  97767. sum += qlp_coeff[ 3] * data[i- 4];
  97768. sum += qlp_coeff[ 2] * data[i- 3];
  97769. sum += qlp_coeff[ 1] * data[i- 2];
  97770. sum += qlp_coeff[ 0] * data[i- 1];
  97771. }
  97772. residual[i] = data[i] - (sum >> lp_quantization);
  97773. }
  97774. }
  97775. }
  97776. #endif
  97777. 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[])
  97778. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97779. {
  97780. unsigned i, j;
  97781. FLAC__int64 sum;
  97782. const FLAC__int32 *history;
  97783. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97784. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97785. for(i=0;i<order;i++)
  97786. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97787. fprintf(stderr,"\n");
  97788. #endif
  97789. FLAC__ASSERT(order > 0);
  97790. for(i = 0; i < data_len; i++) {
  97791. sum = 0;
  97792. history = data;
  97793. for(j = 0; j < order; j++)
  97794. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97795. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97796. #if defined _MSC_VER
  97797. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97798. #else
  97799. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97800. #endif
  97801. break;
  97802. }
  97803. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97804. #if defined _MSC_VER
  97805. 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));
  97806. #else
  97807. 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)));
  97808. #endif
  97809. break;
  97810. }
  97811. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97812. }
  97813. }
  97814. #else /* fully unrolled version for normal use */
  97815. {
  97816. int i;
  97817. FLAC__int64 sum;
  97818. FLAC__ASSERT(order > 0);
  97819. FLAC__ASSERT(order <= 32);
  97820. /*
  97821. * We do unique versions up to 12th order since that's the subset limit.
  97822. * Also they are roughly ordered to match frequency of occurrence to
  97823. * minimize branching.
  97824. */
  97825. if(order <= 12) {
  97826. if(order > 8) {
  97827. if(order > 10) {
  97828. if(order == 12) {
  97829. for(i = 0; i < (int)data_len; i++) {
  97830. sum = 0;
  97831. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97832. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97833. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97834. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97835. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97836. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97837. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97838. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97839. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97840. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97841. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97842. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97843. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97844. }
  97845. }
  97846. else { /* order == 11 */
  97847. for(i = 0; i < (int)data_len; i++) {
  97848. sum = 0;
  97849. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97850. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97851. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97852. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97853. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97854. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97855. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97856. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97857. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97858. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97859. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97860. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97861. }
  97862. }
  97863. }
  97864. else {
  97865. if(order == 10) {
  97866. for(i = 0; i < (int)data_len; i++) {
  97867. sum = 0;
  97868. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97869. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97870. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97871. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97872. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97873. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97874. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97875. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97876. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97877. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97878. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97879. }
  97880. }
  97881. else { /* order == 9 */
  97882. for(i = 0; i < (int)data_len; i++) {
  97883. sum = 0;
  97884. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97885. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97886. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97887. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97888. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97889. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97890. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97891. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97892. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97893. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97894. }
  97895. }
  97896. }
  97897. }
  97898. else if(order > 4) {
  97899. if(order > 6) {
  97900. if(order == 8) {
  97901. for(i = 0; i < (int)data_len; i++) {
  97902. sum = 0;
  97903. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97904. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97905. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97906. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97907. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97908. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97909. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97910. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97911. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97912. }
  97913. }
  97914. else { /* order == 7 */
  97915. for(i = 0; i < (int)data_len; i++) {
  97916. sum = 0;
  97917. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97918. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97919. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97920. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97921. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97922. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97923. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97924. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97925. }
  97926. }
  97927. }
  97928. else {
  97929. if(order == 6) {
  97930. for(i = 0; i < (int)data_len; i++) {
  97931. sum = 0;
  97932. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97933. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97934. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97935. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97936. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97937. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97938. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97939. }
  97940. }
  97941. else { /* order == 5 */
  97942. for(i = 0; i < (int)data_len; i++) {
  97943. sum = 0;
  97944. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97945. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97946. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97947. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97948. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97949. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97950. }
  97951. }
  97952. }
  97953. }
  97954. else {
  97955. if(order > 2) {
  97956. if(order == 4) {
  97957. for(i = 0; i < (int)data_len; i++) {
  97958. sum = 0;
  97959. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97960. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97961. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97962. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97963. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97964. }
  97965. }
  97966. else { /* order == 3 */
  97967. for(i = 0; i < (int)data_len; i++) {
  97968. sum = 0;
  97969. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97970. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97971. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97972. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97973. }
  97974. }
  97975. }
  97976. else {
  97977. if(order == 2) {
  97978. for(i = 0; i < (int)data_len; i++) {
  97979. sum = 0;
  97980. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97981. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97982. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97983. }
  97984. }
  97985. else { /* order == 1 */
  97986. for(i = 0; i < (int)data_len; i++)
  97987. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97988. }
  97989. }
  97990. }
  97991. }
  97992. else { /* order > 12 */
  97993. for(i = 0; i < (int)data_len; i++) {
  97994. sum = 0;
  97995. switch(order) {
  97996. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97997. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97998. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97999. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98000. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98001. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98002. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98003. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98004. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98005. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98006. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98007. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98008. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98009. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98010. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98011. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98012. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98013. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98014. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98015. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98016. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98017. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98018. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98019. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98020. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98021. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98022. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98023. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98024. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98025. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98026. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98027. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98028. }
  98029. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98030. }
  98031. }
  98032. }
  98033. #endif
  98034. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98035. 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[])
  98036. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98037. {
  98038. FLAC__int64 sumo;
  98039. unsigned i, j;
  98040. FLAC__int32 sum;
  98041. const FLAC__int32 *r = residual, *history;
  98042. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98043. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98044. for(i=0;i<order;i++)
  98045. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98046. fprintf(stderr,"\n");
  98047. #endif
  98048. FLAC__ASSERT(order > 0);
  98049. for(i = 0; i < data_len; i++) {
  98050. sumo = 0;
  98051. sum = 0;
  98052. history = data;
  98053. for(j = 0; j < order; j++) {
  98054. sum += qlp_coeff[j] * (*(--history));
  98055. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98056. #if defined _MSC_VER
  98057. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98058. 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);
  98059. #else
  98060. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98061. 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);
  98062. #endif
  98063. }
  98064. *(data++) = *(r++) + (sum >> lp_quantization);
  98065. }
  98066. /* Here's a slower but clearer version:
  98067. for(i = 0; i < data_len; i++) {
  98068. sum = 0;
  98069. for(j = 0; j < order; j++)
  98070. sum += qlp_coeff[j] * data[i-j-1];
  98071. data[i] = residual[i] + (sum >> lp_quantization);
  98072. }
  98073. */
  98074. }
  98075. #else /* fully unrolled version for normal use */
  98076. {
  98077. int i;
  98078. FLAC__int32 sum;
  98079. FLAC__ASSERT(order > 0);
  98080. FLAC__ASSERT(order <= 32);
  98081. /*
  98082. * We do unique versions up to 12th order since that's the subset limit.
  98083. * Also they are roughly ordered to match frequency of occurrence to
  98084. * minimize branching.
  98085. */
  98086. if(order <= 12) {
  98087. if(order > 8) {
  98088. if(order > 10) {
  98089. if(order == 12) {
  98090. for(i = 0; i < (int)data_len; i++) {
  98091. sum = 0;
  98092. sum += qlp_coeff[11] * data[i-12];
  98093. sum += qlp_coeff[10] * data[i-11];
  98094. sum += qlp_coeff[9] * data[i-10];
  98095. sum += qlp_coeff[8] * data[i-9];
  98096. sum += qlp_coeff[7] * data[i-8];
  98097. sum += qlp_coeff[6] * data[i-7];
  98098. sum += qlp_coeff[5] * data[i-6];
  98099. sum += qlp_coeff[4] * data[i-5];
  98100. sum += qlp_coeff[3] * data[i-4];
  98101. sum += qlp_coeff[2] * data[i-3];
  98102. sum += qlp_coeff[1] * data[i-2];
  98103. sum += qlp_coeff[0] * data[i-1];
  98104. data[i] = residual[i] + (sum >> lp_quantization);
  98105. }
  98106. }
  98107. else { /* order == 11 */
  98108. for(i = 0; i < (int)data_len; i++) {
  98109. sum = 0;
  98110. sum += qlp_coeff[10] * data[i-11];
  98111. sum += qlp_coeff[9] * data[i-10];
  98112. sum += qlp_coeff[8] * data[i-9];
  98113. sum += qlp_coeff[7] * data[i-8];
  98114. sum += qlp_coeff[6] * data[i-7];
  98115. sum += qlp_coeff[5] * data[i-6];
  98116. sum += qlp_coeff[4] * data[i-5];
  98117. sum += qlp_coeff[3] * data[i-4];
  98118. sum += qlp_coeff[2] * data[i-3];
  98119. sum += qlp_coeff[1] * data[i-2];
  98120. sum += qlp_coeff[0] * data[i-1];
  98121. data[i] = residual[i] + (sum >> lp_quantization);
  98122. }
  98123. }
  98124. }
  98125. else {
  98126. if(order == 10) {
  98127. for(i = 0; i < (int)data_len; i++) {
  98128. sum = 0;
  98129. sum += qlp_coeff[9] * data[i-10];
  98130. sum += qlp_coeff[8] * data[i-9];
  98131. sum += qlp_coeff[7] * data[i-8];
  98132. sum += qlp_coeff[6] * data[i-7];
  98133. sum += qlp_coeff[5] * data[i-6];
  98134. sum += qlp_coeff[4] * data[i-5];
  98135. sum += qlp_coeff[3] * data[i-4];
  98136. sum += qlp_coeff[2] * data[i-3];
  98137. sum += qlp_coeff[1] * data[i-2];
  98138. sum += qlp_coeff[0] * data[i-1];
  98139. data[i] = residual[i] + (sum >> lp_quantization);
  98140. }
  98141. }
  98142. else { /* order == 9 */
  98143. for(i = 0; i < (int)data_len; i++) {
  98144. sum = 0;
  98145. sum += qlp_coeff[8] * data[i-9];
  98146. sum += qlp_coeff[7] * data[i-8];
  98147. sum += qlp_coeff[6] * data[i-7];
  98148. sum += qlp_coeff[5] * data[i-6];
  98149. sum += qlp_coeff[4] * data[i-5];
  98150. sum += qlp_coeff[3] * data[i-4];
  98151. sum += qlp_coeff[2] * data[i-3];
  98152. sum += qlp_coeff[1] * data[i-2];
  98153. sum += qlp_coeff[0] * data[i-1];
  98154. data[i] = residual[i] + (sum >> lp_quantization);
  98155. }
  98156. }
  98157. }
  98158. }
  98159. else if(order > 4) {
  98160. if(order > 6) {
  98161. if(order == 8) {
  98162. for(i = 0; i < (int)data_len; i++) {
  98163. sum = 0;
  98164. sum += qlp_coeff[7] * data[i-8];
  98165. sum += qlp_coeff[6] * data[i-7];
  98166. sum += qlp_coeff[5] * data[i-6];
  98167. sum += qlp_coeff[4] * data[i-5];
  98168. sum += qlp_coeff[3] * data[i-4];
  98169. sum += qlp_coeff[2] * data[i-3];
  98170. sum += qlp_coeff[1] * data[i-2];
  98171. sum += qlp_coeff[0] * data[i-1];
  98172. data[i] = residual[i] + (sum >> lp_quantization);
  98173. }
  98174. }
  98175. else { /* order == 7 */
  98176. for(i = 0; i < (int)data_len; i++) {
  98177. sum = 0;
  98178. sum += qlp_coeff[6] * data[i-7];
  98179. sum += qlp_coeff[5] * data[i-6];
  98180. sum += qlp_coeff[4] * data[i-5];
  98181. sum += qlp_coeff[3] * data[i-4];
  98182. sum += qlp_coeff[2] * data[i-3];
  98183. sum += qlp_coeff[1] * data[i-2];
  98184. sum += qlp_coeff[0] * data[i-1];
  98185. data[i] = residual[i] + (sum >> lp_quantization);
  98186. }
  98187. }
  98188. }
  98189. else {
  98190. if(order == 6) {
  98191. for(i = 0; i < (int)data_len; i++) {
  98192. sum = 0;
  98193. sum += qlp_coeff[5] * data[i-6];
  98194. sum += qlp_coeff[4] * data[i-5];
  98195. sum += qlp_coeff[3] * data[i-4];
  98196. sum += qlp_coeff[2] * data[i-3];
  98197. sum += qlp_coeff[1] * data[i-2];
  98198. sum += qlp_coeff[0] * data[i-1];
  98199. data[i] = residual[i] + (sum >> lp_quantization);
  98200. }
  98201. }
  98202. else { /* order == 5 */
  98203. for(i = 0; i < (int)data_len; i++) {
  98204. sum = 0;
  98205. sum += qlp_coeff[4] * data[i-5];
  98206. sum += qlp_coeff[3] * data[i-4];
  98207. sum += qlp_coeff[2] * data[i-3];
  98208. sum += qlp_coeff[1] * data[i-2];
  98209. sum += qlp_coeff[0] * data[i-1];
  98210. data[i] = residual[i] + (sum >> lp_quantization);
  98211. }
  98212. }
  98213. }
  98214. }
  98215. else {
  98216. if(order > 2) {
  98217. if(order == 4) {
  98218. for(i = 0; i < (int)data_len; i++) {
  98219. sum = 0;
  98220. sum += qlp_coeff[3] * data[i-4];
  98221. sum += qlp_coeff[2] * data[i-3];
  98222. sum += qlp_coeff[1] * data[i-2];
  98223. sum += qlp_coeff[0] * data[i-1];
  98224. data[i] = residual[i] + (sum >> lp_quantization);
  98225. }
  98226. }
  98227. else { /* order == 3 */
  98228. for(i = 0; i < (int)data_len; i++) {
  98229. sum = 0;
  98230. sum += qlp_coeff[2] * data[i-3];
  98231. sum += qlp_coeff[1] * data[i-2];
  98232. sum += qlp_coeff[0] * data[i-1];
  98233. data[i] = residual[i] + (sum >> lp_quantization);
  98234. }
  98235. }
  98236. }
  98237. else {
  98238. if(order == 2) {
  98239. for(i = 0; i < (int)data_len; i++) {
  98240. sum = 0;
  98241. sum += qlp_coeff[1] * data[i-2];
  98242. sum += qlp_coeff[0] * data[i-1];
  98243. data[i] = residual[i] + (sum >> lp_quantization);
  98244. }
  98245. }
  98246. else { /* order == 1 */
  98247. for(i = 0; i < (int)data_len; i++)
  98248. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98249. }
  98250. }
  98251. }
  98252. }
  98253. else { /* order > 12 */
  98254. for(i = 0; i < (int)data_len; i++) {
  98255. sum = 0;
  98256. switch(order) {
  98257. case 32: sum += qlp_coeff[31] * data[i-32];
  98258. case 31: sum += qlp_coeff[30] * data[i-31];
  98259. case 30: sum += qlp_coeff[29] * data[i-30];
  98260. case 29: sum += qlp_coeff[28] * data[i-29];
  98261. case 28: sum += qlp_coeff[27] * data[i-28];
  98262. case 27: sum += qlp_coeff[26] * data[i-27];
  98263. case 26: sum += qlp_coeff[25] * data[i-26];
  98264. case 25: sum += qlp_coeff[24] * data[i-25];
  98265. case 24: sum += qlp_coeff[23] * data[i-24];
  98266. case 23: sum += qlp_coeff[22] * data[i-23];
  98267. case 22: sum += qlp_coeff[21] * data[i-22];
  98268. case 21: sum += qlp_coeff[20] * data[i-21];
  98269. case 20: sum += qlp_coeff[19] * data[i-20];
  98270. case 19: sum += qlp_coeff[18] * data[i-19];
  98271. case 18: sum += qlp_coeff[17] * data[i-18];
  98272. case 17: sum += qlp_coeff[16] * data[i-17];
  98273. case 16: sum += qlp_coeff[15] * data[i-16];
  98274. case 15: sum += qlp_coeff[14] * data[i-15];
  98275. case 14: sum += qlp_coeff[13] * data[i-14];
  98276. case 13: sum += qlp_coeff[12] * data[i-13];
  98277. sum += qlp_coeff[11] * data[i-12];
  98278. sum += qlp_coeff[10] * data[i-11];
  98279. sum += qlp_coeff[ 9] * data[i-10];
  98280. sum += qlp_coeff[ 8] * data[i- 9];
  98281. sum += qlp_coeff[ 7] * data[i- 8];
  98282. sum += qlp_coeff[ 6] * data[i- 7];
  98283. sum += qlp_coeff[ 5] * data[i- 6];
  98284. sum += qlp_coeff[ 4] * data[i- 5];
  98285. sum += qlp_coeff[ 3] * data[i- 4];
  98286. sum += qlp_coeff[ 2] * data[i- 3];
  98287. sum += qlp_coeff[ 1] * data[i- 2];
  98288. sum += qlp_coeff[ 0] * data[i- 1];
  98289. }
  98290. data[i] = residual[i] + (sum >> lp_quantization);
  98291. }
  98292. }
  98293. }
  98294. #endif
  98295. 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[])
  98296. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98297. {
  98298. unsigned i, j;
  98299. FLAC__int64 sum;
  98300. const FLAC__int32 *r = residual, *history;
  98301. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98302. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98303. for(i=0;i<order;i++)
  98304. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98305. fprintf(stderr,"\n");
  98306. #endif
  98307. FLAC__ASSERT(order > 0);
  98308. for(i = 0; i < data_len; i++) {
  98309. sum = 0;
  98310. history = data;
  98311. for(j = 0; j < order; j++)
  98312. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98313. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98314. #ifdef _MSC_VER
  98315. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98316. #else
  98317. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98318. #endif
  98319. break;
  98320. }
  98321. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98322. #ifdef _MSC_VER
  98323. 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));
  98324. #else
  98325. 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)));
  98326. #endif
  98327. break;
  98328. }
  98329. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98330. }
  98331. }
  98332. #else /* fully unrolled version for normal use */
  98333. {
  98334. int i;
  98335. FLAC__int64 sum;
  98336. FLAC__ASSERT(order > 0);
  98337. FLAC__ASSERT(order <= 32);
  98338. /*
  98339. * We do unique versions up to 12th order since that's the subset limit.
  98340. * Also they are roughly ordered to match frequency of occurrence to
  98341. * minimize branching.
  98342. */
  98343. if(order <= 12) {
  98344. if(order > 8) {
  98345. if(order > 10) {
  98346. if(order == 12) {
  98347. for(i = 0; i < (int)data_len; i++) {
  98348. sum = 0;
  98349. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98350. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98351. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98352. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98353. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98354. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98355. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98356. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98357. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98358. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98359. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98360. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98361. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98362. }
  98363. }
  98364. else { /* order == 11 */
  98365. for(i = 0; i < (int)data_len; i++) {
  98366. sum = 0;
  98367. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98368. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98369. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98370. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98371. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98372. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98373. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98374. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98375. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98376. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98377. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98378. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98379. }
  98380. }
  98381. }
  98382. else {
  98383. if(order == 10) {
  98384. for(i = 0; i < (int)data_len; i++) {
  98385. sum = 0;
  98386. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98387. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98388. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98389. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98390. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98391. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98392. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98393. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98394. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98395. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98396. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98397. }
  98398. }
  98399. else { /* order == 9 */
  98400. for(i = 0; i < (int)data_len; i++) {
  98401. sum = 0;
  98402. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98403. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98404. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98405. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98406. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98407. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98408. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98409. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98410. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98411. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98412. }
  98413. }
  98414. }
  98415. }
  98416. else if(order > 4) {
  98417. if(order > 6) {
  98418. if(order == 8) {
  98419. for(i = 0; i < (int)data_len; i++) {
  98420. sum = 0;
  98421. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98422. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98423. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98424. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98425. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98426. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98427. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98428. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98429. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98430. }
  98431. }
  98432. else { /* order == 7 */
  98433. for(i = 0; i < (int)data_len; i++) {
  98434. sum = 0;
  98435. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98436. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98437. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98438. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98439. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98440. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98441. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98442. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98443. }
  98444. }
  98445. }
  98446. else {
  98447. if(order == 6) {
  98448. for(i = 0; i < (int)data_len; i++) {
  98449. sum = 0;
  98450. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98451. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98452. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98453. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98454. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98455. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98456. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98457. }
  98458. }
  98459. else { /* order == 5 */
  98460. for(i = 0; i < (int)data_len; i++) {
  98461. sum = 0;
  98462. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98463. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98464. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98465. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98466. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98467. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98468. }
  98469. }
  98470. }
  98471. }
  98472. else {
  98473. if(order > 2) {
  98474. if(order == 4) {
  98475. for(i = 0; i < (int)data_len; i++) {
  98476. sum = 0;
  98477. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98478. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98479. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98480. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98481. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98482. }
  98483. }
  98484. else { /* order == 3 */
  98485. for(i = 0; i < (int)data_len; i++) {
  98486. sum = 0;
  98487. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98488. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98489. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98490. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98491. }
  98492. }
  98493. }
  98494. else {
  98495. if(order == 2) {
  98496. for(i = 0; i < (int)data_len; i++) {
  98497. sum = 0;
  98498. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98499. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98500. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98501. }
  98502. }
  98503. else { /* order == 1 */
  98504. for(i = 0; i < (int)data_len; i++)
  98505. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98506. }
  98507. }
  98508. }
  98509. }
  98510. else { /* order > 12 */
  98511. for(i = 0; i < (int)data_len; i++) {
  98512. sum = 0;
  98513. switch(order) {
  98514. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98515. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98516. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98517. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98518. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98519. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98520. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98521. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98522. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98523. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98524. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98525. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98526. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98527. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98528. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98529. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98530. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98531. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98532. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98533. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98534. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98535. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98536. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98537. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98538. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98539. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98540. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98541. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98542. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98543. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98544. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98545. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98546. }
  98547. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98548. }
  98549. }
  98550. }
  98551. #endif
  98552. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98553. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98554. {
  98555. FLAC__double error_scale;
  98556. FLAC__ASSERT(total_samples > 0);
  98557. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98558. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98559. }
  98560. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98561. {
  98562. if(lpc_error > 0.0) {
  98563. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98564. if(bps >= 0.0)
  98565. return bps;
  98566. else
  98567. return 0.0;
  98568. }
  98569. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98570. return 1e32;
  98571. }
  98572. else {
  98573. return 0.0;
  98574. }
  98575. }
  98576. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98577. {
  98578. 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 */
  98579. FLAC__double bits, best_bits, error_scale;
  98580. FLAC__ASSERT(max_order > 0);
  98581. FLAC__ASSERT(total_samples > 0);
  98582. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98583. best_index = 0;
  98584. best_bits = (unsigned)(-1);
  98585. for(index = 0, order = 1; index < max_order; index++, order++) {
  98586. 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);
  98587. if(bits < best_bits) {
  98588. best_index = index;
  98589. best_bits = bits;
  98590. }
  98591. }
  98592. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98593. }
  98594. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98595. #endif
  98596. /*** End of inlined file: lpc_flac.c ***/
  98597. /*** Start of inlined file: md5.c ***/
  98598. /*** Start of inlined file: juce_FlacHeader.h ***/
  98599. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98600. // tasks..
  98601. #define VERSION "1.2.1"
  98602. #define FLAC__NO_DLL 1
  98603. #if JUCE_MSVC
  98604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98605. #endif
  98606. #if JUCE_MAC
  98607. #define FLAC__SYS_DARWIN 1
  98608. #endif
  98609. /*** End of inlined file: juce_FlacHeader.h ***/
  98610. #if JUCE_USE_FLAC
  98611. #if HAVE_CONFIG_H
  98612. # include <config.h>
  98613. #endif
  98614. #include <stdlib.h> /* for malloc() */
  98615. #include <string.h> /* for memcpy() */
  98616. /*** Start of inlined file: md5.h ***/
  98617. #ifndef FLAC__PRIVATE__MD5_H
  98618. #define FLAC__PRIVATE__MD5_H
  98619. /*
  98620. * This is the header file for the MD5 message-digest algorithm.
  98621. * The algorithm is due to Ron Rivest. This code was
  98622. * written by Colin Plumb in 1993, no copyright is claimed.
  98623. * This code is in the public domain; do with it what you wish.
  98624. *
  98625. * Equivalent code is available from RSA Data Security, Inc.
  98626. * This code has been tested against that, and is equivalent,
  98627. * except that you don't need to include two pages of legalese
  98628. * with every copy.
  98629. *
  98630. * To compute the message digest of a chunk of bytes, declare an
  98631. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98632. * needed on buffers full of bytes, and then call MD5Final, which
  98633. * will fill a supplied 16-byte array with the digest.
  98634. *
  98635. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98636. * header definitions; now uses stuff from dpkg's config.h
  98637. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98638. * Still in the public domain.
  98639. *
  98640. * Josh Coalson: made some changes to integrate with libFLAC.
  98641. * Still in the public domain, with no warranty.
  98642. */
  98643. typedef struct {
  98644. FLAC__uint32 in[16];
  98645. FLAC__uint32 buf[4];
  98646. FLAC__uint32 bytes[2];
  98647. FLAC__byte *internal_buf;
  98648. size_t capacity;
  98649. } FLAC__MD5Context;
  98650. void FLAC__MD5Init(FLAC__MD5Context *context);
  98651. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98652. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98653. #endif
  98654. /*** End of inlined file: md5.h ***/
  98655. #ifndef FLaC__INLINE
  98656. #define FLaC__INLINE
  98657. #endif
  98658. /*
  98659. * This code implements the MD5 message-digest algorithm.
  98660. * The algorithm is due to Ron Rivest. This code was
  98661. * written by Colin Plumb in 1993, no copyright is claimed.
  98662. * This code is in the public domain; do with it what you wish.
  98663. *
  98664. * Equivalent code is available from RSA Data Security, Inc.
  98665. * This code has been tested against that, and is equivalent,
  98666. * except that you don't need to include two pages of legalese
  98667. * with every copy.
  98668. *
  98669. * To compute the message digest of a chunk of bytes, declare an
  98670. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98671. * needed on buffers full of bytes, and then call MD5Final, which
  98672. * will fill a supplied 16-byte array with the digest.
  98673. *
  98674. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98675. * definitions; now uses stuff from dpkg's config.h.
  98676. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98677. * Still in the public domain.
  98678. *
  98679. * Josh Coalson: made some changes to integrate with libFLAC.
  98680. * Still in the public domain.
  98681. */
  98682. /* The four core functions - F1 is optimized somewhat */
  98683. /* #define F1(x, y, z) (x & y | ~x & z) */
  98684. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98685. #define F2(x, y, z) F1(z, x, y)
  98686. #define F3(x, y, z) (x ^ y ^ z)
  98687. #define F4(x, y, z) (y ^ (x | ~z))
  98688. /* This is the central step in the MD5 algorithm. */
  98689. #define MD5STEP(f,w,x,y,z,in,s) \
  98690. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98691. /*
  98692. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98693. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98694. * the data and converts bytes into longwords for this routine.
  98695. */
  98696. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98697. {
  98698. register FLAC__uint32 a, b, c, d;
  98699. a = buf[0];
  98700. b = buf[1];
  98701. c = buf[2];
  98702. d = buf[3];
  98703. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98704. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98705. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98706. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98707. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98708. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98709. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98710. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98711. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98712. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98713. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98714. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98715. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98716. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98717. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98718. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98719. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98720. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98721. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98722. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98723. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98724. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98725. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98726. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98727. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98728. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98729. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98730. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98731. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98732. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98733. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98734. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98735. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98736. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98737. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98738. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98739. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98740. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98741. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98742. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98743. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98744. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98745. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98746. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98747. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98748. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98749. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98750. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98751. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98752. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98753. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98754. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98755. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98756. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98757. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98758. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98759. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98760. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98761. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98762. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98763. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98764. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98765. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98766. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98767. buf[0] += a;
  98768. buf[1] += b;
  98769. buf[2] += c;
  98770. buf[3] += d;
  98771. }
  98772. #if WORDS_BIGENDIAN
  98773. //@@@@@@ OPT: use bswap/intrinsics
  98774. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98775. {
  98776. register FLAC__uint32 x;
  98777. do {
  98778. x = *buf;
  98779. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98780. *buf++ = (x >> 16) | (x << 16);
  98781. } while (--words);
  98782. }
  98783. static void byteSwapX16(FLAC__uint32 *buf)
  98784. {
  98785. register FLAC__uint32 x;
  98786. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98787. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98788. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98789. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98790. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98791. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98792. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98793. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98794. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98795. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98796. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98797. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98798. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98799. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98800. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98801. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98802. }
  98803. #else
  98804. #define byteSwap(buf, words)
  98805. #define byteSwapX16(buf)
  98806. #endif
  98807. /*
  98808. * Update context to reflect the concatenation of another buffer full
  98809. * of bytes.
  98810. */
  98811. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98812. {
  98813. FLAC__uint32 t;
  98814. /* Update byte count */
  98815. t = ctx->bytes[0];
  98816. if ((ctx->bytes[0] = t + len) < t)
  98817. ctx->bytes[1]++; /* Carry from low to high */
  98818. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98819. if (t > len) {
  98820. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98821. return;
  98822. }
  98823. /* First chunk is an odd size */
  98824. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98825. byteSwapX16(ctx->in);
  98826. FLAC__MD5Transform(ctx->buf, ctx->in);
  98827. buf += t;
  98828. len -= t;
  98829. /* Process data in 64-byte chunks */
  98830. while (len >= 64) {
  98831. memcpy(ctx->in, buf, 64);
  98832. byteSwapX16(ctx->in);
  98833. FLAC__MD5Transform(ctx->buf, ctx->in);
  98834. buf += 64;
  98835. len -= 64;
  98836. }
  98837. /* Handle any remaining bytes of data. */
  98838. memcpy(ctx->in, buf, len);
  98839. }
  98840. /*
  98841. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98842. * initialization constants.
  98843. */
  98844. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98845. {
  98846. ctx->buf[0] = 0x67452301;
  98847. ctx->buf[1] = 0xefcdab89;
  98848. ctx->buf[2] = 0x98badcfe;
  98849. ctx->buf[3] = 0x10325476;
  98850. ctx->bytes[0] = 0;
  98851. ctx->bytes[1] = 0;
  98852. ctx->internal_buf = 0;
  98853. ctx->capacity = 0;
  98854. }
  98855. /*
  98856. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98857. * 1 0* (64-bit count of bits processed, MSB-first)
  98858. */
  98859. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98860. {
  98861. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98862. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98863. /* Set the first char of padding to 0x80. There is always room. */
  98864. *p++ = 0x80;
  98865. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98866. count = 56 - 1 - count;
  98867. if (count < 0) { /* Padding forces an extra block */
  98868. memset(p, 0, count + 8);
  98869. byteSwapX16(ctx->in);
  98870. FLAC__MD5Transform(ctx->buf, ctx->in);
  98871. p = (FLAC__byte *)ctx->in;
  98872. count = 56;
  98873. }
  98874. memset(p, 0, count);
  98875. byteSwap(ctx->in, 14);
  98876. /* Append length in bits and transform */
  98877. ctx->in[14] = ctx->bytes[0] << 3;
  98878. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98879. FLAC__MD5Transform(ctx->buf, ctx->in);
  98880. byteSwap(ctx->buf, 4);
  98881. memcpy(digest, ctx->buf, 16);
  98882. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98883. if(0 != ctx->internal_buf) {
  98884. free(ctx->internal_buf);
  98885. ctx->internal_buf = 0;
  98886. ctx->capacity = 0;
  98887. }
  98888. }
  98889. /*
  98890. * Convert the incoming audio signal to a byte stream
  98891. */
  98892. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98893. {
  98894. unsigned channel, sample;
  98895. register FLAC__int32 a_word;
  98896. register FLAC__byte *buf_ = buf;
  98897. #if WORDS_BIGENDIAN
  98898. #else
  98899. if(channels == 2 && bytes_per_sample == 2) {
  98900. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98901. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98902. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98903. *buf1_ = (FLAC__int16)signal[1][sample];
  98904. }
  98905. else if(channels == 1 && bytes_per_sample == 2) {
  98906. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98907. for(sample = 0; sample < samples; sample++)
  98908. *buf1_++ = (FLAC__int16)signal[0][sample];
  98909. }
  98910. else
  98911. #endif
  98912. if(bytes_per_sample == 2) {
  98913. if(channels == 2) {
  98914. for(sample = 0; sample < samples; sample++) {
  98915. a_word = signal[0][sample];
  98916. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98917. *buf_++ = (FLAC__byte)a_word;
  98918. a_word = signal[1][sample];
  98919. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98920. *buf_++ = (FLAC__byte)a_word;
  98921. }
  98922. }
  98923. else if(channels == 1) {
  98924. for(sample = 0; sample < samples; sample++) {
  98925. a_word = signal[0][sample];
  98926. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98927. *buf_++ = (FLAC__byte)a_word;
  98928. }
  98929. }
  98930. else {
  98931. for(sample = 0; sample < samples; sample++) {
  98932. for(channel = 0; channel < channels; channel++) {
  98933. a_word = signal[channel][sample];
  98934. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98935. *buf_++ = (FLAC__byte)a_word;
  98936. }
  98937. }
  98938. }
  98939. }
  98940. else if(bytes_per_sample == 3) {
  98941. if(channels == 2) {
  98942. for(sample = 0; sample < samples; sample++) {
  98943. a_word = signal[0][sample];
  98944. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98945. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98946. *buf_++ = (FLAC__byte)a_word;
  98947. a_word = signal[1][sample];
  98948. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98949. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98950. *buf_++ = (FLAC__byte)a_word;
  98951. }
  98952. }
  98953. else if(channels == 1) {
  98954. for(sample = 0; sample < samples; sample++) {
  98955. a_word = signal[0][sample];
  98956. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98957. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98958. *buf_++ = (FLAC__byte)a_word;
  98959. }
  98960. }
  98961. else {
  98962. for(sample = 0; sample < samples; sample++) {
  98963. for(channel = 0; channel < channels; channel++) {
  98964. a_word = signal[channel][sample];
  98965. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98966. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98967. *buf_++ = (FLAC__byte)a_word;
  98968. }
  98969. }
  98970. }
  98971. }
  98972. else if(bytes_per_sample == 1) {
  98973. if(channels == 2) {
  98974. for(sample = 0; sample < samples; sample++) {
  98975. a_word = signal[0][sample];
  98976. *buf_++ = (FLAC__byte)a_word;
  98977. a_word = signal[1][sample];
  98978. *buf_++ = (FLAC__byte)a_word;
  98979. }
  98980. }
  98981. else if(channels == 1) {
  98982. for(sample = 0; sample < samples; sample++) {
  98983. a_word = signal[0][sample];
  98984. *buf_++ = (FLAC__byte)a_word;
  98985. }
  98986. }
  98987. else {
  98988. for(sample = 0; sample < samples; sample++) {
  98989. for(channel = 0; channel < channels; channel++) {
  98990. a_word = signal[channel][sample];
  98991. *buf_++ = (FLAC__byte)a_word;
  98992. }
  98993. }
  98994. }
  98995. }
  98996. else { /* bytes_per_sample == 4, maybe optimize more later */
  98997. for(sample = 0; sample < samples; sample++) {
  98998. for(channel = 0; channel < channels; channel++) {
  98999. a_word = signal[channel][sample];
  99000. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99001. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99002. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99003. *buf_++ = (FLAC__byte)a_word;
  99004. }
  99005. }
  99006. }
  99007. }
  99008. /*
  99009. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99010. */
  99011. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99012. {
  99013. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99014. /* overflow check */
  99015. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99016. return false;
  99017. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99018. return false;
  99019. if(ctx->capacity < bytes_needed) {
  99020. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99021. if(0 == tmp) {
  99022. free(ctx->internal_buf);
  99023. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99024. return false;
  99025. }
  99026. ctx->internal_buf = tmp;
  99027. ctx->capacity = bytes_needed;
  99028. }
  99029. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99030. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99031. return true;
  99032. }
  99033. #endif
  99034. /*** End of inlined file: md5.c ***/
  99035. /*** Start of inlined file: memory.c ***/
  99036. /*** Start of inlined file: juce_FlacHeader.h ***/
  99037. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99038. // tasks..
  99039. #define VERSION "1.2.1"
  99040. #define FLAC__NO_DLL 1
  99041. #if JUCE_MSVC
  99042. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99043. #endif
  99044. #if JUCE_MAC
  99045. #define FLAC__SYS_DARWIN 1
  99046. #endif
  99047. /*** End of inlined file: juce_FlacHeader.h ***/
  99048. #if JUCE_USE_FLAC
  99049. #if HAVE_CONFIG_H
  99050. # include <config.h>
  99051. #endif
  99052. /*** Start of inlined file: memory.h ***/
  99053. #ifndef FLAC__PRIVATE__MEMORY_H
  99054. #define FLAC__PRIVATE__MEMORY_H
  99055. #ifdef HAVE_CONFIG_H
  99056. #include <config.h>
  99057. #endif
  99058. #include <stdlib.h> /* for size_t */
  99059. /* Returns the unaligned address returned by malloc.
  99060. * Use free() on this address to deallocate.
  99061. */
  99062. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99063. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99064. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99065. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99066. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99068. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99069. #endif
  99070. #endif
  99071. /*** End of inlined file: memory.h ***/
  99072. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99073. {
  99074. void *x;
  99075. FLAC__ASSERT(0 != aligned_address);
  99076. #ifdef FLAC__ALIGN_MALLOC_DATA
  99077. /* align on 32-byte (256-bit) boundary */
  99078. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99079. #ifdef SIZEOF_VOIDP
  99080. #if SIZEOF_VOIDP == 4
  99081. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99082. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99083. #elif SIZEOF_VOIDP == 8
  99084. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99085. #else
  99086. # error Unsupported sizeof(void*)
  99087. #endif
  99088. #else
  99089. /* there's got to be a better way to do this right for all archs */
  99090. if(sizeof(void*) == sizeof(unsigned))
  99091. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99092. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99093. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99094. else
  99095. return 0;
  99096. #endif
  99097. #else
  99098. x = safe_malloc_(bytes);
  99099. *aligned_address = x;
  99100. #endif
  99101. return x;
  99102. }
  99103. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99104. {
  99105. FLAC__int32 *pu; /* unaligned pointer */
  99106. union { /* union needed to comply with C99 pointer aliasing rules */
  99107. FLAC__int32 *pa; /* aligned pointer */
  99108. void *pv; /* aligned pointer alias */
  99109. } u;
  99110. FLAC__ASSERT(elements > 0);
  99111. FLAC__ASSERT(0 != unaligned_pointer);
  99112. FLAC__ASSERT(0 != aligned_pointer);
  99113. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99114. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99115. if(0 == pu) {
  99116. return false;
  99117. }
  99118. else {
  99119. if(*unaligned_pointer != 0)
  99120. free(*unaligned_pointer);
  99121. *unaligned_pointer = pu;
  99122. *aligned_pointer = u.pa;
  99123. return true;
  99124. }
  99125. }
  99126. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99127. {
  99128. FLAC__uint32 *pu; /* unaligned pointer */
  99129. union { /* union needed to comply with C99 pointer aliasing rules */
  99130. FLAC__uint32 *pa; /* aligned pointer */
  99131. void *pv; /* aligned pointer alias */
  99132. } u;
  99133. FLAC__ASSERT(elements > 0);
  99134. FLAC__ASSERT(0 != unaligned_pointer);
  99135. FLAC__ASSERT(0 != aligned_pointer);
  99136. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99137. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99138. if(0 == pu) {
  99139. return false;
  99140. }
  99141. else {
  99142. if(*unaligned_pointer != 0)
  99143. free(*unaligned_pointer);
  99144. *unaligned_pointer = pu;
  99145. *aligned_pointer = u.pa;
  99146. return true;
  99147. }
  99148. }
  99149. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99150. {
  99151. FLAC__uint64 *pu; /* unaligned pointer */
  99152. union { /* union needed to comply with C99 pointer aliasing rules */
  99153. FLAC__uint64 *pa; /* aligned pointer */
  99154. void *pv; /* aligned pointer alias */
  99155. } u;
  99156. FLAC__ASSERT(elements > 0);
  99157. FLAC__ASSERT(0 != unaligned_pointer);
  99158. FLAC__ASSERT(0 != aligned_pointer);
  99159. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99160. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99161. if(0 == pu) {
  99162. return false;
  99163. }
  99164. else {
  99165. if(*unaligned_pointer != 0)
  99166. free(*unaligned_pointer);
  99167. *unaligned_pointer = pu;
  99168. *aligned_pointer = u.pa;
  99169. return true;
  99170. }
  99171. }
  99172. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99173. {
  99174. unsigned *pu; /* unaligned pointer */
  99175. union { /* union needed to comply with C99 pointer aliasing rules */
  99176. unsigned *pa; /* aligned pointer */
  99177. void *pv; /* aligned pointer alias */
  99178. } u;
  99179. FLAC__ASSERT(elements > 0);
  99180. FLAC__ASSERT(0 != unaligned_pointer);
  99181. FLAC__ASSERT(0 != aligned_pointer);
  99182. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99183. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99184. if(0 == pu) {
  99185. return false;
  99186. }
  99187. else {
  99188. if(*unaligned_pointer != 0)
  99189. free(*unaligned_pointer);
  99190. *unaligned_pointer = pu;
  99191. *aligned_pointer = u.pa;
  99192. return true;
  99193. }
  99194. }
  99195. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99196. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99197. {
  99198. FLAC__real *pu; /* unaligned pointer */
  99199. union { /* union needed to comply with C99 pointer aliasing rules */
  99200. FLAC__real *pa; /* aligned pointer */
  99201. void *pv; /* aligned pointer alias */
  99202. } u;
  99203. FLAC__ASSERT(elements > 0);
  99204. FLAC__ASSERT(0 != unaligned_pointer);
  99205. FLAC__ASSERT(0 != aligned_pointer);
  99206. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99207. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99208. if(0 == pu) {
  99209. return false;
  99210. }
  99211. else {
  99212. if(*unaligned_pointer != 0)
  99213. free(*unaligned_pointer);
  99214. *unaligned_pointer = pu;
  99215. *aligned_pointer = u.pa;
  99216. return true;
  99217. }
  99218. }
  99219. #endif
  99220. #endif
  99221. /*** End of inlined file: memory.c ***/
  99222. /*** Start of inlined file: stream_decoder.c ***/
  99223. /*** Start of inlined file: juce_FlacHeader.h ***/
  99224. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99225. // tasks..
  99226. #define VERSION "1.2.1"
  99227. #define FLAC__NO_DLL 1
  99228. #if JUCE_MSVC
  99229. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99230. #endif
  99231. #if JUCE_MAC
  99232. #define FLAC__SYS_DARWIN 1
  99233. #endif
  99234. /*** End of inlined file: juce_FlacHeader.h ***/
  99235. #if JUCE_USE_FLAC
  99236. #if HAVE_CONFIG_H
  99237. # include <config.h>
  99238. #endif
  99239. #if defined _MSC_VER || defined __MINGW32__
  99240. #include <io.h> /* for _setmode() */
  99241. #include <fcntl.h> /* for _O_BINARY */
  99242. #endif
  99243. #if defined __CYGWIN__ || defined __EMX__
  99244. #include <io.h> /* for setmode(), O_BINARY */
  99245. #include <fcntl.h> /* for _O_BINARY */
  99246. #endif
  99247. #include <stdio.h>
  99248. #include <stdlib.h> /* for malloc() */
  99249. #include <string.h> /* for memset/memcpy() */
  99250. #include <sys/stat.h> /* for stat() */
  99251. #include <sys/types.h> /* for off_t */
  99252. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99253. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99254. #define fseeko fseek
  99255. #define ftello ftell
  99256. #endif
  99257. #endif
  99258. /*** Start of inlined file: stream_decoder.h ***/
  99259. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99260. #define FLAC__PROTECTED__STREAM_DECODER_H
  99261. #if FLAC__HAS_OGG
  99262. #include "include/private/ogg_decoder_aspect.h"
  99263. #endif
  99264. typedef struct FLAC__StreamDecoderProtected {
  99265. FLAC__StreamDecoderState state;
  99266. unsigned channels;
  99267. FLAC__ChannelAssignment channel_assignment;
  99268. unsigned bits_per_sample;
  99269. unsigned sample_rate; /* in Hz */
  99270. unsigned blocksize; /* in samples (per channel) */
  99271. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99272. #if FLAC__HAS_OGG
  99273. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99274. #endif
  99275. } FLAC__StreamDecoderProtected;
  99276. /*
  99277. * return the number of input bytes consumed
  99278. */
  99279. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99280. #endif
  99281. /*** End of inlined file: stream_decoder.h ***/
  99282. #ifdef max
  99283. #undef max
  99284. #endif
  99285. #define max(a,b) ((a)>(b)?(a):(b))
  99286. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99287. #ifdef _MSC_VER
  99288. #define FLAC__U64L(x) x
  99289. #else
  99290. #define FLAC__U64L(x) x##LLU
  99291. #endif
  99292. /* technically this should be in an "export.c" but this is convenient enough */
  99293. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99294. #if FLAC__HAS_OGG
  99295. 1
  99296. #else
  99297. 0
  99298. #endif
  99299. ;
  99300. /***********************************************************************
  99301. *
  99302. * Private static data
  99303. *
  99304. ***********************************************************************/
  99305. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99306. /***********************************************************************
  99307. *
  99308. * Private class method prototypes
  99309. *
  99310. ***********************************************************************/
  99311. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99312. static FILE *get_binary_stdin_(void);
  99313. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99314. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99315. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99316. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99317. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99318. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99319. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99320. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99321. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99322. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99323. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99324. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99325. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99326. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99327. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99328. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99329. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99330. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99331. 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);
  99332. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99333. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99334. #if FLAC__HAS_OGG
  99335. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99336. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99337. #endif
  99338. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99339. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99340. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99341. #if FLAC__HAS_OGG
  99342. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99343. #endif
  99344. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99345. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99346. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99347. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99348. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99349. /***********************************************************************
  99350. *
  99351. * Private class data
  99352. *
  99353. ***********************************************************************/
  99354. typedef struct FLAC__StreamDecoderPrivate {
  99355. #if FLAC__HAS_OGG
  99356. FLAC__bool is_ogg;
  99357. #endif
  99358. FLAC__StreamDecoderReadCallback read_callback;
  99359. FLAC__StreamDecoderSeekCallback seek_callback;
  99360. FLAC__StreamDecoderTellCallback tell_callback;
  99361. FLAC__StreamDecoderLengthCallback length_callback;
  99362. FLAC__StreamDecoderEofCallback eof_callback;
  99363. FLAC__StreamDecoderWriteCallback write_callback;
  99364. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99365. FLAC__StreamDecoderErrorCallback error_callback;
  99366. /* generic 32-bit datapath: */
  99367. 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[]);
  99368. /* generic 64-bit datapath: */
  99369. 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[]);
  99370. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99371. 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[]);
  99372. /* 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: */
  99373. 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[]);
  99374. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99375. void *client_data;
  99376. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99377. FLAC__BitReader *input;
  99378. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99379. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99380. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99381. unsigned output_capacity, output_channels;
  99382. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99383. FLAC__uint64 samples_decoded;
  99384. FLAC__bool has_stream_info, has_seek_table;
  99385. FLAC__StreamMetadata stream_info;
  99386. FLAC__StreamMetadata seek_table;
  99387. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99388. FLAC__byte *metadata_filter_ids;
  99389. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99390. FLAC__Frame frame;
  99391. FLAC__bool cached; /* true if there is a byte in lookahead */
  99392. FLAC__CPUInfo cpuinfo;
  99393. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99394. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99395. /* unaligned (original) pointers to allocated data */
  99396. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99397. 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 */
  99398. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99399. FLAC__bool is_seeking;
  99400. FLAC__MD5Context md5context;
  99401. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99402. /* (the rest of these are only used for seeking) */
  99403. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99404. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99405. FLAC__uint64 target_sample;
  99406. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99407. #if FLAC__HAS_OGG
  99408. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99409. #endif
  99410. } FLAC__StreamDecoderPrivate;
  99411. /***********************************************************************
  99412. *
  99413. * Public static class data
  99414. *
  99415. ***********************************************************************/
  99416. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99417. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99418. "FLAC__STREAM_DECODER_READ_METADATA",
  99419. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99420. "FLAC__STREAM_DECODER_READ_FRAME",
  99421. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99422. "FLAC__STREAM_DECODER_OGG_ERROR",
  99423. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99424. "FLAC__STREAM_DECODER_ABORTED",
  99425. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99426. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99427. };
  99428. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99429. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99430. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99431. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99432. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99433. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99434. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99435. };
  99436. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99437. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99438. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99439. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99440. };
  99441. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99442. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99443. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99444. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99445. };
  99446. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99447. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99448. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99449. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99450. };
  99451. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99452. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99453. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99454. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99455. };
  99456. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99457. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99458. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99459. };
  99460. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99461. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99462. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99463. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99464. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99465. };
  99466. /***********************************************************************
  99467. *
  99468. * Class constructor/destructor
  99469. *
  99470. ***********************************************************************/
  99471. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99472. {
  99473. FLAC__StreamDecoder *decoder;
  99474. unsigned i;
  99475. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99476. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99477. if(decoder == 0) {
  99478. return 0;
  99479. }
  99480. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99481. if(decoder->protected_ == 0) {
  99482. free(decoder);
  99483. return 0;
  99484. }
  99485. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99486. if(decoder->private_ == 0) {
  99487. free(decoder->protected_);
  99488. free(decoder);
  99489. return 0;
  99490. }
  99491. decoder->private_->input = FLAC__bitreader_new();
  99492. if(decoder->private_->input == 0) {
  99493. free(decoder->private_);
  99494. free(decoder->protected_);
  99495. free(decoder);
  99496. return 0;
  99497. }
  99498. decoder->private_->metadata_filter_ids_capacity = 16;
  99499. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99500. FLAC__bitreader_delete(decoder->private_->input);
  99501. free(decoder->private_);
  99502. free(decoder->protected_);
  99503. free(decoder);
  99504. return 0;
  99505. }
  99506. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99507. decoder->private_->output[i] = 0;
  99508. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99509. }
  99510. decoder->private_->output_capacity = 0;
  99511. decoder->private_->output_channels = 0;
  99512. decoder->private_->has_seek_table = false;
  99513. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99514. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99515. decoder->private_->file = 0;
  99516. set_defaults_dec(decoder);
  99517. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99518. return decoder;
  99519. }
  99520. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99521. {
  99522. unsigned i;
  99523. FLAC__ASSERT(0 != decoder);
  99524. FLAC__ASSERT(0 != decoder->protected_);
  99525. FLAC__ASSERT(0 != decoder->private_);
  99526. FLAC__ASSERT(0 != decoder->private_->input);
  99527. (void)FLAC__stream_decoder_finish(decoder);
  99528. if(0 != decoder->private_->metadata_filter_ids)
  99529. free(decoder->private_->metadata_filter_ids);
  99530. FLAC__bitreader_delete(decoder->private_->input);
  99531. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99532. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99533. free(decoder->private_);
  99534. free(decoder->protected_);
  99535. free(decoder);
  99536. }
  99537. /***********************************************************************
  99538. *
  99539. * Public class methods
  99540. *
  99541. ***********************************************************************/
  99542. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99543. FLAC__StreamDecoder *decoder,
  99544. FLAC__StreamDecoderReadCallback read_callback,
  99545. FLAC__StreamDecoderSeekCallback seek_callback,
  99546. FLAC__StreamDecoderTellCallback tell_callback,
  99547. FLAC__StreamDecoderLengthCallback length_callback,
  99548. FLAC__StreamDecoderEofCallback eof_callback,
  99549. FLAC__StreamDecoderWriteCallback write_callback,
  99550. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99551. FLAC__StreamDecoderErrorCallback error_callback,
  99552. void *client_data,
  99553. FLAC__bool is_ogg
  99554. )
  99555. {
  99556. FLAC__ASSERT(0 != decoder);
  99557. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99558. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99559. #if !FLAC__HAS_OGG
  99560. if(is_ogg)
  99561. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99562. #endif
  99563. if(
  99564. 0 == read_callback ||
  99565. 0 == write_callback ||
  99566. 0 == error_callback ||
  99567. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99568. )
  99569. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99570. #if FLAC__HAS_OGG
  99571. decoder->private_->is_ogg = is_ogg;
  99572. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99573. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99574. #endif
  99575. /*
  99576. * get the CPU info and set the function pointers
  99577. */
  99578. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99579. /* first default to the non-asm routines */
  99580. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99581. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99582. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99583. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99584. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99585. /* now override with asm where appropriate */
  99586. #ifndef FLAC__NO_ASM
  99587. if(decoder->private_->cpuinfo.use_asm) {
  99588. #ifdef FLAC__CPU_IA32
  99589. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99590. #ifdef FLAC__HAS_NASM
  99591. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99592. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99593. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99594. #endif
  99595. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99596. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99597. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99598. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99599. }
  99600. else {
  99601. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99602. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99603. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99604. }
  99605. #endif
  99606. #elif defined FLAC__CPU_PPC
  99607. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99608. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99609. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99610. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99611. }
  99612. #endif
  99613. }
  99614. #endif
  99615. /* from here on, errors are fatal */
  99616. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99617. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99618. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99619. }
  99620. decoder->private_->read_callback = read_callback;
  99621. decoder->private_->seek_callback = seek_callback;
  99622. decoder->private_->tell_callback = tell_callback;
  99623. decoder->private_->length_callback = length_callback;
  99624. decoder->private_->eof_callback = eof_callback;
  99625. decoder->private_->write_callback = write_callback;
  99626. decoder->private_->metadata_callback = metadata_callback;
  99627. decoder->private_->error_callback = error_callback;
  99628. decoder->private_->client_data = client_data;
  99629. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99630. decoder->private_->samples_decoded = 0;
  99631. decoder->private_->has_stream_info = false;
  99632. decoder->private_->cached = false;
  99633. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99634. decoder->private_->is_seeking = false;
  99635. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99636. if(!FLAC__stream_decoder_reset(decoder)) {
  99637. /* above call sets the state for us */
  99638. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99639. }
  99640. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99641. }
  99642. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99643. FLAC__StreamDecoder *decoder,
  99644. FLAC__StreamDecoderReadCallback read_callback,
  99645. FLAC__StreamDecoderSeekCallback seek_callback,
  99646. FLAC__StreamDecoderTellCallback tell_callback,
  99647. FLAC__StreamDecoderLengthCallback length_callback,
  99648. FLAC__StreamDecoderEofCallback eof_callback,
  99649. FLAC__StreamDecoderWriteCallback write_callback,
  99650. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99651. FLAC__StreamDecoderErrorCallback error_callback,
  99652. void *client_data
  99653. )
  99654. {
  99655. return init_stream_internal_dec(
  99656. decoder,
  99657. read_callback,
  99658. seek_callback,
  99659. tell_callback,
  99660. length_callback,
  99661. eof_callback,
  99662. write_callback,
  99663. metadata_callback,
  99664. error_callback,
  99665. client_data,
  99666. /*is_ogg=*/false
  99667. );
  99668. }
  99669. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99670. FLAC__StreamDecoder *decoder,
  99671. FLAC__StreamDecoderReadCallback read_callback,
  99672. FLAC__StreamDecoderSeekCallback seek_callback,
  99673. FLAC__StreamDecoderTellCallback tell_callback,
  99674. FLAC__StreamDecoderLengthCallback length_callback,
  99675. FLAC__StreamDecoderEofCallback eof_callback,
  99676. FLAC__StreamDecoderWriteCallback write_callback,
  99677. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99678. FLAC__StreamDecoderErrorCallback error_callback,
  99679. void *client_data
  99680. )
  99681. {
  99682. return init_stream_internal_dec(
  99683. decoder,
  99684. read_callback,
  99685. seek_callback,
  99686. tell_callback,
  99687. length_callback,
  99688. eof_callback,
  99689. write_callback,
  99690. metadata_callback,
  99691. error_callback,
  99692. client_data,
  99693. /*is_ogg=*/true
  99694. );
  99695. }
  99696. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99697. FLAC__StreamDecoder *decoder,
  99698. FILE *file,
  99699. FLAC__StreamDecoderWriteCallback write_callback,
  99700. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99701. FLAC__StreamDecoderErrorCallback error_callback,
  99702. void *client_data,
  99703. FLAC__bool is_ogg
  99704. )
  99705. {
  99706. FLAC__ASSERT(0 != decoder);
  99707. FLAC__ASSERT(0 != file);
  99708. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99709. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99710. if(0 == write_callback || 0 == error_callback)
  99711. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99712. /*
  99713. * To make sure that our file does not go unclosed after an error, we
  99714. * must assign the FILE pointer before any further error can occur in
  99715. * this routine.
  99716. */
  99717. if(file == stdin)
  99718. file = get_binary_stdin_(); /* just to be safe */
  99719. decoder->private_->file = file;
  99720. return init_stream_internal_dec(
  99721. decoder,
  99722. file_read_callback_dec,
  99723. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99724. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99725. decoder->private_->file == stdin? 0: file_length_callback_,
  99726. file_eof_callback_,
  99727. write_callback,
  99728. metadata_callback,
  99729. error_callback,
  99730. client_data,
  99731. is_ogg
  99732. );
  99733. }
  99734. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99735. FLAC__StreamDecoder *decoder,
  99736. FILE *file,
  99737. FLAC__StreamDecoderWriteCallback write_callback,
  99738. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99739. FLAC__StreamDecoderErrorCallback error_callback,
  99740. void *client_data
  99741. )
  99742. {
  99743. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99744. }
  99745. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99746. FLAC__StreamDecoder *decoder,
  99747. FILE *file,
  99748. FLAC__StreamDecoderWriteCallback write_callback,
  99749. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99750. FLAC__StreamDecoderErrorCallback error_callback,
  99751. void *client_data
  99752. )
  99753. {
  99754. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99755. }
  99756. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99757. FLAC__StreamDecoder *decoder,
  99758. const char *filename,
  99759. FLAC__StreamDecoderWriteCallback write_callback,
  99760. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99761. FLAC__StreamDecoderErrorCallback error_callback,
  99762. void *client_data,
  99763. FLAC__bool is_ogg
  99764. )
  99765. {
  99766. FILE *file;
  99767. FLAC__ASSERT(0 != decoder);
  99768. /*
  99769. * To make sure that our file does not go unclosed after an error, we
  99770. * have to do the same entrance checks here that are later performed
  99771. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99772. */
  99773. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99774. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99775. if(0 == write_callback || 0 == error_callback)
  99776. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99777. file = filename? fopen(filename, "rb") : stdin;
  99778. if(0 == file)
  99779. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99780. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99781. }
  99782. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99783. FLAC__StreamDecoder *decoder,
  99784. const char *filename,
  99785. FLAC__StreamDecoderWriteCallback write_callback,
  99786. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99787. FLAC__StreamDecoderErrorCallback error_callback,
  99788. void *client_data
  99789. )
  99790. {
  99791. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99792. }
  99793. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99794. FLAC__StreamDecoder *decoder,
  99795. const char *filename,
  99796. FLAC__StreamDecoderWriteCallback write_callback,
  99797. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99798. FLAC__StreamDecoderErrorCallback error_callback,
  99799. void *client_data
  99800. )
  99801. {
  99802. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99803. }
  99804. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99805. {
  99806. FLAC__bool md5_failed = false;
  99807. unsigned i;
  99808. FLAC__ASSERT(0 != decoder);
  99809. FLAC__ASSERT(0 != decoder->private_);
  99810. FLAC__ASSERT(0 != decoder->protected_);
  99811. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99812. return true;
  99813. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99814. * always call FLAC__MD5Final()
  99815. */
  99816. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99817. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99818. free(decoder->private_->seek_table.data.seek_table.points);
  99819. decoder->private_->seek_table.data.seek_table.points = 0;
  99820. decoder->private_->has_seek_table = false;
  99821. }
  99822. FLAC__bitreader_free(decoder->private_->input);
  99823. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99824. /* WATCHOUT:
  99825. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99826. * output arrays have a buffer of up to 3 zeroes in front
  99827. * (at negative indices) for alignment purposes; we use 4
  99828. * to keep the data well-aligned.
  99829. */
  99830. if(0 != decoder->private_->output[i]) {
  99831. free(decoder->private_->output[i]-4);
  99832. decoder->private_->output[i] = 0;
  99833. }
  99834. if(0 != decoder->private_->residual_unaligned[i]) {
  99835. free(decoder->private_->residual_unaligned[i]);
  99836. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99837. }
  99838. }
  99839. decoder->private_->output_capacity = 0;
  99840. decoder->private_->output_channels = 0;
  99841. #if FLAC__HAS_OGG
  99842. if(decoder->private_->is_ogg)
  99843. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99844. #endif
  99845. if(0 != decoder->private_->file) {
  99846. if(decoder->private_->file != stdin)
  99847. fclose(decoder->private_->file);
  99848. decoder->private_->file = 0;
  99849. }
  99850. if(decoder->private_->do_md5_checking) {
  99851. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99852. md5_failed = true;
  99853. }
  99854. decoder->private_->is_seeking = false;
  99855. set_defaults_dec(decoder);
  99856. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99857. return !md5_failed;
  99858. }
  99859. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99860. {
  99861. FLAC__ASSERT(0 != decoder);
  99862. FLAC__ASSERT(0 != decoder->private_);
  99863. FLAC__ASSERT(0 != decoder->protected_);
  99864. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99865. return false;
  99866. #if FLAC__HAS_OGG
  99867. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99868. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99869. return true;
  99870. #else
  99871. (void)value;
  99872. return false;
  99873. #endif
  99874. }
  99875. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99876. {
  99877. FLAC__ASSERT(0 != decoder);
  99878. FLAC__ASSERT(0 != decoder->protected_);
  99879. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99880. return false;
  99881. decoder->protected_->md5_checking = value;
  99882. return true;
  99883. }
  99884. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99885. {
  99886. FLAC__ASSERT(0 != decoder);
  99887. FLAC__ASSERT(0 != decoder->private_);
  99888. FLAC__ASSERT(0 != decoder->protected_);
  99889. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99890. /* double protection */
  99891. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99892. return false;
  99893. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99894. return false;
  99895. decoder->private_->metadata_filter[type] = true;
  99896. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99897. decoder->private_->metadata_filter_ids_count = 0;
  99898. return true;
  99899. }
  99900. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99901. {
  99902. FLAC__ASSERT(0 != decoder);
  99903. FLAC__ASSERT(0 != decoder->private_);
  99904. FLAC__ASSERT(0 != decoder->protected_);
  99905. FLAC__ASSERT(0 != id);
  99906. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99907. return false;
  99908. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99909. return true;
  99910. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99911. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99912. 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))) {
  99913. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99914. return false;
  99915. }
  99916. decoder->private_->metadata_filter_ids_capacity *= 2;
  99917. }
  99918. 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));
  99919. decoder->private_->metadata_filter_ids_count++;
  99920. return true;
  99921. }
  99922. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99923. {
  99924. unsigned i;
  99925. FLAC__ASSERT(0 != decoder);
  99926. FLAC__ASSERT(0 != decoder->private_);
  99927. FLAC__ASSERT(0 != decoder->protected_);
  99928. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99929. return false;
  99930. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99931. decoder->private_->metadata_filter[i] = true;
  99932. decoder->private_->metadata_filter_ids_count = 0;
  99933. return true;
  99934. }
  99935. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99936. {
  99937. FLAC__ASSERT(0 != decoder);
  99938. FLAC__ASSERT(0 != decoder->private_);
  99939. FLAC__ASSERT(0 != decoder->protected_);
  99940. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99941. /* double protection */
  99942. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99943. return false;
  99944. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99945. return false;
  99946. decoder->private_->metadata_filter[type] = false;
  99947. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99948. decoder->private_->metadata_filter_ids_count = 0;
  99949. return true;
  99950. }
  99951. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99952. {
  99953. FLAC__ASSERT(0 != decoder);
  99954. FLAC__ASSERT(0 != decoder->private_);
  99955. FLAC__ASSERT(0 != decoder->protected_);
  99956. FLAC__ASSERT(0 != id);
  99957. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99958. return false;
  99959. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99960. return true;
  99961. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99962. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99963. 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))) {
  99964. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99965. return false;
  99966. }
  99967. decoder->private_->metadata_filter_ids_capacity *= 2;
  99968. }
  99969. 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));
  99970. decoder->private_->metadata_filter_ids_count++;
  99971. return true;
  99972. }
  99973. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99974. {
  99975. FLAC__ASSERT(0 != decoder);
  99976. FLAC__ASSERT(0 != decoder->private_);
  99977. FLAC__ASSERT(0 != decoder->protected_);
  99978. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99979. return false;
  99980. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99981. decoder->private_->metadata_filter_ids_count = 0;
  99982. return true;
  99983. }
  99984. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99985. {
  99986. FLAC__ASSERT(0 != decoder);
  99987. FLAC__ASSERT(0 != decoder->protected_);
  99988. return decoder->protected_->state;
  99989. }
  99990. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99991. {
  99992. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99993. }
  99994. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99995. {
  99996. FLAC__ASSERT(0 != decoder);
  99997. FLAC__ASSERT(0 != decoder->protected_);
  99998. return decoder->protected_->md5_checking;
  99999. }
  100000. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100001. {
  100002. FLAC__ASSERT(0 != decoder);
  100003. FLAC__ASSERT(0 != decoder->protected_);
  100004. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100005. }
  100006. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100007. {
  100008. FLAC__ASSERT(0 != decoder);
  100009. FLAC__ASSERT(0 != decoder->protected_);
  100010. return decoder->protected_->channels;
  100011. }
  100012. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100013. {
  100014. FLAC__ASSERT(0 != decoder);
  100015. FLAC__ASSERT(0 != decoder->protected_);
  100016. return decoder->protected_->channel_assignment;
  100017. }
  100018. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100019. {
  100020. FLAC__ASSERT(0 != decoder);
  100021. FLAC__ASSERT(0 != decoder->protected_);
  100022. return decoder->protected_->bits_per_sample;
  100023. }
  100024. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100025. {
  100026. FLAC__ASSERT(0 != decoder);
  100027. FLAC__ASSERT(0 != decoder->protected_);
  100028. return decoder->protected_->sample_rate;
  100029. }
  100030. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100031. {
  100032. FLAC__ASSERT(0 != decoder);
  100033. FLAC__ASSERT(0 != decoder->protected_);
  100034. return decoder->protected_->blocksize;
  100035. }
  100036. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100037. {
  100038. FLAC__ASSERT(0 != decoder);
  100039. FLAC__ASSERT(0 != decoder->private_);
  100040. FLAC__ASSERT(0 != position);
  100041. #if FLAC__HAS_OGG
  100042. if(decoder->private_->is_ogg)
  100043. return false;
  100044. #endif
  100045. if(0 == decoder->private_->tell_callback)
  100046. return false;
  100047. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100048. return false;
  100049. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100050. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100051. return false;
  100052. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100053. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100054. return true;
  100055. }
  100056. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100057. {
  100058. FLAC__ASSERT(0 != decoder);
  100059. FLAC__ASSERT(0 != decoder->private_);
  100060. FLAC__ASSERT(0 != decoder->protected_);
  100061. decoder->private_->samples_decoded = 0;
  100062. decoder->private_->do_md5_checking = false;
  100063. #if FLAC__HAS_OGG
  100064. if(decoder->private_->is_ogg)
  100065. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100066. #endif
  100067. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100068. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100069. return false;
  100070. }
  100071. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100072. return true;
  100073. }
  100074. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100075. {
  100076. FLAC__ASSERT(0 != decoder);
  100077. FLAC__ASSERT(0 != decoder->private_);
  100078. FLAC__ASSERT(0 != decoder->protected_);
  100079. if(!FLAC__stream_decoder_flush(decoder)) {
  100080. /* above call sets the state for us */
  100081. return false;
  100082. }
  100083. #if FLAC__HAS_OGG
  100084. /*@@@ could go in !internal_reset_hack block below */
  100085. if(decoder->private_->is_ogg)
  100086. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100087. #endif
  100088. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100089. * (internal_reset_hack) don't try to rewind since we are already at
  100090. * the beginning of the stream and don't want to fail if the input is
  100091. * not seekable.
  100092. */
  100093. if(!decoder->private_->internal_reset_hack) {
  100094. if(decoder->private_->file == stdin)
  100095. return false; /* can't rewind stdin, reset fails */
  100096. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100097. return false; /* seekable and seek fails, reset fails */
  100098. }
  100099. else
  100100. decoder->private_->internal_reset_hack = false;
  100101. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100102. decoder->private_->has_stream_info = false;
  100103. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100104. free(decoder->private_->seek_table.data.seek_table.points);
  100105. decoder->private_->seek_table.data.seek_table.points = 0;
  100106. decoder->private_->has_seek_table = false;
  100107. }
  100108. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100109. /*
  100110. * This goes in reset() and not flush() because according to the spec, a
  100111. * fixed-blocksize stream must stay that way through the whole stream.
  100112. */
  100113. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100114. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100115. * is because md5 checking may be turned on to start and then turned off if
  100116. * a seek occurs. So we init the context here and finalize it in
  100117. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100118. * properly.
  100119. */
  100120. FLAC__MD5Init(&decoder->private_->md5context);
  100121. decoder->private_->first_frame_offset = 0;
  100122. decoder->private_->unparseable_frame_count = 0;
  100123. return true;
  100124. }
  100125. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100126. {
  100127. FLAC__bool got_a_frame;
  100128. FLAC__ASSERT(0 != decoder);
  100129. FLAC__ASSERT(0 != decoder->protected_);
  100130. while(1) {
  100131. switch(decoder->protected_->state) {
  100132. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100133. if(!find_metadata_(decoder))
  100134. return false; /* above function sets the status for us */
  100135. break;
  100136. case FLAC__STREAM_DECODER_READ_METADATA:
  100137. if(!read_metadata_(decoder))
  100138. return false; /* above function sets the status for us */
  100139. else
  100140. return true;
  100141. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100142. if(!frame_sync_(decoder))
  100143. return true; /* above function sets the status for us */
  100144. break;
  100145. case FLAC__STREAM_DECODER_READ_FRAME:
  100146. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100147. return false; /* above function sets the status for us */
  100148. if(got_a_frame)
  100149. return true; /* above function sets the status for us */
  100150. break;
  100151. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100152. case FLAC__STREAM_DECODER_ABORTED:
  100153. return true;
  100154. default:
  100155. FLAC__ASSERT(0);
  100156. return false;
  100157. }
  100158. }
  100159. }
  100160. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100161. {
  100162. FLAC__ASSERT(0 != decoder);
  100163. FLAC__ASSERT(0 != decoder->protected_);
  100164. while(1) {
  100165. switch(decoder->protected_->state) {
  100166. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100167. if(!find_metadata_(decoder))
  100168. return false; /* above function sets the status for us */
  100169. break;
  100170. case FLAC__STREAM_DECODER_READ_METADATA:
  100171. if(!read_metadata_(decoder))
  100172. return false; /* above function sets the status for us */
  100173. break;
  100174. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100175. case FLAC__STREAM_DECODER_READ_FRAME:
  100176. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100177. case FLAC__STREAM_DECODER_ABORTED:
  100178. return true;
  100179. default:
  100180. FLAC__ASSERT(0);
  100181. return false;
  100182. }
  100183. }
  100184. }
  100185. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100186. {
  100187. FLAC__bool dummy;
  100188. FLAC__ASSERT(0 != decoder);
  100189. FLAC__ASSERT(0 != decoder->protected_);
  100190. while(1) {
  100191. switch(decoder->protected_->state) {
  100192. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100193. if(!find_metadata_(decoder))
  100194. return false; /* above function sets the status for us */
  100195. break;
  100196. case FLAC__STREAM_DECODER_READ_METADATA:
  100197. if(!read_metadata_(decoder))
  100198. return false; /* above function sets the status for us */
  100199. break;
  100200. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100201. if(!frame_sync_(decoder))
  100202. return true; /* above function sets the status for us */
  100203. break;
  100204. case FLAC__STREAM_DECODER_READ_FRAME:
  100205. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100206. return false; /* above function sets the status for us */
  100207. break;
  100208. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100209. case FLAC__STREAM_DECODER_ABORTED:
  100210. return true;
  100211. default:
  100212. FLAC__ASSERT(0);
  100213. return false;
  100214. }
  100215. }
  100216. }
  100217. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100218. {
  100219. FLAC__bool got_a_frame;
  100220. FLAC__ASSERT(0 != decoder);
  100221. FLAC__ASSERT(0 != decoder->protected_);
  100222. while(1) {
  100223. switch(decoder->protected_->state) {
  100224. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100225. case FLAC__STREAM_DECODER_READ_METADATA:
  100226. return false; /* above function sets the status for us */
  100227. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100228. if(!frame_sync_(decoder))
  100229. return true; /* above function sets the status for us */
  100230. break;
  100231. case FLAC__STREAM_DECODER_READ_FRAME:
  100232. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100233. return false; /* above function sets the status for us */
  100234. if(got_a_frame)
  100235. return true; /* above function sets the status for us */
  100236. break;
  100237. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100238. case FLAC__STREAM_DECODER_ABORTED:
  100239. return true;
  100240. default:
  100241. FLAC__ASSERT(0);
  100242. return false;
  100243. }
  100244. }
  100245. }
  100246. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100247. {
  100248. FLAC__uint64 length;
  100249. FLAC__ASSERT(0 != decoder);
  100250. if(
  100251. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100252. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100253. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100254. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100255. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100256. )
  100257. return false;
  100258. if(0 == decoder->private_->seek_callback)
  100259. return false;
  100260. FLAC__ASSERT(decoder->private_->seek_callback);
  100261. FLAC__ASSERT(decoder->private_->tell_callback);
  100262. FLAC__ASSERT(decoder->private_->length_callback);
  100263. FLAC__ASSERT(decoder->private_->eof_callback);
  100264. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100265. return false;
  100266. decoder->private_->is_seeking = true;
  100267. /* turn off md5 checking if a seek is attempted */
  100268. decoder->private_->do_md5_checking = false;
  100269. /* 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) */
  100270. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100271. decoder->private_->is_seeking = false;
  100272. return false;
  100273. }
  100274. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100275. if(
  100276. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100277. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100278. ) {
  100279. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100280. /* above call sets the state for us */
  100281. decoder->private_->is_seeking = false;
  100282. return false;
  100283. }
  100284. /* check this again in case we didn't know total_samples the first time */
  100285. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100286. decoder->private_->is_seeking = false;
  100287. return false;
  100288. }
  100289. }
  100290. {
  100291. const FLAC__bool ok =
  100292. #if FLAC__HAS_OGG
  100293. decoder->private_->is_ogg?
  100294. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100295. #endif
  100296. seek_to_absolute_sample_(decoder, length, sample)
  100297. ;
  100298. decoder->private_->is_seeking = false;
  100299. return ok;
  100300. }
  100301. }
  100302. /***********************************************************************
  100303. *
  100304. * Protected class methods
  100305. *
  100306. ***********************************************************************/
  100307. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100308. {
  100309. FLAC__ASSERT(0 != decoder);
  100310. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100311. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100312. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100313. }
  100314. /***********************************************************************
  100315. *
  100316. * Private class methods
  100317. *
  100318. ***********************************************************************/
  100319. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100320. {
  100321. #if FLAC__HAS_OGG
  100322. decoder->private_->is_ogg = false;
  100323. #endif
  100324. decoder->private_->read_callback = 0;
  100325. decoder->private_->seek_callback = 0;
  100326. decoder->private_->tell_callback = 0;
  100327. decoder->private_->length_callback = 0;
  100328. decoder->private_->eof_callback = 0;
  100329. decoder->private_->write_callback = 0;
  100330. decoder->private_->metadata_callback = 0;
  100331. decoder->private_->error_callback = 0;
  100332. decoder->private_->client_data = 0;
  100333. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100334. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100335. decoder->private_->metadata_filter_ids_count = 0;
  100336. decoder->protected_->md5_checking = false;
  100337. #if FLAC__HAS_OGG
  100338. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100339. #endif
  100340. }
  100341. /*
  100342. * This will forcibly set stdin to binary mode (for OSes that require it)
  100343. */
  100344. FILE *get_binary_stdin_(void)
  100345. {
  100346. /* if something breaks here it is probably due to the presence or
  100347. * absence of an underscore before the identifiers 'setmode',
  100348. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100349. */
  100350. #if defined _MSC_VER || defined __MINGW32__
  100351. _setmode(_fileno(stdin), _O_BINARY);
  100352. #elif defined __CYGWIN__
  100353. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100354. setmode(_fileno(stdin), _O_BINARY);
  100355. #elif defined __EMX__
  100356. setmode(fileno(stdin), O_BINARY);
  100357. #endif
  100358. return stdin;
  100359. }
  100360. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100361. {
  100362. unsigned i;
  100363. FLAC__int32 *tmp;
  100364. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100365. return true;
  100366. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100367. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100368. if(0 != decoder->private_->output[i]) {
  100369. free(decoder->private_->output[i]-4);
  100370. decoder->private_->output[i] = 0;
  100371. }
  100372. if(0 != decoder->private_->residual_unaligned[i]) {
  100373. free(decoder->private_->residual_unaligned[i]);
  100374. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100375. }
  100376. }
  100377. for(i = 0; i < channels; i++) {
  100378. /* WATCHOUT:
  100379. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100380. * output arrays have a buffer of up to 3 zeroes in front
  100381. * (at negative indices) for alignment purposes; we use 4
  100382. * to keep the data well-aligned.
  100383. */
  100384. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100385. if(tmp == 0) {
  100386. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100387. return false;
  100388. }
  100389. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100390. decoder->private_->output[i] = tmp + 4;
  100391. /* WATCHOUT:
  100392. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100393. */
  100394. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100395. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100396. return false;
  100397. }
  100398. }
  100399. decoder->private_->output_capacity = size;
  100400. decoder->private_->output_channels = channels;
  100401. return true;
  100402. }
  100403. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100404. {
  100405. size_t i;
  100406. FLAC__ASSERT(0 != decoder);
  100407. FLAC__ASSERT(0 != decoder->private_);
  100408. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100409. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100410. return true;
  100411. return false;
  100412. }
  100413. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100414. {
  100415. FLAC__uint32 x;
  100416. unsigned i, id_;
  100417. FLAC__bool first = true;
  100418. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100419. for(i = id_ = 0; i < 4; ) {
  100420. if(decoder->private_->cached) {
  100421. x = (FLAC__uint32)decoder->private_->lookahead;
  100422. decoder->private_->cached = false;
  100423. }
  100424. else {
  100425. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100426. return false; /* read_callback_ sets the state for us */
  100427. }
  100428. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100429. first = true;
  100430. i++;
  100431. id_ = 0;
  100432. continue;
  100433. }
  100434. if(x == ID3V2_TAG_[id_]) {
  100435. id_++;
  100436. i = 0;
  100437. if(id_ == 3) {
  100438. if(!skip_id3v2_tag_(decoder))
  100439. return false; /* skip_id3v2_tag_ sets the state for us */
  100440. }
  100441. continue;
  100442. }
  100443. id_ = 0;
  100444. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100445. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100446. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100447. return false; /* read_callback_ sets the state for us */
  100448. /* 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 */
  100449. /* else we have to check if the second byte is the end of a sync code */
  100450. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100451. decoder->private_->lookahead = (FLAC__byte)x;
  100452. decoder->private_->cached = true;
  100453. }
  100454. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100455. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100456. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100457. return true;
  100458. }
  100459. }
  100460. i = 0;
  100461. if(first) {
  100462. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100463. first = false;
  100464. }
  100465. }
  100466. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100467. return true;
  100468. }
  100469. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100470. {
  100471. FLAC__bool is_last;
  100472. FLAC__uint32 i, x, type, length;
  100473. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100474. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100475. return false; /* read_callback_ sets the state for us */
  100476. is_last = x? true : false;
  100477. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100478. return false; /* read_callback_ sets the state for us */
  100479. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100480. return false; /* read_callback_ sets the state for us */
  100481. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100482. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100483. return false;
  100484. decoder->private_->has_stream_info = true;
  100485. 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))
  100486. decoder->private_->do_md5_checking = false;
  100487. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100488. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100489. }
  100490. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100491. if(!read_metadata_seektable_(decoder, is_last, length))
  100492. return false;
  100493. decoder->private_->has_seek_table = true;
  100494. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100495. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100496. }
  100497. else {
  100498. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100499. unsigned real_length = length;
  100500. FLAC__StreamMetadata block;
  100501. block.is_last = is_last;
  100502. block.type = (FLAC__MetadataType)type;
  100503. block.length = length;
  100504. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100505. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100506. return false; /* read_callback_ sets the state for us */
  100507. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100508. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100509. return false;
  100510. }
  100511. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100512. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100513. skip_it = !skip_it;
  100514. }
  100515. if(skip_it) {
  100516. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100517. return false; /* read_callback_ sets the state for us */
  100518. }
  100519. else {
  100520. switch(type) {
  100521. case FLAC__METADATA_TYPE_PADDING:
  100522. /* skip the padding bytes */
  100523. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100524. return false; /* read_callback_ sets the state for us */
  100525. break;
  100526. case FLAC__METADATA_TYPE_APPLICATION:
  100527. /* remember, we read the ID already */
  100528. if(real_length > 0) {
  100529. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100530. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100531. return false;
  100532. }
  100533. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100534. return false; /* read_callback_ sets the state for us */
  100535. }
  100536. else
  100537. block.data.application.data = 0;
  100538. break;
  100539. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100540. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100541. return false;
  100542. break;
  100543. case FLAC__METADATA_TYPE_CUESHEET:
  100544. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100545. return false;
  100546. break;
  100547. case FLAC__METADATA_TYPE_PICTURE:
  100548. if(!read_metadata_picture_(decoder, &block.data.picture))
  100549. return false;
  100550. break;
  100551. case FLAC__METADATA_TYPE_STREAMINFO:
  100552. case FLAC__METADATA_TYPE_SEEKTABLE:
  100553. FLAC__ASSERT(0);
  100554. break;
  100555. default:
  100556. if(real_length > 0) {
  100557. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100558. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100559. return false;
  100560. }
  100561. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100562. return false; /* read_callback_ sets the state for us */
  100563. }
  100564. else
  100565. block.data.unknown.data = 0;
  100566. break;
  100567. }
  100568. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100569. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100570. /* now we have to free any malloc()ed data in the block */
  100571. switch(type) {
  100572. case FLAC__METADATA_TYPE_PADDING:
  100573. break;
  100574. case FLAC__METADATA_TYPE_APPLICATION:
  100575. if(0 != block.data.application.data)
  100576. free(block.data.application.data);
  100577. break;
  100578. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100579. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100580. free(block.data.vorbis_comment.vendor_string.entry);
  100581. if(block.data.vorbis_comment.num_comments > 0)
  100582. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100583. if(0 != block.data.vorbis_comment.comments[i].entry)
  100584. free(block.data.vorbis_comment.comments[i].entry);
  100585. if(0 != block.data.vorbis_comment.comments)
  100586. free(block.data.vorbis_comment.comments);
  100587. break;
  100588. case FLAC__METADATA_TYPE_CUESHEET:
  100589. if(block.data.cue_sheet.num_tracks > 0)
  100590. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100591. if(0 != block.data.cue_sheet.tracks[i].indices)
  100592. free(block.data.cue_sheet.tracks[i].indices);
  100593. if(0 != block.data.cue_sheet.tracks)
  100594. free(block.data.cue_sheet.tracks);
  100595. break;
  100596. case FLAC__METADATA_TYPE_PICTURE:
  100597. if(0 != block.data.picture.mime_type)
  100598. free(block.data.picture.mime_type);
  100599. if(0 != block.data.picture.description)
  100600. free(block.data.picture.description);
  100601. if(0 != block.data.picture.data)
  100602. free(block.data.picture.data);
  100603. break;
  100604. case FLAC__METADATA_TYPE_STREAMINFO:
  100605. case FLAC__METADATA_TYPE_SEEKTABLE:
  100606. FLAC__ASSERT(0);
  100607. default:
  100608. if(0 != block.data.unknown.data)
  100609. free(block.data.unknown.data);
  100610. break;
  100611. }
  100612. }
  100613. }
  100614. if(is_last) {
  100615. /* if this fails, it's OK, it's just a hint for the seek routine */
  100616. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100617. decoder->private_->first_frame_offset = 0;
  100618. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100619. }
  100620. return true;
  100621. }
  100622. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100623. {
  100624. FLAC__uint32 x;
  100625. unsigned bits, used_bits = 0;
  100626. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100627. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100628. decoder->private_->stream_info.is_last = is_last;
  100629. decoder->private_->stream_info.length = length;
  100630. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100631. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100632. return false; /* read_callback_ sets the state for us */
  100633. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100634. used_bits += bits;
  100635. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100636. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100637. return false; /* read_callback_ sets the state for us */
  100638. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100639. used_bits += bits;
  100640. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100641. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100642. return false; /* read_callback_ sets the state for us */
  100643. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100644. used_bits += bits;
  100645. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100646. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100647. return false; /* read_callback_ sets the state for us */
  100648. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100649. used_bits += bits;
  100650. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100651. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100652. return false; /* read_callback_ sets the state for us */
  100653. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100654. used_bits += bits;
  100655. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100656. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100657. return false; /* read_callback_ sets the state for us */
  100658. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100659. used_bits += bits;
  100660. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100661. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100662. return false; /* read_callback_ sets the state for us */
  100663. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100664. used_bits += bits;
  100665. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100666. 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))
  100667. return false; /* read_callback_ sets the state for us */
  100668. used_bits += bits;
  100669. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100670. return false; /* read_callback_ sets the state for us */
  100671. used_bits += 16*8;
  100672. /* skip the rest of the block */
  100673. FLAC__ASSERT(used_bits % 8 == 0);
  100674. length -= (used_bits / 8);
  100675. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100676. return false; /* read_callback_ sets the state for us */
  100677. return true;
  100678. }
  100679. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100680. {
  100681. FLAC__uint32 i, x;
  100682. FLAC__uint64 xx;
  100683. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100684. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100685. decoder->private_->seek_table.is_last = is_last;
  100686. decoder->private_->seek_table.length = length;
  100687. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100688. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100689. 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)))) {
  100690. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100691. return false;
  100692. }
  100693. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100694. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100695. return false; /* read_callback_ sets the state for us */
  100696. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100697. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100698. return false; /* read_callback_ sets the state for us */
  100699. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100701. return false; /* read_callback_ sets the state for us */
  100702. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100703. }
  100704. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100705. /* if there is a partial point left, skip over it */
  100706. if(length > 0) {
  100707. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100708. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100709. return false; /* read_callback_ sets the state for us */
  100710. }
  100711. return true;
  100712. }
  100713. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100714. {
  100715. FLAC__uint32 i;
  100716. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100717. /* read vendor string */
  100718. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100719. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100720. return false; /* read_callback_ sets the state for us */
  100721. if(obj->vendor_string.length > 0) {
  100722. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100723. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100724. return false;
  100725. }
  100726. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100727. return false; /* read_callback_ sets the state for us */
  100728. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100729. }
  100730. else
  100731. obj->vendor_string.entry = 0;
  100732. /* read num comments */
  100733. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100734. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100735. return false; /* read_callback_ sets the state for us */
  100736. /* read comments */
  100737. if(obj->num_comments > 0) {
  100738. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100739. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100740. return false;
  100741. }
  100742. for(i = 0; i < obj->num_comments; i++) {
  100743. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100744. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100745. return false; /* read_callback_ sets the state for us */
  100746. if(obj->comments[i].length > 0) {
  100747. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100748. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100749. return false;
  100750. }
  100751. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100752. return false; /* read_callback_ sets the state for us */
  100753. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100754. }
  100755. else
  100756. obj->comments[i].entry = 0;
  100757. }
  100758. }
  100759. else {
  100760. obj->comments = 0;
  100761. }
  100762. return true;
  100763. }
  100764. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100765. {
  100766. FLAC__uint32 i, j, x;
  100767. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100768. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100769. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100770. 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))
  100771. return false; /* read_callback_ sets the state for us */
  100772. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100773. return false; /* read_callback_ sets the state for us */
  100774. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100775. return false; /* read_callback_ sets the state for us */
  100776. obj->is_cd = x? true : false;
  100777. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100778. return false; /* read_callback_ sets the state for us */
  100779. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100780. return false; /* read_callback_ sets the state for us */
  100781. obj->num_tracks = x;
  100782. if(obj->num_tracks > 0) {
  100783. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100784. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100785. return false;
  100786. }
  100787. for(i = 0; i < obj->num_tracks; i++) {
  100788. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100789. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100790. return false; /* read_callback_ sets the state for us */
  100791. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100792. return false; /* read_callback_ sets the state for us */
  100793. track->number = (FLAC__byte)x;
  100794. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100795. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100796. return false; /* read_callback_ sets the state for us */
  100797. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100798. return false; /* read_callback_ sets the state for us */
  100799. track->type = x;
  100800. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100801. return false; /* read_callback_ sets the state for us */
  100802. track->pre_emphasis = x;
  100803. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100804. return false; /* read_callback_ sets the state for us */
  100805. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100806. return false; /* read_callback_ sets the state for us */
  100807. track->num_indices = (FLAC__byte)x;
  100808. if(track->num_indices > 0) {
  100809. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100810. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100811. return false;
  100812. }
  100813. for(j = 0; j < track->num_indices; j++) {
  100814. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100815. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100816. return false; /* read_callback_ sets the state for us */
  100817. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100818. return false; /* read_callback_ sets the state for us */
  100819. index->number = (FLAC__byte)x;
  100820. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100821. return false; /* read_callback_ sets the state for us */
  100822. }
  100823. }
  100824. }
  100825. }
  100826. return true;
  100827. }
  100828. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100829. {
  100830. FLAC__uint32 x;
  100831. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100832. /* read type */
  100833. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100834. return false; /* read_callback_ sets the state for us */
  100835. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100836. /* read MIME type */
  100837. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100838. return false; /* read_callback_ sets the state for us */
  100839. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100840. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100841. return false;
  100842. }
  100843. if(x > 0) {
  100844. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100845. return false; /* read_callback_ sets the state for us */
  100846. }
  100847. obj->mime_type[x] = '\0';
  100848. /* read description */
  100849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100850. return false; /* read_callback_ sets the state for us */
  100851. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100852. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100853. return false;
  100854. }
  100855. if(x > 0) {
  100856. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100857. return false; /* read_callback_ sets the state for us */
  100858. }
  100859. obj->description[x] = '\0';
  100860. /* read width */
  100861. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100862. return false; /* read_callback_ sets the state for us */
  100863. /* read height */
  100864. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100865. return false; /* read_callback_ sets the state for us */
  100866. /* read depth */
  100867. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100868. return false; /* read_callback_ sets the state for us */
  100869. /* read colors */
  100870. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100871. return false; /* read_callback_ sets the state for us */
  100872. /* read data */
  100873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100874. return false; /* read_callback_ sets the state for us */
  100875. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100876. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100877. return false;
  100878. }
  100879. if(obj->data_length > 0) {
  100880. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100881. return false; /* read_callback_ sets the state for us */
  100882. }
  100883. return true;
  100884. }
  100885. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100886. {
  100887. FLAC__uint32 x;
  100888. unsigned i, skip;
  100889. /* skip the version and flags bytes */
  100890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100891. return false; /* read_callback_ sets the state for us */
  100892. /* get the size (in bytes) to skip */
  100893. skip = 0;
  100894. for(i = 0; i < 4; i++) {
  100895. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100896. return false; /* read_callback_ sets the state for us */
  100897. skip <<= 7;
  100898. skip |= (x & 0x7f);
  100899. }
  100900. /* skip the rest of the tag */
  100901. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100902. return false; /* read_callback_ sets the state for us */
  100903. return true;
  100904. }
  100905. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100906. {
  100907. FLAC__uint32 x;
  100908. FLAC__bool first = true;
  100909. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100910. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100911. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100912. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100913. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100914. return true;
  100915. }
  100916. }
  100917. /* make sure we're byte aligned */
  100918. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100919. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100920. return false; /* read_callback_ sets the state for us */
  100921. }
  100922. while(1) {
  100923. if(decoder->private_->cached) {
  100924. x = (FLAC__uint32)decoder->private_->lookahead;
  100925. decoder->private_->cached = false;
  100926. }
  100927. else {
  100928. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100929. return false; /* read_callback_ sets the state for us */
  100930. }
  100931. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100932. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100933. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100934. return false; /* read_callback_ sets the state for us */
  100935. /* 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 */
  100936. /* else we have to check if the second byte is the end of a sync code */
  100937. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100938. decoder->private_->lookahead = (FLAC__byte)x;
  100939. decoder->private_->cached = true;
  100940. }
  100941. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100942. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100943. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100944. return true;
  100945. }
  100946. }
  100947. if(first) {
  100948. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100949. first = false;
  100950. }
  100951. }
  100952. return true;
  100953. }
  100954. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100955. {
  100956. unsigned channel;
  100957. unsigned i;
  100958. FLAC__int32 mid, side;
  100959. unsigned frame_crc; /* the one we calculate from the input stream */
  100960. FLAC__uint32 x;
  100961. *got_a_frame = false;
  100962. /* init the CRC */
  100963. frame_crc = 0;
  100964. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100965. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100966. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100967. if(!read_frame_header_(decoder))
  100968. return false;
  100969. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100970. return true;
  100971. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100972. return false;
  100973. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100974. /*
  100975. * first figure the correct bits-per-sample of the subframe
  100976. */
  100977. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100978. switch(decoder->private_->frame.header.channel_assignment) {
  100979. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100980. /* no adjustment needed */
  100981. break;
  100982. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100983. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100984. if(channel == 1)
  100985. bps++;
  100986. break;
  100987. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100988. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100989. if(channel == 0)
  100990. bps++;
  100991. break;
  100992. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100993. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100994. if(channel == 1)
  100995. bps++;
  100996. break;
  100997. default:
  100998. FLAC__ASSERT(0);
  100999. }
  101000. /*
  101001. * now read it
  101002. */
  101003. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101004. return false;
  101005. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101006. return true;
  101007. }
  101008. if(!read_zero_padding_(decoder))
  101009. return false;
  101010. 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) */
  101011. return true;
  101012. /*
  101013. * Read the frame CRC-16 from the footer and check
  101014. */
  101015. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101016. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101017. return false; /* read_callback_ sets the state for us */
  101018. if(frame_crc == x) {
  101019. if(do_full_decode) {
  101020. /* Undo any special channel coding */
  101021. switch(decoder->private_->frame.header.channel_assignment) {
  101022. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101023. /* do nothing */
  101024. break;
  101025. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101026. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101027. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101028. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101029. break;
  101030. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101031. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101032. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101033. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101034. break;
  101035. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101036. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101037. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101038. #if 1
  101039. mid = decoder->private_->output[0][i];
  101040. side = decoder->private_->output[1][i];
  101041. mid <<= 1;
  101042. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101043. decoder->private_->output[0][i] = (mid + side) >> 1;
  101044. decoder->private_->output[1][i] = (mid - side) >> 1;
  101045. #else
  101046. /* OPT: without 'side' temp variable */
  101047. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101048. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101049. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101050. #endif
  101051. }
  101052. break;
  101053. default:
  101054. FLAC__ASSERT(0);
  101055. break;
  101056. }
  101057. }
  101058. }
  101059. else {
  101060. /* Bad frame, emit error and zero the output signal */
  101061. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101062. if(do_full_decode) {
  101063. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101064. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101065. }
  101066. }
  101067. }
  101068. *got_a_frame = true;
  101069. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101070. if(decoder->private_->next_fixed_block_size)
  101071. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101072. /* put the latest values into the public section of the decoder instance */
  101073. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101074. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101075. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101076. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101077. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101078. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101079. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101080. /* write it */
  101081. if(do_full_decode) {
  101082. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101083. return false;
  101084. }
  101085. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101086. return true;
  101087. }
  101088. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101089. {
  101090. FLAC__uint32 x;
  101091. FLAC__uint64 xx;
  101092. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101093. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101094. unsigned raw_header_len;
  101095. FLAC__bool is_unparseable = false;
  101096. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101097. /* init the raw header with the saved bits from synchronization */
  101098. raw_header[0] = decoder->private_->header_warmup[0];
  101099. raw_header[1] = decoder->private_->header_warmup[1];
  101100. raw_header_len = 2;
  101101. /* check to make sure that reserved bit is 0 */
  101102. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101103. is_unparseable = true;
  101104. /*
  101105. * Note that along the way as we read the header, we look for a sync
  101106. * code inside. If we find one it would indicate that our original
  101107. * sync was bad since there cannot be a sync code in a valid header.
  101108. *
  101109. * Three kinds of things can go wrong when reading the frame header:
  101110. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101111. * If we don't find a sync code, it can end up looking like we read
  101112. * a valid but unparseable header, until getting to the frame header
  101113. * CRC. Even then we could get a false positive on the CRC.
  101114. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101115. * future encoder).
  101116. * 3) We may be on a damaged frame which appears valid but unparseable.
  101117. *
  101118. * For all these reasons, we try and read a complete frame header as
  101119. * long as it seems valid, even if unparseable, up until the frame
  101120. * header CRC.
  101121. */
  101122. /*
  101123. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101124. */
  101125. for(i = 0; i < 2; i++) {
  101126. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101127. return false; /* read_callback_ sets the state for us */
  101128. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101129. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101130. decoder->private_->lookahead = (FLAC__byte)x;
  101131. decoder->private_->cached = true;
  101132. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101133. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101134. return true;
  101135. }
  101136. raw_header[raw_header_len++] = (FLAC__byte)x;
  101137. }
  101138. switch(x = raw_header[2] >> 4) {
  101139. case 0:
  101140. is_unparseable = true;
  101141. break;
  101142. case 1:
  101143. decoder->private_->frame.header.blocksize = 192;
  101144. break;
  101145. case 2:
  101146. case 3:
  101147. case 4:
  101148. case 5:
  101149. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101150. break;
  101151. case 6:
  101152. case 7:
  101153. blocksize_hint = x;
  101154. break;
  101155. case 8:
  101156. case 9:
  101157. case 10:
  101158. case 11:
  101159. case 12:
  101160. case 13:
  101161. case 14:
  101162. case 15:
  101163. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101164. break;
  101165. default:
  101166. FLAC__ASSERT(0);
  101167. break;
  101168. }
  101169. switch(x = raw_header[2] & 0x0f) {
  101170. case 0:
  101171. if(decoder->private_->has_stream_info)
  101172. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101173. else
  101174. is_unparseable = true;
  101175. break;
  101176. case 1:
  101177. decoder->private_->frame.header.sample_rate = 88200;
  101178. break;
  101179. case 2:
  101180. decoder->private_->frame.header.sample_rate = 176400;
  101181. break;
  101182. case 3:
  101183. decoder->private_->frame.header.sample_rate = 192000;
  101184. break;
  101185. case 4:
  101186. decoder->private_->frame.header.sample_rate = 8000;
  101187. break;
  101188. case 5:
  101189. decoder->private_->frame.header.sample_rate = 16000;
  101190. break;
  101191. case 6:
  101192. decoder->private_->frame.header.sample_rate = 22050;
  101193. break;
  101194. case 7:
  101195. decoder->private_->frame.header.sample_rate = 24000;
  101196. break;
  101197. case 8:
  101198. decoder->private_->frame.header.sample_rate = 32000;
  101199. break;
  101200. case 9:
  101201. decoder->private_->frame.header.sample_rate = 44100;
  101202. break;
  101203. case 10:
  101204. decoder->private_->frame.header.sample_rate = 48000;
  101205. break;
  101206. case 11:
  101207. decoder->private_->frame.header.sample_rate = 96000;
  101208. break;
  101209. case 12:
  101210. case 13:
  101211. case 14:
  101212. sample_rate_hint = x;
  101213. break;
  101214. case 15:
  101215. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101216. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101217. return true;
  101218. default:
  101219. FLAC__ASSERT(0);
  101220. }
  101221. x = (unsigned)(raw_header[3] >> 4);
  101222. if(x & 8) {
  101223. decoder->private_->frame.header.channels = 2;
  101224. switch(x & 7) {
  101225. case 0:
  101226. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101227. break;
  101228. case 1:
  101229. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101230. break;
  101231. case 2:
  101232. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101233. break;
  101234. default:
  101235. is_unparseable = true;
  101236. break;
  101237. }
  101238. }
  101239. else {
  101240. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101241. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101242. }
  101243. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101244. case 0:
  101245. if(decoder->private_->has_stream_info)
  101246. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101247. else
  101248. is_unparseable = true;
  101249. break;
  101250. case 1:
  101251. decoder->private_->frame.header.bits_per_sample = 8;
  101252. break;
  101253. case 2:
  101254. decoder->private_->frame.header.bits_per_sample = 12;
  101255. break;
  101256. case 4:
  101257. decoder->private_->frame.header.bits_per_sample = 16;
  101258. break;
  101259. case 5:
  101260. decoder->private_->frame.header.bits_per_sample = 20;
  101261. break;
  101262. case 6:
  101263. decoder->private_->frame.header.bits_per_sample = 24;
  101264. break;
  101265. case 3:
  101266. case 7:
  101267. is_unparseable = true;
  101268. break;
  101269. default:
  101270. FLAC__ASSERT(0);
  101271. break;
  101272. }
  101273. /* check to make sure that reserved bit is 0 */
  101274. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101275. is_unparseable = true;
  101276. /* read the frame's starting sample number (or frame number as the case may be) */
  101277. if(
  101278. raw_header[1] & 0x01 ||
  101279. /*@@@ 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 */
  101280. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101281. ) { /* variable blocksize */
  101282. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101283. return false; /* read_callback_ sets the state for us */
  101284. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101285. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101286. decoder->private_->cached = true;
  101287. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101288. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101289. return true;
  101290. }
  101291. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101292. decoder->private_->frame.header.number.sample_number = xx;
  101293. }
  101294. else { /* fixed blocksize */
  101295. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101296. return false; /* read_callback_ sets the state for us */
  101297. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101298. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101299. decoder->private_->cached = true;
  101300. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101301. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101302. return true;
  101303. }
  101304. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101305. decoder->private_->frame.header.number.frame_number = x;
  101306. }
  101307. if(blocksize_hint) {
  101308. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101309. return false; /* read_callback_ sets the state for us */
  101310. raw_header[raw_header_len++] = (FLAC__byte)x;
  101311. if(blocksize_hint == 7) {
  101312. FLAC__uint32 _x;
  101313. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101314. return false; /* read_callback_ sets the state for us */
  101315. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101316. x = (x << 8) | _x;
  101317. }
  101318. decoder->private_->frame.header.blocksize = x+1;
  101319. }
  101320. if(sample_rate_hint) {
  101321. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101322. return false; /* read_callback_ sets the state for us */
  101323. raw_header[raw_header_len++] = (FLAC__byte)x;
  101324. if(sample_rate_hint != 12) {
  101325. FLAC__uint32 _x;
  101326. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101327. return false; /* read_callback_ sets the state for us */
  101328. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101329. x = (x << 8) | _x;
  101330. }
  101331. if(sample_rate_hint == 12)
  101332. decoder->private_->frame.header.sample_rate = x*1000;
  101333. else if(sample_rate_hint == 13)
  101334. decoder->private_->frame.header.sample_rate = x;
  101335. else
  101336. decoder->private_->frame.header.sample_rate = x*10;
  101337. }
  101338. /* read the CRC-8 byte */
  101339. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101340. return false; /* read_callback_ sets the state for us */
  101341. crc8 = (FLAC__byte)x;
  101342. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101343. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101344. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101345. return true;
  101346. }
  101347. /* calculate the sample number from the frame number if needed */
  101348. decoder->private_->next_fixed_block_size = 0;
  101349. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101350. x = decoder->private_->frame.header.number.frame_number;
  101351. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101352. if(decoder->private_->fixed_block_size)
  101353. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101354. else if(decoder->private_->has_stream_info) {
  101355. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101356. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101357. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101358. }
  101359. else
  101360. is_unparseable = true;
  101361. }
  101362. else if(x == 0) {
  101363. decoder->private_->frame.header.number.sample_number = 0;
  101364. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101365. }
  101366. else {
  101367. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101368. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101369. }
  101370. }
  101371. if(is_unparseable) {
  101372. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101373. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101374. return true;
  101375. }
  101376. return true;
  101377. }
  101378. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101379. {
  101380. FLAC__uint32 x;
  101381. FLAC__bool wasted_bits;
  101382. unsigned i;
  101383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101384. return false; /* read_callback_ sets the state for us */
  101385. wasted_bits = (x & 1);
  101386. x &= 0xfe;
  101387. if(wasted_bits) {
  101388. unsigned u;
  101389. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101390. return false; /* read_callback_ sets the state for us */
  101391. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101392. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101393. }
  101394. else
  101395. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101396. /*
  101397. * Lots of magic numbers here
  101398. */
  101399. if(x & 0x80) {
  101400. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101401. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101402. return true;
  101403. }
  101404. else if(x == 0) {
  101405. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101406. return false;
  101407. }
  101408. else if(x == 2) {
  101409. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101410. return false;
  101411. }
  101412. else if(x < 16) {
  101413. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101414. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101415. return true;
  101416. }
  101417. else if(x <= 24) {
  101418. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101419. return false;
  101420. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101421. return true;
  101422. }
  101423. else if(x < 64) {
  101424. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101425. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101426. return true;
  101427. }
  101428. else {
  101429. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101430. return false;
  101431. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101432. return true;
  101433. }
  101434. if(wasted_bits && do_full_decode) {
  101435. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101436. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101437. decoder->private_->output[channel][i] <<= x;
  101438. }
  101439. return true;
  101440. }
  101441. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101442. {
  101443. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101444. FLAC__int32 x;
  101445. unsigned i;
  101446. FLAC__int32 *output = decoder->private_->output[channel];
  101447. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101448. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101449. return false; /* read_callback_ sets the state for us */
  101450. subframe->value = x;
  101451. /* decode the subframe */
  101452. if(do_full_decode) {
  101453. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101454. output[i] = x;
  101455. }
  101456. return true;
  101457. }
  101458. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101459. {
  101460. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101461. FLAC__int32 i32;
  101462. FLAC__uint32 u32;
  101463. unsigned u;
  101464. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101465. subframe->residual = decoder->private_->residual[channel];
  101466. subframe->order = order;
  101467. /* read warm-up samples */
  101468. for(u = 0; u < order; u++) {
  101469. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101470. return false; /* read_callback_ sets the state for us */
  101471. subframe->warmup[u] = i32;
  101472. }
  101473. /* read entropy coding method info */
  101474. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101475. return false; /* read_callback_ sets the state for us */
  101476. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101477. switch(subframe->entropy_coding_method.type) {
  101478. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101479. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101480. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101481. return false; /* read_callback_ sets the state for us */
  101482. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101483. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101484. break;
  101485. default:
  101486. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101487. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101488. return true;
  101489. }
  101490. /* read residual */
  101491. switch(subframe->entropy_coding_method.type) {
  101492. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101493. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101494. 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))
  101495. return false;
  101496. break;
  101497. default:
  101498. FLAC__ASSERT(0);
  101499. }
  101500. /* decode the subframe */
  101501. if(do_full_decode) {
  101502. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101503. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101504. }
  101505. return true;
  101506. }
  101507. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101508. {
  101509. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101510. FLAC__int32 i32;
  101511. FLAC__uint32 u32;
  101512. unsigned u;
  101513. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101514. subframe->residual = decoder->private_->residual[channel];
  101515. subframe->order = order;
  101516. /* read warm-up samples */
  101517. for(u = 0; u < order; u++) {
  101518. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101519. return false; /* read_callback_ sets the state for us */
  101520. subframe->warmup[u] = i32;
  101521. }
  101522. /* read qlp coeff precision */
  101523. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101524. return false; /* read_callback_ sets the state for us */
  101525. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101526. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101527. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101528. return true;
  101529. }
  101530. subframe->qlp_coeff_precision = u32+1;
  101531. /* read qlp shift */
  101532. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101533. return false; /* read_callback_ sets the state for us */
  101534. subframe->quantization_level = i32;
  101535. /* read quantized lp coefficiencts */
  101536. for(u = 0; u < order; u++) {
  101537. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101538. return false; /* read_callback_ sets the state for us */
  101539. subframe->qlp_coeff[u] = i32;
  101540. }
  101541. /* read entropy coding method info */
  101542. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101543. return false; /* read_callback_ sets the state for us */
  101544. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101545. switch(subframe->entropy_coding_method.type) {
  101546. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101547. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101548. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101549. return false; /* read_callback_ sets the state for us */
  101550. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101551. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101552. break;
  101553. default:
  101554. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101555. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101556. return true;
  101557. }
  101558. /* read residual */
  101559. switch(subframe->entropy_coding_method.type) {
  101560. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101561. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101562. 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))
  101563. return false;
  101564. break;
  101565. default:
  101566. FLAC__ASSERT(0);
  101567. }
  101568. /* decode the subframe */
  101569. if(do_full_decode) {
  101570. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101571. /*@@@@@@ technically not pessimistic enough, should be more like
  101572. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101573. */
  101574. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101575. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101576. if(order <= 8)
  101577. 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);
  101578. else
  101579. 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);
  101580. }
  101581. else
  101582. 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);
  101583. else
  101584. 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);
  101585. }
  101586. return true;
  101587. }
  101588. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101589. {
  101590. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101591. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101592. unsigned i;
  101593. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101594. subframe->data = residual;
  101595. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101596. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101597. return false; /* read_callback_ sets the state for us */
  101598. residual[i] = x;
  101599. }
  101600. /* decode the subframe */
  101601. if(do_full_decode)
  101602. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101603. return true;
  101604. }
  101605. 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)
  101606. {
  101607. FLAC__uint32 rice_parameter;
  101608. int i;
  101609. unsigned partition, sample, u;
  101610. const unsigned partitions = 1u << partition_order;
  101611. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101612. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101613. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101614. /* sanity checks */
  101615. if(partition_order == 0) {
  101616. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101617. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101618. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101619. return true;
  101620. }
  101621. }
  101622. else {
  101623. if(partition_samples < predictor_order) {
  101624. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101625. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101626. return true;
  101627. }
  101628. }
  101629. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101630. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101631. return false;
  101632. }
  101633. sample = 0;
  101634. for(partition = 0; partition < partitions; partition++) {
  101635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101636. return false; /* read_callback_ sets the state for us */
  101637. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101638. if(rice_parameter < pesc) {
  101639. partitioned_rice_contents->raw_bits[partition] = 0;
  101640. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101641. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101642. return false; /* read_callback_ sets the state for us */
  101643. sample += u;
  101644. }
  101645. else {
  101646. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101647. return false; /* read_callback_ sets the state for us */
  101648. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101649. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101650. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101651. return false; /* read_callback_ sets the state for us */
  101652. residual[sample] = i;
  101653. }
  101654. }
  101655. }
  101656. return true;
  101657. }
  101658. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101659. {
  101660. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101661. FLAC__uint32 zero = 0;
  101662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101663. return false; /* read_callback_ sets the state for us */
  101664. if(zero != 0) {
  101665. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101666. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101667. }
  101668. }
  101669. return true;
  101670. }
  101671. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101672. {
  101673. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101674. if(
  101675. #if FLAC__HAS_OGG
  101676. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101677. !decoder->private_->is_ogg &&
  101678. #endif
  101679. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101680. ) {
  101681. *bytes = 0;
  101682. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101683. return false;
  101684. }
  101685. else if(*bytes > 0) {
  101686. /* While seeking, it is possible for our seek to land in the
  101687. * middle of audio data that looks exactly like a frame header
  101688. * from a future version of an encoder. When that happens, our
  101689. * error callback will get an
  101690. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101691. * unparseable_frame_count. But there is a remote possibility
  101692. * that it is properly synced at such a "future-codec frame",
  101693. * so to make sure, we wait to see many "unparseable" errors in
  101694. * a row before bailing out.
  101695. */
  101696. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101697. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101698. return false;
  101699. }
  101700. else {
  101701. const FLAC__StreamDecoderReadStatus status =
  101702. #if FLAC__HAS_OGG
  101703. decoder->private_->is_ogg?
  101704. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101705. #endif
  101706. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101707. ;
  101708. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101709. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101710. return false;
  101711. }
  101712. else if(*bytes == 0) {
  101713. if(
  101714. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101715. (
  101716. #if FLAC__HAS_OGG
  101717. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101718. !decoder->private_->is_ogg &&
  101719. #endif
  101720. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101721. )
  101722. ) {
  101723. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101724. return false;
  101725. }
  101726. else
  101727. return true;
  101728. }
  101729. else
  101730. return true;
  101731. }
  101732. }
  101733. else {
  101734. /* abort to avoid a deadlock */
  101735. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101736. return false;
  101737. }
  101738. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101739. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101740. * and at the same time hit the end of the stream (for example, seeking
  101741. * to a point that is after the beginning of the last Ogg page). There
  101742. * is no way to report an Ogg sync loss through the callbacks (see note
  101743. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101744. * So to keep the decoder from stopping at this point we gate the call
  101745. * to the eof_callback and let the Ogg decoder aspect set the
  101746. * end-of-stream state when it is needed.
  101747. */
  101748. }
  101749. #if FLAC__HAS_OGG
  101750. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101751. {
  101752. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101753. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101754. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101755. /* we don't really have a way to handle lost sync via read
  101756. * callback so we'll let it pass and let the underlying
  101757. * FLAC decoder catch the error
  101758. */
  101759. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101760. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101761. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101762. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101763. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101764. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101765. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101766. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101767. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101768. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101769. default:
  101770. FLAC__ASSERT(0);
  101771. /* double protection */
  101772. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101773. }
  101774. }
  101775. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101776. {
  101777. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101778. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101779. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101780. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101781. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101782. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101783. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101784. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101785. default:
  101786. /* double protection: */
  101787. FLAC__ASSERT(0);
  101788. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101789. }
  101790. }
  101791. #endif
  101792. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101793. {
  101794. if(decoder->private_->is_seeking) {
  101795. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101796. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101797. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101798. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101799. #if FLAC__HAS_OGG
  101800. decoder->private_->got_a_frame = true;
  101801. #endif
  101802. decoder->private_->last_frame = *frame; /* save the frame */
  101803. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101804. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101805. /* kick out of seek mode */
  101806. decoder->private_->is_seeking = false;
  101807. /* shift out the samples before target_sample */
  101808. if(delta > 0) {
  101809. unsigned channel;
  101810. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101811. for(channel = 0; channel < frame->header.channels; channel++)
  101812. newbuffer[channel] = buffer[channel] + delta;
  101813. decoder->private_->last_frame.header.blocksize -= delta;
  101814. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101815. /* write the relevant samples */
  101816. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101817. }
  101818. else {
  101819. /* write the relevant samples */
  101820. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101821. }
  101822. }
  101823. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101824. }
  101825. /*
  101826. * If we never got STREAMINFO, turn off MD5 checking to save
  101827. * cycles since we don't have a sum to compare to anyway
  101828. */
  101829. if(!decoder->private_->has_stream_info)
  101830. decoder->private_->do_md5_checking = false;
  101831. if(decoder->private_->do_md5_checking) {
  101832. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101833. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101834. }
  101835. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101836. }
  101837. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101838. {
  101839. if(!decoder->private_->is_seeking)
  101840. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101841. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101842. decoder->private_->unparseable_frame_count++;
  101843. }
  101844. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101845. {
  101846. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101847. FLAC__int64 pos = -1;
  101848. int i;
  101849. unsigned approx_bytes_per_frame;
  101850. FLAC__bool first_seek = true;
  101851. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101852. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101853. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101854. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101855. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101856. /* take these from the current frame in case they've changed mid-stream */
  101857. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101858. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101859. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101860. /* use values from stream info if we didn't decode a frame */
  101861. if(channels == 0)
  101862. channels = decoder->private_->stream_info.data.stream_info.channels;
  101863. if(bps == 0)
  101864. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101865. /* we are just guessing here */
  101866. if(max_framesize > 0)
  101867. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101868. /*
  101869. * Check if it's a known fixed-blocksize stream. Note that though
  101870. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101871. * never get a STREAMINFO block when decoding so the value of
  101872. * min_blocksize might be zero.
  101873. */
  101874. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101875. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101876. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101877. }
  101878. else
  101879. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101880. /*
  101881. * First, we set an upper and lower bound on where in the
  101882. * stream we will search. For now we assume the worst case
  101883. * scenario, which is our best guess at the beginning of
  101884. * the first frame and end of the stream.
  101885. */
  101886. lower_bound = first_frame_offset;
  101887. lower_bound_sample = 0;
  101888. upper_bound = stream_length;
  101889. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101890. /*
  101891. * Now we refine the bounds if we have a seektable with
  101892. * suitable points. Note that according to the spec they
  101893. * must be ordered by ascending sample number.
  101894. *
  101895. * Note: to protect against invalid seek tables we will ignore points
  101896. * that have frame_samples==0 or sample_number>=total_samples
  101897. */
  101898. if(seek_table) {
  101899. FLAC__uint64 new_lower_bound = lower_bound;
  101900. FLAC__uint64 new_upper_bound = upper_bound;
  101901. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101902. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101903. /* find the closest seek point <= target_sample, if it exists */
  101904. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101905. if(
  101906. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101907. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101908. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101909. seek_table->points[i].sample_number <= target_sample
  101910. )
  101911. break;
  101912. }
  101913. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101914. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101915. new_lower_bound_sample = seek_table->points[i].sample_number;
  101916. }
  101917. /* find the closest seek point > target_sample, if it exists */
  101918. for(i = 0; i < (int)seek_table->num_points; i++) {
  101919. if(
  101920. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101921. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101922. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101923. seek_table->points[i].sample_number > target_sample
  101924. )
  101925. break;
  101926. }
  101927. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101928. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101929. new_upper_bound_sample = seek_table->points[i].sample_number;
  101930. }
  101931. /* final protection against unsorted seek tables; keep original values if bogus */
  101932. if(new_upper_bound >= new_lower_bound) {
  101933. lower_bound = new_lower_bound;
  101934. upper_bound = new_upper_bound;
  101935. lower_bound_sample = new_lower_bound_sample;
  101936. upper_bound_sample = new_upper_bound_sample;
  101937. }
  101938. }
  101939. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101940. /* there are 2 insidious ways that the following equality occurs, which
  101941. * we need to fix:
  101942. * 1) total_samples is 0 (unknown) and target_sample is 0
  101943. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101944. * exactly equal to the last seek point in the seek table; this
  101945. * means there is no seek point above it, and upper_bound_samples
  101946. * remains equal to the estimate (of target_samples) we made above
  101947. * in either case it does not hurt to move upper_bound_sample up by 1
  101948. */
  101949. if(upper_bound_sample == lower_bound_sample)
  101950. upper_bound_sample++;
  101951. decoder->private_->target_sample = target_sample;
  101952. while(1) {
  101953. /* check if the bounds are still ok */
  101954. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101955. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101956. return false;
  101957. }
  101958. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101959. #if defined _MSC_VER || defined __MINGW32__
  101960. /* with VC++ you have to spoon feed it the casting */
  101961. 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;
  101962. #else
  101963. 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;
  101964. #endif
  101965. #else
  101966. /* a little less accurate: */
  101967. if(upper_bound - lower_bound < 0xffffffff)
  101968. 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;
  101969. else /* @@@ WATCHOUT, ~2TB limit */
  101970. 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;
  101971. #endif
  101972. if(pos >= (FLAC__int64)upper_bound)
  101973. pos = (FLAC__int64)upper_bound - 1;
  101974. if(pos < (FLAC__int64)lower_bound)
  101975. pos = (FLAC__int64)lower_bound;
  101976. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101977. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101978. return false;
  101979. }
  101980. if(!FLAC__stream_decoder_flush(decoder)) {
  101981. /* above call sets the state for us */
  101982. return false;
  101983. }
  101984. /* Now we need to get a frame. First we need to reset our
  101985. * unparseable_frame_count; if we get too many unparseable
  101986. * frames in a row, the read callback will return
  101987. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101988. * FLAC__stream_decoder_process_single() to return false.
  101989. */
  101990. decoder->private_->unparseable_frame_count = 0;
  101991. if(!FLAC__stream_decoder_process_single(decoder)) {
  101992. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101993. return false;
  101994. }
  101995. /* our write callback will change the state when it gets to the target frame */
  101996. /* 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 */
  101997. #if 0
  101998. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101999. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102000. break;
  102001. #endif
  102002. if(!decoder->private_->is_seeking)
  102003. break;
  102004. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102005. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102006. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102007. if (pos == (FLAC__int64)lower_bound) {
  102008. /* can't move back any more than the first frame, something is fatally wrong */
  102009. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102010. return false;
  102011. }
  102012. /* our last move backwards wasn't big enough, try again */
  102013. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102014. continue;
  102015. }
  102016. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102017. first_seek = false;
  102018. /* make sure we are not seeking in corrupted stream */
  102019. if (this_frame_sample < lower_bound_sample) {
  102020. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102021. return false;
  102022. }
  102023. /* we need to narrow the search */
  102024. if(target_sample < this_frame_sample) {
  102025. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102026. /*@@@@@@ what will decode position be if at end of stream? */
  102027. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102028. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102029. return false;
  102030. }
  102031. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102032. }
  102033. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102034. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102035. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102036. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102037. return false;
  102038. }
  102039. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102040. }
  102041. }
  102042. return true;
  102043. }
  102044. #if FLAC__HAS_OGG
  102045. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102046. {
  102047. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102048. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102049. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102050. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102051. FLAC__bool did_a_seek;
  102052. unsigned iteration = 0;
  102053. /* In the first iterations, we will calculate the target byte position
  102054. * by the distance from the target sample to left_sample and
  102055. * right_sample (let's call it "proportional search"). After that, we
  102056. * will switch to binary search.
  102057. */
  102058. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102059. /* We will switch to a linear search once our current sample is less
  102060. * than this number of samples ahead of the target sample
  102061. */
  102062. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102063. /* If the total number of samples is unknown, use a large value, and
  102064. * force binary search immediately.
  102065. */
  102066. if(right_sample == 0) {
  102067. right_sample = (FLAC__uint64)(-1);
  102068. BINARY_SEARCH_AFTER_ITERATION = 0;
  102069. }
  102070. decoder->private_->target_sample = target_sample;
  102071. for( ; ; iteration++) {
  102072. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102073. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102074. pos = (right_pos + left_pos) / 2;
  102075. }
  102076. else {
  102077. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102078. #if defined _MSC_VER || defined __MINGW32__
  102079. /* with MSVC you have to spoon feed it the casting */
  102080. 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));
  102081. #else
  102082. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102083. #endif
  102084. #else
  102085. /* a little less accurate: */
  102086. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102087. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102088. else /* @@@ WATCHOUT, ~2TB limit */
  102089. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102090. #endif
  102091. /* @@@ TODO: might want to limit pos to some distance
  102092. * before EOF, to make sure we land before the last frame,
  102093. * thereby getting a this_frame_sample and so having a better
  102094. * estimate.
  102095. */
  102096. }
  102097. /* physical seek */
  102098. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102099. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102100. return false;
  102101. }
  102102. if(!FLAC__stream_decoder_flush(decoder)) {
  102103. /* above call sets the state for us */
  102104. return false;
  102105. }
  102106. did_a_seek = true;
  102107. }
  102108. else
  102109. did_a_seek = false;
  102110. decoder->private_->got_a_frame = false;
  102111. if(!FLAC__stream_decoder_process_single(decoder)) {
  102112. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102113. return false;
  102114. }
  102115. if(!decoder->private_->got_a_frame) {
  102116. if(did_a_seek) {
  102117. /* this can happen if we seek to a point after the last frame; we drop
  102118. * to binary search right away in this case to avoid any wasted
  102119. * iterations of proportional search.
  102120. */
  102121. right_pos = pos;
  102122. BINARY_SEARCH_AFTER_ITERATION = 0;
  102123. }
  102124. else {
  102125. /* this can probably only happen if total_samples is unknown and the
  102126. * target_sample is past the end of the stream
  102127. */
  102128. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102129. return false;
  102130. }
  102131. }
  102132. /* our write callback will change the state when it gets to the target frame */
  102133. else if(!decoder->private_->is_seeking) {
  102134. break;
  102135. }
  102136. else {
  102137. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102138. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102139. if (did_a_seek) {
  102140. if (this_frame_sample <= target_sample) {
  102141. /* The 'equal' case should not happen, since
  102142. * FLAC__stream_decoder_process_single()
  102143. * should recognize that it has hit the
  102144. * target sample and we would exit through
  102145. * the 'break' above.
  102146. */
  102147. FLAC__ASSERT(this_frame_sample != target_sample);
  102148. left_sample = this_frame_sample;
  102149. /* sanity check to avoid infinite loop */
  102150. if (left_pos == pos) {
  102151. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102152. return false;
  102153. }
  102154. left_pos = pos;
  102155. }
  102156. else if(this_frame_sample > target_sample) {
  102157. right_sample = this_frame_sample;
  102158. /* sanity check to avoid infinite loop */
  102159. if (right_pos == pos) {
  102160. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102161. return false;
  102162. }
  102163. right_pos = pos;
  102164. }
  102165. }
  102166. }
  102167. }
  102168. return true;
  102169. }
  102170. #endif
  102171. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102172. {
  102173. (void)client_data;
  102174. if(*bytes > 0) {
  102175. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102176. if(ferror(decoder->private_->file))
  102177. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102178. else if(*bytes == 0)
  102179. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102180. else
  102181. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102182. }
  102183. else
  102184. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102185. }
  102186. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102187. {
  102188. (void)client_data;
  102189. if(decoder->private_->file == stdin)
  102190. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102191. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102192. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102193. else
  102194. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102195. }
  102196. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102197. {
  102198. off_t pos;
  102199. (void)client_data;
  102200. if(decoder->private_->file == stdin)
  102201. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102202. else if((pos = ftello(decoder->private_->file)) < 0)
  102203. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102204. else {
  102205. *absolute_byte_offset = (FLAC__uint64)pos;
  102206. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102207. }
  102208. }
  102209. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102210. {
  102211. struct stat filestats;
  102212. (void)client_data;
  102213. if(decoder->private_->file == stdin)
  102214. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102215. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102216. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102217. else {
  102218. *stream_length = (FLAC__uint64)filestats.st_size;
  102219. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102220. }
  102221. }
  102222. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102223. {
  102224. (void)client_data;
  102225. return feof(decoder->private_->file)? true : false;
  102226. }
  102227. #endif
  102228. /*** End of inlined file: stream_decoder.c ***/
  102229. /*** Start of inlined file: stream_encoder.c ***/
  102230. /*** Start of inlined file: juce_FlacHeader.h ***/
  102231. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102232. // tasks..
  102233. #define VERSION "1.2.1"
  102234. #define FLAC__NO_DLL 1
  102235. #if JUCE_MSVC
  102236. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102237. #endif
  102238. #if JUCE_MAC
  102239. #define FLAC__SYS_DARWIN 1
  102240. #endif
  102241. /*** End of inlined file: juce_FlacHeader.h ***/
  102242. #if JUCE_USE_FLAC
  102243. #if HAVE_CONFIG_H
  102244. # include <config.h>
  102245. #endif
  102246. #if defined _MSC_VER || defined __MINGW32__
  102247. #include <io.h> /* for _setmode() */
  102248. #include <fcntl.h> /* for _O_BINARY */
  102249. #endif
  102250. #if defined __CYGWIN__ || defined __EMX__
  102251. #include <io.h> /* for setmode(), O_BINARY */
  102252. #include <fcntl.h> /* for _O_BINARY */
  102253. #endif
  102254. #include <limits.h>
  102255. #include <stdio.h>
  102256. #include <stdlib.h> /* for malloc() */
  102257. #include <string.h> /* for memcpy() */
  102258. #include <sys/types.h> /* for off_t */
  102259. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102260. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102261. #define fseeko fseek
  102262. #define ftello ftell
  102263. #endif
  102264. #endif
  102265. /*** Start of inlined file: stream_encoder.h ***/
  102266. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102267. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102268. #if FLAC__HAS_OGG
  102269. #include "private/ogg_encoder_aspect.h"
  102270. #endif
  102271. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102272. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102273. typedef enum {
  102274. FLAC__APODIZATION_BARTLETT,
  102275. FLAC__APODIZATION_BARTLETT_HANN,
  102276. FLAC__APODIZATION_BLACKMAN,
  102277. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102278. FLAC__APODIZATION_CONNES,
  102279. FLAC__APODIZATION_FLATTOP,
  102280. FLAC__APODIZATION_GAUSS,
  102281. FLAC__APODIZATION_HAMMING,
  102282. FLAC__APODIZATION_HANN,
  102283. FLAC__APODIZATION_KAISER_BESSEL,
  102284. FLAC__APODIZATION_NUTTALL,
  102285. FLAC__APODIZATION_RECTANGLE,
  102286. FLAC__APODIZATION_TRIANGLE,
  102287. FLAC__APODIZATION_TUKEY,
  102288. FLAC__APODIZATION_WELCH
  102289. } FLAC__ApodizationFunction;
  102290. typedef struct {
  102291. FLAC__ApodizationFunction type;
  102292. union {
  102293. struct {
  102294. FLAC__real stddev;
  102295. } gauss;
  102296. struct {
  102297. FLAC__real p;
  102298. } tukey;
  102299. } parameters;
  102300. } FLAC__ApodizationSpecification;
  102301. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102302. typedef struct FLAC__StreamEncoderProtected {
  102303. FLAC__StreamEncoderState state;
  102304. FLAC__bool verify;
  102305. FLAC__bool streamable_subset;
  102306. FLAC__bool do_md5;
  102307. FLAC__bool do_mid_side_stereo;
  102308. FLAC__bool loose_mid_side_stereo;
  102309. unsigned channels;
  102310. unsigned bits_per_sample;
  102311. unsigned sample_rate;
  102312. unsigned blocksize;
  102313. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102314. unsigned num_apodizations;
  102315. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102316. #endif
  102317. unsigned max_lpc_order;
  102318. unsigned qlp_coeff_precision;
  102319. FLAC__bool do_qlp_coeff_prec_search;
  102320. FLAC__bool do_exhaustive_model_search;
  102321. FLAC__bool do_escape_coding;
  102322. unsigned min_residual_partition_order;
  102323. unsigned max_residual_partition_order;
  102324. unsigned rice_parameter_search_dist;
  102325. FLAC__uint64 total_samples_estimate;
  102326. FLAC__StreamMetadata **metadata;
  102327. unsigned num_metadata_blocks;
  102328. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102329. #if FLAC__HAS_OGG
  102330. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102331. #endif
  102332. } FLAC__StreamEncoderProtected;
  102333. #endif
  102334. /*** End of inlined file: stream_encoder.h ***/
  102335. #if FLAC__HAS_OGG
  102336. #include "include/private/ogg_helper.h"
  102337. #include "include/private/ogg_mapping.h"
  102338. #endif
  102339. /*** Start of inlined file: stream_encoder_framing.h ***/
  102340. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102341. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102342. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102343. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102344. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102345. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102346. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102347. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102348. #endif
  102349. /*** End of inlined file: stream_encoder_framing.h ***/
  102350. /*** Start of inlined file: window.h ***/
  102351. #ifndef FLAC__PRIVATE__WINDOW_H
  102352. #define FLAC__PRIVATE__WINDOW_H
  102353. #ifdef HAVE_CONFIG_H
  102354. #include <config.h>
  102355. #endif
  102356. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102357. /*
  102358. * FLAC__window_*()
  102359. * --------------------------------------------------------------------
  102360. * Calculates window coefficients according to different apodization
  102361. * functions.
  102362. *
  102363. * OUT window[0,L-1]
  102364. * IN L (number of points in window)
  102365. */
  102366. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102367. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102368. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102369. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102370. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102371. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102372. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102373. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102374. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102375. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102376. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102377. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102378. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102379. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102380. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102381. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102382. #endif
  102383. /*** End of inlined file: window.h ***/
  102384. #ifndef FLaC__INLINE
  102385. #define FLaC__INLINE
  102386. #endif
  102387. #ifdef min
  102388. #undef min
  102389. #endif
  102390. #define min(x,y) ((x)<(y)?(x):(y))
  102391. #ifdef max
  102392. #undef max
  102393. #endif
  102394. #define max(x,y) ((x)>(y)?(x):(y))
  102395. /* Exact Rice codeword length calculation is off by default. The simple
  102396. * (and fast) estimation (of how many bits a residual value will be
  102397. * encoded with) in this encoder is very good, almost always yielding
  102398. * compression within 0.1% of exact calculation.
  102399. */
  102400. #undef EXACT_RICE_BITS_CALCULATION
  102401. /* Rice parameter searching is off by default. The simple (and fast)
  102402. * parameter estimation in this encoder is very good, almost always
  102403. * yielding compression within 0.1% of the optimal parameters.
  102404. */
  102405. #undef ENABLE_RICE_PARAMETER_SEARCH
  102406. typedef struct {
  102407. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102408. unsigned size; /* of each data[] in samples */
  102409. unsigned tail;
  102410. } verify_input_fifo;
  102411. typedef struct {
  102412. const FLAC__byte *data;
  102413. unsigned capacity;
  102414. unsigned bytes;
  102415. } verify_output;
  102416. typedef enum {
  102417. ENCODER_IN_MAGIC = 0,
  102418. ENCODER_IN_METADATA = 1,
  102419. ENCODER_IN_AUDIO = 2
  102420. } EncoderStateHint;
  102421. static struct CompressionLevels {
  102422. FLAC__bool do_mid_side_stereo;
  102423. FLAC__bool loose_mid_side_stereo;
  102424. unsigned max_lpc_order;
  102425. unsigned qlp_coeff_precision;
  102426. FLAC__bool do_qlp_coeff_prec_search;
  102427. FLAC__bool do_escape_coding;
  102428. FLAC__bool do_exhaustive_model_search;
  102429. unsigned min_residual_partition_order;
  102430. unsigned max_residual_partition_order;
  102431. unsigned rice_parameter_search_dist;
  102432. } compression_levels_[] = {
  102433. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102434. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102435. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102436. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102437. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102438. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102439. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102440. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102441. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102442. };
  102443. /***********************************************************************
  102444. *
  102445. * Private class method prototypes
  102446. *
  102447. ***********************************************************************/
  102448. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102449. static void free_(FLAC__StreamEncoder *encoder);
  102450. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102451. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102452. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102453. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102454. #if FLAC__HAS_OGG
  102455. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102456. #endif
  102457. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102458. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102459. static FLAC__bool process_subframe_(
  102460. FLAC__StreamEncoder *encoder,
  102461. unsigned min_partition_order,
  102462. unsigned max_partition_order,
  102463. const FLAC__FrameHeader *frame_header,
  102464. unsigned subframe_bps,
  102465. const FLAC__int32 integer_signal[],
  102466. FLAC__Subframe *subframe[2],
  102467. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102468. FLAC__int32 *residual[2],
  102469. unsigned *best_subframe,
  102470. unsigned *best_bits
  102471. );
  102472. static FLAC__bool add_subframe_(
  102473. FLAC__StreamEncoder *encoder,
  102474. unsigned blocksize,
  102475. unsigned subframe_bps,
  102476. const FLAC__Subframe *subframe,
  102477. FLAC__BitWriter *frame
  102478. );
  102479. static unsigned evaluate_constant_subframe_(
  102480. FLAC__StreamEncoder *encoder,
  102481. const FLAC__int32 signal,
  102482. unsigned blocksize,
  102483. unsigned subframe_bps,
  102484. FLAC__Subframe *subframe
  102485. );
  102486. static unsigned evaluate_fixed_subframe_(
  102487. FLAC__StreamEncoder *encoder,
  102488. const FLAC__int32 signal[],
  102489. FLAC__int32 residual[],
  102490. FLAC__uint64 abs_residual_partition_sums[],
  102491. unsigned raw_bits_per_partition[],
  102492. unsigned blocksize,
  102493. unsigned subframe_bps,
  102494. unsigned order,
  102495. unsigned rice_parameter,
  102496. unsigned rice_parameter_limit,
  102497. unsigned min_partition_order,
  102498. unsigned max_partition_order,
  102499. FLAC__bool do_escape_coding,
  102500. unsigned rice_parameter_search_dist,
  102501. FLAC__Subframe *subframe,
  102502. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102503. );
  102504. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102505. static unsigned evaluate_lpc_subframe_(
  102506. FLAC__StreamEncoder *encoder,
  102507. const FLAC__int32 signal[],
  102508. FLAC__int32 residual[],
  102509. FLAC__uint64 abs_residual_partition_sums[],
  102510. unsigned raw_bits_per_partition[],
  102511. const FLAC__real lp_coeff[],
  102512. unsigned blocksize,
  102513. unsigned subframe_bps,
  102514. unsigned order,
  102515. unsigned qlp_coeff_precision,
  102516. unsigned rice_parameter,
  102517. unsigned rice_parameter_limit,
  102518. unsigned min_partition_order,
  102519. unsigned max_partition_order,
  102520. FLAC__bool do_escape_coding,
  102521. unsigned rice_parameter_search_dist,
  102522. FLAC__Subframe *subframe,
  102523. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102524. );
  102525. #endif
  102526. static unsigned evaluate_verbatim_subframe_(
  102527. FLAC__StreamEncoder *encoder,
  102528. const FLAC__int32 signal[],
  102529. unsigned blocksize,
  102530. unsigned subframe_bps,
  102531. FLAC__Subframe *subframe
  102532. );
  102533. static unsigned find_best_partition_order_(
  102534. struct FLAC__StreamEncoderPrivate *private_,
  102535. const FLAC__int32 residual[],
  102536. FLAC__uint64 abs_residual_partition_sums[],
  102537. unsigned raw_bits_per_partition[],
  102538. unsigned residual_samples,
  102539. unsigned predictor_order,
  102540. unsigned rice_parameter,
  102541. unsigned rice_parameter_limit,
  102542. unsigned min_partition_order,
  102543. unsigned max_partition_order,
  102544. unsigned bps,
  102545. FLAC__bool do_escape_coding,
  102546. unsigned rice_parameter_search_dist,
  102547. FLAC__EntropyCodingMethod *best_ecm
  102548. );
  102549. static void precompute_partition_info_sums_(
  102550. const FLAC__int32 residual[],
  102551. FLAC__uint64 abs_residual_partition_sums[],
  102552. unsigned residual_samples,
  102553. unsigned predictor_order,
  102554. unsigned min_partition_order,
  102555. unsigned max_partition_order,
  102556. unsigned bps
  102557. );
  102558. static void precompute_partition_info_escapes_(
  102559. const FLAC__int32 residual[],
  102560. unsigned raw_bits_per_partition[],
  102561. unsigned residual_samples,
  102562. unsigned predictor_order,
  102563. unsigned min_partition_order,
  102564. unsigned max_partition_order
  102565. );
  102566. static FLAC__bool set_partitioned_rice_(
  102567. #ifdef EXACT_RICE_BITS_CALCULATION
  102568. const FLAC__int32 residual[],
  102569. #endif
  102570. const FLAC__uint64 abs_residual_partition_sums[],
  102571. const unsigned raw_bits_per_partition[],
  102572. const unsigned residual_samples,
  102573. const unsigned predictor_order,
  102574. const unsigned suggested_rice_parameter,
  102575. const unsigned rice_parameter_limit,
  102576. const unsigned rice_parameter_search_dist,
  102577. const unsigned partition_order,
  102578. const FLAC__bool search_for_escapes,
  102579. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102580. unsigned *bits
  102581. );
  102582. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102583. /* verify-related routines: */
  102584. static void append_to_verify_fifo_(
  102585. verify_input_fifo *fifo,
  102586. const FLAC__int32 * const input[],
  102587. unsigned input_offset,
  102588. unsigned channels,
  102589. unsigned wide_samples
  102590. );
  102591. static void append_to_verify_fifo_interleaved_(
  102592. verify_input_fifo *fifo,
  102593. const FLAC__int32 input[],
  102594. unsigned input_offset,
  102595. unsigned channels,
  102596. unsigned wide_samples
  102597. );
  102598. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102599. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102600. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102601. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102602. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102603. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102604. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102605. 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);
  102606. static FILE *get_binary_stdout_(void);
  102607. /***********************************************************************
  102608. *
  102609. * Private class data
  102610. *
  102611. ***********************************************************************/
  102612. typedef struct FLAC__StreamEncoderPrivate {
  102613. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102614. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102615. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102616. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102617. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102618. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102619. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102620. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102621. #endif
  102622. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102623. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102624. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102625. FLAC__int32 *residual_workspace_mid_side[2][2];
  102626. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102627. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102628. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102629. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102630. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102631. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102632. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102633. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102634. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102635. unsigned best_subframe_mid_side[2];
  102636. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102637. unsigned best_subframe_bits_mid_side[2];
  102638. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102639. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102640. FLAC__BitWriter *frame; /* the current frame being worked on */
  102641. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102642. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102643. FLAC__ChannelAssignment last_channel_assignment;
  102644. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102645. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102646. unsigned current_sample_number;
  102647. unsigned current_frame_number;
  102648. FLAC__MD5Context md5context;
  102649. FLAC__CPUInfo cpuinfo;
  102650. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102651. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102652. #else
  102653. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102654. #endif
  102655. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102656. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102657. 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[]);
  102658. 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[]);
  102659. 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[]);
  102660. #endif
  102661. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102662. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102663. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102664. FLAC__bool disable_constant_subframes;
  102665. FLAC__bool disable_fixed_subframes;
  102666. FLAC__bool disable_verbatim_subframes;
  102667. #if FLAC__HAS_OGG
  102668. FLAC__bool is_ogg;
  102669. #endif
  102670. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102671. FLAC__StreamEncoderSeekCallback seek_callback;
  102672. FLAC__StreamEncoderTellCallback tell_callback;
  102673. FLAC__StreamEncoderWriteCallback write_callback;
  102674. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102675. FLAC__StreamEncoderProgressCallback progress_callback;
  102676. void *client_data;
  102677. unsigned first_seekpoint_to_check;
  102678. FILE *file; /* only used when encoding to a file */
  102679. FLAC__uint64 bytes_written;
  102680. FLAC__uint64 samples_written;
  102681. unsigned frames_written;
  102682. unsigned total_frames_estimate;
  102683. /* unaligned (original) pointers to allocated data */
  102684. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102685. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102686. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102687. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102688. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102689. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102690. FLAC__real *windowed_signal_unaligned;
  102691. #endif
  102692. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102693. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102694. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102695. unsigned *raw_bits_per_partition_unaligned;
  102696. /*
  102697. * These fields have been moved here from private function local
  102698. * declarations merely to save stack space during encoding.
  102699. */
  102700. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102701. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102702. #endif
  102703. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102704. /*
  102705. * The data for the verify section
  102706. */
  102707. struct {
  102708. FLAC__StreamDecoder *decoder;
  102709. EncoderStateHint state_hint;
  102710. FLAC__bool needs_magic_hack;
  102711. verify_input_fifo input_fifo;
  102712. verify_output output;
  102713. struct {
  102714. FLAC__uint64 absolute_sample;
  102715. unsigned frame_number;
  102716. unsigned channel;
  102717. unsigned sample;
  102718. FLAC__int32 expected;
  102719. FLAC__int32 got;
  102720. } error_stats;
  102721. } verify;
  102722. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102723. } FLAC__StreamEncoderPrivate;
  102724. /***********************************************************************
  102725. *
  102726. * Public static class data
  102727. *
  102728. ***********************************************************************/
  102729. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102730. "FLAC__STREAM_ENCODER_OK",
  102731. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102732. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102733. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102734. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102735. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102736. "FLAC__STREAM_ENCODER_IO_ERROR",
  102737. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102738. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102739. };
  102740. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102741. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102742. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102743. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102744. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102745. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102746. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102747. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102748. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102749. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102750. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102751. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102752. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102753. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102754. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102755. };
  102756. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102757. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102758. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102759. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102760. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102761. };
  102762. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102763. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102764. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102765. };
  102766. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102767. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102768. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102769. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102770. };
  102771. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102772. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102773. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102774. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102775. };
  102776. /* Number of samples that will be overread to watch for end of stream. By
  102777. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102778. * always try to read blocksize+1 samples before encoding a block, so that
  102779. * even if the stream has a total sample count that is an integral multiple
  102780. * of the blocksize, we will still notice when we are encoding the last
  102781. * block. This is needed, for example, to correctly set the end-of-stream
  102782. * marker in Ogg FLAC.
  102783. *
  102784. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102785. * not really any reason to change it.
  102786. */
  102787. static const unsigned OVERREAD_ = 1;
  102788. /***********************************************************************
  102789. *
  102790. * Class constructor/destructor
  102791. *
  102792. */
  102793. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102794. {
  102795. FLAC__StreamEncoder *encoder;
  102796. unsigned i;
  102797. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102798. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102799. if(encoder == 0) {
  102800. return 0;
  102801. }
  102802. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102803. if(encoder->protected_ == 0) {
  102804. free(encoder);
  102805. return 0;
  102806. }
  102807. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102808. if(encoder->private_ == 0) {
  102809. free(encoder->protected_);
  102810. free(encoder);
  102811. return 0;
  102812. }
  102813. encoder->private_->frame = FLAC__bitwriter_new();
  102814. if(encoder->private_->frame == 0) {
  102815. free(encoder->private_);
  102816. free(encoder->protected_);
  102817. free(encoder);
  102818. return 0;
  102819. }
  102820. encoder->private_->file = 0;
  102821. set_defaults_enc(encoder);
  102822. encoder->private_->is_being_deleted = false;
  102823. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102824. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102825. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102826. }
  102827. for(i = 0; i < 2; i++) {
  102828. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102829. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102830. }
  102831. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102832. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102833. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102834. }
  102835. for(i = 0; i < 2; i++) {
  102836. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102837. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102838. }
  102839. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102840. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102841. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102842. }
  102843. for(i = 0; i < 2; i++) {
  102844. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102845. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102846. }
  102847. for(i = 0; i < 2; i++)
  102848. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102849. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102850. return encoder;
  102851. }
  102852. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102853. {
  102854. unsigned i;
  102855. FLAC__ASSERT(0 != encoder);
  102856. FLAC__ASSERT(0 != encoder->protected_);
  102857. FLAC__ASSERT(0 != encoder->private_);
  102858. FLAC__ASSERT(0 != encoder->private_->frame);
  102859. encoder->private_->is_being_deleted = true;
  102860. (void)FLAC__stream_encoder_finish(encoder);
  102861. if(0 != encoder->private_->verify.decoder)
  102862. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102863. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102864. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102865. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102866. }
  102867. for(i = 0; i < 2; i++) {
  102868. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102869. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102870. }
  102871. for(i = 0; i < 2; i++)
  102872. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102873. FLAC__bitwriter_delete(encoder->private_->frame);
  102874. free(encoder->private_);
  102875. free(encoder->protected_);
  102876. free(encoder);
  102877. }
  102878. /***********************************************************************
  102879. *
  102880. * Public class methods
  102881. *
  102882. ***********************************************************************/
  102883. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102884. FLAC__StreamEncoder *encoder,
  102885. FLAC__StreamEncoderReadCallback read_callback,
  102886. FLAC__StreamEncoderWriteCallback write_callback,
  102887. FLAC__StreamEncoderSeekCallback seek_callback,
  102888. FLAC__StreamEncoderTellCallback tell_callback,
  102889. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102890. void *client_data,
  102891. FLAC__bool is_ogg
  102892. )
  102893. {
  102894. unsigned i;
  102895. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102896. FLAC__ASSERT(0 != encoder);
  102897. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102898. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102899. #if !FLAC__HAS_OGG
  102900. if(is_ogg)
  102901. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102902. #endif
  102903. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102904. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102905. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102906. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102907. if(encoder->protected_->channels != 2) {
  102908. encoder->protected_->do_mid_side_stereo = false;
  102909. encoder->protected_->loose_mid_side_stereo = false;
  102910. }
  102911. else if(!encoder->protected_->do_mid_side_stereo)
  102912. encoder->protected_->loose_mid_side_stereo = false;
  102913. if(encoder->protected_->bits_per_sample >= 32)
  102914. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102915. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102916. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102917. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102918. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102919. if(encoder->protected_->blocksize == 0) {
  102920. if(encoder->protected_->max_lpc_order == 0)
  102921. encoder->protected_->blocksize = 1152;
  102922. else
  102923. encoder->protected_->blocksize = 4096;
  102924. }
  102925. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102926. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102927. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102928. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102929. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102930. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102931. if(encoder->protected_->qlp_coeff_precision == 0) {
  102932. if(encoder->protected_->bits_per_sample < 16) {
  102933. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102934. /* @@@ until then we'll make a guess */
  102935. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102936. }
  102937. else if(encoder->protected_->bits_per_sample == 16) {
  102938. if(encoder->protected_->blocksize <= 192)
  102939. encoder->protected_->qlp_coeff_precision = 7;
  102940. else if(encoder->protected_->blocksize <= 384)
  102941. encoder->protected_->qlp_coeff_precision = 8;
  102942. else if(encoder->protected_->blocksize <= 576)
  102943. encoder->protected_->qlp_coeff_precision = 9;
  102944. else if(encoder->protected_->blocksize <= 1152)
  102945. encoder->protected_->qlp_coeff_precision = 10;
  102946. else if(encoder->protected_->blocksize <= 2304)
  102947. encoder->protected_->qlp_coeff_precision = 11;
  102948. else if(encoder->protected_->blocksize <= 4608)
  102949. encoder->protected_->qlp_coeff_precision = 12;
  102950. else
  102951. encoder->protected_->qlp_coeff_precision = 13;
  102952. }
  102953. else {
  102954. if(encoder->protected_->blocksize <= 384)
  102955. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102956. else if(encoder->protected_->blocksize <= 1152)
  102957. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102958. else
  102959. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102960. }
  102961. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102962. }
  102963. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102964. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102965. if(encoder->protected_->streamable_subset) {
  102966. if(
  102967. encoder->protected_->blocksize != 192 &&
  102968. encoder->protected_->blocksize != 576 &&
  102969. encoder->protected_->blocksize != 1152 &&
  102970. encoder->protected_->blocksize != 2304 &&
  102971. encoder->protected_->blocksize != 4608 &&
  102972. encoder->protected_->blocksize != 256 &&
  102973. encoder->protected_->blocksize != 512 &&
  102974. encoder->protected_->blocksize != 1024 &&
  102975. encoder->protected_->blocksize != 2048 &&
  102976. encoder->protected_->blocksize != 4096 &&
  102977. encoder->protected_->blocksize != 8192 &&
  102978. encoder->protected_->blocksize != 16384
  102979. )
  102980. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102981. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102982. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102983. if(
  102984. encoder->protected_->bits_per_sample != 8 &&
  102985. encoder->protected_->bits_per_sample != 12 &&
  102986. encoder->protected_->bits_per_sample != 16 &&
  102987. encoder->protected_->bits_per_sample != 20 &&
  102988. encoder->protected_->bits_per_sample != 24
  102989. )
  102990. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102991. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102992. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102993. if(
  102994. encoder->protected_->sample_rate <= 48000 &&
  102995. (
  102996. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102997. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102998. )
  102999. ) {
  103000. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103001. }
  103002. }
  103003. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103004. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103005. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103006. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103007. #if FLAC__HAS_OGG
  103008. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103009. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103010. unsigned i;
  103011. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103012. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103013. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103014. for( ; i > 0; i--)
  103015. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103016. encoder->protected_->metadata[0] = vc;
  103017. break;
  103018. }
  103019. }
  103020. }
  103021. #endif
  103022. /* keep track of any SEEKTABLE block */
  103023. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103024. unsigned i;
  103025. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103026. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103027. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103028. break; /* take only the first one */
  103029. }
  103030. }
  103031. }
  103032. /* validate metadata */
  103033. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103034. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103035. metadata_has_seektable = false;
  103036. metadata_has_vorbis_comment = false;
  103037. metadata_picture_has_type1 = false;
  103038. metadata_picture_has_type2 = false;
  103039. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103040. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103041. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103042. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103043. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103044. if(metadata_has_seektable) /* only one is allowed */
  103045. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103046. metadata_has_seektable = true;
  103047. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103048. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103049. }
  103050. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103051. if(metadata_has_vorbis_comment) /* only one is allowed */
  103052. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103053. metadata_has_vorbis_comment = true;
  103054. }
  103055. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103056. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103057. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103058. }
  103059. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103060. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103061. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103062. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103063. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103064. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103065. metadata_picture_has_type1 = true;
  103066. /* standard icon must be 32x32 pixel PNG */
  103067. if(
  103068. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103069. (
  103070. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103071. m->data.picture.width != 32 ||
  103072. m->data.picture.height != 32
  103073. )
  103074. )
  103075. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103076. }
  103077. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103078. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103079. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103080. metadata_picture_has_type2 = true;
  103081. }
  103082. }
  103083. }
  103084. encoder->private_->input_capacity = 0;
  103085. for(i = 0; i < encoder->protected_->channels; i++) {
  103086. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103087. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103088. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103089. #endif
  103090. }
  103091. for(i = 0; i < 2; i++) {
  103092. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103093. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103094. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103095. #endif
  103096. }
  103097. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103098. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103099. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103100. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103101. #endif
  103102. for(i = 0; i < encoder->protected_->channels; i++) {
  103103. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103104. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103105. encoder->private_->best_subframe[i] = 0;
  103106. }
  103107. for(i = 0; i < 2; i++) {
  103108. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103109. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103110. encoder->private_->best_subframe_mid_side[i] = 0;
  103111. }
  103112. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103113. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103114. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103115. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103116. #else
  103117. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103118. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103119. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103120. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103121. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103122. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103123. 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);
  103124. #endif
  103125. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103126. encoder->private_->loose_mid_side_stereo_frames = 1;
  103127. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103128. encoder->private_->current_sample_number = 0;
  103129. encoder->private_->current_frame_number = 0;
  103130. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103131. 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? */
  103132. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103133. /*
  103134. * get the CPU info and set the function pointers
  103135. */
  103136. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103137. /* first default to the non-asm routines */
  103138. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103139. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103140. #endif
  103141. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103142. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103143. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103144. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103145. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103146. #endif
  103147. /* now override with asm where appropriate */
  103148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103149. # ifndef FLAC__NO_ASM
  103150. if(encoder->private_->cpuinfo.use_asm) {
  103151. # ifdef FLAC__CPU_IA32
  103152. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103153. # ifdef FLAC__HAS_NASM
  103154. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103155. if(encoder->protected_->max_lpc_order < 4)
  103156. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103157. else if(encoder->protected_->max_lpc_order < 8)
  103158. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103159. else if(encoder->protected_->max_lpc_order < 12)
  103160. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103161. else
  103162. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103163. }
  103164. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103165. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103166. else
  103167. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103168. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103169. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103170. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103171. }
  103172. else {
  103173. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103174. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103175. }
  103176. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103177. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103178. # endif /* FLAC__HAS_NASM */
  103179. # endif /* FLAC__CPU_IA32 */
  103180. }
  103181. # endif /* !FLAC__NO_ASM */
  103182. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103183. /* finally override based on wide-ness if necessary */
  103184. if(encoder->private_->use_wide_by_block) {
  103185. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103186. }
  103187. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103188. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103189. #if FLAC__HAS_OGG
  103190. encoder->private_->is_ogg = is_ogg;
  103191. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103192. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103193. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103194. }
  103195. #endif
  103196. encoder->private_->read_callback = read_callback;
  103197. encoder->private_->write_callback = write_callback;
  103198. encoder->private_->seek_callback = seek_callback;
  103199. encoder->private_->tell_callback = tell_callback;
  103200. encoder->private_->metadata_callback = metadata_callback;
  103201. encoder->private_->client_data = client_data;
  103202. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103203. /* the above function sets the state for us in case of an error */
  103204. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103205. }
  103206. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103207. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103208. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103209. }
  103210. /*
  103211. * Set up the verify stuff if necessary
  103212. */
  103213. if(encoder->protected_->verify) {
  103214. /*
  103215. * First, set up the fifo which will hold the
  103216. * original signal to compare against
  103217. */
  103218. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103219. for(i = 0; i < encoder->protected_->channels; i++) {
  103220. 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))) {
  103221. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103222. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103223. }
  103224. }
  103225. encoder->private_->verify.input_fifo.tail = 0;
  103226. /*
  103227. * Now set up a stream decoder for verification
  103228. */
  103229. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103230. if(0 == encoder->private_->verify.decoder) {
  103231. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103232. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103233. }
  103234. 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) {
  103235. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103236. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103237. }
  103238. }
  103239. encoder->private_->verify.error_stats.absolute_sample = 0;
  103240. encoder->private_->verify.error_stats.frame_number = 0;
  103241. encoder->private_->verify.error_stats.channel = 0;
  103242. encoder->private_->verify.error_stats.sample = 0;
  103243. encoder->private_->verify.error_stats.expected = 0;
  103244. encoder->private_->verify.error_stats.got = 0;
  103245. /*
  103246. * These must be done before we write any metadata, because that
  103247. * calls the write_callback, which uses these values.
  103248. */
  103249. encoder->private_->first_seekpoint_to_check = 0;
  103250. encoder->private_->samples_written = 0;
  103251. encoder->protected_->streaminfo_offset = 0;
  103252. encoder->protected_->seektable_offset = 0;
  103253. encoder->protected_->audio_offset = 0;
  103254. /*
  103255. * write the stream header
  103256. */
  103257. if(encoder->protected_->verify)
  103258. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103259. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103260. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103261. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103262. }
  103263. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103264. /* the above function sets the state for us in case of an error */
  103265. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103266. }
  103267. /*
  103268. * write the STREAMINFO metadata block
  103269. */
  103270. if(encoder->protected_->verify)
  103271. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103272. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103273. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103274. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103275. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103276. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103277. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103278. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103279. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103280. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103281. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103282. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103283. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103284. if(encoder->protected_->do_md5)
  103285. FLAC__MD5Init(&encoder->private_->md5context);
  103286. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103287. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103288. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103289. }
  103290. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103291. /* the above function sets the state for us in case of an error */
  103292. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103293. }
  103294. /*
  103295. * Now that the STREAMINFO block is written, we can init this to an
  103296. * absurdly-high value...
  103297. */
  103298. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103299. /* ... and clear this to 0 */
  103300. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103301. /*
  103302. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103303. * if not, we will write an empty one (FLAC__add_metadata_block()
  103304. * automatically supplies the vendor string).
  103305. *
  103306. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103307. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103308. * true it will have already insured that the metadata list is properly
  103309. * ordered.)
  103310. */
  103311. if(!metadata_has_vorbis_comment) {
  103312. FLAC__StreamMetadata vorbis_comment;
  103313. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103314. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103315. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103316. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103317. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103318. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103319. vorbis_comment.data.vorbis_comment.comments = 0;
  103320. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103321. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103322. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103323. }
  103324. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103325. /* the above function sets the state for us in case of an error */
  103326. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103327. }
  103328. }
  103329. /*
  103330. * write the user's metadata blocks
  103331. */
  103332. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103333. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103334. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103335. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103336. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103337. }
  103338. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103339. /* the above function sets the state for us in case of an error */
  103340. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103341. }
  103342. }
  103343. /* now that all the metadata is written, we save the stream offset */
  103344. 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 */
  103345. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103346. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103347. }
  103348. if(encoder->protected_->verify)
  103349. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103350. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103351. }
  103352. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103353. FLAC__StreamEncoder *encoder,
  103354. FLAC__StreamEncoderWriteCallback write_callback,
  103355. FLAC__StreamEncoderSeekCallback seek_callback,
  103356. FLAC__StreamEncoderTellCallback tell_callback,
  103357. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103358. void *client_data
  103359. )
  103360. {
  103361. return init_stream_internal_enc(
  103362. encoder,
  103363. /*read_callback=*/0,
  103364. write_callback,
  103365. seek_callback,
  103366. tell_callback,
  103367. metadata_callback,
  103368. client_data,
  103369. /*is_ogg=*/false
  103370. );
  103371. }
  103372. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103373. FLAC__StreamEncoder *encoder,
  103374. FLAC__StreamEncoderReadCallback read_callback,
  103375. FLAC__StreamEncoderWriteCallback write_callback,
  103376. FLAC__StreamEncoderSeekCallback seek_callback,
  103377. FLAC__StreamEncoderTellCallback tell_callback,
  103378. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103379. void *client_data
  103380. )
  103381. {
  103382. return init_stream_internal_enc(
  103383. encoder,
  103384. read_callback,
  103385. write_callback,
  103386. seek_callback,
  103387. tell_callback,
  103388. metadata_callback,
  103389. client_data,
  103390. /*is_ogg=*/true
  103391. );
  103392. }
  103393. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103394. FLAC__StreamEncoder *encoder,
  103395. FILE *file,
  103396. FLAC__StreamEncoderProgressCallback progress_callback,
  103397. void *client_data,
  103398. FLAC__bool is_ogg
  103399. )
  103400. {
  103401. FLAC__StreamEncoderInitStatus init_status;
  103402. FLAC__ASSERT(0 != encoder);
  103403. FLAC__ASSERT(0 != file);
  103404. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103405. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103406. /* double protection */
  103407. if(file == 0) {
  103408. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103409. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103410. }
  103411. /*
  103412. * To make sure that our file does not go unclosed after an error, we
  103413. * must assign the FILE pointer before any further error can occur in
  103414. * this routine.
  103415. */
  103416. if(file == stdout)
  103417. file = get_binary_stdout_(); /* just to be safe */
  103418. encoder->private_->file = file;
  103419. encoder->private_->progress_callback = progress_callback;
  103420. encoder->private_->bytes_written = 0;
  103421. encoder->private_->samples_written = 0;
  103422. encoder->private_->frames_written = 0;
  103423. init_status = init_stream_internal_enc(
  103424. encoder,
  103425. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103426. file_write_callback_,
  103427. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103428. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103429. /*metadata_callback=*/0,
  103430. client_data,
  103431. is_ogg
  103432. );
  103433. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103434. /* the above function sets the state for us in case of an error */
  103435. return init_status;
  103436. }
  103437. {
  103438. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103439. FLAC__ASSERT(blocksize != 0);
  103440. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103441. }
  103442. return init_status;
  103443. }
  103444. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103445. FLAC__StreamEncoder *encoder,
  103446. FILE *file,
  103447. FLAC__StreamEncoderProgressCallback progress_callback,
  103448. void *client_data
  103449. )
  103450. {
  103451. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103452. }
  103453. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103454. FLAC__StreamEncoder *encoder,
  103455. FILE *file,
  103456. FLAC__StreamEncoderProgressCallback progress_callback,
  103457. void *client_data
  103458. )
  103459. {
  103460. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103461. }
  103462. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103463. FLAC__StreamEncoder *encoder,
  103464. const char *filename,
  103465. FLAC__StreamEncoderProgressCallback progress_callback,
  103466. void *client_data,
  103467. FLAC__bool is_ogg
  103468. )
  103469. {
  103470. FILE *file;
  103471. FLAC__ASSERT(0 != encoder);
  103472. /*
  103473. * To make sure that our file does not go unclosed after an error, we
  103474. * have to do the same entrance checks here that are later performed
  103475. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103476. */
  103477. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103478. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103479. file = filename? fopen(filename, "w+b") : stdout;
  103480. if(file == 0) {
  103481. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103482. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103483. }
  103484. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103485. }
  103486. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103487. FLAC__StreamEncoder *encoder,
  103488. const char *filename,
  103489. FLAC__StreamEncoderProgressCallback progress_callback,
  103490. void *client_data
  103491. )
  103492. {
  103493. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103494. }
  103495. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103496. FLAC__StreamEncoder *encoder,
  103497. const char *filename,
  103498. FLAC__StreamEncoderProgressCallback progress_callback,
  103499. void *client_data
  103500. )
  103501. {
  103502. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103503. }
  103504. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103505. {
  103506. FLAC__bool error = false;
  103507. FLAC__ASSERT(0 != encoder);
  103508. FLAC__ASSERT(0 != encoder->private_);
  103509. FLAC__ASSERT(0 != encoder->protected_);
  103510. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103511. return true;
  103512. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103513. if(encoder->private_->current_sample_number != 0) {
  103514. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103515. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103516. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103517. error = true;
  103518. }
  103519. }
  103520. if(encoder->protected_->do_md5)
  103521. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103522. if(!encoder->private_->is_being_deleted) {
  103523. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103524. if(encoder->private_->seek_callback) {
  103525. #if FLAC__HAS_OGG
  103526. if(encoder->private_->is_ogg)
  103527. update_ogg_metadata_(encoder);
  103528. else
  103529. #endif
  103530. update_metadata_(encoder);
  103531. /* check if an error occurred while updating metadata */
  103532. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103533. error = true;
  103534. }
  103535. if(encoder->private_->metadata_callback)
  103536. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103537. }
  103538. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103539. if(!error)
  103540. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103541. error = true;
  103542. }
  103543. }
  103544. if(0 != encoder->private_->file) {
  103545. if(encoder->private_->file != stdout)
  103546. fclose(encoder->private_->file);
  103547. encoder->private_->file = 0;
  103548. }
  103549. #if FLAC__HAS_OGG
  103550. if(encoder->private_->is_ogg)
  103551. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103552. #endif
  103553. free_(encoder);
  103554. set_defaults_enc(encoder);
  103555. if(!error)
  103556. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103557. return !error;
  103558. }
  103559. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103560. {
  103561. FLAC__ASSERT(0 != encoder);
  103562. FLAC__ASSERT(0 != encoder->private_);
  103563. FLAC__ASSERT(0 != encoder->protected_);
  103564. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103565. return false;
  103566. #if FLAC__HAS_OGG
  103567. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103568. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103569. return true;
  103570. #else
  103571. (void)value;
  103572. return false;
  103573. #endif
  103574. }
  103575. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103576. {
  103577. FLAC__ASSERT(0 != encoder);
  103578. FLAC__ASSERT(0 != encoder->private_);
  103579. FLAC__ASSERT(0 != encoder->protected_);
  103580. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103581. return false;
  103582. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103583. encoder->protected_->verify = value;
  103584. #endif
  103585. return true;
  103586. }
  103587. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103588. {
  103589. FLAC__ASSERT(0 != encoder);
  103590. FLAC__ASSERT(0 != encoder->private_);
  103591. FLAC__ASSERT(0 != encoder->protected_);
  103592. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103593. return false;
  103594. encoder->protected_->streamable_subset = value;
  103595. return true;
  103596. }
  103597. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103598. {
  103599. FLAC__ASSERT(0 != encoder);
  103600. FLAC__ASSERT(0 != encoder->private_);
  103601. FLAC__ASSERT(0 != encoder->protected_);
  103602. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103603. return false;
  103604. encoder->protected_->do_md5 = value;
  103605. return true;
  103606. }
  103607. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103608. {
  103609. FLAC__ASSERT(0 != encoder);
  103610. FLAC__ASSERT(0 != encoder->private_);
  103611. FLAC__ASSERT(0 != encoder->protected_);
  103612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103613. return false;
  103614. encoder->protected_->channels = value;
  103615. return true;
  103616. }
  103617. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103618. {
  103619. FLAC__ASSERT(0 != encoder);
  103620. FLAC__ASSERT(0 != encoder->private_);
  103621. FLAC__ASSERT(0 != encoder->protected_);
  103622. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103623. return false;
  103624. encoder->protected_->bits_per_sample = value;
  103625. return true;
  103626. }
  103627. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103628. {
  103629. FLAC__ASSERT(0 != encoder);
  103630. FLAC__ASSERT(0 != encoder->private_);
  103631. FLAC__ASSERT(0 != encoder->protected_);
  103632. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103633. return false;
  103634. encoder->protected_->sample_rate = value;
  103635. return true;
  103636. }
  103637. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103638. {
  103639. FLAC__bool ok = true;
  103640. FLAC__ASSERT(0 != encoder);
  103641. FLAC__ASSERT(0 != encoder->private_);
  103642. FLAC__ASSERT(0 != encoder->protected_);
  103643. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103644. return false;
  103645. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103646. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103647. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103648. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103649. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103650. #if 0
  103651. /* was: */
  103652. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103653. /* but it's too hard to specify the string in a locale-specific way */
  103654. #else
  103655. encoder->protected_->num_apodizations = 1;
  103656. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103657. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103658. #endif
  103659. #endif
  103660. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103661. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103662. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103663. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103664. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103665. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103666. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103667. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103668. return ok;
  103669. }
  103670. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103671. {
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103676. return false;
  103677. encoder->protected_->blocksize = value;
  103678. return true;
  103679. }
  103680. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103681. {
  103682. FLAC__ASSERT(0 != encoder);
  103683. FLAC__ASSERT(0 != encoder->private_);
  103684. FLAC__ASSERT(0 != encoder->protected_);
  103685. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103686. return false;
  103687. encoder->protected_->do_mid_side_stereo = value;
  103688. return true;
  103689. }
  103690. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103691. {
  103692. FLAC__ASSERT(0 != encoder);
  103693. FLAC__ASSERT(0 != encoder->private_);
  103694. FLAC__ASSERT(0 != encoder->protected_);
  103695. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103696. return false;
  103697. encoder->protected_->loose_mid_side_stereo = value;
  103698. return true;
  103699. }
  103700. /*@@@@add to tests*/
  103701. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103702. {
  103703. FLAC__ASSERT(0 != encoder);
  103704. FLAC__ASSERT(0 != encoder->private_);
  103705. FLAC__ASSERT(0 != encoder->protected_);
  103706. FLAC__ASSERT(0 != specification);
  103707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103708. return false;
  103709. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103710. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103711. #else
  103712. encoder->protected_->num_apodizations = 0;
  103713. while(1) {
  103714. const char *s = strchr(specification, ';');
  103715. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103716. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103717. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103718. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103719. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103720. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103721. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103722. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103723. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103724. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103725. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103726. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103727. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103728. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103729. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103730. if (stddev > 0.0 && stddev <= 0.5) {
  103731. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103732. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103733. }
  103734. }
  103735. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103736. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103737. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103738. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103739. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103740. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103741. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103742. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103743. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103744. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103745. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103746. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103747. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103748. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103749. if (p >= 0.0 && p <= 1.0) {
  103750. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103751. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103752. }
  103753. }
  103754. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103755. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103756. if (encoder->protected_->num_apodizations == 32)
  103757. break;
  103758. if (s)
  103759. specification = s+1;
  103760. else
  103761. break;
  103762. }
  103763. if(encoder->protected_->num_apodizations == 0) {
  103764. encoder->protected_->num_apodizations = 1;
  103765. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103766. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103767. }
  103768. #endif
  103769. return true;
  103770. }
  103771. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103772. {
  103773. FLAC__ASSERT(0 != encoder);
  103774. FLAC__ASSERT(0 != encoder->private_);
  103775. FLAC__ASSERT(0 != encoder->protected_);
  103776. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103777. return false;
  103778. encoder->protected_->max_lpc_order = value;
  103779. return true;
  103780. }
  103781. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103782. {
  103783. FLAC__ASSERT(0 != encoder);
  103784. FLAC__ASSERT(0 != encoder->private_);
  103785. FLAC__ASSERT(0 != encoder->protected_);
  103786. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103787. return false;
  103788. encoder->protected_->qlp_coeff_precision = value;
  103789. return true;
  103790. }
  103791. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103792. {
  103793. FLAC__ASSERT(0 != encoder);
  103794. FLAC__ASSERT(0 != encoder->private_);
  103795. FLAC__ASSERT(0 != encoder->protected_);
  103796. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103797. return false;
  103798. encoder->protected_->do_qlp_coeff_prec_search = value;
  103799. return true;
  103800. }
  103801. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103802. {
  103803. FLAC__ASSERT(0 != encoder);
  103804. FLAC__ASSERT(0 != encoder->private_);
  103805. FLAC__ASSERT(0 != encoder->protected_);
  103806. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103807. return false;
  103808. #if 0
  103809. /*@@@ deprecated: */
  103810. encoder->protected_->do_escape_coding = value;
  103811. #else
  103812. (void)value;
  103813. #endif
  103814. return true;
  103815. }
  103816. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103817. {
  103818. FLAC__ASSERT(0 != encoder);
  103819. FLAC__ASSERT(0 != encoder->private_);
  103820. FLAC__ASSERT(0 != encoder->protected_);
  103821. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103822. return false;
  103823. encoder->protected_->do_exhaustive_model_search = value;
  103824. return true;
  103825. }
  103826. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103827. {
  103828. FLAC__ASSERT(0 != encoder);
  103829. FLAC__ASSERT(0 != encoder->private_);
  103830. FLAC__ASSERT(0 != encoder->protected_);
  103831. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103832. return false;
  103833. encoder->protected_->min_residual_partition_order = value;
  103834. return true;
  103835. }
  103836. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103837. {
  103838. FLAC__ASSERT(0 != encoder);
  103839. FLAC__ASSERT(0 != encoder->private_);
  103840. FLAC__ASSERT(0 != encoder->protected_);
  103841. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103842. return false;
  103843. encoder->protected_->max_residual_partition_order = value;
  103844. return true;
  103845. }
  103846. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103847. {
  103848. FLAC__ASSERT(0 != encoder);
  103849. FLAC__ASSERT(0 != encoder->private_);
  103850. FLAC__ASSERT(0 != encoder->protected_);
  103851. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103852. return false;
  103853. #if 0
  103854. /*@@@ deprecated: */
  103855. encoder->protected_->rice_parameter_search_dist = value;
  103856. #else
  103857. (void)value;
  103858. #endif
  103859. return true;
  103860. }
  103861. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103862. {
  103863. FLAC__ASSERT(0 != encoder);
  103864. FLAC__ASSERT(0 != encoder->private_);
  103865. FLAC__ASSERT(0 != encoder->protected_);
  103866. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103867. return false;
  103868. encoder->protected_->total_samples_estimate = value;
  103869. return true;
  103870. }
  103871. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103872. {
  103873. FLAC__ASSERT(0 != encoder);
  103874. FLAC__ASSERT(0 != encoder->private_);
  103875. FLAC__ASSERT(0 != encoder->protected_);
  103876. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103877. return false;
  103878. if(0 == metadata)
  103879. num_blocks = 0;
  103880. if(0 == num_blocks)
  103881. metadata = 0;
  103882. /* realloc() does not do exactly what we want so... */
  103883. if(encoder->protected_->metadata) {
  103884. free(encoder->protected_->metadata);
  103885. encoder->protected_->metadata = 0;
  103886. encoder->protected_->num_metadata_blocks = 0;
  103887. }
  103888. if(num_blocks) {
  103889. FLAC__StreamMetadata **m;
  103890. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103891. return false;
  103892. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103893. encoder->protected_->metadata = m;
  103894. encoder->protected_->num_metadata_blocks = num_blocks;
  103895. }
  103896. #if FLAC__HAS_OGG
  103897. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103898. return false;
  103899. #endif
  103900. return true;
  103901. }
  103902. /*
  103903. * These three functions are not static, but not publically exposed in
  103904. * include/FLAC/ either. They are used by the test suite.
  103905. */
  103906. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103907. {
  103908. FLAC__ASSERT(0 != encoder);
  103909. FLAC__ASSERT(0 != encoder->private_);
  103910. FLAC__ASSERT(0 != encoder->protected_);
  103911. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103912. return false;
  103913. encoder->private_->disable_constant_subframes = value;
  103914. return true;
  103915. }
  103916. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103917. {
  103918. FLAC__ASSERT(0 != encoder);
  103919. FLAC__ASSERT(0 != encoder->private_);
  103920. FLAC__ASSERT(0 != encoder->protected_);
  103921. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103922. return false;
  103923. encoder->private_->disable_fixed_subframes = value;
  103924. return true;
  103925. }
  103926. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103927. {
  103928. FLAC__ASSERT(0 != encoder);
  103929. FLAC__ASSERT(0 != encoder->private_);
  103930. FLAC__ASSERT(0 != encoder->protected_);
  103931. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103932. return false;
  103933. encoder->private_->disable_verbatim_subframes = value;
  103934. return true;
  103935. }
  103936. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103937. {
  103938. FLAC__ASSERT(0 != encoder);
  103939. FLAC__ASSERT(0 != encoder->private_);
  103940. FLAC__ASSERT(0 != encoder->protected_);
  103941. return encoder->protected_->state;
  103942. }
  103943. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103944. {
  103945. FLAC__ASSERT(0 != encoder);
  103946. FLAC__ASSERT(0 != encoder->private_);
  103947. FLAC__ASSERT(0 != encoder->protected_);
  103948. if(encoder->protected_->verify)
  103949. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103950. else
  103951. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103952. }
  103953. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103954. {
  103955. FLAC__ASSERT(0 != encoder);
  103956. FLAC__ASSERT(0 != encoder->private_);
  103957. FLAC__ASSERT(0 != encoder->protected_);
  103958. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103959. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103960. else
  103961. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103962. }
  103963. 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)
  103964. {
  103965. FLAC__ASSERT(0 != encoder);
  103966. FLAC__ASSERT(0 != encoder->private_);
  103967. FLAC__ASSERT(0 != encoder->protected_);
  103968. if(0 != absolute_sample)
  103969. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103970. if(0 != frame_number)
  103971. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103972. if(0 != channel)
  103973. *channel = encoder->private_->verify.error_stats.channel;
  103974. if(0 != sample)
  103975. *sample = encoder->private_->verify.error_stats.sample;
  103976. if(0 != expected)
  103977. *expected = encoder->private_->verify.error_stats.expected;
  103978. if(0 != got)
  103979. *got = encoder->private_->verify.error_stats.got;
  103980. }
  103981. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103982. {
  103983. FLAC__ASSERT(0 != encoder);
  103984. FLAC__ASSERT(0 != encoder->private_);
  103985. FLAC__ASSERT(0 != encoder->protected_);
  103986. return encoder->protected_->verify;
  103987. }
  103988. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103989. {
  103990. FLAC__ASSERT(0 != encoder);
  103991. FLAC__ASSERT(0 != encoder->private_);
  103992. FLAC__ASSERT(0 != encoder->protected_);
  103993. return encoder->protected_->streamable_subset;
  103994. }
  103995. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103996. {
  103997. FLAC__ASSERT(0 != encoder);
  103998. FLAC__ASSERT(0 != encoder->private_);
  103999. FLAC__ASSERT(0 != encoder->protected_);
  104000. return encoder->protected_->do_md5;
  104001. }
  104002. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104003. {
  104004. FLAC__ASSERT(0 != encoder);
  104005. FLAC__ASSERT(0 != encoder->private_);
  104006. FLAC__ASSERT(0 != encoder->protected_);
  104007. return encoder->protected_->channels;
  104008. }
  104009. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104010. {
  104011. FLAC__ASSERT(0 != encoder);
  104012. FLAC__ASSERT(0 != encoder->private_);
  104013. FLAC__ASSERT(0 != encoder->protected_);
  104014. return encoder->protected_->bits_per_sample;
  104015. }
  104016. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104017. {
  104018. FLAC__ASSERT(0 != encoder);
  104019. FLAC__ASSERT(0 != encoder->private_);
  104020. FLAC__ASSERT(0 != encoder->protected_);
  104021. return encoder->protected_->sample_rate;
  104022. }
  104023. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104024. {
  104025. FLAC__ASSERT(0 != encoder);
  104026. FLAC__ASSERT(0 != encoder->private_);
  104027. FLAC__ASSERT(0 != encoder->protected_);
  104028. return encoder->protected_->blocksize;
  104029. }
  104030. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104031. {
  104032. FLAC__ASSERT(0 != encoder);
  104033. FLAC__ASSERT(0 != encoder->private_);
  104034. FLAC__ASSERT(0 != encoder->protected_);
  104035. return encoder->protected_->do_mid_side_stereo;
  104036. }
  104037. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104038. {
  104039. FLAC__ASSERT(0 != encoder);
  104040. FLAC__ASSERT(0 != encoder->private_);
  104041. FLAC__ASSERT(0 != encoder->protected_);
  104042. return encoder->protected_->loose_mid_side_stereo;
  104043. }
  104044. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104045. {
  104046. FLAC__ASSERT(0 != encoder);
  104047. FLAC__ASSERT(0 != encoder->private_);
  104048. FLAC__ASSERT(0 != encoder->protected_);
  104049. return encoder->protected_->max_lpc_order;
  104050. }
  104051. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104052. {
  104053. FLAC__ASSERT(0 != encoder);
  104054. FLAC__ASSERT(0 != encoder->private_);
  104055. FLAC__ASSERT(0 != encoder->protected_);
  104056. return encoder->protected_->qlp_coeff_precision;
  104057. }
  104058. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104059. {
  104060. FLAC__ASSERT(0 != encoder);
  104061. FLAC__ASSERT(0 != encoder->private_);
  104062. FLAC__ASSERT(0 != encoder->protected_);
  104063. return encoder->protected_->do_qlp_coeff_prec_search;
  104064. }
  104065. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104066. {
  104067. FLAC__ASSERT(0 != encoder);
  104068. FLAC__ASSERT(0 != encoder->private_);
  104069. FLAC__ASSERT(0 != encoder->protected_);
  104070. return encoder->protected_->do_escape_coding;
  104071. }
  104072. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104073. {
  104074. FLAC__ASSERT(0 != encoder);
  104075. FLAC__ASSERT(0 != encoder->private_);
  104076. FLAC__ASSERT(0 != encoder->protected_);
  104077. return encoder->protected_->do_exhaustive_model_search;
  104078. }
  104079. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104080. {
  104081. FLAC__ASSERT(0 != encoder);
  104082. FLAC__ASSERT(0 != encoder->private_);
  104083. FLAC__ASSERT(0 != encoder->protected_);
  104084. return encoder->protected_->min_residual_partition_order;
  104085. }
  104086. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104087. {
  104088. FLAC__ASSERT(0 != encoder);
  104089. FLAC__ASSERT(0 != encoder->private_);
  104090. FLAC__ASSERT(0 != encoder->protected_);
  104091. return encoder->protected_->max_residual_partition_order;
  104092. }
  104093. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104094. {
  104095. FLAC__ASSERT(0 != encoder);
  104096. FLAC__ASSERT(0 != encoder->private_);
  104097. FLAC__ASSERT(0 != encoder->protected_);
  104098. return encoder->protected_->rice_parameter_search_dist;
  104099. }
  104100. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104101. {
  104102. FLAC__ASSERT(0 != encoder);
  104103. FLAC__ASSERT(0 != encoder->private_);
  104104. FLAC__ASSERT(0 != encoder->protected_);
  104105. return encoder->protected_->total_samples_estimate;
  104106. }
  104107. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104108. {
  104109. unsigned i, j = 0, channel;
  104110. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104111. FLAC__ASSERT(0 != encoder);
  104112. FLAC__ASSERT(0 != encoder->private_);
  104113. FLAC__ASSERT(0 != encoder->protected_);
  104114. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104115. do {
  104116. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104117. if(encoder->protected_->verify)
  104118. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104119. for(channel = 0; channel < channels; channel++)
  104120. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104121. if(encoder->protected_->do_mid_side_stereo) {
  104122. FLAC__ASSERT(channels == 2);
  104123. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104124. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104125. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104126. 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' ! */
  104127. }
  104128. }
  104129. else
  104130. j += n;
  104131. encoder->private_->current_sample_number += n;
  104132. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104133. if(encoder->private_->current_sample_number > blocksize) {
  104134. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104135. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104136. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104137. return false;
  104138. /* move unprocessed overread samples to beginnings of arrays */
  104139. for(channel = 0; channel < channels; channel++)
  104140. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104141. if(encoder->protected_->do_mid_side_stereo) {
  104142. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104143. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104144. }
  104145. encoder->private_->current_sample_number = 1;
  104146. }
  104147. } while(j < samples);
  104148. return true;
  104149. }
  104150. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104151. {
  104152. unsigned i, j, k, channel;
  104153. FLAC__int32 x, mid, side;
  104154. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104155. FLAC__ASSERT(0 != encoder);
  104156. FLAC__ASSERT(0 != encoder->private_);
  104157. FLAC__ASSERT(0 != encoder->protected_);
  104158. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104159. j = k = 0;
  104160. /*
  104161. * we have several flavors of the same basic loop, optimized for
  104162. * different conditions:
  104163. */
  104164. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104165. /*
  104166. * stereo coding: unroll channel loop
  104167. */
  104168. do {
  104169. if(encoder->protected_->verify)
  104170. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104171. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104172. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104173. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104174. x = buffer[k++];
  104175. encoder->private_->integer_signal[1][i] = x;
  104176. mid += x;
  104177. side -= x;
  104178. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104179. encoder->private_->integer_signal_mid_side[1][i] = side;
  104180. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104181. }
  104182. encoder->private_->current_sample_number = i;
  104183. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104184. if(i > blocksize) {
  104185. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104186. return false;
  104187. /* move unprocessed overread samples to beginnings of arrays */
  104188. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104189. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104190. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104191. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104192. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104193. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104194. encoder->private_->current_sample_number = 1;
  104195. }
  104196. } while(j < samples);
  104197. }
  104198. else {
  104199. /*
  104200. * independent channel coding: buffer each channel in inner loop
  104201. */
  104202. do {
  104203. if(encoder->protected_->verify)
  104204. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104205. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104206. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104207. for(channel = 0; channel < channels; channel++)
  104208. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104209. }
  104210. encoder->private_->current_sample_number = i;
  104211. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104212. if(i > blocksize) {
  104213. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104214. return false;
  104215. /* move unprocessed overread samples to beginnings of arrays */
  104216. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104217. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104218. for(channel = 0; channel < channels; channel++)
  104219. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104220. encoder->private_->current_sample_number = 1;
  104221. }
  104222. } while(j < samples);
  104223. }
  104224. return true;
  104225. }
  104226. /***********************************************************************
  104227. *
  104228. * Private class methods
  104229. *
  104230. ***********************************************************************/
  104231. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104232. {
  104233. FLAC__ASSERT(0 != encoder);
  104234. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104235. encoder->protected_->verify = true;
  104236. #else
  104237. encoder->protected_->verify = false;
  104238. #endif
  104239. encoder->protected_->streamable_subset = true;
  104240. encoder->protected_->do_md5 = true;
  104241. encoder->protected_->do_mid_side_stereo = false;
  104242. encoder->protected_->loose_mid_side_stereo = false;
  104243. encoder->protected_->channels = 2;
  104244. encoder->protected_->bits_per_sample = 16;
  104245. encoder->protected_->sample_rate = 44100;
  104246. encoder->protected_->blocksize = 0;
  104247. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104248. encoder->protected_->num_apodizations = 1;
  104249. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104250. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104251. #endif
  104252. encoder->protected_->max_lpc_order = 0;
  104253. encoder->protected_->qlp_coeff_precision = 0;
  104254. encoder->protected_->do_qlp_coeff_prec_search = false;
  104255. encoder->protected_->do_exhaustive_model_search = false;
  104256. encoder->protected_->do_escape_coding = false;
  104257. encoder->protected_->min_residual_partition_order = 0;
  104258. encoder->protected_->max_residual_partition_order = 0;
  104259. encoder->protected_->rice_parameter_search_dist = 0;
  104260. encoder->protected_->total_samples_estimate = 0;
  104261. encoder->protected_->metadata = 0;
  104262. encoder->protected_->num_metadata_blocks = 0;
  104263. encoder->private_->seek_table = 0;
  104264. encoder->private_->disable_constant_subframes = false;
  104265. encoder->private_->disable_fixed_subframes = false;
  104266. encoder->private_->disable_verbatim_subframes = false;
  104267. #if FLAC__HAS_OGG
  104268. encoder->private_->is_ogg = false;
  104269. #endif
  104270. encoder->private_->read_callback = 0;
  104271. encoder->private_->write_callback = 0;
  104272. encoder->private_->seek_callback = 0;
  104273. encoder->private_->tell_callback = 0;
  104274. encoder->private_->metadata_callback = 0;
  104275. encoder->private_->progress_callback = 0;
  104276. encoder->private_->client_data = 0;
  104277. #if FLAC__HAS_OGG
  104278. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104279. #endif
  104280. }
  104281. void free_(FLAC__StreamEncoder *encoder)
  104282. {
  104283. unsigned i, channel;
  104284. FLAC__ASSERT(0 != encoder);
  104285. if(encoder->protected_->metadata) {
  104286. free(encoder->protected_->metadata);
  104287. encoder->protected_->metadata = 0;
  104288. encoder->protected_->num_metadata_blocks = 0;
  104289. }
  104290. for(i = 0; i < encoder->protected_->channels; i++) {
  104291. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104292. free(encoder->private_->integer_signal_unaligned[i]);
  104293. encoder->private_->integer_signal_unaligned[i] = 0;
  104294. }
  104295. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104296. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104297. free(encoder->private_->real_signal_unaligned[i]);
  104298. encoder->private_->real_signal_unaligned[i] = 0;
  104299. }
  104300. #endif
  104301. }
  104302. for(i = 0; i < 2; i++) {
  104303. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104304. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104305. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104306. }
  104307. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104308. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104309. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104310. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104311. }
  104312. #endif
  104313. }
  104314. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104315. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104316. if(0 != encoder->private_->window_unaligned[i]) {
  104317. free(encoder->private_->window_unaligned[i]);
  104318. encoder->private_->window_unaligned[i] = 0;
  104319. }
  104320. }
  104321. if(0 != encoder->private_->windowed_signal_unaligned) {
  104322. free(encoder->private_->windowed_signal_unaligned);
  104323. encoder->private_->windowed_signal_unaligned = 0;
  104324. }
  104325. #endif
  104326. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104327. for(i = 0; i < 2; i++) {
  104328. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104329. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104330. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104331. }
  104332. }
  104333. }
  104334. for(channel = 0; channel < 2; channel++) {
  104335. for(i = 0; i < 2; i++) {
  104336. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104337. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104338. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104339. }
  104340. }
  104341. }
  104342. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104343. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104344. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104345. }
  104346. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104347. free(encoder->private_->raw_bits_per_partition_unaligned);
  104348. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104349. }
  104350. if(encoder->protected_->verify) {
  104351. for(i = 0; i < encoder->protected_->channels; i++) {
  104352. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104353. free(encoder->private_->verify.input_fifo.data[i]);
  104354. encoder->private_->verify.input_fifo.data[i] = 0;
  104355. }
  104356. }
  104357. }
  104358. FLAC__bitwriter_free(encoder->private_->frame);
  104359. }
  104360. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104361. {
  104362. FLAC__bool ok;
  104363. unsigned i, channel;
  104364. FLAC__ASSERT(new_blocksize > 0);
  104365. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104366. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104367. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104368. if(new_blocksize <= encoder->private_->input_capacity)
  104369. return true;
  104370. ok = true;
  104371. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104372. * requires that the input arrays (in our case the integer signals)
  104373. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104374. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104375. */
  104376. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104377. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104378. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104379. encoder->private_->integer_signal[i] += 4;
  104380. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104381. #if 0 /* @@@ currently unused */
  104382. if(encoder->protected_->max_lpc_order > 0)
  104383. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104384. #endif
  104385. #endif
  104386. }
  104387. for(i = 0; ok && i < 2; i++) {
  104388. 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]);
  104389. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104390. encoder->private_->integer_signal_mid_side[i] += 4;
  104391. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104392. #if 0 /* @@@ currently unused */
  104393. if(encoder->protected_->max_lpc_order > 0)
  104394. 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]);
  104395. #endif
  104396. #endif
  104397. }
  104398. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104399. if(ok && encoder->protected_->max_lpc_order > 0) {
  104400. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104401. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104402. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104403. }
  104404. #endif
  104405. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104406. for(i = 0; ok && i < 2; i++) {
  104407. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104408. }
  104409. }
  104410. for(channel = 0; ok && channel < 2; channel++) {
  104411. for(i = 0; ok && i < 2; i++) {
  104412. 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]);
  104413. }
  104414. }
  104415. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104416. /*@@@ 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) */
  104417. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104418. if(encoder->protected_->do_escape_coding)
  104419. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104420. /* now adjust the windows if the blocksize has changed */
  104421. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104422. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104423. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104424. switch(encoder->protected_->apodizations[i].type) {
  104425. case FLAC__APODIZATION_BARTLETT:
  104426. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104427. break;
  104428. case FLAC__APODIZATION_BARTLETT_HANN:
  104429. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104430. break;
  104431. case FLAC__APODIZATION_BLACKMAN:
  104432. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104433. break;
  104434. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104435. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104436. break;
  104437. case FLAC__APODIZATION_CONNES:
  104438. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104439. break;
  104440. case FLAC__APODIZATION_FLATTOP:
  104441. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104442. break;
  104443. case FLAC__APODIZATION_GAUSS:
  104444. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104445. break;
  104446. case FLAC__APODIZATION_HAMMING:
  104447. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104448. break;
  104449. case FLAC__APODIZATION_HANN:
  104450. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104451. break;
  104452. case FLAC__APODIZATION_KAISER_BESSEL:
  104453. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104454. break;
  104455. case FLAC__APODIZATION_NUTTALL:
  104456. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104457. break;
  104458. case FLAC__APODIZATION_RECTANGLE:
  104459. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104460. break;
  104461. case FLAC__APODIZATION_TRIANGLE:
  104462. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104463. break;
  104464. case FLAC__APODIZATION_TUKEY:
  104465. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104466. break;
  104467. case FLAC__APODIZATION_WELCH:
  104468. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104469. break;
  104470. default:
  104471. FLAC__ASSERT(0);
  104472. /* double protection */
  104473. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104474. break;
  104475. }
  104476. }
  104477. }
  104478. #endif
  104479. if(ok)
  104480. encoder->private_->input_capacity = new_blocksize;
  104481. else
  104482. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104483. return ok;
  104484. }
  104485. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104486. {
  104487. const FLAC__byte *buffer;
  104488. size_t bytes;
  104489. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104490. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104491. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104492. return false;
  104493. }
  104494. if(encoder->protected_->verify) {
  104495. encoder->private_->verify.output.data = buffer;
  104496. encoder->private_->verify.output.bytes = bytes;
  104497. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104498. encoder->private_->verify.needs_magic_hack = true;
  104499. }
  104500. else {
  104501. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104502. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104503. FLAC__bitwriter_clear(encoder->private_->frame);
  104504. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104505. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104506. return false;
  104507. }
  104508. }
  104509. }
  104510. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104511. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104512. FLAC__bitwriter_clear(encoder->private_->frame);
  104513. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104514. return false;
  104515. }
  104516. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104517. FLAC__bitwriter_clear(encoder->private_->frame);
  104518. if(samples > 0) {
  104519. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104520. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104521. }
  104522. return true;
  104523. }
  104524. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104525. {
  104526. FLAC__StreamEncoderWriteStatus status;
  104527. FLAC__uint64 output_position = 0;
  104528. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104529. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104530. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104531. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104532. }
  104533. /*
  104534. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104535. */
  104536. if(samples == 0) {
  104537. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104538. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104539. encoder->protected_->streaminfo_offset = output_position;
  104540. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104541. encoder->protected_->seektable_offset = output_position;
  104542. }
  104543. /*
  104544. * Mark the current seek point if hit (if audio_offset == 0 that
  104545. * means we're still writing metadata and haven't hit the first
  104546. * frame yet)
  104547. */
  104548. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104549. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104550. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104551. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104552. FLAC__uint64 test_sample;
  104553. unsigned i;
  104554. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104555. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104556. if(test_sample > frame_last_sample) {
  104557. break;
  104558. }
  104559. else if(test_sample >= frame_first_sample) {
  104560. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104561. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104562. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104563. encoder->private_->first_seekpoint_to_check++;
  104564. /* DO NOT: "break;" and here's why:
  104565. * The seektable template may contain more than one target
  104566. * sample for any given frame; we will keep looping, generating
  104567. * duplicate seekpoints for them, and we'll clean it up later,
  104568. * just before writing the seektable back to the metadata.
  104569. */
  104570. }
  104571. else {
  104572. encoder->private_->first_seekpoint_to_check++;
  104573. }
  104574. }
  104575. }
  104576. #if FLAC__HAS_OGG
  104577. if(encoder->private_->is_ogg) {
  104578. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104579. &encoder->protected_->ogg_encoder_aspect,
  104580. buffer,
  104581. bytes,
  104582. samples,
  104583. encoder->private_->current_frame_number,
  104584. is_last_block,
  104585. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104586. encoder,
  104587. encoder->private_->client_data
  104588. );
  104589. }
  104590. else
  104591. #endif
  104592. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104593. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104594. encoder->private_->bytes_written += bytes;
  104595. encoder->private_->samples_written += samples;
  104596. /* we keep a high watermark on the number of frames written because
  104597. * when the encoder goes back to write metadata, 'current_frame'
  104598. * will drop back to 0.
  104599. */
  104600. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104601. }
  104602. else
  104603. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104604. return status;
  104605. }
  104606. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104607. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104608. {
  104609. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104610. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104611. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104612. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104613. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104614. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104615. FLAC__StreamEncoderSeekStatus seek_status;
  104616. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104617. /* All this is based on intimate knowledge of the stream header
  104618. * layout, but a change to the header format that would break this
  104619. * would also break all streams encoded in the previous format.
  104620. */
  104621. /*
  104622. * Write MD5 signature
  104623. */
  104624. {
  104625. const unsigned md5_offset =
  104626. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104627. (
  104628. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104629. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104630. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104631. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104632. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104633. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104634. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104635. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104636. ) / 8;
  104637. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104638. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104639. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104640. return;
  104641. }
  104642. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104643. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104644. return;
  104645. }
  104646. }
  104647. /*
  104648. * Write total samples
  104649. */
  104650. {
  104651. const unsigned total_samples_byte_offset =
  104652. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104653. (
  104654. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104655. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104656. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104657. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104658. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104659. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104660. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104661. - 4
  104662. ) / 8;
  104663. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104664. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104665. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104666. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104667. b[4] = (FLAC__byte)(samples & 0xFF);
  104668. 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) {
  104669. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104670. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104671. return;
  104672. }
  104673. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104674. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104675. return;
  104676. }
  104677. }
  104678. /*
  104679. * Write min/max framesize
  104680. */
  104681. {
  104682. const unsigned min_framesize_offset =
  104683. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104684. (
  104685. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104686. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104687. ) / 8;
  104688. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104689. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104690. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104691. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104692. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104693. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104694. 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) {
  104695. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104696. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104697. return;
  104698. }
  104699. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104700. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104701. return;
  104702. }
  104703. }
  104704. /*
  104705. * Write seektable
  104706. */
  104707. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104708. unsigned i;
  104709. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104710. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104711. 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) {
  104712. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104713. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104714. return;
  104715. }
  104716. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104717. FLAC__uint64 xx;
  104718. unsigned x;
  104719. xx = encoder->private_->seek_table->points[i].sample_number;
  104720. b[7] = (FLAC__byte)xx; xx >>= 8;
  104721. b[6] = (FLAC__byte)xx; xx >>= 8;
  104722. b[5] = (FLAC__byte)xx; xx >>= 8;
  104723. b[4] = (FLAC__byte)xx; xx >>= 8;
  104724. b[3] = (FLAC__byte)xx; xx >>= 8;
  104725. b[2] = (FLAC__byte)xx; xx >>= 8;
  104726. b[1] = (FLAC__byte)xx; xx >>= 8;
  104727. b[0] = (FLAC__byte)xx; xx >>= 8;
  104728. xx = encoder->private_->seek_table->points[i].stream_offset;
  104729. b[15] = (FLAC__byte)xx; xx >>= 8;
  104730. b[14] = (FLAC__byte)xx; xx >>= 8;
  104731. b[13] = (FLAC__byte)xx; xx >>= 8;
  104732. b[12] = (FLAC__byte)xx; xx >>= 8;
  104733. b[11] = (FLAC__byte)xx; xx >>= 8;
  104734. b[10] = (FLAC__byte)xx; xx >>= 8;
  104735. b[9] = (FLAC__byte)xx; xx >>= 8;
  104736. b[8] = (FLAC__byte)xx; xx >>= 8;
  104737. x = encoder->private_->seek_table->points[i].frame_samples;
  104738. b[17] = (FLAC__byte)x; x >>= 8;
  104739. b[16] = (FLAC__byte)x; x >>= 8;
  104740. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104741. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104742. return;
  104743. }
  104744. }
  104745. }
  104746. }
  104747. #if FLAC__HAS_OGG
  104748. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104749. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104750. {
  104751. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104752. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104753. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104754. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104755. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104756. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104757. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104758. FLAC__STREAM_SYNC_LENGTH
  104759. ;
  104760. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104761. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104762. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104763. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104764. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104765. ogg_page page;
  104766. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104767. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104768. /* Pre-check that client supports seeking, since we don't want the
  104769. * ogg_helper code to ever have to deal with this condition.
  104770. */
  104771. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104772. return;
  104773. /* All this is based on intimate knowledge of the stream header
  104774. * layout, but a change to the header format that would break this
  104775. * would also break all streams encoded in the previous format.
  104776. */
  104777. /**
  104778. ** Write STREAMINFO stats
  104779. **/
  104780. simple_ogg_page__init(&page);
  104781. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104782. simple_ogg_page__clear(&page);
  104783. return; /* state already set */
  104784. }
  104785. /*
  104786. * Write MD5 signature
  104787. */
  104788. {
  104789. const unsigned md5_offset =
  104790. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104791. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104792. (
  104793. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104794. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104795. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104796. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104797. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104798. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104799. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104800. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104801. ) / 8;
  104802. if(md5_offset + 16 > (unsigned)page.body_len) {
  104803. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104804. simple_ogg_page__clear(&page);
  104805. return;
  104806. }
  104807. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104808. }
  104809. /*
  104810. * Write total samples
  104811. */
  104812. {
  104813. const unsigned total_samples_byte_offset =
  104814. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104815. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104816. (
  104817. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104818. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104819. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104820. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104821. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104822. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104823. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104824. - 4
  104825. ) / 8;
  104826. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104827. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104828. simple_ogg_page__clear(&page);
  104829. return;
  104830. }
  104831. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104832. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104833. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104834. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104835. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104836. b[4] = (FLAC__byte)(samples & 0xFF);
  104837. memcpy(page.body + total_samples_byte_offset, b, 5);
  104838. }
  104839. /*
  104840. * Write min/max framesize
  104841. */
  104842. {
  104843. const unsigned min_framesize_offset =
  104844. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104845. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104846. (
  104847. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104848. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104849. ) / 8;
  104850. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104851. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104852. simple_ogg_page__clear(&page);
  104853. return;
  104854. }
  104855. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104856. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104857. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104858. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104859. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104860. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104861. memcpy(page.body + min_framesize_offset, b, 6);
  104862. }
  104863. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104864. simple_ogg_page__clear(&page);
  104865. return; /* state already set */
  104866. }
  104867. simple_ogg_page__clear(&page);
  104868. /*
  104869. * Write seektable
  104870. */
  104871. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104872. unsigned i;
  104873. FLAC__byte *p;
  104874. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104875. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104876. simple_ogg_page__init(&page);
  104877. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104878. simple_ogg_page__clear(&page);
  104879. return; /* state already set */
  104880. }
  104881. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104882. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104883. simple_ogg_page__clear(&page);
  104884. return;
  104885. }
  104886. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104887. FLAC__uint64 xx;
  104888. unsigned x;
  104889. xx = encoder->private_->seek_table->points[i].sample_number;
  104890. b[7] = (FLAC__byte)xx; xx >>= 8;
  104891. b[6] = (FLAC__byte)xx; xx >>= 8;
  104892. b[5] = (FLAC__byte)xx; xx >>= 8;
  104893. b[4] = (FLAC__byte)xx; xx >>= 8;
  104894. b[3] = (FLAC__byte)xx; xx >>= 8;
  104895. b[2] = (FLAC__byte)xx; xx >>= 8;
  104896. b[1] = (FLAC__byte)xx; xx >>= 8;
  104897. b[0] = (FLAC__byte)xx; xx >>= 8;
  104898. xx = encoder->private_->seek_table->points[i].stream_offset;
  104899. b[15] = (FLAC__byte)xx; xx >>= 8;
  104900. b[14] = (FLAC__byte)xx; xx >>= 8;
  104901. b[13] = (FLAC__byte)xx; xx >>= 8;
  104902. b[12] = (FLAC__byte)xx; xx >>= 8;
  104903. b[11] = (FLAC__byte)xx; xx >>= 8;
  104904. b[10] = (FLAC__byte)xx; xx >>= 8;
  104905. b[9] = (FLAC__byte)xx; xx >>= 8;
  104906. b[8] = (FLAC__byte)xx; xx >>= 8;
  104907. x = encoder->private_->seek_table->points[i].frame_samples;
  104908. b[17] = (FLAC__byte)x; x >>= 8;
  104909. b[16] = (FLAC__byte)x; x >>= 8;
  104910. memcpy(p, b, 18);
  104911. }
  104912. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104913. simple_ogg_page__clear(&page);
  104914. return; /* state already set */
  104915. }
  104916. simple_ogg_page__clear(&page);
  104917. }
  104918. }
  104919. #endif
  104920. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104921. {
  104922. FLAC__uint16 crc;
  104923. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104924. /*
  104925. * Accumulate raw signal to the MD5 signature
  104926. */
  104927. 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)) {
  104928. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104929. return false;
  104930. }
  104931. /*
  104932. * Process the frame header and subframes into the frame bitbuffer
  104933. */
  104934. if(!process_subframes_(encoder, is_fractional_block)) {
  104935. /* the above function sets the state for us in case of an error */
  104936. return false;
  104937. }
  104938. /*
  104939. * Zero-pad the frame to a byte_boundary
  104940. */
  104941. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104942. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104943. return false;
  104944. }
  104945. /*
  104946. * CRC-16 the whole thing
  104947. */
  104948. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104949. if(
  104950. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104951. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104952. ) {
  104953. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104954. return false;
  104955. }
  104956. /*
  104957. * Write it
  104958. */
  104959. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104960. /* the above function sets the state for us in case of an error */
  104961. return false;
  104962. }
  104963. /*
  104964. * Get ready for the next frame
  104965. */
  104966. encoder->private_->current_sample_number = 0;
  104967. encoder->private_->current_frame_number++;
  104968. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104969. return true;
  104970. }
  104971. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104972. {
  104973. FLAC__FrameHeader frame_header;
  104974. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104975. FLAC__bool do_independent, do_mid_side;
  104976. /*
  104977. * Calculate the min,max Rice partition orders
  104978. */
  104979. if(is_fractional_block) {
  104980. max_partition_order = 0;
  104981. }
  104982. else {
  104983. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104984. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104985. }
  104986. min_partition_order = min(min_partition_order, max_partition_order);
  104987. /*
  104988. * Setup the frame
  104989. */
  104990. frame_header.blocksize = encoder->protected_->blocksize;
  104991. frame_header.sample_rate = encoder->protected_->sample_rate;
  104992. frame_header.channels = encoder->protected_->channels;
  104993. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104994. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104995. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104996. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104997. /*
  104998. * Figure out what channel assignments to try
  104999. */
  105000. if(encoder->protected_->do_mid_side_stereo) {
  105001. if(encoder->protected_->loose_mid_side_stereo) {
  105002. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105003. do_independent = true;
  105004. do_mid_side = true;
  105005. }
  105006. else {
  105007. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105008. do_mid_side = !do_independent;
  105009. }
  105010. }
  105011. else {
  105012. do_independent = true;
  105013. do_mid_side = true;
  105014. }
  105015. }
  105016. else {
  105017. do_independent = true;
  105018. do_mid_side = false;
  105019. }
  105020. FLAC__ASSERT(do_independent || do_mid_side);
  105021. /*
  105022. * Check for wasted bits; set effective bps for each subframe
  105023. */
  105024. if(do_independent) {
  105025. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105026. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105027. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105028. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105029. }
  105030. }
  105031. if(do_mid_side) {
  105032. FLAC__ASSERT(encoder->protected_->channels == 2);
  105033. for(channel = 0; channel < 2; channel++) {
  105034. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105035. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105036. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105037. }
  105038. }
  105039. /*
  105040. * First do a normal encoding pass of each independent channel
  105041. */
  105042. if(do_independent) {
  105043. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105044. if(!
  105045. process_subframe_(
  105046. encoder,
  105047. min_partition_order,
  105048. max_partition_order,
  105049. &frame_header,
  105050. encoder->private_->subframe_bps[channel],
  105051. encoder->private_->integer_signal[channel],
  105052. encoder->private_->subframe_workspace_ptr[channel],
  105053. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105054. encoder->private_->residual_workspace[channel],
  105055. encoder->private_->best_subframe+channel,
  105056. encoder->private_->best_subframe_bits+channel
  105057. )
  105058. )
  105059. return false;
  105060. }
  105061. }
  105062. /*
  105063. * Now do mid and side channels if requested
  105064. */
  105065. if(do_mid_side) {
  105066. FLAC__ASSERT(encoder->protected_->channels == 2);
  105067. for(channel = 0; channel < 2; channel++) {
  105068. if(!
  105069. process_subframe_(
  105070. encoder,
  105071. min_partition_order,
  105072. max_partition_order,
  105073. &frame_header,
  105074. encoder->private_->subframe_bps_mid_side[channel],
  105075. encoder->private_->integer_signal_mid_side[channel],
  105076. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105077. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105078. encoder->private_->residual_workspace_mid_side[channel],
  105079. encoder->private_->best_subframe_mid_side+channel,
  105080. encoder->private_->best_subframe_bits_mid_side+channel
  105081. )
  105082. )
  105083. return false;
  105084. }
  105085. }
  105086. /*
  105087. * Compose the frame bitbuffer
  105088. */
  105089. if(do_mid_side) {
  105090. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105091. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105092. FLAC__ChannelAssignment channel_assignment;
  105093. FLAC__ASSERT(encoder->protected_->channels == 2);
  105094. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105095. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105096. }
  105097. else {
  105098. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105099. unsigned min_bits;
  105100. int ca;
  105101. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105102. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105103. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105104. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105105. FLAC__ASSERT(do_independent && do_mid_side);
  105106. /* We have to figure out which channel assignent results in the smallest frame */
  105107. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105108. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105109. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105110. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105111. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105112. min_bits = bits[channel_assignment];
  105113. for(ca = 1; ca <= 3; ca++) {
  105114. if(bits[ca] < min_bits) {
  105115. min_bits = bits[ca];
  105116. channel_assignment = (FLAC__ChannelAssignment)ca;
  105117. }
  105118. }
  105119. }
  105120. frame_header.channel_assignment = channel_assignment;
  105121. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105122. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105123. return false;
  105124. }
  105125. switch(channel_assignment) {
  105126. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105127. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105128. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105129. break;
  105130. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105131. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105132. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105133. break;
  105134. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105135. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105136. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105137. break;
  105138. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105139. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105140. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105141. break;
  105142. default:
  105143. FLAC__ASSERT(0);
  105144. }
  105145. switch(channel_assignment) {
  105146. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105147. left_bps = encoder->private_->subframe_bps [0];
  105148. right_bps = encoder->private_->subframe_bps [1];
  105149. break;
  105150. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105151. left_bps = encoder->private_->subframe_bps [0];
  105152. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105153. break;
  105154. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105155. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105156. right_bps = encoder->private_->subframe_bps [1];
  105157. break;
  105158. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105159. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105160. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105161. break;
  105162. default:
  105163. FLAC__ASSERT(0);
  105164. }
  105165. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105166. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105167. return false;
  105168. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105169. return false;
  105170. }
  105171. else {
  105172. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105173. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105174. return false;
  105175. }
  105176. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105177. 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)) {
  105178. /* the above function sets the state for us in case of an error */
  105179. return false;
  105180. }
  105181. }
  105182. }
  105183. if(encoder->protected_->loose_mid_side_stereo) {
  105184. encoder->private_->loose_mid_side_stereo_frame_count++;
  105185. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105186. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105187. }
  105188. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105189. return true;
  105190. }
  105191. FLAC__bool process_subframe_(
  105192. FLAC__StreamEncoder *encoder,
  105193. unsigned min_partition_order,
  105194. unsigned max_partition_order,
  105195. const FLAC__FrameHeader *frame_header,
  105196. unsigned subframe_bps,
  105197. const FLAC__int32 integer_signal[],
  105198. FLAC__Subframe *subframe[2],
  105199. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105200. FLAC__int32 *residual[2],
  105201. unsigned *best_subframe,
  105202. unsigned *best_bits
  105203. )
  105204. {
  105205. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105206. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105207. #else
  105208. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105209. #endif
  105210. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105211. FLAC__double lpc_residual_bits_per_sample;
  105212. 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 */
  105213. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105214. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105215. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105216. #endif
  105217. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105218. unsigned rice_parameter;
  105219. unsigned _candidate_bits, _best_bits;
  105220. unsigned _best_subframe;
  105221. /* only use RICE2 partitions if stream bps > 16 */
  105222. 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;
  105223. FLAC__ASSERT(frame_header->blocksize > 0);
  105224. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105225. _best_subframe = 0;
  105226. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105227. _best_bits = UINT_MAX;
  105228. else
  105229. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105230. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105231. unsigned signal_is_constant = false;
  105232. 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);
  105233. /* check for constant subframe */
  105234. if(
  105235. !encoder->private_->disable_constant_subframes &&
  105236. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105237. fixed_residual_bits_per_sample[1] == 0.0
  105238. #else
  105239. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105240. #endif
  105241. ) {
  105242. /* the above means it's possible all samples are the same value; now double-check it: */
  105243. unsigned i;
  105244. signal_is_constant = true;
  105245. for(i = 1; i < frame_header->blocksize; i++) {
  105246. if(integer_signal[0] != integer_signal[i]) {
  105247. signal_is_constant = false;
  105248. break;
  105249. }
  105250. }
  105251. }
  105252. if(signal_is_constant) {
  105253. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105254. if(_candidate_bits < _best_bits) {
  105255. _best_subframe = !_best_subframe;
  105256. _best_bits = _candidate_bits;
  105257. }
  105258. }
  105259. else {
  105260. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105261. /* encode fixed */
  105262. if(encoder->protected_->do_exhaustive_model_search) {
  105263. min_fixed_order = 0;
  105264. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105265. }
  105266. else {
  105267. min_fixed_order = max_fixed_order = guess_fixed_order;
  105268. }
  105269. if(max_fixed_order >= frame_header->blocksize)
  105270. max_fixed_order = frame_header->blocksize - 1;
  105271. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105272. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105273. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105274. continue; /* don't even try */
  105275. 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 */
  105276. #else
  105277. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105278. continue; /* don't even try */
  105279. 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 */
  105280. #endif
  105281. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105282. if(rice_parameter >= rice_parameter_limit) {
  105283. #ifdef DEBUG_VERBOSE
  105284. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105285. #endif
  105286. rice_parameter = rice_parameter_limit - 1;
  105287. }
  105288. _candidate_bits =
  105289. evaluate_fixed_subframe_(
  105290. encoder,
  105291. integer_signal,
  105292. residual[!_best_subframe],
  105293. encoder->private_->abs_residual_partition_sums,
  105294. encoder->private_->raw_bits_per_partition,
  105295. frame_header->blocksize,
  105296. subframe_bps,
  105297. fixed_order,
  105298. rice_parameter,
  105299. rice_parameter_limit,
  105300. min_partition_order,
  105301. max_partition_order,
  105302. encoder->protected_->do_escape_coding,
  105303. encoder->protected_->rice_parameter_search_dist,
  105304. subframe[!_best_subframe],
  105305. partitioned_rice_contents[!_best_subframe]
  105306. );
  105307. if(_candidate_bits < _best_bits) {
  105308. _best_subframe = !_best_subframe;
  105309. _best_bits = _candidate_bits;
  105310. }
  105311. }
  105312. }
  105313. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105314. /* encode lpc */
  105315. if(encoder->protected_->max_lpc_order > 0) {
  105316. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105317. max_lpc_order = frame_header->blocksize-1;
  105318. else
  105319. max_lpc_order = encoder->protected_->max_lpc_order;
  105320. if(max_lpc_order > 0) {
  105321. unsigned a;
  105322. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105323. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105324. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105325. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105326. if(autoc[0] != 0.0) {
  105327. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105328. if(encoder->protected_->do_exhaustive_model_search) {
  105329. min_lpc_order = 1;
  105330. }
  105331. else {
  105332. const unsigned guess_lpc_order =
  105333. FLAC__lpc_compute_best_order(
  105334. lpc_error,
  105335. max_lpc_order,
  105336. frame_header->blocksize,
  105337. subframe_bps + (
  105338. encoder->protected_->do_qlp_coeff_prec_search?
  105339. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105340. encoder->protected_->qlp_coeff_precision
  105341. )
  105342. );
  105343. min_lpc_order = max_lpc_order = guess_lpc_order;
  105344. }
  105345. if(max_lpc_order >= frame_header->blocksize)
  105346. max_lpc_order = frame_header->blocksize - 1;
  105347. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105348. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105349. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105350. continue; /* don't even try */
  105351. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105352. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105353. if(rice_parameter >= rice_parameter_limit) {
  105354. #ifdef DEBUG_VERBOSE
  105355. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105356. #endif
  105357. rice_parameter = rice_parameter_limit - 1;
  105358. }
  105359. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105360. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105361. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105362. if(subframe_bps <= 17) {
  105363. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105364. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105365. }
  105366. else
  105367. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105368. }
  105369. else {
  105370. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105371. }
  105372. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105373. _candidate_bits =
  105374. evaluate_lpc_subframe_(
  105375. encoder,
  105376. integer_signal,
  105377. residual[!_best_subframe],
  105378. encoder->private_->abs_residual_partition_sums,
  105379. encoder->private_->raw_bits_per_partition,
  105380. encoder->private_->lp_coeff[lpc_order-1],
  105381. frame_header->blocksize,
  105382. subframe_bps,
  105383. lpc_order,
  105384. qlp_coeff_precision,
  105385. rice_parameter,
  105386. rice_parameter_limit,
  105387. min_partition_order,
  105388. max_partition_order,
  105389. encoder->protected_->do_escape_coding,
  105390. encoder->protected_->rice_parameter_search_dist,
  105391. subframe[!_best_subframe],
  105392. partitioned_rice_contents[!_best_subframe]
  105393. );
  105394. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105395. if(_candidate_bits < _best_bits) {
  105396. _best_subframe = !_best_subframe;
  105397. _best_bits = _candidate_bits;
  105398. }
  105399. }
  105400. }
  105401. }
  105402. }
  105403. }
  105404. }
  105405. }
  105406. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105407. }
  105408. }
  105409. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105410. if(_best_bits == UINT_MAX) {
  105411. FLAC__ASSERT(_best_subframe == 0);
  105412. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105413. }
  105414. *best_subframe = _best_subframe;
  105415. *best_bits = _best_bits;
  105416. return true;
  105417. }
  105418. FLAC__bool add_subframe_(
  105419. FLAC__StreamEncoder *encoder,
  105420. unsigned blocksize,
  105421. unsigned subframe_bps,
  105422. const FLAC__Subframe *subframe,
  105423. FLAC__BitWriter *frame
  105424. )
  105425. {
  105426. switch(subframe->type) {
  105427. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105428. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105429. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105430. return false;
  105431. }
  105432. break;
  105433. case FLAC__SUBFRAME_TYPE_FIXED:
  105434. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105435. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105436. return false;
  105437. }
  105438. break;
  105439. case FLAC__SUBFRAME_TYPE_LPC:
  105440. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105441. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105442. return false;
  105443. }
  105444. break;
  105445. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105446. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105447. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105448. return false;
  105449. }
  105450. break;
  105451. default:
  105452. FLAC__ASSERT(0);
  105453. }
  105454. return true;
  105455. }
  105456. #define SPOTCHECK_ESTIMATE 0
  105457. #if SPOTCHECK_ESTIMATE
  105458. static void spotcheck_subframe_estimate_(
  105459. FLAC__StreamEncoder *encoder,
  105460. unsigned blocksize,
  105461. unsigned subframe_bps,
  105462. const FLAC__Subframe *subframe,
  105463. unsigned estimate
  105464. )
  105465. {
  105466. FLAC__bool ret;
  105467. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105468. if(frame == 0) {
  105469. fprintf(stderr, "EST: can't allocate frame\n");
  105470. return;
  105471. }
  105472. if(!FLAC__bitwriter_init(frame)) {
  105473. fprintf(stderr, "EST: can't init frame\n");
  105474. return;
  105475. }
  105476. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105477. FLAC__ASSERT(ret);
  105478. {
  105479. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105480. if(estimate != actual)
  105481. 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);
  105482. }
  105483. FLAC__bitwriter_delete(frame);
  105484. }
  105485. #endif
  105486. unsigned evaluate_constant_subframe_(
  105487. FLAC__StreamEncoder *encoder,
  105488. const FLAC__int32 signal,
  105489. unsigned blocksize,
  105490. unsigned subframe_bps,
  105491. FLAC__Subframe *subframe
  105492. )
  105493. {
  105494. unsigned estimate;
  105495. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105496. subframe->data.constant.value = signal;
  105497. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105498. #if SPOTCHECK_ESTIMATE
  105499. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105500. #else
  105501. (void)encoder, (void)blocksize;
  105502. #endif
  105503. return estimate;
  105504. }
  105505. unsigned evaluate_fixed_subframe_(
  105506. FLAC__StreamEncoder *encoder,
  105507. const FLAC__int32 signal[],
  105508. FLAC__int32 residual[],
  105509. FLAC__uint64 abs_residual_partition_sums[],
  105510. unsigned raw_bits_per_partition[],
  105511. unsigned blocksize,
  105512. unsigned subframe_bps,
  105513. unsigned order,
  105514. unsigned rice_parameter,
  105515. unsigned rice_parameter_limit,
  105516. unsigned min_partition_order,
  105517. unsigned max_partition_order,
  105518. FLAC__bool do_escape_coding,
  105519. unsigned rice_parameter_search_dist,
  105520. FLAC__Subframe *subframe,
  105521. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105522. )
  105523. {
  105524. unsigned i, residual_bits, estimate;
  105525. const unsigned residual_samples = blocksize - order;
  105526. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105527. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105528. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105529. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105530. subframe->data.fixed.residual = residual;
  105531. residual_bits =
  105532. find_best_partition_order_(
  105533. encoder->private_,
  105534. residual,
  105535. abs_residual_partition_sums,
  105536. raw_bits_per_partition,
  105537. residual_samples,
  105538. order,
  105539. rice_parameter,
  105540. rice_parameter_limit,
  105541. min_partition_order,
  105542. max_partition_order,
  105543. subframe_bps,
  105544. do_escape_coding,
  105545. rice_parameter_search_dist,
  105546. &subframe->data.fixed.entropy_coding_method
  105547. );
  105548. subframe->data.fixed.order = order;
  105549. for(i = 0; i < order; i++)
  105550. subframe->data.fixed.warmup[i] = signal[i];
  105551. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105552. #if SPOTCHECK_ESTIMATE
  105553. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105554. #endif
  105555. return estimate;
  105556. }
  105557. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105558. unsigned evaluate_lpc_subframe_(
  105559. FLAC__StreamEncoder *encoder,
  105560. const FLAC__int32 signal[],
  105561. FLAC__int32 residual[],
  105562. FLAC__uint64 abs_residual_partition_sums[],
  105563. unsigned raw_bits_per_partition[],
  105564. const FLAC__real lp_coeff[],
  105565. unsigned blocksize,
  105566. unsigned subframe_bps,
  105567. unsigned order,
  105568. unsigned qlp_coeff_precision,
  105569. unsigned rice_parameter,
  105570. unsigned rice_parameter_limit,
  105571. unsigned min_partition_order,
  105572. unsigned max_partition_order,
  105573. FLAC__bool do_escape_coding,
  105574. unsigned rice_parameter_search_dist,
  105575. FLAC__Subframe *subframe,
  105576. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105577. )
  105578. {
  105579. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105580. unsigned i, residual_bits, estimate;
  105581. int quantization, ret;
  105582. const unsigned residual_samples = blocksize - order;
  105583. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105584. if(subframe_bps <= 16) {
  105585. FLAC__ASSERT(order > 0);
  105586. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105587. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105588. }
  105589. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105590. if(ret != 0)
  105591. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105592. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105593. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105594. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105595. else
  105596. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105597. else
  105598. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105599. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105600. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105601. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105602. subframe->data.lpc.residual = residual;
  105603. residual_bits =
  105604. find_best_partition_order_(
  105605. encoder->private_,
  105606. residual,
  105607. abs_residual_partition_sums,
  105608. raw_bits_per_partition,
  105609. residual_samples,
  105610. order,
  105611. rice_parameter,
  105612. rice_parameter_limit,
  105613. min_partition_order,
  105614. max_partition_order,
  105615. subframe_bps,
  105616. do_escape_coding,
  105617. rice_parameter_search_dist,
  105618. &subframe->data.lpc.entropy_coding_method
  105619. );
  105620. subframe->data.lpc.order = order;
  105621. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105622. subframe->data.lpc.quantization_level = quantization;
  105623. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105624. for(i = 0; i < order; i++)
  105625. subframe->data.lpc.warmup[i] = signal[i];
  105626. 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;
  105627. #if SPOTCHECK_ESTIMATE
  105628. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105629. #endif
  105630. return estimate;
  105631. }
  105632. #endif
  105633. unsigned evaluate_verbatim_subframe_(
  105634. FLAC__StreamEncoder *encoder,
  105635. const FLAC__int32 signal[],
  105636. unsigned blocksize,
  105637. unsigned subframe_bps,
  105638. FLAC__Subframe *subframe
  105639. )
  105640. {
  105641. unsigned estimate;
  105642. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105643. subframe->data.verbatim.data = signal;
  105644. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105645. #if SPOTCHECK_ESTIMATE
  105646. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105647. #else
  105648. (void)encoder;
  105649. #endif
  105650. return estimate;
  105651. }
  105652. unsigned find_best_partition_order_(
  105653. FLAC__StreamEncoderPrivate *private_,
  105654. const FLAC__int32 residual[],
  105655. FLAC__uint64 abs_residual_partition_sums[],
  105656. unsigned raw_bits_per_partition[],
  105657. unsigned residual_samples,
  105658. unsigned predictor_order,
  105659. unsigned rice_parameter,
  105660. unsigned rice_parameter_limit,
  105661. unsigned min_partition_order,
  105662. unsigned max_partition_order,
  105663. unsigned bps,
  105664. FLAC__bool do_escape_coding,
  105665. unsigned rice_parameter_search_dist,
  105666. FLAC__EntropyCodingMethod *best_ecm
  105667. )
  105668. {
  105669. unsigned residual_bits, best_residual_bits = 0;
  105670. unsigned best_parameters_index = 0;
  105671. unsigned best_partition_order = 0;
  105672. const unsigned blocksize = residual_samples + predictor_order;
  105673. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105674. min_partition_order = min(min_partition_order, max_partition_order);
  105675. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105676. if(do_escape_coding)
  105677. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105678. {
  105679. int partition_order;
  105680. unsigned sum;
  105681. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105682. if(!
  105683. set_partitioned_rice_(
  105684. #ifdef EXACT_RICE_BITS_CALCULATION
  105685. residual,
  105686. #endif
  105687. abs_residual_partition_sums+sum,
  105688. raw_bits_per_partition+sum,
  105689. residual_samples,
  105690. predictor_order,
  105691. rice_parameter,
  105692. rice_parameter_limit,
  105693. rice_parameter_search_dist,
  105694. (unsigned)partition_order,
  105695. do_escape_coding,
  105696. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105697. &residual_bits
  105698. )
  105699. )
  105700. {
  105701. FLAC__ASSERT(best_residual_bits != 0);
  105702. break;
  105703. }
  105704. sum += 1u << partition_order;
  105705. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105706. best_residual_bits = residual_bits;
  105707. best_parameters_index = !best_parameters_index;
  105708. best_partition_order = partition_order;
  105709. }
  105710. }
  105711. }
  105712. best_ecm->data.partitioned_rice.order = best_partition_order;
  105713. {
  105714. /*
  105715. * We are allowed to de-const the pointer based on our special
  105716. * knowledge; it is const to the outside world.
  105717. */
  105718. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105719. unsigned partition;
  105720. /* save best parameters and raw_bits */
  105721. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105722. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105723. if(do_escape_coding)
  105724. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105725. /*
  105726. * Now need to check if the type should be changed to
  105727. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105728. * size of the rice parameters.
  105729. */
  105730. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105731. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105732. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105733. break;
  105734. }
  105735. }
  105736. }
  105737. return best_residual_bits;
  105738. }
  105739. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105740. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105741. const FLAC__int32 residual[],
  105742. FLAC__uint64 abs_residual_partition_sums[],
  105743. unsigned blocksize,
  105744. unsigned predictor_order,
  105745. unsigned min_partition_order,
  105746. unsigned max_partition_order
  105747. );
  105748. #endif
  105749. void precompute_partition_info_sums_(
  105750. const FLAC__int32 residual[],
  105751. FLAC__uint64 abs_residual_partition_sums[],
  105752. unsigned residual_samples,
  105753. unsigned predictor_order,
  105754. unsigned min_partition_order,
  105755. unsigned max_partition_order,
  105756. unsigned bps
  105757. )
  105758. {
  105759. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105760. unsigned partitions = 1u << max_partition_order;
  105761. FLAC__ASSERT(default_partition_samples > predictor_order);
  105762. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105763. /* slightly pessimistic but still catches all common cases */
  105764. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105765. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105766. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105767. return;
  105768. }
  105769. #endif
  105770. /* first do max_partition_order */
  105771. {
  105772. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105773. /* slightly pessimistic but still catches all common cases */
  105774. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105775. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105776. FLAC__uint32 abs_residual_partition_sum;
  105777. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105778. end += default_partition_samples;
  105779. abs_residual_partition_sum = 0;
  105780. for( ; residual_sample < end; residual_sample++)
  105781. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105782. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105783. }
  105784. }
  105785. else { /* have to pessimistically use 64 bits for accumulator */
  105786. FLAC__uint64 abs_residual_partition_sum;
  105787. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105788. end += default_partition_samples;
  105789. abs_residual_partition_sum = 0;
  105790. for( ; residual_sample < end; residual_sample++)
  105791. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105792. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105793. }
  105794. }
  105795. }
  105796. /* now merge partitions for lower orders */
  105797. {
  105798. unsigned from_partition = 0, to_partition = partitions;
  105799. int partition_order;
  105800. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105801. unsigned i;
  105802. partitions >>= 1;
  105803. for(i = 0; i < partitions; i++) {
  105804. abs_residual_partition_sums[to_partition++] =
  105805. abs_residual_partition_sums[from_partition ] +
  105806. abs_residual_partition_sums[from_partition+1];
  105807. from_partition += 2;
  105808. }
  105809. }
  105810. }
  105811. }
  105812. void precompute_partition_info_escapes_(
  105813. const FLAC__int32 residual[],
  105814. unsigned raw_bits_per_partition[],
  105815. unsigned residual_samples,
  105816. unsigned predictor_order,
  105817. unsigned min_partition_order,
  105818. unsigned max_partition_order
  105819. )
  105820. {
  105821. int partition_order;
  105822. unsigned from_partition, to_partition = 0;
  105823. const unsigned blocksize = residual_samples + predictor_order;
  105824. /* first do max_partition_order */
  105825. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105826. FLAC__int32 r;
  105827. FLAC__uint32 rmax;
  105828. unsigned partition, partition_sample, partition_samples, residual_sample;
  105829. const unsigned partitions = 1u << partition_order;
  105830. const unsigned default_partition_samples = blocksize >> partition_order;
  105831. FLAC__ASSERT(default_partition_samples > predictor_order);
  105832. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105833. partition_samples = default_partition_samples;
  105834. if(partition == 0)
  105835. partition_samples -= predictor_order;
  105836. rmax = 0;
  105837. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105838. r = residual[residual_sample++];
  105839. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105840. if(r < 0)
  105841. rmax |= ~r;
  105842. else
  105843. rmax |= r;
  105844. }
  105845. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105846. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105847. }
  105848. to_partition = partitions;
  105849. break; /*@@@ yuck, should remove the 'for' loop instead */
  105850. }
  105851. /* now merge partitions for lower orders */
  105852. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105853. unsigned m;
  105854. unsigned i;
  105855. const unsigned partitions = 1u << partition_order;
  105856. for(i = 0; i < partitions; i++) {
  105857. m = raw_bits_per_partition[from_partition];
  105858. from_partition++;
  105859. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105860. from_partition++;
  105861. to_partition++;
  105862. }
  105863. }
  105864. }
  105865. #ifdef EXACT_RICE_BITS_CALCULATION
  105866. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105867. const unsigned rice_parameter,
  105868. const unsigned partition_samples,
  105869. const FLAC__int32 *residual
  105870. )
  105871. {
  105872. unsigned i, partition_bits =
  105873. 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 */
  105874. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105875. ;
  105876. for(i = 0; i < partition_samples; i++)
  105877. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105878. return partition_bits;
  105879. }
  105880. #else
  105881. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105882. const unsigned rice_parameter,
  105883. const unsigned partition_samples,
  105884. const FLAC__uint64 abs_residual_partition_sum
  105885. )
  105886. {
  105887. return
  105888. 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 */
  105889. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105890. (
  105891. rice_parameter?
  105892. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105893. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105894. )
  105895. - (partition_samples >> 1)
  105896. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105897. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105898. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105899. * So the subtraction term tries to guess how many extra bits were contributed.
  105900. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105901. */
  105902. ;
  105903. }
  105904. #endif
  105905. FLAC__bool set_partitioned_rice_(
  105906. #ifdef EXACT_RICE_BITS_CALCULATION
  105907. const FLAC__int32 residual[],
  105908. #endif
  105909. const FLAC__uint64 abs_residual_partition_sums[],
  105910. const unsigned raw_bits_per_partition[],
  105911. const unsigned residual_samples,
  105912. const unsigned predictor_order,
  105913. const unsigned suggested_rice_parameter,
  105914. const unsigned rice_parameter_limit,
  105915. const unsigned rice_parameter_search_dist,
  105916. const unsigned partition_order,
  105917. const FLAC__bool search_for_escapes,
  105918. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105919. unsigned *bits
  105920. )
  105921. {
  105922. unsigned rice_parameter, partition_bits;
  105923. unsigned best_partition_bits, best_rice_parameter = 0;
  105924. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105925. unsigned *parameters, *raw_bits;
  105926. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105927. unsigned min_rice_parameter, max_rice_parameter;
  105928. #else
  105929. (void)rice_parameter_search_dist;
  105930. #endif
  105931. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105932. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105933. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105934. parameters = partitioned_rice_contents->parameters;
  105935. raw_bits = partitioned_rice_contents->raw_bits;
  105936. if(partition_order == 0) {
  105937. best_partition_bits = (unsigned)(-1);
  105938. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105939. if(rice_parameter_search_dist) {
  105940. if(suggested_rice_parameter < rice_parameter_search_dist)
  105941. min_rice_parameter = 0;
  105942. else
  105943. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105944. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105945. if(max_rice_parameter >= rice_parameter_limit) {
  105946. #ifdef DEBUG_VERBOSE
  105947. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105948. #endif
  105949. max_rice_parameter = rice_parameter_limit - 1;
  105950. }
  105951. }
  105952. else
  105953. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105954. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105955. #else
  105956. rice_parameter = suggested_rice_parameter;
  105957. #endif
  105958. #ifdef EXACT_RICE_BITS_CALCULATION
  105959. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105960. #else
  105961. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105962. #endif
  105963. if(partition_bits < best_partition_bits) {
  105964. best_rice_parameter = rice_parameter;
  105965. best_partition_bits = partition_bits;
  105966. }
  105967. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105968. }
  105969. #endif
  105970. if(search_for_escapes) {
  105971. 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;
  105972. if(partition_bits <= best_partition_bits) {
  105973. raw_bits[0] = raw_bits_per_partition[0];
  105974. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105975. best_partition_bits = partition_bits;
  105976. }
  105977. else
  105978. raw_bits[0] = 0;
  105979. }
  105980. parameters[0] = best_rice_parameter;
  105981. bits_ += best_partition_bits;
  105982. }
  105983. else {
  105984. unsigned partition, residual_sample;
  105985. unsigned partition_samples;
  105986. FLAC__uint64 mean, k;
  105987. const unsigned partitions = 1u << partition_order;
  105988. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105989. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105990. if(partition == 0) {
  105991. if(partition_samples <= predictor_order)
  105992. return false;
  105993. else
  105994. partition_samples -= predictor_order;
  105995. }
  105996. mean = abs_residual_partition_sums[partition];
  105997. /* we are basically calculating the size in bits of the
  105998. * average residual magnitude in the partition:
  105999. * rice_parameter = floor(log2(mean/partition_samples))
  106000. * 'mean' is not a good name for the variable, it is
  106001. * actually the sum of magnitudes of all residual values
  106002. * in the partition, so the actual mean is
  106003. * mean/partition_samples
  106004. */
  106005. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106006. ;
  106007. if(rice_parameter >= rice_parameter_limit) {
  106008. #ifdef DEBUG_VERBOSE
  106009. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106010. #endif
  106011. rice_parameter = rice_parameter_limit - 1;
  106012. }
  106013. best_partition_bits = (unsigned)(-1);
  106014. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106015. if(rice_parameter_search_dist) {
  106016. if(rice_parameter < rice_parameter_search_dist)
  106017. min_rice_parameter = 0;
  106018. else
  106019. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106020. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106021. if(max_rice_parameter >= rice_parameter_limit) {
  106022. #ifdef DEBUG_VERBOSE
  106023. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106024. #endif
  106025. max_rice_parameter = rice_parameter_limit - 1;
  106026. }
  106027. }
  106028. else
  106029. min_rice_parameter = max_rice_parameter = rice_parameter;
  106030. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106031. #endif
  106032. #ifdef EXACT_RICE_BITS_CALCULATION
  106033. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106034. #else
  106035. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106036. #endif
  106037. if(partition_bits < best_partition_bits) {
  106038. best_rice_parameter = rice_parameter;
  106039. best_partition_bits = partition_bits;
  106040. }
  106041. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106042. }
  106043. #endif
  106044. if(search_for_escapes) {
  106045. 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;
  106046. if(partition_bits <= best_partition_bits) {
  106047. raw_bits[partition] = raw_bits_per_partition[partition];
  106048. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106049. best_partition_bits = partition_bits;
  106050. }
  106051. else
  106052. raw_bits[partition] = 0;
  106053. }
  106054. parameters[partition] = best_rice_parameter;
  106055. bits_ += best_partition_bits;
  106056. residual_sample += partition_samples;
  106057. }
  106058. }
  106059. *bits = bits_;
  106060. return true;
  106061. }
  106062. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106063. {
  106064. unsigned i, shift;
  106065. FLAC__int32 x = 0;
  106066. for(i = 0; i < samples && !(x&1); i++)
  106067. x |= signal[i];
  106068. if(x == 0) {
  106069. shift = 0;
  106070. }
  106071. else {
  106072. for(shift = 0; !(x&1); shift++)
  106073. x >>= 1;
  106074. }
  106075. if(shift > 0) {
  106076. for(i = 0; i < samples; i++)
  106077. signal[i] >>= shift;
  106078. }
  106079. return shift;
  106080. }
  106081. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106082. {
  106083. unsigned channel;
  106084. for(channel = 0; channel < channels; channel++)
  106085. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106086. fifo->tail += wide_samples;
  106087. FLAC__ASSERT(fifo->tail <= fifo->size);
  106088. }
  106089. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106090. {
  106091. unsigned channel;
  106092. unsigned sample, wide_sample;
  106093. unsigned tail = fifo->tail;
  106094. sample = input_offset * channels;
  106095. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106096. for(channel = 0; channel < channels; channel++)
  106097. fifo->data[channel][tail] = input[sample++];
  106098. tail++;
  106099. }
  106100. fifo->tail = tail;
  106101. FLAC__ASSERT(fifo->tail <= fifo->size);
  106102. }
  106103. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106104. {
  106105. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106106. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106107. (void)decoder;
  106108. if(encoder->private_->verify.needs_magic_hack) {
  106109. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106110. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106111. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106112. encoder->private_->verify.needs_magic_hack = false;
  106113. }
  106114. else {
  106115. if(encoded_bytes == 0) {
  106116. /*
  106117. * If we get here, a FIFO underflow has occurred,
  106118. * which means there is a bug somewhere.
  106119. */
  106120. FLAC__ASSERT(0);
  106121. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106122. }
  106123. else if(encoded_bytes < *bytes)
  106124. *bytes = encoded_bytes;
  106125. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106126. encoder->private_->verify.output.data += *bytes;
  106127. encoder->private_->verify.output.bytes -= *bytes;
  106128. }
  106129. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106130. }
  106131. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106132. {
  106133. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106134. unsigned channel;
  106135. const unsigned channels = frame->header.channels;
  106136. const unsigned blocksize = frame->header.blocksize;
  106137. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106138. (void)decoder;
  106139. for(channel = 0; channel < channels; channel++) {
  106140. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106141. unsigned i, sample = 0;
  106142. FLAC__int32 expect = 0, got = 0;
  106143. for(i = 0; i < blocksize; i++) {
  106144. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106145. sample = i;
  106146. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106147. got = (FLAC__int32)buffer[channel][i];
  106148. break;
  106149. }
  106150. }
  106151. FLAC__ASSERT(i < blocksize);
  106152. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106153. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106154. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106155. encoder->private_->verify.error_stats.channel = channel;
  106156. encoder->private_->verify.error_stats.sample = sample;
  106157. encoder->private_->verify.error_stats.expected = expect;
  106158. encoder->private_->verify.error_stats.got = got;
  106159. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106160. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106161. }
  106162. }
  106163. /* dequeue the frame from the fifo */
  106164. encoder->private_->verify.input_fifo.tail -= blocksize;
  106165. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106166. for(channel = 0; channel < channels; channel++)
  106167. 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]));
  106168. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106169. }
  106170. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106171. {
  106172. (void)decoder, (void)metadata, (void)client_data;
  106173. }
  106174. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106175. {
  106176. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106177. (void)decoder, (void)status;
  106178. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106179. }
  106180. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106181. {
  106182. (void)client_data;
  106183. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106184. if (*bytes == 0) {
  106185. if (feof(encoder->private_->file))
  106186. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106187. else if (ferror(encoder->private_->file))
  106188. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106189. }
  106190. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106191. }
  106192. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106193. {
  106194. (void)client_data;
  106195. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106196. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106197. else
  106198. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106199. }
  106200. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106201. {
  106202. off_t offset;
  106203. (void)client_data;
  106204. offset = ftello(encoder->private_->file);
  106205. if(offset < 0) {
  106206. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106207. }
  106208. else {
  106209. *absolute_byte_offset = (FLAC__uint64)offset;
  106210. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106211. }
  106212. }
  106213. #ifdef FLAC__VALGRIND_TESTING
  106214. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106215. {
  106216. size_t ret = fwrite(ptr, size, nmemb, stream);
  106217. if(!ferror(stream))
  106218. fflush(stream);
  106219. return ret;
  106220. }
  106221. #else
  106222. #define local__fwrite fwrite
  106223. #endif
  106224. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106225. {
  106226. (void)client_data, (void)current_frame;
  106227. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106228. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106229. #if FLAC__HAS_OGG
  106230. /* We would like to be able to use 'samples > 0' in the
  106231. * clause here but currently because of the nature of our
  106232. * Ogg writing implementation, 'samples' is always 0 (see
  106233. * ogg_encoder_aspect.c). The downside is extra progress
  106234. * callbacks.
  106235. */
  106236. encoder->private_->is_ogg? true :
  106237. #endif
  106238. samples > 0
  106239. );
  106240. if(call_it) {
  106241. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106242. * because at this point in the callback chain, the stats
  106243. * have not been updated. Only after we return and control
  106244. * gets back to write_frame_() are the stats updated
  106245. */
  106246. 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);
  106247. }
  106248. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106249. }
  106250. else
  106251. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106252. }
  106253. /*
  106254. * This will forcibly set stdout to binary mode (for OSes that require it)
  106255. */
  106256. FILE *get_binary_stdout_(void)
  106257. {
  106258. /* if something breaks here it is probably due to the presence or
  106259. * absence of an underscore before the identifiers 'setmode',
  106260. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106261. */
  106262. #if defined _MSC_VER || defined __MINGW32__
  106263. _setmode(_fileno(stdout), _O_BINARY);
  106264. #elif defined __CYGWIN__
  106265. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106266. setmode(_fileno(stdout), _O_BINARY);
  106267. #elif defined __EMX__
  106268. setmode(fileno(stdout), O_BINARY);
  106269. #endif
  106270. return stdout;
  106271. }
  106272. #endif
  106273. /*** End of inlined file: stream_encoder.c ***/
  106274. /*** Start of inlined file: stream_encoder_framing.c ***/
  106275. /*** Start of inlined file: juce_FlacHeader.h ***/
  106276. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106277. // tasks..
  106278. #define VERSION "1.2.1"
  106279. #define FLAC__NO_DLL 1
  106280. #if JUCE_MSVC
  106281. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106282. #endif
  106283. #if JUCE_MAC
  106284. #define FLAC__SYS_DARWIN 1
  106285. #endif
  106286. /*** End of inlined file: juce_FlacHeader.h ***/
  106287. #if JUCE_USE_FLAC
  106288. #if HAVE_CONFIG_H
  106289. # include <config.h>
  106290. #endif
  106291. #include <stdio.h>
  106292. #include <string.h> /* for strlen() */
  106293. #ifdef max
  106294. #undef max
  106295. #endif
  106296. #define max(x,y) ((x)>(y)?(x):(y))
  106297. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106298. 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);
  106299. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106300. {
  106301. unsigned i, j;
  106302. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106303. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106304. return false;
  106305. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106306. return false;
  106307. /*
  106308. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106309. */
  106310. i = metadata->length;
  106311. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106312. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106313. i -= metadata->data.vorbis_comment.vendor_string.length;
  106314. i += vendor_string_length;
  106315. }
  106316. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106317. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106318. return false;
  106319. switch(metadata->type) {
  106320. case FLAC__METADATA_TYPE_STREAMINFO:
  106321. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106322. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106323. return false;
  106324. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106325. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106326. return false;
  106327. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106328. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106329. return false;
  106330. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106331. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106332. return false;
  106333. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106334. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106335. return false;
  106336. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106337. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106338. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106339. return false;
  106340. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106341. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106342. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106343. return false;
  106344. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106345. return false;
  106346. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106347. return false;
  106348. break;
  106349. case FLAC__METADATA_TYPE_PADDING:
  106350. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106351. return false;
  106352. break;
  106353. case FLAC__METADATA_TYPE_APPLICATION:
  106354. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106355. return false;
  106356. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106357. return false;
  106358. break;
  106359. case FLAC__METADATA_TYPE_SEEKTABLE:
  106360. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106361. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106362. return false;
  106363. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106364. return false;
  106365. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106366. return false;
  106367. }
  106368. break;
  106369. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106370. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106371. return false;
  106372. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106373. return false;
  106374. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106375. return false;
  106376. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106377. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106378. return false;
  106379. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106380. return false;
  106381. }
  106382. break;
  106383. case FLAC__METADATA_TYPE_CUESHEET:
  106384. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106385. 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))
  106386. return false;
  106387. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106388. return false;
  106389. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106390. return false;
  106391. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106392. return false;
  106393. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106394. return false;
  106395. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106396. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106397. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106398. return false;
  106399. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106400. return false;
  106401. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106402. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106403. return false;
  106404. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106405. return false;
  106406. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106407. return false;
  106408. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106409. return false;
  106410. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106411. return false;
  106412. for(j = 0; j < track->num_indices; j++) {
  106413. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106414. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106415. return false;
  106416. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106417. return false;
  106418. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106419. return false;
  106420. }
  106421. }
  106422. break;
  106423. case FLAC__METADATA_TYPE_PICTURE:
  106424. {
  106425. size_t len;
  106426. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106427. return false;
  106428. len = strlen(metadata->data.picture.mime_type);
  106429. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106430. return false;
  106431. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106432. return false;
  106433. len = strlen((const char *)metadata->data.picture.description);
  106434. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106435. return false;
  106436. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106437. return false;
  106438. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106439. return false;
  106440. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106441. return false;
  106442. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106443. return false;
  106444. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106445. return false;
  106446. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106447. return false;
  106448. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106449. return false;
  106450. }
  106451. break;
  106452. default:
  106453. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106454. return false;
  106455. break;
  106456. }
  106457. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106458. return true;
  106459. }
  106460. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106461. {
  106462. unsigned u, blocksize_hint, sample_rate_hint;
  106463. FLAC__byte crc;
  106464. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106465. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106466. return false;
  106467. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106468. return false;
  106469. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106470. return false;
  106471. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106472. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106473. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106474. blocksize_hint = 0;
  106475. switch(header->blocksize) {
  106476. case 192: u = 1; break;
  106477. case 576: u = 2; break;
  106478. case 1152: u = 3; break;
  106479. case 2304: u = 4; break;
  106480. case 4608: u = 5; break;
  106481. case 256: u = 8; break;
  106482. case 512: u = 9; break;
  106483. case 1024: u = 10; break;
  106484. case 2048: u = 11; break;
  106485. case 4096: u = 12; break;
  106486. case 8192: u = 13; break;
  106487. case 16384: u = 14; break;
  106488. case 32768: u = 15; break;
  106489. default:
  106490. if(header->blocksize <= 0x100)
  106491. blocksize_hint = u = 6;
  106492. else
  106493. blocksize_hint = u = 7;
  106494. break;
  106495. }
  106496. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106497. return false;
  106498. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106499. sample_rate_hint = 0;
  106500. switch(header->sample_rate) {
  106501. case 88200: u = 1; break;
  106502. case 176400: u = 2; break;
  106503. case 192000: u = 3; break;
  106504. case 8000: u = 4; break;
  106505. case 16000: u = 5; break;
  106506. case 22050: u = 6; break;
  106507. case 24000: u = 7; break;
  106508. case 32000: u = 8; break;
  106509. case 44100: u = 9; break;
  106510. case 48000: u = 10; break;
  106511. case 96000: u = 11; break;
  106512. default:
  106513. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106514. sample_rate_hint = u = 12;
  106515. else if(header->sample_rate % 10 == 0)
  106516. sample_rate_hint = u = 14;
  106517. else if(header->sample_rate <= 0xffff)
  106518. sample_rate_hint = u = 13;
  106519. else
  106520. u = 0;
  106521. break;
  106522. }
  106523. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106524. return false;
  106525. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106526. switch(header->channel_assignment) {
  106527. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106528. u = header->channels - 1;
  106529. break;
  106530. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106531. FLAC__ASSERT(header->channels == 2);
  106532. u = 8;
  106533. break;
  106534. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106535. FLAC__ASSERT(header->channels == 2);
  106536. u = 9;
  106537. break;
  106538. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106539. FLAC__ASSERT(header->channels == 2);
  106540. u = 10;
  106541. break;
  106542. default:
  106543. FLAC__ASSERT(0);
  106544. }
  106545. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106546. return false;
  106547. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106548. switch(header->bits_per_sample) {
  106549. case 8 : u = 1; break;
  106550. case 12: u = 2; break;
  106551. case 16: u = 4; break;
  106552. case 20: u = 5; break;
  106553. case 24: u = 6; break;
  106554. default: u = 0; break;
  106555. }
  106556. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106557. return false;
  106558. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106559. return false;
  106560. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106561. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106562. return false;
  106563. }
  106564. else {
  106565. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106566. return false;
  106567. }
  106568. if(blocksize_hint)
  106569. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106570. return false;
  106571. switch(sample_rate_hint) {
  106572. case 12:
  106573. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106574. return false;
  106575. break;
  106576. case 13:
  106577. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106578. return false;
  106579. break;
  106580. case 14:
  106581. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106582. return false;
  106583. break;
  106584. }
  106585. /* write the CRC */
  106586. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106587. return false;
  106588. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106589. return false;
  106590. return true;
  106591. }
  106592. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106593. {
  106594. FLAC__bool ok;
  106595. ok =
  106596. 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) &&
  106597. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106598. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106599. ;
  106600. return ok;
  106601. }
  106602. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106603. {
  106604. unsigned i;
  106605. 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))
  106606. return false;
  106607. if(wasted_bits)
  106608. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106609. return false;
  106610. for(i = 0; i < subframe->order; i++)
  106611. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106612. return false;
  106613. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106614. return false;
  106615. switch(subframe->entropy_coding_method.type) {
  106616. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106617. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106618. if(!add_residual_partitioned_rice_(
  106619. bw,
  106620. subframe->residual,
  106621. residual_samples,
  106622. subframe->order,
  106623. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106624. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106625. subframe->entropy_coding_method.data.partitioned_rice.order,
  106626. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106627. ))
  106628. return false;
  106629. break;
  106630. default:
  106631. FLAC__ASSERT(0);
  106632. }
  106633. return true;
  106634. }
  106635. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106636. {
  106637. unsigned i;
  106638. 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))
  106639. return false;
  106640. if(wasted_bits)
  106641. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106642. return false;
  106643. for(i = 0; i < subframe->order; i++)
  106644. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106645. return false;
  106646. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106647. return false;
  106648. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106649. return false;
  106650. for(i = 0; i < subframe->order; i++)
  106651. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106652. return false;
  106653. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106654. return false;
  106655. switch(subframe->entropy_coding_method.type) {
  106656. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106657. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106658. if(!add_residual_partitioned_rice_(
  106659. bw,
  106660. subframe->residual,
  106661. residual_samples,
  106662. subframe->order,
  106663. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106664. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106665. subframe->entropy_coding_method.data.partitioned_rice.order,
  106666. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106667. ))
  106668. return false;
  106669. break;
  106670. default:
  106671. FLAC__ASSERT(0);
  106672. }
  106673. return true;
  106674. }
  106675. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106676. {
  106677. unsigned i;
  106678. const FLAC__int32 *signal = subframe->data;
  106679. 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))
  106680. return false;
  106681. if(wasted_bits)
  106682. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106683. return false;
  106684. for(i = 0; i < samples; i++)
  106685. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106686. return false;
  106687. return true;
  106688. }
  106689. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106690. {
  106691. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106692. return false;
  106693. switch(method->type) {
  106694. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106695. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106696. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106697. return false;
  106698. break;
  106699. default:
  106700. FLAC__ASSERT(0);
  106701. }
  106702. return true;
  106703. }
  106704. 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)
  106705. {
  106706. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106707. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106708. if(partition_order == 0) {
  106709. unsigned i;
  106710. if(raw_bits[0] == 0) {
  106711. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106712. return false;
  106713. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106714. return false;
  106715. }
  106716. else {
  106717. FLAC__ASSERT(rice_parameters[0] == 0);
  106718. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106719. return false;
  106720. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106721. return false;
  106722. for(i = 0; i < residual_samples; i++) {
  106723. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106724. return false;
  106725. }
  106726. }
  106727. return true;
  106728. }
  106729. else {
  106730. unsigned i, j, k = 0, k_last = 0;
  106731. unsigned partition_samples;
  106732. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106733. for(i = 0; i < (1u<<partition_order); i++) {
  106734. partition_samples = default_partition_samples;
  106735. if(i == 0)
  106736. partition_samples -= predictor_order;
  106737. k += partition_samples;
  106738. if(raw_bits[i] == 0) {
  106739. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106740. return false;
  106741. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106742. return false;
  106743. }
  106744. else {
  106745. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106746. return false;
  106747. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106748. return false;
  106749. for(j = k_last; j < k; j++) {
  106750. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106751. return false;
  106752. }
  106753. }
  106754. k_last = k;
  106755. }
  106756. return true;
  106757. }
  106758. }
  106759. #endif
  106760. /*** End of inlined file: stream_encoder_framing.c ***/
  106761. /*** Start of inlined file: window_flac.c ***/
  106762. /*** Start of inlined file: juce_FlacHeader.h ***/
  106763. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106764. // tasks..
  106765. #define VERSION "1.2.1"
  106766. #define FLAC__NO_DLL 1
  106767. #if JUCE_MSVC
  106768. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106769. #endif
  106770. #if JUCE_MAC
  106771. #define FLAC__SYS_DARWIN 1
  106772. #endif
  106773. /*** End of inlined file: juce_FlacHeader.h ***/
  106774. #if JUCE_USE_FLAC
  106775. #if HAVE_CONFIG_H
  106776. # include <config.h>
  106777. #endif
  106778. #include <math.h>
  106779. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106780. #ifndef M_PI
  106781. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106782. #define M_PI 3.14159265358979323846
  106783. #endif
  106784. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106785. {
  106786. const FLAC__int32 N = L - 1;
  106787. FLAC__int32 n;
  106788. if (L & 1) {
  106789. for (n = 0; n <= N/2; n++)
  106790. window[n] = 2.0f * n / (float)N;
  106791. for (; n <= N; n++)
  106792. window[n] = 2.0f - 2.0f * n / (float)N;
  106793. }
  106794. else {
  106795. for (n = 0; n <= L/2-1; n++)
  106796. window[n] = 2.0f * n / (float)N;
  106797. for (; n <= N; n++)
  106798. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106799. }
  106800. }
  106801. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106802. {
  106803. const FLAC__int32 N = L - 1;
  106804. FLAC__int32 n;
  106805. for (n = 0; n < L; n++)
  106806. 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)));
  106807. }
  106808. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106809. {
  106810. const FLAC__int32 N = L - 1;
  106811. FLAC__int32 n;
  106812. for (n = 0; n < L; n++)
  106813. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106814. }
  106815. /* 4-term -92dB side-lobe */
  106816. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106817. {
  106818. const FLAC__int32 N = L - 1;
  106819. FLAC__int32 n;
  106820. for (n = 0; n <= N; n++)
  106821. 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));
  106822. }
  106823. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106824. {
  106825. const FLAC__int32 N = L - 1;
  106826. const double N2 = (double)N / 2.;
  106827. FLAC__int32 n;
  106828. for (n = 0; n <= N; n++) {
  106829. double k = ((double)n - N2) / N2;
  106830. k = 1.0f - k * k;
  106831. window[n] = (FLAC__real)(k * k);
  106832. }
  106833. }
  106834. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106835. {
  106836. const FLAC__int32 N = L - 1;
  106837. FLAC__int32 n;
  106838. for (n = 0; n < L; n++)
  106839. 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));
  106840. }
  106841. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106842. {
  106843. const FLAC__int32 N = L - 1;
  106844. const double N2 = (double)N / 2.;
  106845. FLAC__int32 n;
  106846. for (n = 0; n <= N; n++) {
  106847. const double k = ((double)n - N2) / (stddev * N2);
  106848. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106849. }
  106850. }
  106851. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106852. {
  106853. const FLAC__int32 N = L - 1;
  106854. FLAC__int32 n;
  106855. for (n = 0; n < L; n++)
  106856. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106857. }
  106858. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106859. {
  106860. const FLAC__int32 N = L - 1;
  106861. FLAC__int32 n;
  106862. for (n = 0; n < L; n++)
  106863. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106864. }
  106865. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106866. {
  106867. const FLAC__int32 N = L - 1;
  106868. FLAC__int32 n;
  106869. for (n = 0; n < L; n++)
  106870. 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));
  106871. }
  106872. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106873. {
  106874. const FLAC__int32 N = L - 1;
  106875. FLAC__int32 n;
  106876. for (n = 0; n < L; n++)
  106877. 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));
  106878. }
  106879. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106880. {
  106881. FLAC__int32 n;
  106882. for (n = 0; n < L; n++)
  106883. window[n] = 1.0f;
  106884. }
  106885. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106886. {
  106887. FLAC__int32 n;
  106888. if (L & 1) {
  106889. for (n = 1; n <= L+1/2; n++)
  106890. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106891. for (; n <= L; n++)
  106892. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106893. }
  106894. else {
  106895. for (n = 1; n <= L/2; n++)
  106896. window[n-1] = 2.0f * n / (float)L;
  106897. for (; n <= L; n++)
  106898. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106899. }
  106900. }
  106901. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106902. {
  106903. if (p <= 0.0)
  106904. FLAC__window_rectangle(window, L);
  106905. else if (p >= 1.0)
  106906. FLAC__window_hann(window, L);
  106907. else {
  106908. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106909. FLAC__int32 n;
  106910. /* start with rectangle... */
  106911. FLAC__window_rectangle(window, L);
  106912. /* ...replace ends with hann */
  106913. if (Np > 0) {
  106914. for (n = 0; n <= Np; n++) {
  106915. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106916. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106917. }
  106918. }
  106919. }
  106920. }
  106921. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106922. {
  106923. const FLAC__int32 N = L - 1;
  106924. const double N2 = (double)N / 2.;
  106925. FLAC__int32 n;
  106926. for (n = 0; n <= N; n++) {
  106927. const double k = ((double)n - N2) / N2;
  106928. window[n] = (FLAC__real)(1.0f - k * k);
  106929. }
  106930. }
  106931. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106932. #endif
  106933. /*** End of inlined file: window_flac.c ***/
  106934. #else
  106935. #include <FLAC/all.h>
  106936. #endif
  106937. }
  106938. #undef max
  106939. #undef min
  106940. BEGIN_JUCE_NAMESPACE
  106941. static const char* const flacFormatName = "FLAC file";
  106942. static const char* const flacExtensions[] = { ".flac", 0 };
  106943. class FlacReader : public AudioFormatReader
  106944. {
  106945. public:
  106946. FlacReader (InputStream* const in)
  106947. : AudioFormatReader (in, TRANS (flacFormatName)),
  106948. reservoir (2, 0),
  106949. reservoirStart (0),
  106950. samplesInReservoir (0),
  106951. scanningForLength (false)
  106952. {
  106953. using namespace FlacNamespace;
  106954. lengthInSamples = 0;
  106955. decoder = FLAC__stream_decoder_new();
  106956. ok = FLAC__stream_decoder_init_stream (decoder,
  106957. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106958. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106959. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106960. if (ok)
  106961. {
  106962. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106963. if (lengthInSamples == 0 && sampleRate > 0)
  106964. {
  106965. // the length hasn't been stored in the metadata, so we'll need to
  106966. // work it out the length the hard way, by scanning the whole file..
  106967. scanningForLength = true;
  106968. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106969. scanningForLength = false;
  106970. const int64 tempLength = lengthInSamples;
  106971. FLAC__stream_decoder_reset (decoder);
  106972. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106973. lengthInSamples = tempLength;
  106974. }
  106975. }
  106976. }
  106977. ~FlacReader()
  106978. {
  106979. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106980. }
  106981. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106982. {
  106983. sampleRate = info.sample_rate;
  106984. bitsPerSample = info.bits_per_sample;
  106985. lengthInSamples = (unsigned int) info.total_samples;
  106986. numChannels = info.channels;
  106987. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106988. }
  106989. // returns the number of samples read
  106990. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106991. int64 startSampleInFile, int numSamples)
  106992. {
  106993. using namespace FlacNamespace;
  106994. if (! ok)
  106995. return false;
  106996. while (numSamples > 0)
  106997. {
  106998. if (startSampleInFile >= reservoirStart
  106999. && startSampleInFile < reservoirStart + samplesInReservoir)
  107000. {
  107001. const int num = (int) jmin ((int64) numSamples,
  107002. reservoirStart + samplesInReservoir - startSampleInFile);
  107003. jassert (num > 0);
  107004. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107005. if (destSamples[i] != 0)
  107006. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107007. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107008. sizeof (int) * num);
  107009. startOffsetInDestBuffer += num;
  107010. startSampleInFile += num;
  107011. numSamples -= num;
  107012. }
  107013. else
  107014. {
  107015. if (startSampleInFile >= (int) lengthInSamples)
  107016. {
  107017. samplesInReservoir = 0;
  107018. }
  107019. else if (startSampleInFile < reservoirStart
  107020. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107021. {
  107022. // had some problems with flac crashing if the read pos is aligned more
  107023. // accurately than this. Probably fixed in newer versions of the library, though.
  107024. reservoirStart = (int) (startSampleInFile & ~511);
  107025. samplesInReservoir = 0;
  107026. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107027. }
  107028. else
  107029. {
  107030. reservoirStart += samplesInReservoir;
  107031. samplesInReservoir = 0;
  107032. FLAC__stream_decoder_process_single (decoder);
  107033. }
  107034. if (samplesInReservoir == 0)
  107035. break;
  107036. }
  107037. }
  107038. if (numSamples > 0)
  107039. {
  107040. for (int i = numDestChannels; --i >= 0;)
  107041. if (destSamples[i] != 0)
  107042. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107043. sizeof (int) * numSamples);
  107044. }
  107045. return true;
  107046. }
  107047. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107048. {
  107049. if (scanningForLength)
  107050. {
  107051. lengthInSamples += numSamples;
  107052. }
  107053. else
  107054. {
  107055. if (numSamples > reservoir.getNumSamples())
  107056. reservoir.setSize (numChannels, numSamples, false, false, true);
  107057. const int bitsToShift = 32 - bitsPerSample;
  107058. for (int i = 0; i < (int) numChannels; ++i)
  107059. {
  107060. const FlacNamespace::FLAC__int32* src = buffer[i];
  107061. int n = i;
  107062. while (src == 0 && n > 0)
  107063. src = buffer [--n];
  107064. if (src != 0)
  107065. {
  107066. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107067. for (int j = 0; j < numSamples; ++j)
  107068. dest[j] = src[j] << bitsToShift;
  107069. }
  107070. }
  107071. samplesInReservoir = numSamples;
  107072. }
  107073. }
  107074. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107075. {
  107076. using namespace FlacNamespace;
  107077. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107078. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107079. }
  107080. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107081. {
  107082. using namespace FlacNamespace;
  107083. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107084. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107085. }
  107086. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107087. {
  107088. using namespace FlacNamespace;
  107089. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107090. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107091. }
  107092. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107093. {
  107094. using namespace FlacNamespace;
  107095. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107096. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107097. }
  107098. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107099. {
  107100. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107101. }
  107102. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107103. const FlacNamespace::FLAC__Frame* frame,
  107104. const FlacNamespace::FLAC__int32* const buffer[],
  107105. void* client_data)
  107106. {
  107107. using namespace FlacNamespace;
  107108. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107109. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107110. }
  107111. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107112. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107113. void* client_data)
  107114. {
  107115. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107116. }
  107117. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107118. {
  107119. }
  107120. private:
  107121. FlacNamespace::FLAC__StreamDecoder* decoder;
  107122. AudioSampleBuffer reservoir;
  107123. int reservoirStart, samplesInReservoir;
  107124. bool ok, scanningForLength;
  107125. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  107126. };
  107127. class FlacWriter : public AudioFormatWriter
  107128. {
  107129. public:
  107130. FlacWriter (OutputStream* const out, double sampleRate_,
  107131. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107132. : AudioFormatWriter (out, TRANS (flacFormatName),
  107133. sampleRate_, numChannels_, bitsPerSample_)
  107134. {
  107135. using namespace FlacNamespace;
  107136. encoder = FLAC__stream_encoder_new();
  107137. if (qualityOptionIndex > 0)
  107138. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107139. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107140. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107141. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107142. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107143. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107144. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107145. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107146. ok = FLAC__stream_encoder_init_stream (encoder,
  107147. encodeWriteCallback, encodeSeekCallback,
  107148. encodeTellCallback, encodeMetadataCallback,
  107149. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107150. }
  107151. ~FlacWriter()
  107152. {
  107153. if (ok)
  107154. {
  107155. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107156. output->flush();
  107157. }
  107158. else
  107159. {
  107160. output = 0; // to stop the base class deleting this, as it needs to be returned
  107161. // to the caller of createWriter()
  107162. }
  107163. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107164. }
  107165. bool write (const int** samplesToWrite, int numSamples)
  107166. {
  107167. using namespace FlacNamespace;
  107168. if (! ok)
  107169. return false;
  107170. int* buf[3];
  107171. HeapBlock<int> temp;
  107172. const int bitsToShift = 32 - bitsPerSample;
  107173. if (bitsToShift > 0)
  107174. {
  107175. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107176. temp.malloc (numSamples * numChannelsToWrite);
  107177. buf[0] = temp.getData();
  107178. buf[1] = temp.getData() + numSamples;
  107179. buf[2] = 0;
  107180. for (int i = numChannelsToWrite; --i >= 0;)
  107181. if (samplesToWrite[i] != 0)
  107182. for (int j = 0; j < numSamples; ++j)
  107183. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107184. samplesToWrite = const_cast<const int**> (buf);
  107185. }
  107186. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  107187. }
  107188. bool writeData (const void* const data, const int size) const
  107189. {
  107190. return output->write (data, size);
  107191. }
  107192. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107193. {
  107194. using namespace FlacNamespace;
  107195. b += bytes;
  107196. for (int i = 0; i < bytes; ++i)
  107197. {
  107198. *(--b) = (FLAC__byte) (val & 0xff);
  107199. val >>= 8;
  107200. }
  107201. }
  107202. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107203. {
  107204. using namespace FlacNamespace;
  107205. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107206. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107207. const unsigned int channelsMinus1 = info.channels - 1;
  107208. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107209. packUint32 (info.min_blocksize, buffer, 2);
  107210. packUint32 (info.max_blocksize, buffer + 2, 2);
  107211. packUint32 (info.min_framesize, buffer + 4, 3);
  107212. packUint32 (info.max_framesize, buffer + 7, 3);
  107213. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107214. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107215. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107216. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107217. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107218. memcpy (buffer + 18, info.md5sum, 16);
  107219. const bool seekOk = output->setPosition (4);
  107220. (void) seekOk;
  107221. // if this fails, you've given it an output stream that can't seek! It needs
  107222. // to be able to seek back to write the header
  107223. jassert (seekOk);
  107224. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107225. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107226. }
  107227. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107228. const FlacNamespace::FLAC__byte buffer[],
  107229. size_t bytes,
  107230. unsigned int /*samples*/,
  107231. unsigned int /*current_frame*/,
  107232. void* client_data)
  107233. {
  107234. using namespace FlacNamespace;
  107235. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107236. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107237. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107238. }
  107239. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107240. {
  107241. using namespace FlacNamespace;
  107242. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107243. }
  107244. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107245. {
  107246. using namespace FlacNamespace;
  107247. if (client_data == 0)
  107248. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107249. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107250. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107251. }
  107252. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107253. {
  107254. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107255. }
  107256. bool ok;
  107257. private:
  107258. FlacNamespace::FLAC__StreamEncoder* encoder;
  107259. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107260. };
  107261. FlacAudioFormat::FlacAudioFormat()
  107262. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107263. {
  107264. }
  107265. FlacAudioFormat::~FlacAudioFormat()
  107266. {
  107267. }
  107268. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107269. {
  107270. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107271. return Array <int> (rates);
  107272. }
  107273. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107274. {
  107275. const int depths[] = { 16, 24, 0 };
  107276. return Array <int> (depths);
  107277. }
  107278. bool FlacAudioFormat::canDoStereo() { return true; }
  107279. bool FlacAudioFormat::canDoMono() { return true; }
  107280. bool FlacAudioFormat::isCompressed() { return true; }
  107281. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107282. const bool deleteStreamIfOpeningFails)
  107283. {
  107284. ScopedPointer<FlacReader> r (new FlacReader (in));
  107285. if (r->sampleRate > 0)
  107286. return r.release();
  107287. if (! deleteStreamIfOpeningFails)
  107288. r->input = 0;
  107289. return 0;
  107290. }
  107291. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107292. double sampleRate,
  107293. unsigned int numberOfChannels,
  107294. int bitsPerSample,
  107295. const StringPairArray& /*metadataValues*/,
  107296. int qualityOptionIndex)
  107297. {
  107298. if (getPossibleBitDepths().contains (bitsPerSample))
  107299. {
  107300. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107301. if (w->ok)
  107302. return w.release();
  107303. }
  107304. return 0;
  107305. }
  107306. END_JUCE_NAMESPACE
  107307. #endif
  107308. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107309. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107310. #if JUCE_USE_OGGVORBIS
  107311. #if JUCE_MAC
  107312. #define __MACOSX__ 1
  107313. #endif
  107314. namespace OggVorbisNamespace
  107315. {
  107316. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107317. /*** Start of inlined file: vorbisenc.h ***/
  107318. #ifndef _OV_ENC_H_
  107319. #define _OV_ENC_H_
  107320. #ifdef __cplusplus
  107321. extern "C"
  107322. {
  107323. #endif /* __cplusplus */
  107324. /*** Start of inlined file: codec.h ***/
  107325. #ifndef _vorbis_codec_h_
  107326. #define _vorbis_codec_h_
  107327. #ifdef __cplusplus
  107328. extern "C"
  107329. {
  107330. #endif /* __cplusplus */
  107331. /*** Start of inlined file: ogg.h ***/
  107332. #ifndef _OGG_H
  107333. #define _OGG_H
  107334. #ifdef __cplusplus
  107335. extern "C" {
  107336. #endif
  107337. /*** Start of inlined file: os_types.h ***/
  107338. #ifndef _OS_TYPES_H
  107339. #define _OS_TYPES_H
  107340. /* make it easy on the folks that want to compile the libs with a
  107341. different malloc than stdlib */
  107342. #define _ogg_malloc malloc
  107343. #define _ogg_calloc calloc
  107344. #define _ogg_realloc realloc
  107345. #define _ogg_free free
  107346. #if defined(_WIN32)
  107347. # if defined(__CYGWIN__)
  107348. # include <_G_config.h>
  107349. typedef _G_int64_t ogg_int64_t;
  107350. typedef _G_int32_t ogg_int32_t;
  107351. typedef _G_uint32_t ogg_uint32_t;
  107352. typedef _G_int16_t ogg_int16_t;
  107353. typedef _G_uint16_t ogg_uint16_t;
  107354. # elif defined(__MINGW32__)
  107355. typedef short ogg_int16_t;
  107356. typedef unsigned short ogg_uint16_t;
  107357. typedef int ogg_int32_t;
  107358. typedef unsigned int ogg_uint32_t;
  107359. typedef long long ogg_int64_t;
  107360. typedef unsigned long long ogg_uint64_t;
  107361. # elif defined(__MWERKS__)
  107362. typedef long long ogg_int64_t;
  107363. typedef int ogg_int32_t;
  107364. typedef unsigned int ogg_uint32_t;
  107365. typedef short ogg_int16_t;
  107366. typedef unsigned short ogg_uint16_t;
  107367. # else
  107368. /* MSVC/Borland */
  107369. typedef __int64 ogg_int64_t;
  107370. typedef __int32 ogg_int32_t;
  107371. typedef unsigned __int32 ogg_uint32_t;
  107372. typedef __int16 ogg_int16_t;
  107373. typedef unsigned __int16 ogg_uint16_t;
  107374. # endif
  107375. #elif defined(__MACOS__)
  107376. # include <sys/types.h>
  107377. typedef SInt16 ogg_int16_t;
  107378. typedef UInt16 ogg_uint16_t;
  107379. typedef SInt32 ogg_int32_t;
  107380. typedef UInt32 ogg_uint32_t;
  107381. typedef SInt64 ogg_int64_t;
  107382. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107383. # include <sys/types.h>
  107384. typedef int16_t ogg_int16_t;
  107385. typedef u_int16_t ogg_uint16_t;
  107386. typedef int32_t ogg_int32_t;
  107387. typedef u_int32_t ogg_uint32_t;
  107388. typedef int64_t ogg_int64_t;
  107389. #elif defined(__BEOS__)
  107390. /* Be */
  107391. # include <inttypes.h>
  107392. typedef int16_t ogg_int16_t;
  107393. typedef u_int16_t ogg_uint16_t;
  107394. typedef int32_t ogg_int32_t;
  107395. typedef u_int32_t ogg_uint32_t;
  107396. typedef int64_t ogg_int64_t;
  107397. #elif defined (__EMX__)
  107398. /* OS/2 GCC */
  107399. typedef short ogg_int16_t;
  107400. typedef unsigned short ogg_uint16_t;
  107401. typedef int ogg_int32_t;
  107402. typedef unsigned int ogg_uint32_t;
  107403. typedef long long ogg_int64_t;
  107404. #elif defined (DJGPP)
  107405. /* DJGPP */
  107406. typedef short ogg_int16_t;
  107407. typedef int ogg_int32_t;
  107408. typedef unsigned int ogg_uint32_t;
  107409. typedef long long ogg_int64_t;
  107410. #elif defined(R5900)
  107411. /* PS2 EE */
  107412. typedef long ogg_int64_t;
  107413. typedef int ogg_int32_t;
  107414. typedef unsigned ogg_uint32_t;
  107415. typedef short ogg_int16_t;
  107416. #elif defined(__SYMBIAN32__)
  107417. /* Symbian GCC */
  107418. typedef signed short ogg_int16_t;
  107419. typedef unsigned short ogg_uint16_t;
  107420. typedef signed int ogg_int32_t;
  107421. typedef unsigned int ogg_uint32_t;
  107422. typedef long long int ogg_int64_t;
  107423. #else
  107424. # include <sys/types.h>
  107425. /*** Start of inlined file: config_types.h ***/
  107426. #ifndef __CONFIG_TYPES_H__
  107427. #define __CONFIG_TYPES_H__
  107428. typedef int16_t ogg_int16_t;
  107429. typedef unsigned short ogg_uint16_t;
  107430. typedef int32_t ogg_int32_t;
  107431. typedef unsigned int ogg_uint32_t;
  107432. typedef int64_t ogg_int64_t;
  107433. #endif
  107434. /*** End of inlined file: config_types.h ***/
  107435. #endif
  107436. #endif /* _OS_TYPES_H */
  107437. /*** End of inlined file: os_types.h ***/
  107438. typedef struct {
  107439. long endbyte;
  107440. int endbit;
  107441. unsigned char *buffer;
  107442. unsigned char *ptr;
  107443. long storage;
  107444. } oggpack_buffer;
  107445. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107446. typedef struct {
  107447. unsigned char *header;
  107448. long header_len;
  107449. unsigned char *body;
  107450. long body_len;
  107451. } ogg_page;
  107452. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107453. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107454. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107455. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107456. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107457. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107458. }
  107459. /* ogg_stream_state contains the current encode/decode state of a logical
  107460. Ogg bitstream **********************************************************/
  107461. typedef struct {
  107462. unsigned char *body_data; /* bytes from packet bodies */
  107463. long body_storage; /* storage elements allocated */
  107464. long body_fill; /* elements stored; fill mark */
  107465. long body_returned; /* elements of fill returned */
  107466. int *lacing_vals; /* The values that will go to the segment table */
  107467. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107468. this way, but it is simple coupled to the
  107469. lacing fifo */
  107470. long lacing_storage;
  107471. long lacing_fill;
  107472. long lacing_packet;
  107473. long lacing_returned;
  107474. unsigned char header[282]; /* working space for header encode */
  107475. int header_fill;
  107476. int e_o_s; /* set when we have buffered the last packet in the
  107477. logical bitstream */
  107478. int b_o_s; /* set after we've written the initial page
  107479. of a logical bitstream */
  107480. long serialno;
  107481. long pageno;
  107482. ogg_int64_t packetno; /* sequence number for decode; the framing
  107483. knows where there's a hole in the data,
  107484. but we need coupling so that the codec
  107485. (which is in a seperate abstraction
  107486. layer) also knows about the gap */
  107487. ogg_int64_t granulepos;
  107488. } ogg_stream_state;
  107489. /* ogg_packet is used to encapsulate the data and metadata belonging
  107490. to a single raw Ogg/Vorbis packet *************************************/
  107491. typedef struct {
  107492. unsigned char *packet;
  107493. long bytes;
  107494. long b_o_s;
  107495. long e_o_s;
  107496. ogg_int64_t granulepos;
  107497. ogg_int64_t packetno; /* sequence number for decode; the framing
  107498. knows where there's a hole in the data,
  107499. but we need coupling so that the codec
  107500. (which is in a seperate abstraction
  107501. layer) also knows about the gap */
  107502. } ogg_packet;
  107503. typedef struct {
  107504. unsigned char *data;
  107505. int storage;
  107506. int fill;
  107507. int returned;
  107508. int unsynced;
  107509. int headerbytes;
  107510. int bodybytes;
  107511. } ogg_sync_state;
  107512. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107513. extern void oggpack_writeinit(oggpack_buffer *b);
  107514. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107515. extern void oggpack_writealign(oggpack_buffer *b);
  107516. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107517. extern void oggpack_reset(oggpack_buffer *b);
  107518. extern void oggpack_writeclear(oggpack_buffer *b);
  107519. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107520. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107521. extern long oggpack_look(oggpack_buffer *b,int bits);
  107522. extern long oggpack_look1(oggpack_buffer *b);
  107523. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107524. extern void oggpack_adv1(oggpack_buffer *b);
  107525. extern long oggpack_read(oggpack_buffer *b,int bits);
  107526. extern long oggpack_read1(oggpack_buffer *b);
  107527. extern long oggpack_bytes(oggpack_buffer *b);
  107528. extern long oggpack_bits(oggpack_buffer *b);
  107529. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107530. extern void oggpackB_writeinit(oggpack_buffer *b);
  107531. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107532. extern void oggpackB_writealign(oggpack_buffer *b);
  107533. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107534. extern void oggpackB_reset(oggpack_buffer *b);
  107535. extern void oggpackB_writeclear(oggpack_buffer *b);
  107536. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107537. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107538. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107539. extern long oggpackB_look1(oggpack_buffer *b);
  107540. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107541. extern void oggpackB_adv1(oggpack_buffer *b);
  107542. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107543. extern long oggpackB_read1(oggpack_buffer *b);
  107544. extern long oggpackB_bytes(oggpack_buffer *b);
  107545. extern long oggpackB_bits(oggpack_buffer *b);
  107546. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107547. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107548. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107549. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107550. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107551. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107552. extern int ogg_sync_init(ogg_sync_state *oy);
  107553. extern int ogg_sync_clear(ogg_sync_state *oy);
  107554. extern int ogg_sync_reset(ogg_sync_state *oy);
  107555. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107556. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107557. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107558. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107559. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107560. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107561. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107562. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107563. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107564. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107565. extern int ogg_stream_clear(ogg_stream_state *os);
  107566. extern int ogg_stream_reset(ogg_stream_state *os);
  107567. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107568. extern int ogg_stream_destroy(ogg_stream_state *os);
  107569. extern int ogg_stream_eos(ogg_stream_state *os);
  107570. extern void ogg_page_checksum_set(ogg_page *og);
  107571. extern int ogg_page_version(ogg_page *og);
  107572. extern int ogg_page_continued(ogg_page *og);
  107573. extern int ogg_page_bos(ogg_page *og);
  107574. extern int ogg_page_eos(ogg_page *og);
  107575. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107576. extern int ogg_page_serialno(ogg_page *og);
  107577. extern long ogg_page_pageno(ogg_page *og);
  107578. extern int ogg_page_packets(ogg_page *og);
  107579. extern void ogg_packet_clear(ogg_packet *op);
  107580. #ifdef __cplusplus
  107581. }
  107582. #endif
  107583. #endif /* _OGG_H */
  107584. /*** End of inlined file: ogg.h ***/
  107585. typedef struct vorbis_info{
  107586. int version;
  107587. int channels;
  107588. long rate;
  107589. /* The below bitrate declarations are *hints*.
  107590. Combinations of the three values carry the following implications:
  107591. all three set to the same value:
  107592. implies a fixed rate bitstream
  107593. only nominal set:
  107594. implies a VBR stream that averages the nominal bitrate. No hard
  107595. upper/lower limit
  107596. upper and or lower set:
  107597. implies a VBR bitstream that obeys the bitrate limits. nominal
  107598. may also be set to give a nominal rate.
  107599. none set:
  107600. the coder does not care to speculate.
  107601. */
  107602. long bitrate_upper;
  107603. long bitrate_nominal;
  107604. long bitrate_lower;
  107605. long bitrate_window;
  107606. void *codec_setup;
  107607. } vorbis_info;
  107608. /* vorbis_dsp_state buffers the current vorbis audio
  107609. analysis/synthesis state. The DSP state belongs to a specific
  107610. logical bitstream ****************************************************/
  107611. typedef struct vorbis_dsp_state{
  107612. int analysisp;
  107613. vorbis_info *vi;
  107614. float **pcm;
  107615. float **pcmret;
  107616. int pcm_storage;
  107617. int pcm_current;
  107618. int pcm_returned;
  107619. int preextrapolate;
  107620. int eofflag;
  107621. long lW;
  107622. long W;
  107623. long nW;
  107624. long centerW;
  107625. ogg_int64_t granulepos;
  107626. ogg_int64_t sequence;
  107627. ogg_int64_t glue_bits;
  107628. ogg_int64_t time_bits;
  107629. ogg_int64_t floor_bits;
  107630. ogg_int64_t res_bits;
  107631. void *backend_state;
  107632. } vorbis_dsp_state;
  107633. typedef struct vorbis_block{
  107634. /* necessary stream state for linking to the framing abstraction */
  107635. float **pcm; /* this is a pointer into local storage */
  107636. oggpack_buffer opb;
  107637. long lW;
  107638. long W;
  107639. long nW;
  107640. int pcmend;
  107641. int mode;
  107642. int eofflag;
  107643. ogg_int64_t granulepos;
  107644. ogg_int64_t sequence;
  107645. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107646. /* local storage to avoid remallocing; it's up to the mapping to
  107647. structure it */
  107648. void *localstore;
  107649. long localtop;
  107650. long localalloc;
  107651. long totaluse;
  107652. struct alloc_chain *reap;
  107653. /* bitmetrics for the frame */
  107654. long glue_bits;
  107655. long time_bits;
  107656. long floor_bits;
  107657. long res_bits;
  107658. void *internal;
  107659. } vorbis_block;
  107660. /* vorbis_block is a single block of data to be processed as part of
  107661. the analysis/synthesis stream; it belongs to a specific logical
  107662. bitstream, but is independant from other vorbis_blocks belonging to
  107663. that logical bitstream. *************************************************/
  107664. struct alloc_chain{
  107665. void *ptr;
  107666. struct alloc_chain *next;
  107667. };
  107668. /* vorbis_info contains all the setup information specific to the
  107669. specific compression/decompression mode in progress (eg,
  107670. psychoacoustic settings, channel setup, options, codebook
  107671. etc). vorbis_info and substructures are in backends.h.
  107672. *********************************************************************/
  107673. /* the comments are not part of vorbis_info so that vorbis_info can be
  107674. static storage */
  107675. typedef struct vorbis_comment{
  107676. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107677. whatever vendor is set to in encode */
  107678. char **user_comments;
  107679. int *comment_lengths;
  107680. int comments;
  107681. char *vendor;
  107682. } vorbis_comment;
  107683. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107684. and produce a packet (see docs/analysis.txt). The packet is then
  107685. coded into a framed OggSquish bitstream by the second layer (see
  107686. docs/framing.txt). Decode is the reverse process; we sync/frame
  107687. the bitstream and extract individual packets, then decode the
  107688. packet back into PCM audio.
  107689. The extra framing/packetizing is used in streaming formats, such as
  107690. files. Over the net (such as with UDP), the framing and
  107691. packetization aren't necessary as they're provided by the transport
  107692. and the streaming layer is not used */
  107693. /* Vorbis PRIMITIVES: general ***************************************/
  107694. extern void vorbis_info_init(vorbis_info *vi);
  107695. extern void vorbis_info_clear(vorbis_info *vi);
  107696. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107697. extern void vorbis_comment_init(vorbis_comment *vc);
  107698. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107699. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107700. const char *tag, char *contents);
  107701. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107702. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107703. extern void vorbis_comment_clear(vorbis_comment *vc);
  107704. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107705. extern int vorbis_block_clear(vorbis_block *vb);
  107706. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107707. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107708. ogg_int64_t granulepos);
  107709. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107710. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107711. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107712. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107713. vorbis_comment *vc,
  107714. ogg_packet *op,
  107715. ogg_packet *op_comm,
  107716. ogg_packet *op_code);
  107717. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107718. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107719. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107720. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107721. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107722. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107723. ogg_packet *op);
  107724. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107725. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107726. ogg_packet *op);
  107727. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107728. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107729. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107730. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107731. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107732. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107733. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107734. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107735. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107736. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107737. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107738. /* Vorbis ERRORS and return codes ***********************************/
  107739. #define OV_FALSE -1
  107740. #define OV_EOF -2
  107741. #define OV_HOLE -3
  107742. #define OV_EREAD -128
  107743. #define OV_EFAULT -129
  107744. #define OV_EIMPL -130
  107745. #define OV_EINVAL -131
  107746. #define OV_ENOTVORBIS -132
  107747. #define OV_EBADHEADER -133
  107748. #define OV_EVERSION -134
  107749. #define OV_ENOTAUDIO -135
  107750. #define OV_EBADPACKET -136
  107751. #define OV_EBADLINK -137
  107752. #define OV_ENOSEEK -138
  107753. #ifdef __cplusplus
  107754. }
  107755. #endif /* __cplusplus */
  107756. #endif
  107757. /*** End of inlined file: codec.h ***/
  107758. extern int vorbis_encode_init(vorbis_info *vi,
  107759. long channels,
  107760. long rate,
  107761. long max_bitrate,
  107762. long nominal_bitrate,
  107763. long min_bitrate);
  107764. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107765. long channels,
  107766. long rate,
  107767. long max_bitrate,
  107768. long nominal_bitrate,
  107769. long min_bitrate);
  107770. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107771. long channels,
  107772. long rate,
  107773. float quality /* quality level from 0. (lo) to 1. (hi) */
  107774. );
  107775. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107776. long channels,
  107777. long rate,
  107778. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107779. );
  107780. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107781. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107782. /* deprecated rate management supported only for compatability */
  107783. #define OV_ECTL_RATEMANAGE_GET 0x10
  107784. #define OV_ECTL_RATEMANAGE_SET 0x11
  107785. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107786. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107787. struct ovectl_ratemanage_arg {
  107788. int management_active;
  107789. long bitrate_hard_min;
  107790. long bitrate_hard_max;
  107791. double bitrate_hard_window;
  107792. long bitrate_av_lo;
  107793. long bitrate_av_hi;
  107794. double bitrate_av_window;
  107795. double bitrate_av_window_center;
  107796. };
  107797. /* new rate setup */
  107798. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107799. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107800. struct ovectl_ratemanage2_arg {
  107801. int management_active;
  107802. long bitrate_limit_min_kbps;
  107803. long bitrate_limit_max_kbps;
  107804. long bitrate_limit_reservoir_bits;
  107805. double bitrate_limit_reservoir_bias;
  107806. long bitrate_average_kbps;
  107807. double bitrate_average_damping;
  107808. };
  107809. #define OV_ECTL_LOWPASS_GET 0x20
  107810. #define OV_ECTL_LOWPASS_SET 0x21
  107811. #define OV_ECTL_IBLOCK_GET 0x30
  107812. #define OV_ECTL_IBLOCK_SET 0x31
  107813. #ifdef __cplusplus
  107814. }
  107815. #endif /* __cplusplus */
  107816. #endif
  107817. /*** End of inlined file: vorbisenc.h ***/
  107818. /*** Start of inlined file: vorbisfile.h ***/
  107819. #ifndef _OV_FILE_H_
  107820. #define _OV_FILE_H_
  107821. #ifdef __cplusplus
  107822. extern "C"
  107823. {
  107824. #endif /* __cplusplus */
  107825. #include <stdio.h>
  107826. /* The function prototypes for the callbacks are basically the same as for
  107827. * the stdio functions fread, fseek, fclose, ftell.
  107828. * The one difference is that the FILE * arguments have been replaced with
  107829. * a void * - this is to be used as a pointer to whatever internal data these
  107830. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107831. *
  107832. * If you use other functions, check the docs for these functions and return
  107833. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107834. * unseekable
  107835. */
  107836. typedef struct {
  107837. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107838. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107839. int (*close_func) (void *datasource);
  107840. long (*tell_func) (void *datasource);
  107841. } ov_callbacks;
  107842. #define NOTOPEN 0
  107843. #define PARTOPEN 1
  107844. #define OPENED 2
  107845. #define STREAMSET 3
  107846. #define INITSET 4
  107847. typedef struct OggVorbis_File {
  107848. void *datasource; /* Pointer to a FILE *, etc. */
  107849. int seekable;
  107850. ogg_int64_t offset;
  107851. ogg_int64_t end;
  107852. ogg_sync_state oy;
  107853. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107854. stream appears */
  107855. int links;
  107856. ogg_int64_t *offsets;
  107857. ogg_int64_t *dataoffsets;
  107858. long *serialnos;
  107859. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107860. compatability; x2 size, stores both
  107861. beginning and end values */
  107862. vorbis_info *vi;
  107863. vorbis_comment *vc;
  107864. /* Decoding working state local storage */
  107865. ogg_int64_t pcm_offset;
  107866. int ready_state;
  107867. long current_serialno;
  107868. int current_link;
  107869. double bittrack;
  107870. double samptrack;
  107871. ogg_stream_state os; /* take physical pages, weld into a logical
  107872. stream of packets */
  107873. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107874. vorbis_block vb; /* local working space for packet->PCM decode */
  107875. ov_callbacks callbacks;
  107876. } OggVorbis_File;
  107877. extern int ov_clear(OggVorbis_File *vf);
  107878. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107879. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107880. char *initial, long ibytes, ov_callbacks callbacks);
  107881. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107882. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107883. char *initial, long ibytes, ov_callbacks callbacks);
  107884. extern int ov_test_open(OggVorbis_File *vf);
  107885. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107886. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107887. extern long ov_streams(OggVorbis_File *vf);
  107888. extern long ov_seekable(OggVorbis_File *vf);
  107889. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107890. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107891. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107892. extern double ov_time_total(OggVorbis_File *vf,int i);
  107893. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107894. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107895. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107896. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107897. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107898. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107899. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107900. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107901. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107902. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107903. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107904. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107905. extern double ov_time_tell(OggVorbis_File *vf);
  107906. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107907. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107908. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107909. int *bitstream);
  107910. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107911. int bigendianp,int word,int sgned,int *bitstream);
  107912. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107913. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107914. extern int ov_halfrate_p(OggVorbis_File *vf);
  107915. #ifdef __cplusplus
  107916. }
  107917. #endif /* __cplusplus */
  107918. #endif
  107919. /*** End of inlined file: vorbisfile.h ***/
  107920. /*** Start of inlined file: bitwise.c ***/
  107921. /* We're 'LSb' endian; if we write a word but read individual bits,
  107922. then we'll read the lsb first */
  107923. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107924. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107925. // tasks..
  107926. #if JUCE_MSVC
  107927. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107928. #endif
  107929. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107930. #if JUCE_USE_OGGVORBIS
  107931. #include <string.h>
  107932. #include <stdlib.h>
  107933. #define BUFFER_INCREMENT 256
  107934. static const unsigned long mask[]=
  107935. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107936. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107937. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107938. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107939. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107940. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107941. 0x3fffffff,0x7fffffff,0xffffffff };
  107942. static const unsigned int mask8B[]=
  107943. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107944. void oggpack_writeinit(oggpack_buffer *b){
  107945. memset(b,0,sizeof(*b));
  107946. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107947. b->buffer[0]='\0';
  107948. b->storage=BUFFER_INCREMENT;
  107949. }
  107950. void oggpackB_writeinit(oggpack_buffer *b){
  107951. oggpack_writeinit(b);
  107952. }
  107953. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107954. long bytes=bits>>3;
  107955. bits-=bytes*8;
  107956. b->ptr=b->buffer+bytes;
  107957. b->endbit=bits;
  107958. b->endbyte=bytes;
  107959. *b->ptr&=mask[bits];
  107960. }
  107961. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107962. long bytes=bits>>3;
  107963. bits-=bytes*8;
  107964. b->ptr=b->buffer+bytes;
  107965. b->endbit=bits;
  107966. b->endbyte=bytes;
  107967. *b->ptr&=mask8B[bits];
  107968. }
  107969. /* Takes only up to 32 bits. */
  107970. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107971. if(b->endbyte+4>=b->storage){
  107972. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107973. b->storage+=BUFFER_INCREMENT;
  107974. b->ptr=b->buffer+b->endbyte;
  107975. }
  107976. value&=mask[bits];
  107977. bits+=b->endbit;
  107978. b->ptr[0]|=value<<b->endbit;
  107979. if(bits>=8){
  107980. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107981. if(bits>=16){
  107982. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107983. if(bits>=24){
  107984. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107985. if(bits>=32){
  107986. if(b->endbit)
  107987. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107988. else
  107989. b->ptr[4]=0;
  107990. }
  107991. }
  107992. }
  107993. }
  107994. b->endbyte+=bits/8;
  107995. b->ptr+=bits/8;
  107996. b->endbit=bits&7;
  107997. }
  107998. /* Takes only up to 32 bits. */
  107999. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108000. if(b->endbyte+4>=b->storage){
  108001. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108002. b->storage+=BUFFER_INCREMENT;
  108003. b->ptr=b->buffer+b->endbyte;
  108004. }
  108005. value=(value&mask[bits])<<(32-bits);
  108006. bits+=b->endbit;
  108007. b->ptr[0]|=value>>(24+b->endbit);
  108008. if(bits>=8){
  108009. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108010. if(bits>=16){
  108011. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108012. if(bits>=24){
  108013. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108014. if(bits>=32){
  108015. if(b->endbit)
  108016. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108017. else
  108018. b->ptr[4]=0;
  108019. }
  108020. }
  108021. }
  108022. }
  108023. b->endbyte+=bits/8;
  108024. b->ptr+=bits/8;
  108025. b->endbit=bits&7;
  108026. }
  108027. void oggpack_writealign(oggpack_buffer *b){
  108028. int bits=8-b->endbit;
  108029. if(bits<8)
  108030. oggpack_write(b,0,bits);
  108031. }
  108032. void oggpackB_writealign(oggpack_buffer *b){
  108033. int bits=8-b->endbit;
  108034. if(bits<8)
  108035. oggpackB_write(b,0,bits);
  108036. }
  108037. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108038. void *source,
  108039. long bits,
  108040. void (*w)(oggpack_buffer *,
  108041. unsigned long,
  108042. int),
  108043. int msb){
  108044. unsigned char *ptr=(unsigned char *)source;
  108045. long bytes=bits/8;
  108046. bits-=bytes*8;
  108047. if(b->endbit){
  108048. int i;
  108049. /* unaligned copy. Do it the hard way. */
  108050. for(i=0;i<bytes;i++)
  108051. w(b,(unsigned long)(ptr[i]),8);
  108052. }else{
  108053. /* aligned block copy */
  108054. if(b->endbyte+bytes+1>=b->storage){
  108055. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108056. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108057. b->ptr=b->buffer+b->endbyte;
  108058. }
  108059. memmove(b->ptr,source,bytes);
  108060. b->ptr+=bytes;
  108061. b->endbyte+=bytes;
  108062. *b->ptr=0;
  108063. }
  108064. if(bits){
  108065. if(msb)
  108066. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108067. else
  108068. w(b,(unsigned long)(ptr[bytes]),bits);
  108069. }
  108070. }
  108071. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108072. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108073. }
  108074. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108075. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108076. }
  108077. void oggpack_reset(oggpack_buffer *b){
  108078. b->ptr=b->buffer;
  108079. b->buffer[0]=0;
  108080. b->endbit=b->endbyte=0;
  108081. }
  108082. void oggpackB_reset(oggpack_buffer *b){
  108083. oggpack_reset(b);
  108084. }
  108085. void oggpack_writeclear(oggpack_buffer *b){
  108086. _ogg_free(b->buffer);
  108087. memset(b,0,sizeof(*b));
  108088. }
  108089. void oggpackB_writeclear(oggpack_buffer *b){
  108090. oggpack_writeclear(b);
  108091. }
  108092. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108093. memset(b,0,sizeof(*b));
  108094. b->buffer=b->ptr=buf;
  108095. b->storage=bytes;
  108096. }
  108097. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108098. oggpack_readinit(b,buf,bytes);
  108099. }
  108100. /* Read in bits without advancing the bitptr; bits <= 32 */
  108101. long oggpack_look(oggpack_buffer *b,int bits){
  108102. unsigned long ret;
  108103. unsigned long m=mask[bits];
  108104. bits+=b->endbit;
  108105. if(b->endbyte+4>=b->storage){
  108106. /* not the main path */
  108107. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108108. }
  108109. ret=b->ptr[0]>>b->endbit;
  108110. if(bits>8){
  108111. ret|=b->ptr[1]<<(8-b->endbit);
  108112. if(bits>16){
  108113. ret|=b->ptr[2]<<(16-b->endbit);
  108114. if(bits>24){
  108115. ret|=b->ptr[3]<<(24-b->endbit);
  108116. if(bits>32 && b->endbit)
  108117. ret|=b->ptr[4]<<(32-b->endbit);
  108118. }
  108119. }
  108120. }
  108121. return(m&ret);
  108122. }
  108123. /* Read in bits without advancing the bitptr; bits <= 32 */
  108124. long oggpackB_look(oggpack_buffer *b,int bits){
  108125. unsigned long ret;
  108126. int m=32-bits;
  108127. bits+=b->endbit;
  108128. if(b->endbyte+4>=b->storage){
  108129. /* not the main path */
  108130. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108131. }
  108132. ret=b->ptr[0]<<(24+b->endbit);
  108133. if(bits>8){
  108134. ret|=b->ptr[1]<<(16+b->endbit);
  108135. if(bits>16){
  108136. ret|=b->ptr[2]<<(8+b->endbit);
  108137. if(bits>24){
  108138. ret|=b->ptr[3]<<(b->endbit);
  108139. if(bits>32 && b->endbit)
  108140. ret|=b->ptr[4]>>(8-b->endbit);
  108141. }
  108142. }
  108143. }
  108144. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108145. }
  108146. long oggpack_look1(oggpack_buffer *b){
  108147. if(b->endbyte>=b->storage)return(-1);
  108148. return((b->ptr[0]>>b->endbit)&1);
  108149. }
  108150. long oggpackB_look1(oggpack_buffer *b){
  108151. if(b->endbyte>=b->storage)return(-1);
  108152. return((b->ptr[0]>>(7-b->endbit))&1);
  108153. }
  108154. void oggpack_adv(oggpack_buffer *b,int bits){
  108155. bits+=b->endbit;
  108156. b->ptr+=bits/8;
  108157. b->endbyte+=bits/8;
  108158. b->endbit=bits&7;
  108159. }
  108160. void oggpackB_adv(oggpack_buffer *b,int bits){
  108161. oggpack_adv(b,bits);
  108162. }
  108163. void oggpack_adv1(oggpack_buffer *b){
  108164. if(++(b->endbit)>7){
  108165. b->endbit=0;
  108166. b->ptr++;
  108167. b->endbyte++;
  108168. }
  108169. }
  108170. void oggpackB_adv1(oggpack_buffer *b){
  108171. oggpack_adv1(b);
  108172. }
  108173. /* bits <= 32 */
  108174. long oggpack_read(oggpack_buffer *b,int bits){
  108175. long ret;
  108176. unsigned long m=mask[bits];
  108177. bits+=b->endbit;
  108178. if(b->endbyte+4>=b->storage){
  108179. /* not the main path */
  108180. ret=-1L;
  108181. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108182. }
  108183. ret=b->ptr[0]>>b->endbit;
  108184. if(bits>8){
  108185. ret|=b->ptr[1]<<(8-b->endbit);
  108186. if(bits>16){
  108187. ret|=b->ptr[2]<<(16-b->endbit);
  108188. if(bits>24){
  108189. ret|=b->ptr[3]<<(24-b->endbit);
  108190. if(bits>32 && b->endbit){
  108191. ret|=b->ptr[4]<<(32-b->endbit);
  108192. }
  108193. }
  108194. }
  108195. }
  108196. ret&=m;
  108197. overflow:
  108198. b->ptr+=bits/8;
  108199. b->endbyte+=bits/8;
  108200. b->endbit=bits&7;
  108201. return(ret);
  108202. }
  108203. /* bits <= 32 */
  108204. long oggpackB_read(oggpack_buffer *b,int bits){
  108205. long ret;
  108206. long m=32-bits;
  108207. bits+=b->endbit;
  108208. if(b->endbyte+4>=b->storage){
  108209. /* not the main path */
  108210. ret=-1L;
  108211. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108212. }
  108213. ret=b->ptr[0]<<(24+b->endbit);
  108214. if(bits>8){
  108215. ret|=b->ptr[1]<<(16+b->endbit);
  108216. if(bits>16){
  108217. ret|=b->ptr[2]<<(8+b->endbit);
  108218. if(bits>24){
  108219. ret|=b->ptr[3]<<(b->endbit);
  108220. if(bits>32 && b->endbit)
  108221. ret|=b->ptr[4]>>(8-b->endbit);
  108222. }
  108223. }
  108224. }
  108225. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108226. overflow:
  108227. b->ptr+=bits/8;
  108228. b->endbyte+=bits/8;
  108229. b->endbit=bits&7;
  108230. return(ret);
  108231. }
  108232. long oggpack_read1(oggpack_buffer *b){
  108233. long ret;
  108234. if(b->endbyte>=b->storage){
  108235. /* not the main path */
  108236. ret=-1L;
  108237. goto overflow;
  108238. }
  108239. ret=(b->ptr[0]>>b->endbit)&1;
  108240. overflow:
  108241. b->endbit++;
  108242. if(b->endbit>7){
  108243. b->endbit=0;
  108244. b->ptr++;
  108245. b->endbyte++;
  108246. }
  108247. return(ret);
  108248. }
  108249. long oggpackB_read1(oggpack_buffer *b){
  108250. long ret;
  108251. if(b->endbyte>=b->storage){
  108252. /* not the main path */
  108253. ret=-1L;
  108254. goto overflow;
  108255. }
  108256. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108257. overflow:
  108258. b->endbit++;
  108259. if(b->endbit>7){
  108260. b->endbit=0;
  108261. b->ptr++;
  108262. b->endbyte++;
  108263. }
  108264. return(ret);
  108265. }
  108266. long oggpack_bytes(oggpack_buffer *b){
  108267. return(b->endbyte+(b->endbit+7)/8);
  108268. }
  108269. long oggpack_bits(oggpack_buffer *b){
  108270. return(b->endbyte*8+b->endbit);
  108271. }
  108272. long oggpackB_bytes(oggpack_buffer *b){
  108273. return oggpack_bytes(b);
  108274. }
  108275. long oggpackB_bits(oggpack_buffer *b){
  108276. return oggpack_bits(b);
  108277. }
  108278. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108279. return(b->buffer);
  108280. }
  108281. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108282. return oggpack_get_buffer(b);
  108283. }
  108284. /* Self test of the bitwise routines; everything else is based on
  108285. them, so they damned well better be solid. */
  108286. #ifdef _V_SELFTEST
  108287. #include <stdio.h>
  108288. static int ilog(unsigned int v){
  108289. int ret=0;
  108290. while(v){
  108291. ret++;
  108292. v>>=1;
  108293. }
  108294. return(ret);
  108295. }
  108296. oggpack_buffer o;
  108297. oggpack_buffer r;
  108298. void report(char *in){
  108299. fprintf(stderr,"%s",in);
  108300. exit(1);
  108301. }
  108302. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108303. long bytes,i;
  108304. unsigned char *buffer;
  108305. oggpack_reset(&o);
  108306. for(i=0;i<vals;i++)
  108307. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108308. buffer=oggpack_get_buffer(&o);
  108309. bytes=oggpack_bytes(&o);
  108310. if(bytes!=compsize)report("wrong number of bytes!\n");
  108311. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108312. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108313. report("wrote incorrect value!\n");
  108314. }
  108315. oggpack_readinit(&r,buffer,bytes);
  108316. for(i=0;i<vals;i++){
  108317. int tbit=bits?bits:ilog(b[i]);
  108318. if(oggpack_look(&r,tbit)==-1)
  108319. report("out of data!\n");
  108320. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108321. report("looked at incorrect value!\n");
  108322. if(tbit==1)
  108323. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108324. report("looked at single bit incorrect value!\n");
  108325. if(tbit==1){
  108326. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108327. report("read incorrect single bit value!\n");
  108328. }else{
  108329. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108330. report("read incorrect value!\n");
  108331. }
  108332. }
  108333. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108334. }
  108335. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108336. long bytes,i;
  108337. unsigned char *buffer;
  108338. oggpackB_reset(&o);
  108339. for(i=0;i<vals;i++)
  108340. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108341. buffer=oggpackB_get_buffer(&o);
  108342. bytes=oggpackB_bytes(&o);
  108343. if(bytes!=compsize)report("wrong number of bytes!\n");
  108344. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108345. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108346. report("wrote incorrect value!\n");
  108347. }
  108348. oggpackB_readinit(&r,buffer,bytes);
  108349. for(i=0;i<vals;i++){
  108350. int tbit=bits?bits:ilog(b[i]);
  108351. if(oggpackB_look(&r,tbit)==-1)
  108352. report("out of data!\n");
  108353. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108354. report("looked at incorrect value!\n");
  108355. if(tbit==1)
  108356. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108357. report("looked at single bit incorrect value!\n");
  108358. if(tbit==1){
  108359. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108360. report("read incorrect single bit value!\n");
  108361. }else{
  108362. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108363. report("read incorrect value!\n");
  108364. }
  108365. }
  108366. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108367. }
  108368. int main(void){
  108369. unsigned char *buffer;
  108370. long bytes,i;
  108371. static unsigned long testbuffer1[]=
  108372. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108373. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108374. int test1size=43;
  108375. static unsigned long testbuffer2[]=
  108376. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108377. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108378. 85525151,0,12321,1,349528352};
  108379. int test2size=21;
  108380. static unsigned long testbuffer3[]=
  108381. {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,
  108382. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108383. int test3size=56;
  108384. static unsigned long large[]=
  108385. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108386. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108387. 85525151,0,12321,1,2146528352};
  108388. int onesize=33;
  108389. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108390. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108391. 223,4};
  108392. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108393. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108394. 245,251,128};
  108395. int twosize=6;
  108396. static int two[6]={61,255,255,251,231,29};
  108397. static int twoB[6]={247,63,255,253,249,120};
  108398. int threesize=54;
  108399. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108400. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108401. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108402. 100,52,4,14,18,86,77,1};
  108403. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108404. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108405. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108406. 200,20,254,4,58,106,176,144,0};
  108407. int foursize=38;
  108408. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108409. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108410. 28,2,133,0,1};
  108411. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108412. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108413. 129,10,4,32};
  108414. int fivesize=45;
  108415. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108416. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108417. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108418. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108419. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108420. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108421. int sixsize=7;
  108422. static int six[7]={17,177,170,242,169,19,148};
  108423. static int sixB[7]={136,141,85,79,149,200,41};
  108424. /* Test read/write together */
  108425. /* Later we test against pregenerated bitstreams */
  108426. oggpack_writeinit(&o);
  108427. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108428. cliptest(testbuffer1,test1size,0,one,onesize);
  108429. fprintf(stderr,"ok.");
  108430. fprintf(stderr,"\nNull bit call (LSb): ");
  108431. cliptest(testbuffer3,test3size,0,two,twosize);
  108432. fprintf(stderr,"ok.");
  108433. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108434. cliptest(testbuffer2,test2size,0,three,threesize);
  108435. fprintf(stderr,"ok.");
  108436. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108437. oggpack_reset(&o);
  108438. for(i=0;i<test2size;i++)
  108439. oggpack_write(&o,large[i],32);
  108440. buffer=oggpack_get_buffer(&o);
  108441. bytes=oggpack_bytes(&o);
  108442. oggpack_readinit(&r,buffer,bytes);
  108443. for(i=0;i<test2size;i++){
  108444. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108445. if(oggpack_look(&r,32)!=large[i]){
  108446. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108447. oggpack_look(&r,32),large[i]);
  108448. report("read incorrect value!\n");
  108449. }
  108450. oggpack_adv(&r,32);
  108451. }
  108452. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108453. fprintf(stderr,"ok.");
  108454. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108455. cliptest(testbuffer1,test1size,7,four,foursize);
  108456. fprintf(stderr,"ok.");
  108457. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108458. cliptest(testbuffer2,test2size,17,five,fivesize);
  108459. fprintf(stderr,"ok.");
  108460. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108461. cliptest(testbuffer3,test3size,1,six,sixsize);
  108462. fprintf(stderr,"ok.");
  108463. fprintf(stderr,"\nTesting read past end (LSb): ");
  108464. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108465. for(i=0;i<64;i++){
  108466. if(oggpack_read(&r,1)!=0){
  108467. fprintf(stderr,"failed; got -1 prematurely.\n");
  108468. exit(1);
  108469. }
  108470. }
  108471. if(oggpack_look(&r,1)!=-1 ||
  108472. oggpack_read(&r,1)!=-1){
  108473. fprintf(stderr,"failed; read past end without -1.\n");
  108474. exit(1);
  108475. }
  108476. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108477. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108478. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108479. exit(1);
  108480. }
  108481. if(oggpack_look(&r,18)!=0 ||
  108482. oggpack_look(&r,18)!=0){
  108483. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108484. exit(1);
  108485. }
  108486. if(oggpack_look(&r,19)!=-1 ||
  108487. oggpack_look(&r,19)!=-1){
  108488. fprintf(stderr,"failed; read past end without -1.\n");
  108489. exit(1);
  108490. }
  108491. if(oggpack_look(&r,32)!=-1 ||
  108492. oggpack_look(&r,32)!=-1){
  108493. fprintf(stderr,"failed; read past end without -1.\n");
  108494. exit(1);
  108495. }
  108496. oggpack_writeclear(&o);
  108497. fprintf(stderr,"ok.\n");
  108498. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108499. /* Test read/write together */
  108500. /* Later we test against pregenerated bitstreams */
  108501. oggpackB_writeinit(&o);
  108502. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108503. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108504. fprintf(stderr,"ok.");
  108505. fprintf(stderr,"\nNull bit call (MSb): ");
  108506. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108507. fprintf(stderr,"ok.");
  108508. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108509. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108510. fprintf(stderr,"ok.");
  108511. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108512. oggpackB_reset(&o);
  108513. for(i=0;i<test2size;i++)
  108514. oggpackB_write(&o,large[i],32);
  108515. buffer=oggpackB_get_buffer(&o);
  108516. bytes=oggpackB_bytes(&o);
  108517. oggpackB_readinit(&r,buffer,bytes);
  108518. for(i=0;i<test2size;i++){
  108519. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108520. if(oggpackB_look(&r,32)!=large[i]){
  108521. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108522. oggpackB_look(&r,32),large[i]);
  108523. report("read incorrect value!\n");
  108524. }
  108525. oggpackB_adv(&r,32);
  108526. }
  108527. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108528. fprintf(stderr,"ok.");
  108529. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108530. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108531. fprintf(stderr,"ok.");
  108532. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108533. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108534. fprintf(stderr,"ok.");
  108535. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108536. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108537. fprintf(stderr,"ok.");
  108538. fprintf(stderr,"\nTesting read past end (MSb): ");
  108539. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108540. for(i=0;i<64;i++){
  108541. if(oggpackB_read(&r,1)!=0){
  108542. fprintf(stderr,"failed; got -1 prematurely.\n");
  108543. exit(1);
  108544. }
  108545. }
  108546. if(oggpackB_look(&r,1)!=-1 ||
  108547. oggpackB_read(&r,1)!=-1){
  108548. fprintf(stderr,"failed; read past end without -1.\n");
  108549. exit(1);
  108550. }
  108551. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108552. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108553. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108554. exit(1);
  108555. }
  108556. if(oggpackB_look(&r,18)!=0 ||
  108557. oggpackB_look(&r,18)!=0){
  108558. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108559. exit(1);
  108560. }
  108561. if(oggpackB_look(&r,19)!=-1 ||
  108562. oggpackB_look(&r,19)!=-1){
  108563. fprintf(stderr,"failed; read past end without -1.\n");
  108564. exit(1);
  108565. }
  108566. if(oggpackB_look(&r,32)!=-1 ||
  108567. oggpackB_look(&r,32)!=-1){
  108568. fprintf(stderr,"failed; read past end without -1.\n");
  108569. exit(1);
  108570. }
  108571. oggpackB_writeclear(&o);
  108572. fprintf(stderr,"ok.\n\n");
  108573. return(0);
  108574. }
  108575. #endif /* _V_SELFTEST */
  108576. #undef BUFFER_INCREMENT
  108577. #endif
  108578. /*** End of inlined file: bitwise.c ***/
  108579. /*** Start of inlined file: framing.c ***/
  108580. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108581. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108582. // tasks..
  108583. #if JUCE_MSVC
  108584. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108585. #endif
  108586. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108587. #if JUCE_USE_OGGVORBIS
  108588. #include <stdlib.h>
  108589. #include <string.h>
  108590. /* A complete description of Ogg framing exists in docs/framing.html */
  108591. int ogg_page_version(ogg_page *og){
  108592. return((int)(og->header[4]));
  108593. }
  108594. int ogg_page_continued(ogg_page *og){
  108595. return((int)(og->header[5]&0x01));
  108596. }
  108597. int ogg_page_bos(ogg_page *og){
  108598. return((int)(og->header[5]&0x02));
  108599. }
  108600. int ogg_page_eos(ogg_page *og){
  108601. return((int)(og->header[5]&0x04));
  108602. }
  108603. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108604. unsigned char *page=og->header;
  108605. ogg_int64_t granulepos=page[13]&(0xff);
  108606. granulepos= (granulepos<<8)|(page[12]&0xff);
  108607. granulepos= (granulepos<<8)|(page[11]&0xff);
  108608. granulepos= (granulepos<<8)|(page[10]&0xff);
  108609. granulepos= (granulepos<<8)|(page[9]&0xff);
  108610. granulepos= (granulepos<<8)|(page[8]&0xff);
  108611. granulepos= (granulepos<<8)|(page[7]&0xff);
  108612. granulepos= (granulepos<<8)|(page[6]&0xff);
  108613. return(granulepos);
  108614. }
  108615. int ogg_page_serialno(ogg_page *og){
  108616. return(og->header[14] |
  108617. (og->header[15]<<8) |
  108618. (og->header[16]<<16) |
  108619. (og->header[17]<<24));
  108620. }
  108621. long ogg_page_pageno(ogg_page *og){
  108622. return(og->header[18] |
  108623. (og->header[19]<<8) |
  108624. (og->header[20]<<16) |
  108625. (og->header[21]<<24));
  108626. }
  108627. /* returns the number of packets that are completed on this page (if
  108628. the leading packet is begun on a previous page, but ends on this
  108629. page, it's counted */
  108630. /* NOTE:
  108631. If a page consists of a packet begun on a previous page, and a new
  108632. packet begun (but not completed) on this page, the return will be:
  108633. ogg_page_packets(page) ==1,
  108634. ogg_page_continued(page) !=0
  108635. If a page happens to be a single packet that was begun on a
  108636. previous page, and spans to the next page (in the case of a three or
  108637. more page packet), the return will be:
  108638. ogg_page_packets(page) ==0,
  108639. ogg_page_continued(page) !=0
  108640. */
  108641. int ogg_page_packets(ogg_page *og){
  108642. int i,n=og->header[26],count=0;
  108643. for(i=0;i<n;i++)
  108644. if(og->header[27+i]<255)count++;
  108645. return(count);
  108646. }
  108647. #if 0
  108648. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108649. use the static init below) */
  108650. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108651. int i;
  108652. unsigned long r;
  108653. r = index << 24;
  108654. for (i=0; i<8; i++)
  108655. if (r & 0x80000000UL)
  108656. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108657. polynomial, although we use an
  108658. unreflected alg and an init/final
  108659. of 0, not 0xffffffff */
  108660. else
  108661. r<<=1;
  108662. return (r & 0xffffffffUL);
  108663. }
  108664. #endif
  108665. static const ogg_uint32_t crc_lookup[256]={
  108666. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108667. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108668. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108669. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108670. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108671. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108672. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108673. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108674. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108675. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108676. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108677. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108678. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108679. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108680. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108681. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108682. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108683. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108684. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108685. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108686. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108687. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108688. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108689. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108690. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108691. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108692. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108693. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108694. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108695. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108696. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108697. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108698. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108699. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108700. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108701. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108702. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108703. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108704. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108705. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108706. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108707. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108708. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108709. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108710. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108711. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108712. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108713. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108714. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108715. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108716. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108717. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108718. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108719. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108720. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108721. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108722. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108723. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108724. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108725. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108726. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108727. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108728. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108729. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108730. /* init the encode/decode logical stream state */
  108731. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108732. if(os){
  108733. memset(os,0,sizeof(*os));
  108734. os->body_storage=16*1024;
  108735. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108736. os->lacing_storage=1024;
  108737. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108738. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108739. os->serialno=serialno;
  108740. return(0);
  108741. }
  108742. return(-1);
  108743. }
  108744. /* _clear does not free os, only the non-flat storage within */
  108745. int ogg_stream_clear(ogg_stream_state *os){
  108746. if(os){
  108747. if(os->body_data)_ogg_free(os->body_data);
  108748. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108749. if(os->granule_vals)_ogg_free(os->granule_vals);
  108750. memset(os,0,sizeof(*os));
  108751. }
  108752. return(0);
  108753. }
  108754. int ogg_stream_destroy(ogg_stream_state *os){
  108755. if(os){
  108756. ogg_stream_clear(os);
  108757. _ogg_free(os);
  108758. }
  108759. return(0);
  108760. }
  108761. /* Helpers for ogg_stream_encode; this keeps the structure and
  108762. what's happening fairly clear */
  108763. static void _os_body_expand(ogg_stream_state *os,int needed){
  108764. if(os->body_storage<=os->body_fill+needed){
  108765. os->body_storage+=(needed+1024);
  108766. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108767. }
  108768. }
  108769. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108770. if(os->lacing_storage<=os->lacing_fill+needed){
  108771. os->lacing_storage+=(needed+32);
  108772. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108773. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108774. }
  108775. }
  108776. /* checksum the page */
  108777. /* Direct table CRC; note that this will be faster in the future if we
  108778. perform the checksum silmultaneously with other copies */
  108779. void ogg_page_checksum_set(ogg_page *og){
  108780. if(og){
  108781. ogg_uint32_t crc_reg=0;
  108782. int i;
  108783. /* safety; needed for API behavior, but not framing code */
  108784. og->header[22]=0;
  108785. og->header[23]=0;
  108786. og->header[24]=0;
  108787. og->header[25]=0;
  108788. for(i=0;i<og->header_len;i++)
  108789. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108790. for(i=0;i<og->body_len;i++)
  108791. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108792. og->header[22]=(unsigned char)(crc_reg&0xff);
  108793. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108794. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108795. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108796. }
  108797. }
  108798. /* submit data to the internal buffer of the framing engine */
  108799. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108800. int lacing_vals=op->bytes/255+1,i;
  108801. if(os->body_returned){
  108802. /* advance packet data according to the body_returned pointer. We
  108803. had to keep it around to return a pointer into the buffer last
  108804. call */
  108805. os->body_fill-=os->body_returned;
  108806. if(os->body_fill)
  108807. memmove(os->body_data,os->body_data+os->body_returned,
  108808. os->body_fill);
  108809. os->body_returned=0;
  108810. }
  108811. /* make sure we have the buffer storage */
  108812. _os_body_expand(os,op->bytes);
  108813. _os_lacing_expand(os,lacing_vals);
  108814. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108815. the liability of overly clean abstraction for the time being. It
  108816. will actually be fairly easy to eliminate the extra copy in the
  108817. future */
  108818. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108819. os->body_fill+=op->bytes;
  108820. /* Store lacing vals for this packet */
  108821. for(i=0;i<lacing_vals-1;i++){
  108822. os->lacing_vals[os->lacing_fill+i]=255;
  108823. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108824. }
  108825. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108826. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108827. /* flag the first segment as the beginning of the packet */
  108828. os->lacing_vals[os->lacing_fill]|= 0x100;
  108829. os->lacing_fill+=lacing_vals;
  108830. /* for the sake of completeness */
  108831. os->packetno++;
  108832. if(op->e_o_s)os->e_o_s=1;
  108833. return(0);
  108834. }
  108835. /* This will flush remaining packets into a page (returning nonzero),
  108836. even if there is not enough data to trigger a flush normally
  108837. (undersized page). If there are no packets or partial packets to
  108838. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108839. try to flush a normal sized page like ogg_stream_pageout; a call to
  108840. ogg_stream_flush does not guarantee that all packets have flushed.
  108841. Only a return value of 0 from ogg_stream_flush indicates all packet
  108842. data is flushed into pages.
  108843. since ogg_stream_flush will flush the last page in a stream even if
  108844. it's undersized, you almost certainly want to use ogg_stream_pageout
  108845. (and *not* ogg_stream_flush) unless you specifically need to flush
  108846. an page regardless of size in the middle of a stream. */
  108847. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108848. int i;
  108849. int vals=0;
  108850. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108851. int bytes=0;
  108852. long acc=0;
  108853. ogg_int64_t granule_pos=-1;
  108854. if(maxvals==0)return(0);
  108855. /* construct a page */
  108856. /* decide how many segments to include */
  108857. /* If this is the initial header case, the first page must only include
  108858. the initial header packet */
  108859. if(os->b_o_s==0){ /* 'initial header page' case */
  108860. granule_pos=0;
  108861. for(vals=0;vals<maxvals;vals++){
  108862. if((os->lacing_vals[vals]&0x0ff)<255){
  108863. vals++;
  108864. break;
  108865. }
  108866. }
  108867. }else{
  108868. for(vals=0;vals<maxvals;vals++){
  108869. if(acc>4096)break;
  108870. acc+=os->lacing_vals[vals]&0x0ff;
  108871. if((os->lacing_vals[vals]&0xff)<255)
  108872. granule_pos=os->granule_vals[vals];
  108873. }
  108874. }
  108875. /* construct the header in temp storage */
  108876. memcpy(os->header,"OggS",4);
  108877. /* stream structure version */
  108878. os->header[4]=0x00;
  108879. /* continued packet flag? */
  108880. os->header[5]=0x00;
  108881. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108882. /* first page flag? */
  108883. if(os->b_o_s==0)os->header[5]|=0x02;
  108884. /* last page flag? */
  108885. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108886. os->b_o_s=1;
  108887. /* 64 bits of PCM position */
  108888. for(i=6;i<14;i++){
  108889. os->header[i]=(unsigned char)(granule_pos&0xff);
  108890. granule_pos>>=8;
  108891. }
  108892. /* 32 bits of stream serial number */
  108893. {
  108894. long serialno=os->serialno;
  108895. for(i=14;i<18;i++){
  108896. os->header[i]=(unsigned char)(serialno&0xff);
  108897. serialno>>=8;
  108898. }
  108899. }
  108900. /* 32 bits of page counter (we have both counter and page header
  108901. because this val can roll over) */
  108902. if(os->pageno==-1)os->pageno=0; /* because someone called
  108903. stream_reset; this would be a
  108904. strange thing to do in an
  108905. encode stream, but it has
  108906. plausible uses */
  108907. {
  108908. long pageno=os->pageno++;
  108909. for(i=18;i<22;i++){
  108910. os->header[i]=(unsigned char)(pageno&0xff);
  108911. pageno>>=8;
  108912. }
  108913. }
  108914. /* zero for computation; filled in later */
  108915. os->header[22]=0;
  108916. os->header[23]=0;
  108917. os->header[24]=0;
  108918. os->header[25]=0;
  108919. /* segment table */
  108920. os->header[26]=(unsigned char)(vals&0xff);
  108921. for(i=0;i<vals;i++)
  108922. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108923. /* set pointers in the ogg_page struct */
  108924. og->header=os->header;
  108925. og->header_len=os->header_fill=vals+27;
  108926. og->body=os->body_data+os->body_returned;
  108927. og->body_len=bytes;
  108928. /* advance the lacing data and set the body_returned pointer */
  108929. os->lacing_fill-=vals;
  108930. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108931. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108932. os->body_returned+=bytes;
  108933. /* calculate the checksum */
  108934. ogg_page_checksum_set(og);
  108935. /* done */
  108936. return(1);
  108937. }
  108938. /* This constructs pages from buffered packet segments. The pointers
  108939. returned are to static buffers; do not free. The returned buffers are
  108940. good only until the next call (using the same ogg_stream_state) */
  108941. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108942. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108943. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108944. os->lacing_fill>=255 || /* 'segment table full' case */
  108945. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108946. return(ogg_stream_flush(os,og));
  108947. }
  108948. /* not enough data to construct a page and not end of stream */
  108949. return(0);
  108950. }
  108951. int ogg_stream_eos(ogg_stream_state *os){
  108952. return os->e_o_s;
  108953. }
  108954. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108955. /* This has two layers to place more of the multi-serialno and paging
  108956. control in the application's hands. First, we expose a data buffer
  108957. using ogg_sync_buffer(). The app either copies into the
  108958. buffer, or passes it directly to read(), etc. We then call
  108959. ogg_sync_wrote() to tell how many bytes we just added.
  108960. Pages are returned (pointers into the buffer in ogg_sync_state)
  108961. by ogg_sync_pageout(). The page is then submitted to
  108962. ogg_stream_pagein() along with the appropriate
  108963. ogg_stream_state* (ie, matching serialno). We then get raw
  108964. packets out calling ogg_stream_packetout() with a
  108965. ogg_stream_state. */
  108966. /* initialize the struct to a known state */
  108967. int ogg_sync_init(ogg_sync_state *oy){
  108968. if(oy){
  108969. memset(oy,0,sizeof(*oy));
  108970. }
  108971. return(0);
  108972. }
  108973. /* clear non-flat storage within */
  108974. int ogg_sync_clear(ogg_sync_state *oy){
  108975. if(oy){
  108976. if(oy->data)_ogg_free(oy->data);
  108977. ogg_sync_init(oy);
  108978. }
  108979. return(0);
  108980. }
  108981. int ogg_sync_destroy(ogg_sync_state *oy){
  108982. if(oy){
  108983. ogg_sync_clear(oy);
  108984. _ogg_free(oy);
  108985. }
  108986. return(0);
  108987. }
  108988. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108989. /* first, clear out any space that has been previously returned */
  108990. if(oy->returned){
  108991. oy->fill-=oy->returned;
  108992. if(oy->fill>0)
  108993. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108994. oy->returned=0;
  108995. }
  108996. if(size>oy->storage-oy->fill){
  108997. /* We need to extend the internal buffer */
  108998. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108999. if(oy->data)
  109000. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109001. else
  109002. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109003. oy->storage=newsize;
  109004. }
  109005. /* expose a segment at least as large as requested at the fill mark */
  109006. return((char *)oy->data+oy->fill);
  109007. }
  109008. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109009. if(oy->fill+bytes>oy->storage)return(-1);
  109010. oy->fill+=bytes;
  109011. return(0);
  109012. }
  109013. /* sync the stream. This is meant to be useful for finding page
  109014. boundaries.
  109015. return values for this:
  109016. -n) skipped n bytes
  109017. 0) page not ready; more data (no bytes skipped)
  109018. n) page synced at current location; page length n bytes
  109019. */
  109020. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109021. unsigned char *page=oy->data+oy->returned;
  109022. unsigned char *next;
  109023. long bytes=oy->fill-oy->returned;
  109024. if(oy->headerbytes==0){
  109025. int headerbytes,i;
  109026. if(bytes<27)return(0); /* not enough for a header */
  109027. /* verify capture pattern */
  109028. if(memcmp(page,"OggS",4))goto sync_fail;
  109029. headerbytes=page[26]+27;
  109030. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109031. /* count up body length in the segment table */
  109032. for(i=0;i<page[26];i++)
  109033. oy->bodybytes+=page[27+i];
  109034. oy->headerbytes=headerbytes;
  109035. }
  109036. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109037. /* The whole test page is buffered. Verify the checksum */
  109038. {
  109039. /* Grab the checksum bytes, set the header field to zero */
  109040. char chksum[4];
  109041. ogg_page log;
  109042. memcpy(chksum,page+22,4);
  109043. memset(page+22,0,4);
  109044. /* set up a temp page struct and recompute the checksum */
  109045. log.header=page;
  109046. log.header_len=oy->headerbytes;
  109047. log.body=page+oy->headerbytes;
  109048. log.body_len=oy->bodybytes;
  109049. ogg_page_checksum_set(&log);
  109050. /* Compare */
  109051. if(memcmp(chksum,page+22,4)){
  109052. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109053. at all) */
  109054. /* replace the computed checksum with the one actually read in */
  109055. memcpy(page+22,chksum,4);
  109056. /* Bad checksum. Lose sync */
  109057. goto sync_fail;
  109058. }
  109059. }
  109060. /* yes, have a whole page all ready to go */
  109061. {
  109062. unsigned char *page=oy->data+oy->returned;
  109063. long bytes;
  109064. if(og){
  109065. og->header=page;
  109066. og->header_len=oy->headerbytes;
  109067. og->body=page+oy->headerbytes;
  109068. og->body_len=oy->bodybytes;
  109069. }
  109070. oy->unsynced=0;
  109071. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109072. oy->headerbytes=0;
  109073. oy->bodybytes=0;
  109074. return(bytes);
  109075. }
  109076. sync_fail:
  109077. oy->headerbytes=0;
  109078. oy->bodybytes=0;
  109079. /* search for possible capture */
  109080. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109081. if(!next)
  109082. next=oy->data+oy->fill;
  109083. oy->returned=next-oy->data;
  109084. return(-(next-page));
  109085. }
  109086. /* sync the stream and get a page. Keep trying until we find a page.
  109087. Supress 'sync errors' after reporting the first.
  109088. return values:
  109089. -1) recapture (hole in data)
  109090. 0) need more data
  109091. 1) page returned
  109092. Returns pointers into buffered data; invalidated by next call to
  109093. _stream, _clear, _init, or _buffer */
  109094. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109095. /* all we need to do is verify a page at the head of the stream
  109096. buffer. If it doesn't verify, we look for the next potential
  109097. frame */
  109098. for(;;){
  109099. long ret=ogg_sync_pageseek(oy,og);
  109100. if(ret>0){
  109101. /* have a page */
  109102. return(1);
  109103. }
  109104. if(ret==0){
  109105. /* need more data */
  109106. return(0);
  109107. }
  109108. /* head did not start a synced page... skipped some bytes */
  109109. if(!oy->unsynced){
  109110. oy->unsynced=1;
  109111. return(-1);
  109112. }
  109113. /* loop. keep looking */
  109114. }
  109115. }
  109116. /* add the incoming page to the stream state; we decompose the page
  109117. into packet segments here as well. */
  109118. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109119. unsigned char *header=og->header;
  109120. unsigned char *body=og->body;
  109121. long bodysize=og->body_len;
  109122. int segptr=0;
  109123. int version=ogg_page_version(og);
  109124. int continued=ogg_page_continued(og);
  109125. int bos=ogg_page_bos(og);
  109126. int eos=ogg_page_eos(og);
  109127. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109128. int serialno=ogg_page_serialno(og);
  109129. long pageno=ogg_page_pageno(og);
  109130. int segments=header[26];
  109131. /* clean up 'returned data' */
  109132. {
  109133. long lr=os->lacing_returned;
  109134. long br=os->body_returned;
  109135. /* body data */
  109136. if(br){
  109137. os->body_fill-=br;
  109138. if(os->body_fill)
  109139. memmove(os->body_data,os->body_data+br,os->body_fill);
  109140. os->body_returned=0;
  109141. }
  109142. if(lr){
  109143. /* segment table */
  109144. if(os->lacing_fill-lr){
  109145. memmove(os->lacing_vals,os->lacing_vals+lr,
  109146. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109147. memmove(os->granule_vals,os->granule_vals+lr,
  109148. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109149. }
  109150. os->lacing_fill-=lr;
  109151. os->lacing_packet-=lr;
  109152. os->lacing_returned=0;
  109153. }
  109154. }
  109155. /* check the serial number */
  109156. if(serialno!=os->serialno)return(-1);
  109157. if(version>0)return(-1);
  109158. _os_lacing_expand(os,segments+1);
  109159. /* are we in sequence? */
  109160. if(pageno!=os->pageno){
  109161. int i;
  109162. /* unroll previous partial packet (if any) */
  109163. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109164. os->body_fill-=os->lacing_vals[i]&0xff;
  109165. os->lacing_fill=os->lacing_packet;
  109166. /* make a note of dropped data in segment table */
  109167. if(os->pageno!=-1){
  109168. os->lacing_vals[os->lacing_fill++]=0x400;
  109169. os->lacing_packet++;
  109170. }
  109171. }
  109172. /* are we a 'continued packet' page? If so, we may need to skip
  109173. some segments */
  109174. if(continued){
  109175. if(os->lacing_fill<1 ||
  109176. os->lacing_vals[os->lacing_fill-1]==0x400){
  109177. bos=0;
  109178. for(;segptr<segments;segptr++){
  109179. int val=header[27+segptr];
  109180. body+=val;
  109181. bodysize-=val;
  109182. if(val<255){
  109183. segptr++;
  109184. break;
  109185. }
  109186. }
  109187. }
  109188. }
  109189. if(bodysize){
  109190. _os_body_expand(os,bodysize);
  109191. memcpy(os->body_data+os->body_fill,body,bodysize);
  109192. os->body_fill+=bodysize;
  109193. }
  109194. {
  109195. int saved=-1;
  109196. while(segptr<segments){
  109197. int val=header[27+segptr];
  109198. os->lacing_vals[os->lacing_fill]=val;
  109199. os->granule_vals[os->lacing_fill]=-1;
  109200. if(bos){
  109201. os->lacing_vals[os->lacing_fill]|=0x100;
  109202. bos=0;
  109203. }
  109204. if(val<255)saved=os->lacing_fill;
  109205. os->lacing_fill++;
  109206. segptr++;
  109207. if(val<255)os->lacing_packet=os->lacing_fill;
  109208. }
  109209. /* set the granulepos on the last granuleval of the last full packet */
  109210. if(saved!=-1){
  109211. os->granule_vals[saved]=granulepos;
  109212. }
  109213. }
  109214. if(eos){
  109215. os->e_o_s=1;
  109216. if(os->lacing_fill>0)
  109217. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109218. }
  109219. os->pageno=pageno+1;
  109220. return(0);
  109221. }
  109222. /* clear things to an initial state. Good to call, eg, before seeking */
  109223. int ogg_sync_reset(ogg_sync_state *oy){
  109224. oy->fill=0;
  109225. oy->returned=0;
  109226. oy->unsynced=0;
  109227. oy->headerbytes=0;
  109228. oy->bodybytes=0;
  109229. return(0);
  109230. }
  109231. int ogg_stream_reset(ogg_stream_state *os){
  109232. os->body_fill=0;
  109233. os->body_returned=0;
  109234. os->lacing_fill=0;
  109235. os->lacing_packet=0;
  109236. os->lacing_returned=0;
  109237. os->header_fill=0;
  109238. os->e_o_s=0;
  109239. os->b_o_s=0;
  109240. os->pageno=-1;
  109241. os->packetno=0;
  109242. os->granulepos=0;
  109243. return(0);
  109244. }
  109245. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109246. ogg_stream_reset(os);
  109247. os->serialno=serialno;
  109248. return(0);
  109249. }
  109250. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109251. /* The last part of decode. We have the stream broken into packet
  109252. segments. Now we need to group them into packets (or return the
  109253. out of sync markers) */
  109254. int ptr=os->lacing_returned;
  109255. if(os->lacing_packet<=ptr)return(0);
  109256. if(os->lacing_vals[ptr]&0x400){
  109257. /* we need to tell the codec there's a gap; it might need to
  109258. handle previous packet dependencies. */
  109259. os->lacing_returned++;
  109260. os->packetno++;
  109261. return(-1);
  109262. }
  109263. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109264. to ask if there's a whole packet
  109265. waiting */
  109266. /* Gather the whole packet. We'll have no holes or a partial packet */
  109267. {
  109268. int size=os->lacing_vals[ptr]&0xff;
  109269. int bytes=size;
  109270. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109271. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109272. while(size==255){
  109273. int val=os->lacing_vals[++ptr];
  109274. size=val&0xff;
  109275. if(val&0x200)eos=0x200;
  109276. bytes+=size;
  109277. }
  109278. if(op){
  109279. op->e_o_s=eos;
  109280. op->b_o_s=bos;
  109281. op->packet=os->body_data+os->body_returned;
  109282. op->packetno=os->packetno;
  109283. op->granulepos=os->granule_vals[ptr];
  109284. op->bytes=bytes;
  109285. }
  109286. if(adv){
  109287. os->body_returned+=bytes;
  109288. os->lacing_returned=ptr+1;
  109289. os->packetno++;
  109290. }
  109291. }
  109292. return(1);
  109293. }
  109294. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109295. return _packetout(os,op,1);
  109296. }
  109297. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109298. return _packetout(os,op,0);
  109299. }
  109300. void ogg_packet_clear(ogg_packet *op) {
  109301. _ogg_free(op->packet);
  109302. memset(op, 0, sizeof(*op));
  109303. }
  109304. #ifdef _V_SELFTEST
  109305. #include <stdio.h>
  109306. ogg_stream_state os_en, os_de;
  109307. ogg_sync_state oy;
  109308. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109309. long j;
  109310. static int sequence=0;
  109311. static int lastno=0;
  109312. if(op->bytes!=len){
  109313. fprintf(stderr,"incorrect packet length!\n");
  109314. exit(1);
  109315. }
  109316. if(op->granulepos!=pos){
  109317. fprintf(stderr,"incorrect packet position!\n");
  109318. exit(1);
  109319. }
  109320. /* packet number just follows sequence/gap; adjust the input number
  109321. for that */
  109322. if(no==0){
  109323. sequence=0;
  109324. }else{
  109325. sequence++;
  109326. if(no>lastno+1)
  109327. sequence++;
  109328. }
  109329. lastno=no;
  109330. if(op->packetno!=sequence){
  109331. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109332. (long)(op->packetno),sequence);
  109333. exit(1);
  109334. }
  109335. /* Test data */
  109336. for(j=0;j<op->bytes;j++)
  109337. if(op->packet[j]!=((j+no)&0xff)){
  109338. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109339. j,op->packet[j],(j+no)&0xff);
  109340. exit(1);
  109341. }
  109342. }
  109343. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109344. long j;
  109345. /* Test data */
  109346. for(j=0;j<og->body_len;j++)
  109347. if(og->body[j]!=data[j]){
  109348. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109349. j,data[j],og->body[j]);
  109350. exit(1);
  109351. }
  109352. /* Test header */
  109353. for(j=0;j<og->header_len;j++){
  109354. if(og->header[j]!=header[j]){
  109355. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109356. for(j=0;j<header[26]+27;j++)
  109357. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109358. fprintf(stderr,"\n");
  109359. exit(1);
  109360. }
  109361. }
  109362. if(og->header_len!=header[26]+27){
  109363. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109364. og->header_len,header[26]+27);
  109365. exit(1);
  109366. }
  109367. }
  109368. void print_header(ogg_page *og){
  109369. int j;
  109370. fprintf(stderr,"\nHEADER:\n");
  109371. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109372. og->header[0],og->header[1],og->header[2],og->header[3],
  109373. (int)og->header[4],(int)og->header[5]);
  109374. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109375. (og->header[9]<<24)|(og->header[8]<<16)|
  109376. (og->header[7]<<8)|og->header[6],
  109377. (og->header[17]<<24)|(og->header[16]<<16)|
  109378. (og->header[15]<<8)|og->header[14],
  109379. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109380. (og->header[19]<<8)|og->header[18]);
  109381. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109382. (int)og->header[22],(int)og->header[23],
  109383. (int)og->header[24],(int)og->header[25],
  109384. (int)og->header[26]);
  109385. for(j=27;j<og->header_len;j++)
  109386. fprintf(stderr,"%d ",(int)og->header[j]);
  109387. fprintf(stderr,")\n\n");
  109388. }
  109389. void copy_page(ogg_page *og){
  109390. unsigned char *temp=_ogg_malloc(og->header_len);
  109391. memcpy(temp,og->header,og->header_len);
  109392. og->header=temp;
  109393. temp=_ogg_malloc(og->body_len);
  109394. memcpy(temp,og->body,og->body_len);
  109395. og->body=temp;
  109396. }
  109397. void free_page(ogg_page *og){
  109398. _ogg_free (og->header);
  109399. _ogg_free (og->body);
  109400. }
  109401. void error(void){
  109402. fprintf(stderr,"error!\n");
  109403. exit(1);
  109404. }
  109405. /* 17 only */
  109406. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109407. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109408. 0x01,0x02,0x03,0x04,0,0,0,0,
  109409. 0x15,0xed,0xec,0x91,
  109410. 1,
  109411. 17};
  109412. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109413. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109414. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109415. 0x01,0x02,0x03,0x04,0,0,0,0,
  109416. 0x59,0x10,0x6c,0x2c,
  109417. 1,
  109418. 17};
  109419. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109420. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109421. 0x01,0x02,0x03,0x04,1,0,0,0,
  109422. 0x89,0x33,0x85,0xce,
  109423. 13,
  109424. 254,255,0,255,1,255,245,255,255,0,
  109425. 255,255,90};
  109426. /* nil packets; beginning,middle,end */
  109427. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109428. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109429. 0x01,0x02,0x03,0x04,0,0,0,0,
  109430. 0xff,0x7b,0x23,0x17,
  109431. 1,
  109432. 0};
  109433. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109434. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109435. 0x01,0x02,0x03,0x04,1,0,0,0,
  109436. 0x5c,0x3f,0x66,0xcb,
  109437. 17,
  109438. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109439. 255,255,90,0};
  109440. /* large initial packet */
  109441. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109442. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109443. 0x01,0x02,0x03,0x04,0,0,0,0,
  109444. 0x01,0x27,0x31,0xaa,
  109445. 18,
  109446. 255,255,255,255,255,255,255,255,
  109447. 255,255,255,255,255,255,255,255,255,10};
  109448. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109449. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109450. 0x01,0x02,0x03,0x04,1,0,0,0,
  109451. 0x7f,0x4e,0x8a,0xd2,
  109452. 4,
  109453. 255,4,255,0};
  109454. /* continuing packet test */
  109455. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109456. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109457. 0x01,0x02,0x03,0x04,0,0,0,0,
  109458. 0xff,0x7b,0x23,0x17,
  109459. 1,
  109460. 0};
  109461. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109462. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109463. 0x01,0x02,0x03,0x04,1,0,0,0,
  109464. 0x54,0x05,0x51,0xc8,
  109465. 17,
  109466. 255,255,255,255,255,255,255,255,
  109467. 255,255,255,255,255,255,255,255,255};
  109468. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109469. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109470. 0x01,0x02,0x03,0x04,2,0,0,0,
  109471. 0xc8,0xc3,0xcb,0xed,
  109472. 5,
  109473. 10,255,4,255,0};
  109474. /* page with the 255 segment limit */
  109475. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109476. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109477. 0x01,0x02,0x03,0x04,0,0,0,0,
  109478. 0xff,0x7b,0x23,0x17,
  109479. 1,
  109480. 0};
  109481. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109482. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109483. 0x01,0x02,0x03,0x04,1,0,0,0,
  109484. 0xed,0x2a,0x2e,0xa7,
  109485. 255,
  109486. 10,10,10,10,10,10,10,10,
  109487. 10,10,10,10,10,10,10,10,
  109488. 10,10,10,10,10,10,10,10,
  109489. 10,10,10,10,10,10,10,10,
  109490. 10,10,10,10,10,10,10,10,
  109491. 10,10,10,10,10,10,10,10,
  109492. 10,10,10,10,10,10,10,10,
  109493. 10,10,10,10,10,10,10,10,
  109494. 10,10,10,10,10,10,10,10,
  109495. 10,10,10,10,10,10,10,10,
  109496. 10,10,10,10,10,10,10,10,
  109497. 10,10,10,10,10,10,10,10,
  109498. 10,10,10,10,10,10,10,10,
  109499. 10,10,10,10,10,10,10,10,
  109500. 10,10,10,10,10,10,10,10,
  109501. 10,10,10,10,10,10,10,10,
  109502. 10,10,10,10,10,10,10,10,
  109503. 10,10,10,10,10,10,10,10,
  109504. 10,10,10,10,10,10,10,10,
  109505. 10,10,10,10,10,10,10,10,
  109506. 10,10,10,10,10,10,10,10,
  109507. 10,10,10,10,10,10,10,10,
  109508. 10,10,10,10,10,10,10,10,
  109509. 10,10,10,10,10,10,10,10,
  109510. 10,10,10,10,10,10,10,10,
  109511. 10,10,10,10,10,10,10,10,
  109512. 10,10,10,10,10,10,10,10,
  109513. 10,10,10,10,10,10,10,10,
  109514. 10,10,10,10,10,10,10,10,
  109515. 10,10,10,10,10,10,10,10,
  109516. 10,10,10,10,10,10,10,10,
  109517. 10,10,10,10,10,10,10};
  109518. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109519. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109520. 0x01,0x02,0x03,0x04,2,0,0,0,
  109521. 0x6c,0x3b,0x82,0x3d,
  109522. 1,
  109523. 50};
  109524. /* packet that overspans over an entire page */
  109525. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109526. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109527. 0x01,0x02,0x03,0x04,0,0,0,0,
  109528. 0xff,0x7b,0x23,0x17,
  109529. 1,
  109530. 0};
  109531. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109532. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109533. 0x01,0x02,0x03,0x04,1,0,0,0,
  109534. 0x3c,0xd9,0x4d,0x3f,
  109535. 17,
  109536. 100,255,255,255,255,255,255,255,255,
  109537. 255,255,255,255,255,255,255,255};
  109538. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109539. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109540. 0x01,0x02,0x03,0x04,2,0,0,0,
  109541. 0x01,0xd2,0xe5,0xe5,
  109542. 17,
  109543. 255,255,255,255,255,255,255,255,
  109544. 255,255,255,255,255,255,255,255,255};
  109545. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109546. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109547. 0x01,0x02,0x03,0x04,3,0,0,0,
  109548. 0xef,0xdd,0x88,0xde,
  109549. 7,
  109550. 255,255,75,255,4,255,0};
  109551. /* packet that overspans over an entire page */
  109552. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109553. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109554. 0x01,0x02,0x03,0x04,0,0,0,0,
  109555. 0xff,0x7b,0x23,0x17,
  109556. 1,
  109557. 0};
  109558. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109559. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109560. 0x01,0x02,0x03,0x04,1,0,0,0,
  109561. 0x3c,0xd9,0x4d,0x3f,
  109562. 17,
  109563. 100,255,255,255,255,255,255,255,255,
  109564. 255,255,255,255,255,255,255,255};
  109565. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109566. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109567. 0x01,0x02,0x03,0x04,2,0,0,0,
  109568. 0xd4,0xe0,0x60,0xe5,
  109569. 1,0};
  109570. void test_pack(const int *pl, const int **headers, int byteskip,
  109571. int pageskip, int packetskip){
  109572. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109573. long inptr=0;
  109574. long outptr=0;
  109575. long deptr=0;
  109576. long depacket=0;
  109577. long granule_pos=7,pageno=0;
  109578. int i,j,packets,pageout=pageskip;
  109579. int eosflag=0;
  109580. int bosflag=0;
  109581. int byteskipcount=0;
  109582. ogg_stream_reset(&os_en);
  109583. ogg_stream_reset(&os_de);
  109584. ogg_sync_reset(&oy);
  109585. for(packets=0;packets<packetskip;packets++)
  109586. depacket+=pl[packets];
  109587. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109588. for(i=0;i<packets;i++){
  109589. /* construct a test packet */
  109590. ogg_packet op;
  109591. int len=pl[i];
  109592. op.packet=data+inptr;
  109593. op.bytes=len;
  109594. op.e_o_s=(pl[i+1]<0?1:0);
  109595. op.granulepos=granule_pos;
  109596. granule_pos+=1024;
  109597. for(j=0;j<len;j++)data[inptr++]=i+j;
  109598. /* submit the test packet */
  109599. ogg_stream_packetin(&os_en,&op);
  109600. /* retrieve any finished pages */
  109601. {
  109602. ogg_page og;
  109603. while(ogg_stream_pageout(&os_en,&og)){
  109604. /* We have a page. Check it carefully */
  109605. fprintf(stderr,"%ld, ",pageno);
  109606. if(headers[pageno]==NULL){
  109607. fprintf(stderr,"coded too many pages!\n");
  109608. exit(1);
  109609. }
  109610. check_page(data+outptr,headers[pageno],&og);
  109611. outptr+=og.body_len;
  109612. pageno++;
  109613. if(pageskip){
  109614. bosflag=1;
  109615. pageskip--;
  109616. deptr+=og.body_len;
  109617. }
  109618. /* have a complete page; submit it to sync/decode */
  109619. {
  109620. ogg_page og_de;
  109621. ogg_packet op_de,op_de2;
  109622. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109623. char *next=buf;
  109624. byteskipcount+=og.header_len;
  109625. if(byteskipcount>byteskip){
  109626. memcpy(next,og.header,byteskipcount-byteskip);
  109627. next+=byteskipcount-byteskip;
  109628. byteskipcount=byteskip;
  109629. }
  109630. byteskipcount+=og.body_len;
  109631. if(byteskipcount>byteskip){
  109632. memcpy(next,og.body,byteskipcount-byteskip);
  109633. next+=byteskipcount-byteskip;
  109634. byteskipcount=byteskip;
  109635. }
  109636. ogg_sync_wrote(&oy,next-buf);
  109637. while(1){
  109638. int ret=ogg_sync_pageout(&oy,&og_de);
  109639. if(ret==0)break;
  109640. if(ret<0)continue;
  109641. /* got a page. Happy happy. Verify that it's good. */
  109642. fprintf(stderr,"(%ld), ",pageout);
  109643. check_page(data+deptr,headers[pageout],&og_de);
  109644. deptr+=og_de.body_len;
  109645. pageout++;
  109646. /* submit it to deconstitution */
  109647. ogg_stream_pagein(&os_de,&og_de);
  109648. /* packets out? */
  109649. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109650. ogg_stream_packetpeek(&os_de,NULL);
  109651. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109652. /* verify peek and out match */
  109653. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109654. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109655. depacket);
  109656. exit(1);
  109657. }
  109658. /* verify the packet! */
  109659. /* check data */
  109660. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109661. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109662. depacket);
  109663. exit(1);
  109664. }
  109665. /* check bos flag */
  109666. if(bosflag==0 && op_de.b_o_s==0){
  109667. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109668. exit(1);
  109669. }
  109670. if(bosflag && op_de.b_o_s){
  109671. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109672. exit(1);
  109673. }
  109674. bosflag=1;
  109675. depacket+=op_de.bytes;
  109676. /* check eos flag */
  109677. if(eosflag){
  109678. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109679. exit(1);
  109680. }
  109681. if(op_de.e_o_s)eosflag=1;
  109682. /* check granulepos flag */
  109683. if(op_de.granulepos!=-1){
  109684. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109685. }
  109686. }
  109687. }
  109688. }
  109689. }
  109690. }
  109691. }
  109692. _ogg_free(data);
  109693. if(headers[pageno]!=NULL){
  109694. fprintf(stderr,"did not write last page!\n");
  109695. exit(1);
  109696. }
  109697. if(headers[pageout]!=NULL){
  109698. fprintf(stderr,"did not decode last page!\n");
  109699. exit(1);
  109700. }
  109701. if(inptr!=outptr){
  109702. fprintf(stderr,"encoded page data incomplete!\n");
  109703. exit(1);
  109704. }
  109705. if(inptr!=deptr){
  109706. fprintf(stderr,"decoded page data incomplete!\n");
  109707. exit(1);
  109708. }
  109709. if(inptr!=depacket){
  109710. fprintf(stderr,"decoded packet data incomplete!\n");
  109711. exit(1);
  109712. }
  109713. if(!eosflag){
  109714. fprintf(stderr,"Never got a packet with EOS set!\n");
  109715. exit(1);
  109716. }
  109717. fprintf(stderr,"ok.\n");
  109718. }
  109719. int main(void){
  109720. ogg_stream_init(&os_en,0x04030201);
  109721. ogg_stream_init(&os_de,0x04030201);
  109722. ogg_sync_init(&oy);
  109723. /* Exercise each code path in the framing code. Also verify that
  109724. the checksums are working. */
  109725. {
  109726. /* 17 only */
  109727. const int packets[]={17, -1};
  109728. const int *headret[]={head1_0,NULL};
  109729. fprintf(stderr,"testing single page encoding... ");
  109730. test_pack(packets,headret,0,0,0);
  109731. }
  109732. {
  109733. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109734. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109735. const int *headret[]={head1_1,head2_1,NULL};
  109736. fprintf(stderr,"testing basic page encoding... ");
  109737. test_pack(packets,headret,0,0,0);
  109738. }
  109739. {
  109740. /* nil packets; beginning,middle,end */
  109741. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109742. const int *headret[]={head1_2,head2_2,NULL};
  109743. fprintf(stderr,"testing basic nil packets... ");
  109744. test_pack(packets,headret,0,0,0);
  109745. }
  109746. {
  109747. /* large initial packet */
  109748. const int packets[]={4345,259,255,-1};
  109749. const int *headret[]={head1_3,head2_3,NULL};
  109750. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109751. test_pack(packets,headret,0,0,0);
  109752. }
  109753. {
  109754. /* continuing packet test */
  109755. const int packets[]={0,4345,259,255,-1};
  109756. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109757. fprintf(stderr,"testing single packet page span... ");
  109758. test_pack(packets,headret,0,0,0);
  109759. }
  109760. /* page with the 255 segment limit */
  109761. {
  109762. const int packets[]={0,10,10,10,10,10,10,10,10,
  109763. 10,10,10,10,10,10,10,10,
  109764. 10,10,10,10,10,10,10,10,
  109765. 10,10,10,10,10,10,10,10,
  109766. 10,10,10,10,10,10,10,10,
  109767. 10,10,10,10,10,10,10,10,
  109768. 10,10,10,10,10,10,10,10,
  109769. 10,10,10,10,10,10,10,10,
  109770. 10,10,10,10,10,10,10,10,
  109771. 10,10,10,10,10,10,10,10,
  109772. 10,10,10,10,10,10,10,10,
  109773. 10,10,10,10,10,10,10,10,
  109774. 10,10,10,10,10,10,10,10,
  109775. 10,10,10,10,10,10,10,10,
  109776. 10,10,10,10,10,10,10,10,
  109777. 10,10,10,10,10,10,10,10,
  109778. 10,10,10,10,10,10,10,10,
  109779. 10,10,10,10,10,10,10,10,
  109780. 10,10,10,10,10,10,10,10,
  109781. 10,10,10,10,10,10,10,10,
  109782. 10,10,10,10,10,10,10,10,
  109783. 10,10,10,10,10,10,10,10,
  109784. 10,10,10,10,10,10,10,10,
  109785. 10,10,10,10,10,10,10,10,
  109786. 10,10,10,10,10,10,10,10,
  109787. 10,10,10,10,10,10,10,10,
  109788. 10,10,10,10,10,10,10,10,
  109789. 10,10,10,10,10,10,10,10,
  109790. 10,10,10,10,10,10,10,10,
  109791. 10,10,10,10,10,10,10,10,
  109792. 10,10,10,10,10,10,10,10,
  109793. 10,10,10,10,10,10,10,50,-1};
  109794. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109795. fprintf(stderr,"testing max packet segments... ");
  109796. test_pack(packets,headret,0,0,0);
  109797. }
  109798. {
  109799. /* packet that overspans over an entire page */
  109800. const int packets[]={0,100,9000,259,255,-1};
  109801. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109802. fprintf(stderr,"testing very large packets... ");
  109803. test_pack(packets,headret,0,0,0);
  109804. }
  109805. {
  109806. /* test for the libogg 1.1.1 resync in large continuation bug
  109807. found by Josh Coalson) */
  109808. const int packets[]={0,100,9000,259,255,-1};
  109809. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109810. fprintf(stderr,"testing continuation resync in very large packets... ");
  109811. test_pack(packets,headret,100,2,3);
  109812. }
  109813. {
  109814. /* term only page. why not? */
  109815. const int packets[]={0,100,4080,-1};
  109816. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109817. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109818. test_pack(packets,headret,0,0,0);
  109819. }
  109820. {
  109821. /* build a bunch of pages for testing */
  109822. unsigned char *data=_ogg_malloc(1024*1024);
  109823. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109824. int inptr=0,i,j;
  109825. ogg_page og[5];
  109826. ogg_stream_reset(&os_en);
  109827. for(i=0;pl[i]!=-1;i++){
  109828. ogg_packet op;
  109829. int len=pl[i];
  109830. op.packet=data+inptr;
  109831. op.bytes=len;
  109832. op.e_o_s=(pl[i+1]<0?1:0);
  109833. op.granulepos=(i+1)*1000;
  109834. for(j=0;j<len;j++)data[inptr++]=i+j;
  109835. ogg_stream_packetin(&os_en,&op);
  109836. }
  109837. _ogg_free(data);
  109838. /* retrieve finished pages */
  109839. for(i=0;i<5;i++){
  109840. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109841. fprintf(stderr,"Too few pages output building sync tests!\n");
  109842. exit(1);
  109843. }
  109844. copy_page(&og[i]);
  109845. }
  109846. /* Test lost pages on pagein/packetout: no rollback */
  109847. {
  109848. ogg_page temp;
  109849. ogg_packet test;
  109850. fprintf(stderr,"Testing loss of pages... ");
  109851. ogg_sync_reset(&oy);
  109852. ogg_stream_reset(&os_de);
  109853. for(i=0;i<5;i++){
  109854. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109855. og[i].header_len);
  109856. ogg_sync_wrote(&oy,og[i].header_len);
  109857. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109858. ogg_sync_wrote(&oy,og[i].body_len);
  109859. }
  109860. ogg_sync_pageout(&oy,&temp);
  109861. ogg_stream_pagein(&os_de,&temp);
  109862. ogg_sync_pageout(&oy,&temp);
  109863. ogg_stream_pagein(&os_de,&temp);
  109864. ogg_sync_pageout(&oy,&temp);
  109865. /* skip */
  109866. ogg_sync_pageout(&oy,&temp);
  109867. ogg_stream_pagein(&os_de,&temp);
  109868. /* do we get the expected results/packets? */
  109869. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109870. checkpacket(&test,0,0,0);
  109871. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109872. checkpacket(&test,100,1,-1);
  109873. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109874. checkpacket(&test,4079,2,3000);
  109875. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109876. fprintf(stderr,"Error: loss of page did not return error\n");
  109877. exit(1);
  109878. }
  109879. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109880. checkpacket(&test,76,5,-1);
  109881. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109882. checkpacket(&test,34,6,-1);
  109883. fprintf(stderr,"ok.\n");
  109884. }
  109885. /* Test lost pages on pagein/packetout: rollback with continuation */
  109886. {
  109887. ogg_page temp;
  109888. ogg_packet test;
  109889. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109890. ogg_sync_reset(&oy);
  109891. ogg_stream_reset(&os_de);
  109892. for(i=0;i<5;i++){
  109893. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109894. og[i].header_len);
  109895. ogg_sync_wrote(&oy,og[i].header_len);
  109896. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109897. ogg_sync_wrote(&oy,og[i].body_len);
  109898. }
  109899. ogg_sync_pageout(&oy,&temp);
  109900. ogg_stream_pagein(&os_de,&temp);
  109901. ogg_sync_pageout(&oy,&temp);
  109902. ogg_stream_pagein(&os_de,&temp);
  109903. ogg_sync_pageout(&oy,&temp);
  109904. ogg_stream_pagein(&os_de,&temp);
  109905. ogg_sync_pageout(&oy,&temp);
  109906. /* skip */
  109907. ogg_sync_pageout(&oy,&temp);
  109908. ogg_stream_pagein(&os_de,&temp);
  109909. /* do we get the expected results/packets? */
  109910. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109911. checkpacket(&test,0,0,0);
  109912. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109913. checkpacket(&test,100,1,-1);
  109914. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109915. checkpacket(&test,4079,2,3000);
  109916. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109917. checkpacket(&test,2956,3,4000);
  109918. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109919. fprintf(stderr,"Error: loss of page did not return error\n");
  109920. exit(1);
  109921. }
  109922. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109923. checkpacket(&test,300,13,14000);
  109924. fprintf(stderr,"ok.\n");
  109925. }
  109926. /* the rest only test sync */
  109927. {
  109928. ogg_page og_de;
  109929. /* Test fractional page inputs: incomplete capture */
  109930. fprintf(stderr,"Testing sync on partial inputs... ");
  109931. ogg_sync_reset(&oy);
  109932. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109933. 3);
  109934. ogg_sync_wrote(&oy,3);
  109935. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109936. /* Test fractional page inputs: incomplete fixed header */
  109937. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109938. 20);
  109939. ogg_sync_wrote(&oy,20);
  109940. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109941. /* Test fractional page inputs: incomplete header */
  109942. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109943. 5);
  109944. ogg_sync_wrote(&oy,5);
  109945. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109946. /* Test fractional page inputs: incomplete body */
  109947. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109948. og[1].header_len-28);
  109949. ogg_sync_wrote(&oy,og[1].header_len-28);
  109950. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109951. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109952. ogg_sync_wrote(&oy,1000);
  109953. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109954. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109955. og[1].body_len-1000);
  109956. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109957. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109958. fprintf(stderr,"ok.\n");
  109959. }
  109960. /* Test fractional page inputs: page + incomplete capture */
  109961. {
  109962. ogg_page og_de;
  109963. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109964. ogg_sync_reset(&oy);
  109965. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109966. og[1].header_len);
  109967. ogg_sync_wrote(&oy,og[1].header_len);
  109968. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109969. og[1].body_len);
  109970. ogg_sync_wrote(&oy,og[1].body_len);
  109971. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109972. 20);
  109973. ogg_sync_wrote(&oy,20);
  109974. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109975. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109976. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109977. og[1].header_len-20);
  109978. ogg_sync_wrote(&oy,og[1].header_len-20);
  109979. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109980. og[1].body_len);
  109981. ogg_sync_wrote(&oy,og[1].body_len);
  109982. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109983. fprintf(stderr,"ok.\n");
  109984. }
  109985. /* Test recapture: garbage + page */
  109986. {
  109987. ogg_page og_de;
  109988. fprintf(stderr,"Testing search for capture... ");
  109989. ogg_sync_reset(&oy);
  109990. /* 'garbage' */
  109991. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109992. og[1].body_len);
  109993. ogg_sync_wrote(&oy,og[1].body_len);
  109994. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109995. og[1].header_len);
  109996. ogg_sync_wrote(&oy,og[1].header_len);
  109997. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109998. og[1].body_len);
  109999. ogg_sync_wrote(&oy,og[1].body_len);
  110000. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110001. 20);
  110002. ogg_sync_wrote(&oy,20);
  110003. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110004. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110005. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110006. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110007. og[2].header_len-20);
  110008. ogg_sync_wrote(&oy,og[2].header_len-20);
  110009. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110010. og[2].body_len);
  110011. ogg_sync_wrote(&oy,og[2].body_len);
  110012. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110013. fprintf(stderr,"ok.\n");
  110014. }
  110015. /* Test recapture: page + garbage + page */
  110016. {
  110017. ogg_page og_de;
  110018. fprintf(stderr,"Testing recapture... ");
  110019. ogg_sync_reset(&oy);
  110020. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110021. og[1].header_len);
  110022. ogg_sync_wrote(&oy,og[1].header_len);
  110023. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110024. og[1].body_len);
  110025. ogg_sync_wrote(&oy,og[1].body_len);
  110026. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110027. og[2].header_len);
  110028. ogg_sync_wrote(&oy,og[2].header_len);
  110029. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110030. og[2].header_len);
  110031. ogg_sync_wrote(&oy,og[2].header_len);
  110032. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110033. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110034. og[2].body_len-5);
  110035. ogg_sync_wrote(&oy,og[2].body_len-5);
  110036. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110037. og[3].header_len);
  110038. ogg_sync_wrote(&oy,og[3].header_len);
  110039. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110040. og[3].body_len);
  110041. ogg_sync_wrote(&oy,og[3].body_len);
  110042. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110043. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110044. fprintf(stderr,"ok.\n");
  110045. }
  110046. /* Free page data that was previously copied */
  110047. {
  110048. for(i=0;i<5;i++){
  110049. free_page(&og[i]);
  110050. }
  110051. }
  110052. }
  110053. return(0);
  110054. }
  110055. #endif
  110056. #endif
  110057. /*** End of inlined file: framing.c ***/
  110058. /*** Start of inlined file: analysis.c ***/
  110059. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110060. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110061. // tasks..
  110062. #if JUCE_MSVC
  110063. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110064. #endif
  110065. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110066. #if JUCE_USE_OGGVORBIS
  110067. #include <stdio.h>
  110068. #include <string.h>
  110069. #include <math.h>
  110070. /*** Start of inlined file: codec_internal.h ***/
  110071. #ifndef _V_CODECI_H_
  110072. #define _V_CODECI_H_
  110073. /*** Start of inlined file: envelope.h ***/
  110074. #ifndef _V_ENVELOPE_
  110075. #define _V_ENVELOPE_
  110076. /*** Start of inlined file: mdct.h ***/
  110077. #ifndef _OGG_mdct_H_
  110078. #define _OGG_mdct_H_
  110079. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110080. #ifdef MDCT_INTEGERIZED
  110081. #define DATA_TYPE int
  110082. #define REG_TYPE register int
  110083. #define TRIGBITS 14
  110084. #define cPI3_8 6270
  110085. #define cPI2_8 11585
  110086. #define cPI1_8 15137
  110087. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110088. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110089. #define HALVE(x) ((x)>>1)
  110090. #else
  110091. #define DATA_TYPE float
  110092. #define REG_TYPE float
  110093. #define cPI3_8 .38268343236508977175F
  110094. #define cPI2_8 .70710678118654752441F
  110095. #define cPI1_8 .92387953251128675613F
  110096. #define FLOAT_CONV(x) (x)
  110097. #define MULT_NORM(x) (x)
  110098. #define HALVE(x) ((x)*.5f)
  110099. #endif
  110100. typedef struct {
  110101. int n;
  110102. int log2n;
  110103. DATA_TYPE *trig;
  110104. int *bitrev;
  110105. DATA_TYPE scale;
  110106. } mdct_lookup;
  110107. extern void mdct_init(mdct_lookup *lookup,int n);
  110108. extern void mdct_clear(mdct_lookup *l);
  110109. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110110. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110111. #endif
  110112. /*** End of inlined file: mdct.h ***/
  110113. #define VE_PRE 16
  110114. #define VE_WIN 4
  110115. #define VE_POST 2
  110116. #define VE_AMP (VE_PRE+VE_POST-1)
  110117. #define VE_BANDS 7
  110118. #define VE_NEARDC 15
  110119. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110120. #define VE_MAXSTRETCH 12 /* one-third full block */
  110121. typedef struct {
  110122. float ampbuf[VE_AMP];
  110123. int ampptr;
  110124. float nearDC[VE_NEARDC];
  110125. float nearDC_acc;
  110126. float nearDC_partialacc;
  110127. int nearptr;
  110128. } envelope_filter_state;
  110129. typedef struct {
  110130. int begin;
  110131. int end;
  110132. float *window;
  110133. float total;
  110134. } envelope_band;
  110135. typedef struct {
  110136. int ch;
  110137. int winlength;
  110138. int searchstep;
  110139. float minenergy;
  110140. mdct_lookup mdct;
  110141. float *mdct_win;
  110142. envelope_band band[VE_BANDS];
  110143. envelope_filter_state *filter;
  110144. int stretch;
  110145. int *mark;
  110146. long storage;
  110147. long current;
  110148. long curmark;
  110149. long cursor;
  110150. } envelope_lookup;
  110151. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110152. extern void _ve_envelope_clear(envelope_lookup *e);
  110153. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110154. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110155. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110156. #endif
  110157. /*** End of inlined file: envelope.h ***/
  110158. /*** Start of inlined file: codebook.h ***/
  110159. #ifndef _V_CODEBOOK_H_
  110160. #define _V_CODEBOOK_H_
  110161. /* This structure encapsulates huffman and VQ style encoding books; it
  110162. doesn't do anything specific to either.
  110163. valuelist/quantlist are nonNULL (and q_* significant) only if
  110164. there's entry->value mapping to be done.
  110165. If encode-side mapping must be done (and thus the entry needs to be
  110166. hunted), the auxiliary encode pointer will point to a decision
  110167. tree. This is true of both VQ and huffman, but is mostly useful
  110168. with VQ.
  110169. */
  110170. typedef struct static_codebook{
  110171. long dim; /* codebook dimensions (elements per vector) */
  110172. long entries; /* codebook entries */
  110173. long *lengthlist; /* codeword lengths in bits */
  110174. /* mapping ***************************************************************/
  110175. int maptype; /* 0=none
  110176. 1=implicitly populated values from map column
  110177. 2=listed arbitrary values */
  110178. /* The below does a linear, single monotonic sequence mapping. */
  110179. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110180. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110181. int q_quant; /* bits: 0 < quant <= 16 */
  110182. int q_sequencep; /* bitflag */
  110183. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110184. map == 2: list of dim*entries quantized entry vals
  110185. */
  110186. /* encode helpers ********************************************************/
  110187. struct encode_aux_nearestmatch *nearest_tree;
  110188. struct encode_aux_threshmatch *thresh_tree;
  110189. struct encode_aux_pigeonhole *pigeon_tree;
  110190. int allocedp;
  110191. } static_codebook;
  110192. /* this structures an arbitrary trained book to quickly find the
  110193. nearest cell match */
  110194. typedef struct encode_aux_nearestmatch{
  110195. /* pre-calculated partitioning tree */
  110196. long *ptr0;
  110197. long *ptr1;
  110198. long *p; /* decision points (each is an entry) */
  110199. long *q; /* decision points (each is an entry) */
  110200. long aux; /* number of tree entries */
  110201. long alloc;
  110202. } encode_aux_nearestmatch;
  110203. /* assumes a maptype of 1; encode side only, so that's OK */
  110204. typedef struct encode_aux_threshmatch{
  110205. float *quantthresh;
  110206. long *quantmap;
  110207. int quantvals;
  110208. int threshvals;
  110209. } encode_aux_threshmatch;
  110210. typedef struct encode_aux_pigeonhole{
  110211. float min;
  110212. float del;
  110213. int mapentries;
  110214. int quantvals;
  110215. long *pigeonmap;
  110216. long fittotal;
  110217. long *fitlist;
  110218. long *fitmap;
  110219. long *fitlength;
  110220. } encode_aux_pigeonhole;
  110221. typedef struct codebook{
  110222. long dim; /* codebook dimensions (elements per vector) */
  110223. long entries; /* codebook entries */
  110224. long used_entries; /* populated codebook entries */
  110225. const static_codebook *c;
  110226. /* for encode, the below are entry-ordered, fully populated */
  110227. /* for decode, the below are ordered by bitreversed codeword and only
  110228. used entries are populated */
  110229. float *valuelist; /* list of dim*entries actual entry values */
  110230. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110231. int *dec_index; /* only used if sparseness collapsed */
  110232. char *dec_codelengths;
  110233. ogg_uint32_t *dec_firsttable;
  110234. int dec_firsttablen;
  110235. int dec_maxlength;
  110236. } codebook;
  110237. extern void vorbis_staticbook_clear(static_codebook *b);
  110238. extern void vorbis_staticbook_destroy(static_codebook *b);
  110239. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110240. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110241. extern void vorbis_book_clear(codebook *b);
  110242. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110243. extern float *_book_logdist(const static_codebook *b,float *vals);
  110244. extern float _float32_unpack(long val);
  110245. extern long _float32_pack(float val);
  110246. extern int _best(codebook *book, float *a, int step);
  110247. extern int _ilog(unsigned int v);
  110248. extern long _book_maptype1_quantvals(const static_codebook *b);
  110249. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110250. extern long vorbis_book_codeword(codebook *book,int entry);
  110251. extern long vorbis_book_codelen(codebook *book,int entry);
  110252. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110253. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110254. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110255. extern int vorbis_book_errorv(codebook *book, float *a);
  110256. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110257. oggpack_buffer *b);
  110258. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110259. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110260. oggpack_buffer *b,int n);
  110261. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110262. oggpack_buffer *b,int n);
  110263. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110264. oggpack_buffer *b,int n);
  110265. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110266. long off,int ch,
  110267. oggpack_buffer *b,int n);
  110268. #endif
  110269. /*** End of inlined file: codebook.h ***/
  110270. #define BLOCKTYPE_IMPULSE 0
  110271. #define BLOCKTYPE_PADDING 1
  110272. #define BLOCKTYPE_TRANSITION 0
  110273. #define BLOCKTYPE_LONG 1
  110274. #define PACKETBLOBS 15
  110275. typedef struct vorbis_block_internal{
  110276. float **pcmdelay; /* this is a pointer into local storage */
  110277. float ampmax;
  110278. int blocktype;
  110279. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110280. blob [PACKETBLOBS/2] points to
  110281. the oggpack_buffer in the
  110282. main vorbis_block */
  110283. } vorbis_block_internal;
  110284. typedef void vorbis_look_floor;
  110285. typedef void vorbis_look_residue;
  110286. typedef void vorbis_look_transform;
  110287. /* mode ************************************************************/
  110288. typedef struct {
  110289. int blockflag;
  110290. int windowtype;
  110291. int transformtype;
  110292. int mapping;
  110293. } vorbis_info_mode;
  110294. typedef void vorbis_info_floor;
  110295. typedef void vorbis_info_residue;
  110296. typedef void vorbis_info_mapping;
  110297. /*** Start of inlined file: psy.h ***/
  110298. #ifndef _V_PSY_H_
  110299. #define _V_PSY_H_
  110300. /*** Start of inlined file: smallft.h ***/
  110301. #ifndef _V_SMFT_H_
  110302. #define _V_SMFT_H_
  110303. typedef struct {
  110304. int n;
  110305. float *trigcache;
  110306. int *splitcache;
  110307. } drft_lookup;
  110308. extern void drft_forward(drft_lookup *l,float *data);
  110309. extern void drft_backward(drft_lookup *l,float *data);
  110310. extern void drft_init(drft_lookup *l,int n);
  110311. extern void drft_clear(drft_lookup *l);
  110312. #endif
  110313. /*** End of inlined file: smallft.h ***/
  110314. /*** Start of inlined file: backends.h ***/
  110315. /* this is exposed up here because we need it for static modes.
  110316. Lookups for each backend aren't exposed because there's no reason
  110317. to do so */
  110318. #ifndef _vorbis_backend_h_
  110319. #define _vorbis_backend_h_
  110320. /* this would all be simpler/shorter with templates, but.... */
  110321. /* Floor backend generic *****************************************/
  110322. typedef struct{
  110323. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110324. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110325. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110326. void (*free_info) (vorbis_info_floor *);
  110327. void (*free_look) (vorbis_look_floor *);
  110328. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110329. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110330. void *buffer,float *);
  110331. } vorbis_func_floor;
  110332. typedef struct{
  110333. int order;
  110334. long rate;
  110335. long barkmap;
  110336. int ampbits;
  110337. int ampdB;
  110338. int numbooks; /* <= 16 */
  110339. int books[16];
  110340. float lessthan; /* encode-only config setting hacks for libvorbis */
  110341. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110342. } vorbis_info_floor0;
  110343. #define VIF_POSIT 63
  110344. #define VIF_CLASS 16
  110345. #define VIF_PARTS 31
  110346. typedef struct{
  110347. int partitions; /* 0 to 31 */
  110348. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110349. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110350. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110351. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110352. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110353. int mult; /* 1 2 3 or 4 */
  110354. int postlist[VIF_POSIT+2]; /* first two implicit */
  110355. /* encode side analysis parameters */
  110356. float maxover;
  110357. float maxunder;
  110358. float maxerr;
  110359. float twofitweight;
  110360. float twofitatten;
  110361. int n;
  110362. } vorbis_info_floor1;
  110363. /* Residue backend generic *****************************************/
  110364. typedef struct{
  110365. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110366. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110367. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110368. vorbis_info_residue *);
  110369. void (*free_info) (vorbis_info_residue *);
  110370. void (*free_look) (vorbis_look_residue *);
  110371. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110372. float **,int *,int);
  110373. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110374. vorbis_look_residue *,
  110375. float **,float **,int *,int,long **);
  110376. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110377. float **,int *,int);
  110378. } vorbis_func_residue;
  110379. typedef struct vorbis_info_residue0{
  110380. /* block-partitioned VQ coded straight residue */
  110381. long begin;
  110382. long end;
  110383. /* first stage (lossless partitioning) */
  110384. int grouping; /* group n vectors per partition */
  110385. int partitions; /* possible codebooks for a partition */
  110386. int groupbook; /* huffbook for partitioning */
  110387. int secondstages[64]; /* expanded out to pointers in lookup */
  110388. int booklist[256]; /* list of second stage books */
  110389. float classmetric1[64];
  110390. float classmetric2[64];
  110391. } vorbis_info_residue0;
  110392. /* Mapping backend generic *****************************************/
  110393. typedef struct{
  110394. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110395. oggpack_buffer *);
  110396. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110397. void (*free_info) (vorbis_info_mapping *);
  110398. int (*forward) (struct vorbis_block *vb);
  110399. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110400. } vorbis_func_mapping;
  110401. typedef struct vorbis_info_mapping0{
  110402. int submaps; /* <= 16 */
  110403. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110404. int floorsubmap[16]; /* [mux] submap to floors */
  110405. int residuesubmap[16]; /* [mux] submap to residue */
  110406. int coupling_steps;
  110407. int coupling_mag[256];
  110408. int coupling_ang[256];
  110409. } vorbis_info_mapping0;
  110410. #endif
  110411. /*** End of inlined file: backends.h ***/
  110412. #ifndef EHMER_MAX
  110413. #define EHMER_MAX 56
  110414. #endif
  110415. /* psychoacoustic setup ********************************************/
  110416. #define P_BANDS 17 /* 62Hz to 16kHz */
  110417. #define P_LEVELS 8 /* 30dB to 100dB */
  110418. #define P_LEVEL_0 30. /* 30 dB */
  110419. #define P_NOISECURVES 3
  110420. #define NOISE_COMPAND_LEVELS 40
  110421. typedef struct vorbis_info_psy{
  110422. int blockflag;
  110423. float ath_adjatt;
  110424. float ath_maxatt;
  110425. float tone_masteratt[P_NOISECURVES];
  110426. float tone_centerboost;
  110427. float tone_decay;
  110428. float tone_abs_limit;
  110429. float toneatt[P_BANDS];
  110430. int noisemaskp;
  110431. float noisemaxsupp;
  110432. float noisewindowlo;
  110433. float noisewindowhi;
  110434. int noisewindowlomin;
  110435. int noisewindowhimin;
  110436. int noisewindowfixed;
  110437. float noiseoff[P_NOISECURVES][P_BANDS];
  110438. float noisecompand[NOISE_COMPAND_LEVELS];
  110439. float max_curve_dB;
  110440. int normal_channel_p;
  110441. int normal_point_p;
  110442. int normal_start;
  110443. int normal_partition;
  110444. double normal_thresh;
  110445. } vorbis_info_psy;
  110446. typedef struct{
  110447. int eighth_octave_lines;
  110448. /* for block long/short tuning; encode only */
  110449. float preecho_thresh[VE_BANDS];
  110450. float postecho_thresh[VE_BANDS];
  110451. float stretch_penalty;
  110452. float preecho_minenergy;
  110453. float ampmax_att_per_sec;
  110454. /* channel coupling config */
  110455. int coupling_pkHz[PACKETBLOBS];
  110456. int coupling_pointlimit[2][PACKETBLOBS];
  110457. int coupling_prepointamp[PACKETBLOBS];
  110458. int coupling_postpointamp[PACKETBLOBS];
  110459. int sliding_lowpass[2][PACKETBLOBS];
  110460. } vorbis_info_psy_global;
  110461. typedef struct {
  110462. float ampmax;
  110463. int channels;
  110464. vorbis_info_psy_global *gi;
  110465. int coupling_pointlimit[2][P_NOISECURVES];
  110466. } vorbis_look_psy_global;
  110467. typedef struct {
  110468. int n;
  110469. struct vorbis_info_psy *vi;
  110470. float ***tonecurves;
  110471. float **noiseoffset;
  110472. float *ath;
  110473. long *octave; /* in n.ocshift format */
  110474. long *bark;
  110475. long firstoc;
  110476. long shiftoc;
  110477. int eighth_octave_lines; /* power of two, please */
  110478. int total_octave_lines;
  110479. long rate; /* cache it */
  110480. float m_val; /* Masking compensation value */
  110481. } vorbis_look_psy;
  110482. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110483. vorbis_info_psy_global *gi,int n,long rate);
  110484. extern void _vp_psy_clear(vorbis_look_psy *p);
  110485. extern void *_vi_psy_dup(void *source);
  110486. extern void _vi_psy_free(vorbis_info_psy *i);
  110487. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110488. extern void _vp_remove_floor(vorbis_look_psy *p,
  110489. float *mdct,
  110490. int *icodedflr,
  110491. float *residue,
  110492. int sliding_lowpass);
  110493. extern void _vp_noisemask(vorbis_look_psy *p,
  110494. float *logmdct,
  110495. float *logmask);
  110496. extern void _vp_tonemask(vorbis_look_psy *p,
  110497. float *logfft,
  110498. float *logmask,
  110499. float global_specmax,
  110500. float local_specmax);
  110501. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110502. float *noise,
  110503. float *tone,
  110504. int offset_select,
  110505. float *logmask,
  110506. float *mdct,
  110507. float *logmdct);
  110508. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110509. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110510. vorbis_info_psy_global *g,
  110511. vorbis_look_psy *p,
  110512. vorbis_info_mapping0 *vi,
  110513. float **mdct);
  110514. extern void _vp_couple(int blobno,
  110515. vorbis_info_psy_global *g,
  110516. vorbis_look_psy *p,
  110517. vorbis_info_mapping0 *vi,
  110518. float **res,
  110519. float **mag_memo,
  110520. int **mag_sort,
  110521. int **ifloor,
  110522. int *nonzero,
  110523. int sliding_lowpass);
  110524. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110525. float *in,float *out,int *sortedindex);
  110526. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110527. float *magnitudes,int *sortedindex);
  110528. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110529. vorbis_look_psy *p,
  110530. vorbis_info_mapping0 *vi,
  110531. float **mags);
  110532. extern void hf_reduction(vorbis_info_psy_global *g,
  110533. vorbis_look_psy *p,
  110534. vorbis_info_mapping0 *vi,
  110535. float **mdct);
  110536. #endif
  110537. /*** End of inlined file: psy.h ***/
  110538. /*** Start of inlined file: bitrate.h ***/
  110539. #ifndef _V_BITRATE_H_
  110540. #define _V_BITRATE_H_
  110541. /*** Start of inlined file: os.h ***/
  110542. #ifndef _OS_H
  110543. #define _OS_H
  110544. /********************************************************************
  110545. * *
  110546. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110547. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110548. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110549. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110550. * *
  110551. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110552. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110553. * *
  110554. ********************************************************************
  110555. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110556. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110557. ********************************************************************/
  110558. #ifdef HAVE_CONFIG_H
  110559. #include "config.h"
  110560. #endif
  110561. #include <math.h>
  110562. /*** Start of inlined file: misc.h ***/
  110563. #ifndef _V_RANDOM_H_
  110564. #define _V_RANDOM_H_
  110565. extern int analysis_noisy;
  110566. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110567. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110568. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110569. ogg_int64_t off);
  110570. #ifdef DEBUG_MALLOC
  110571. #define _VDBG_GRAPHFILE "malloc.m"
  110572. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110573. extern void _VDBG_free(void *ptr,char *file,long line);
  110574. #ifndef MISC_C
  110575. #undef _ogg_malloc
  110576. #undef _ogg_calloc
  110577. #undef _ogg_realloc
  110578. #undef _ogg_free
  110579. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110580. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110581. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110582. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110583. #endif
  110584. #endif
  110585. #endif
  110586. /*** End of inlined file: misc.h ***/
  110587. #ifndef _V_IFDEFJAIL_H_
  110588. # define _V_IFDEFJAIL_H_
  110589. # ifdef __GNUC__
  110590. # define STIN static __inline__
  110591. # elif _WIN32
  110592. # define STIN static __inline
  110593. # else
  110594. # define STIN static
  110595. # endif
  110596. #ifdef DJGPP
  110597. # define rint(x) (floor((x)+0.5f))
  110598. #endif
  110599. #ifndef M_PI
  110600. # define M_PI (3.1415926536f)
  110601. #endif
  110602. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110603. # include <malloc.h>
  110604. # define rint(x) (floor((x)+0.5f))
  110605. # define NO_FLOAT_MATH_LIB
  110606. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110607. #endif
  110608. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110609. void *_alloca(size_t size);
  110610. # define alloca _alloca
  110611. #endif
  110612. #ifndef FAST_HYPOT
  110613. # define FAST_HYPOT hypot
  110614. #endif
  110615. #endif
  110616. #ifdef HAVE_ALLOCA_H
  110617. # include <alloca.h>
  110618. #endif
  110619. #ifdef USE_MEMORY_H
  110620. # include <memory.h>
  110621. #endif
  110622. #ifndef min
  110623. # define min(x,y) ((x)>(y)?(y):(x))
  110624. #endif
  110625. #ifndef max
  110626. # define max(x,y) ((x)<(y)?(y):(x))
  110627. #endif
  110628. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110629. # define VORBIS_FPU_CONTROL
  110630. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110631. Because of encapsulation constraints (GCC can't see inside the asm
  110632. block and so we end up doing stupid things like a store/load that
  110633. is collectively a noop), we do it this way */
  110634. /* we must set up the fpu before this works!! */
  110635. typedef ogg_int16_t vorbis_fpu_control;
  110636. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110637. ogg_int16_t ret;
  110638. ogg_int16_t temp;
  110639. __asm__ __volatile__("fnstcw %0\n\t"
  110640. "movw %0,%%dx\n\t"
  110641. "orw $62463,%%dx\n\t"
  110642. "movw %%dx,%1\n\t"
  110643. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110644. *fpu=ret;
  110645. }
  110646. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110647. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110648. }
  110649. /* assumes the FPU is in round mode! */
  110650. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110651. we get extra fst/fld to
  110652. truncate precision */
  110653. int i;
  110654. __asm__("fistl %0": "=m"(i) : "t"(f));
  110655. return(i);
  110656. }
  110657. #endif
  110658. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110659. # define VORBIS_FPU_CONTROL
  110660. typedef ogg_int16_t vorbis_fpu_control;
  110661. static __inline int vorbis_ftoi(double f){
  110662. int i;
  110663. __asm{
  110664. fld f
  110665. fistp i
  110666. }
  110667. return i;
  110668. }
  110669. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110670. }
  110671. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110672. }
  110673. #endif
  110674. #ifndef VORBIS_FPU_CONTROL
  110675. typedef int vorbis_fpu_control;
  110676. static int vorbis_ftoi(double f){
  110677. return (int)(f+.5);
  110678. }
  110679. /* We don't have special code for this compiler/arch, so do it the slow way */
  110680. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110681. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110682. #endif
  110683. #endif /* _OS_H */
  110684. /*** End of inlined file: os.h ***/
  110685. /* encode side bitrate tracking */
  110686. typedef struct bitrate_manager_state {
  110687. int managed;
  110688. long avg_reservoir;
  110689. long minmax_reservoir;
  110690. long avg_bitsper;
  110691. long min_bitsper;
  110692. long max_bitsper;
  110693. long short_per_long;
  110694. double avgfloat;
  110695. vorbis_block *vb;
  110696. int choice;
  110697. } bitrate_manager_state;
  110698. typedef struct bitrate_manager_info{
  110699. long avg_rate;
  110700. long min_rate;
  110701. long max_rate;
  110702. long reservoir_bits;
  110703. double reservoir_bias;
  110704. double slew_damp;
  110705. } bitrate_manager_info;
  110706. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110707. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110708. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110709. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110710. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110711. #endif
  110712. /*** End of inlined file: bitrate.h ***/
  110713. static int ilog(unsigned int v){
  110714. int ret=0;
  110715. while(v){
  110716. ret++;
  110717. v>>=1;
  110718. }
  110719. return(ret);
  110720. }
  110721. static int ilog2(unsigned int v){
  110722. int ret=0;
  110723. if(v)--v;
  110724. while(v){
  110725. ret++;
  110726. v>>=1;
  110727. }
  110728. return(ret);
  110729. }
  110730. typedef struct private_state {
  110731. /* local lookup storage */
  110732. envelope_lookup *ve; /* envelope lookup */
  110733. int window[2];
  110734. vorbis_look_transform **transform[2]; /* block, type */
  110735. drft_lookup fft_look[2];
  110736. int modebits;
  110737. vorbis_look_floor **flr;
  110738. vorbis_look_residue **residue;
  110739. vorbis_look_psy *psy;
  110740. vorbis_look_psy_global *psy_g_look;
  110741. /* local storage, only used on the encoding side. This way the
  110742. application does not need to worry about freeing some packets'
  110743. memory and not others'; packet storage is always tracked.
  110744. Cleared next call to a _dsp_ function */
  110745. unsigned char *header;
  110746. unsigned char *header1;
  110747. unsigned char *header2;
  110748. bitrate_manager_state bms;
  110749. ogg_int64_t sample_count;
  110750. } private_state;
  110751. /* codec_setup_info contains all the setup information specific to the
  110752. specific compression/decompression mode in progress (eg,
  110753. psychoacoustic settings, channel setup, options, codebook
  110754. etc).
  110755. *********************************************************************/
  110756. /*** Start of inlined file: highlevel.h ***/
  110757. typedef struct highlevel_byblocktype {
  110758. double tone_mask_setting;
  110759. double tone_peaklimit_setting;
  110760. double noise_bias_setting;
  110761. double noise_compand_setting;
  110762. } highlevel_byblocktype;
  110763. typedef struct highlevel_encode_setup {
  110764. void *setup;
  110765. int set_in_stone;
  110766. double base_setting;
  110767. double long_setting;
  110768. double short_setting;
  110769. double impulse_noisetune;
  110770. int managed;
  110771. long bitrate_min;
  110772. long bitrate_av;
  110773. double bitrate_av_damp;
  110774. long bitrate_max;
  110775. long bitrate_reservoir;
  110776. double bitrate_reservoir_bias;
  110777. int impulse_block_p;
  110778. int noise_normalize_p;
  110779. double stereo_point_setting;
  110780. double lowpass_kHz;
  110781. double ath_floating_dB;
  110782. double ath_absolute_dB;
  110783. double amplitude_track_dBpersec;
  110784. double trigger_setting;
  110785. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110786. } highlevel_encode_setup;
  110787. /*** End of inlined file: highlevel.h ***/
  110788. typedef struct codec_setup_info {
  110789. /* Vorbis supports only short and long blocks, but allows the
  110790. encoder to choose the sizes */
  110791. long blocksizes[2];
  110792. /* modes are the primary means of supporting on-the-fly different
  110793. blocksizes, different channel mappings (LR or M/A),
  110794. different residue backends, etc. Each mode consists of a
  110795. blocksize flag and a mapping (along with the mapping setup */
  110796. int modes;
  110797. int maps;
  110798. int floors;
  110799. int residues;
  110800. int books;
  110801. int psys; /* encode only */
  110802. vorbis_info_mode *mode_param[64];
  110803. int map_type[64];
  110804. vorbis_info_mapping *map_param[64];
  110805. int floor_type[64];
  110806. vorbis_info_floor *floor_param[64];
  110807. int residue_type[64];
  110808. vorbis_info_residue *residue_param[64];
  110809. static_codebook *book_param[256];
  110810. codebook *fullbooks;
  110811. vorbis_info_psy *psy_param[4]; /* encode only */
  110812. vorbis_info_psy_global psy_g_param;
  110813. bitrate_manager_info bi;
  110814. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110815. highly redundant structure, but
  110816. improves clarity of program flow. */
  110817. int halfrate_flag; /* painless downsample for decode */
  110818. } codec_setup_info;
  110819. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110820. extern void _vp_global_free(vorbis_look_psy_global *look);
  110821. #endif
  110822. /*** End of inlined file: codec_internal.h ***/
  110823. /*** Start of inlined file: registry.h ***/
  110824. #ifndef _V_REG_H_
  110825. #define _V_REG_H_
  110826. #define VI_TRANSFORMB 1
  110827. #define VI_WINDOWB 1
  110828. #define VI_TIMEB 1
  110829. #define VI_FLOORB 2
  110830. #define VI_RESB 3
  110831. #define VI_MAPB 1
  110832. extern vorbis_func_floor *_floor_P[];
  110833. extern vorbis_func_residue *_residue_P[];
  110834. extern vorbis_func_mapping *_mapping_P[];
  110835. #endif
  110836. /*** End of inlined file: registry.h ***/
  110837. /*** Start of inlined file: scales.h ***/
  110838. #ifndef _V_SCALES_H_
  110839. #define _V_SCALES_H_
  110840. #include <math.h>
  110841. /* 20log10(x) */
  110842. #define VORBIS_IEEE_FLOAT32 1
  110843. #ifdef VORBIS_IEEE_FLOAT32
  110844. static float unitnorm(float x){
  110845. union {
  110846. ogg_uint32_t i;
  110847. float f;
  110848. } ix;
  110849. ix.f = x;
  110850. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110851. return ix.f;
  110852. }
  110853. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110854. static float todB(const float *x){
  110855. union {
  110856. ogg_uint32_t i;
  110857. float f;
  110858. } ix;
  110859. ix.f = *x;
  110860. ix.i = ix.i&0x7fffffff;
  110861. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110862. }
  110863. #define todB_nn(x) todB(x)
  110864. #else
  110865. static float unitnorm(float x){
  110866. if(x<0)return(-1.f);
  110867. return(1.f);
  110868. }
  110869. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110870. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110871. #endif
  110872. #define fromdB(x) (exp((x)*.11512925f))
  110873. /* The bark scale equations are approximations, since the original
  110874. table was somewhat hand rolled. The below are chosen to have the
  110875. best possible fit to the rolled tables, thus their somewhat odd
  110876. appearance (these are more accurate and over a longer range than
  110877. the oft-quoted bark equations found in the texts I have). The
  110878. approximations are valid from 0 - 30kHz (nyquist) or so.
  110879. all f in Hz, z in Bark */
  110880. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110881. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110882. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110883. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110884. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110885. 0.0 */
  110886. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110887. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110888. #endif
  110889. /*** End of inlined file: scales.h ***/
  110890. int analysis_noisy=1;
  110891. /* decides between modes, dispatches to the appropriate mapping. */
  110892. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110893. int ret,i;
  110894. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110895. vb->glue_bits=0;
  110896. vb->time_bits=0;
  110897. vb->floor_bits=0;
  110898. vb->res_bits=0;
  110899. /* first things first. Make sure encode is ready */
  110900. for(i=0;i<PACKETBLOBS;i++)
  110901. oggpack_reset(vbi->packetblob[i]);
  110902. /* we only have one mapping type (0), and we let the mapping code
  110903. itself figure out what soft mode to use. This allows easier
  110904. bitrate management */
  110905. if((ret=_mapping_P[0]->forward(vb)))
  110906. return(ret);
  110907. if(op){
  110908. if(vorbis_bitrate_managed(vb))
  110909. /* The app is using a bitmanaged mode... but not using the
  110910. bitrate management interface. */
  110911. return(OV_EINVAL);
  110912. op->packet=oggpack_get_buffer(&vb->opb);
  110913. op->bytes=oggpack_bytes(&vb->opb);
  110914. op->b_o_s=0;
  110915. op->e_o_s=vb->eofflag;
  110916. op->granulepos=vb->granulepos;
  110917. op->packetno=vb->sequence; /* for sake of completeness */
  110918. }
  110919. return(0);
  110920. }
  110921. /* there was no great place to put this.... */
  110922. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110923. int j;
  110924. FILE *of;
  110925. char buffer[80];
  110926. /* if(i==5870){*/
  110927. sprintf(buffer,"%s_%d.m",base,i);
  110928. of=fopen(buffer,"w");
  110929. if(!of)perror("failed to open data dump file");
  110930. for(j=0;j<n;j++){
  110931. if(bark){
  110932. float b=toBARK((4000.f*j/n)+.25);
  110933. fprintf(of,"%f ",b);
  110934. }else
  110935. if(off!=0)
  110936. fprintf(of,"%f ",(double)(j+off)/8000.);
  110937. else
  110938. fprintf(of,"%f ",(double)j);
  110939. if(dB){
  110940. float val;
  110941. if(v[j]==0.)
  110942. val=-140.;
  110943. else
  110944. val=todB(v+j);
  110945. fprintf(of,"%f\n",val);
  110946. }else{
  110947. fprintf(of,"%f\n",v[j]);
  110948. }
  110949. }
  110950. fclose(of);
  110951. /* } */
  110952. }
  110953. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110954. ogg_int64_t off){
  110955. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110956. }
  110957. #endif
  110958. /*** End of inlined file: analysis.c ***/
  110959. /*** Start of inlined file: bitrate.c ***/
  110960. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110961. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110962. // tasks..
  110963. #if JUCE_MSVC
  110964. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110965. #endif
  110966. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110967. #if JUCE_USE_OGGVORBIS
  110968. #include <stdlib.h>
  110969. #include <string.h>
  110970. #include <math.h>
  110971. /* compute bitrate tracking setup */
  110972. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110973. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110974. bitrate_manager_info *bi=&ci->bi;
  110975. memset(bm,0,sizeof(*bm));
  110976. if(bi && (bi->reservoir_bits>0)){
  110977. long ratesamples=vi->rate;
  110978. int halfsamples=ci->blocksizes[0]>>1;
  110979. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110980. bm->managed=1;
  110981. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110982. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110983. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110984. bm->avgfloat=PACKETBLOBS/2;
  110985. /* not a necessary fix, but one that leads to a more balanced
  110986. typical initialization */
  110987. {
  110988. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110989. bm->minmax_reservoir=desired_fill;
  110990. bm->avg_reservoir=desired_fill;
  110991. }
  110992. }
  110993. }
  110994. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110995. memset(bm,0,sizeof(*bm));
  110996. return;
  110997. }
  110998. int vorbis_bitrate_managed(vorbis_block *vb){
  110999. vorbis_dsp_state *vd=vb->vd;
  111000. private_state *b=(private_state*)vd->backend_state;
  111001. bitrate_manager_state *bm=&b->bms;
  111002. if(bm && bm->managed)return(1);
  111003. return(0);
  111004. }
  111005. /* finish taking in the block we just processed */
  111006. int vorbis_bitrate_addblock(vorbis_block *vb){
  111007. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111008. vorbis_dsp_state *vd=vb->vd;
  111009. private_state *b=(private_state*)vd->backend_state;
  111010. bitrate_manager_state *bm=&b->bms;
  111011. vorbis_info *vi=vd->vi;
  111012. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111013. bitrate_manager_info *bi=&ci->bi;
  111014. int choice=rint(bm->avgfloat);
  111015. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111016. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111017. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111018. int samples=ci->blocksizes[vb->W]>>1;
  111019. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111020. if(!bm->managed){
  111021. /* not a bitrate managed stream, but for API simplicity, we'll
  111022. buffer the packet to keep the code path clean */
  111023. if(bm->vb)return(-1); /* one has been submitted without
  111024. being claimed */
  111025. bm->vb=vb;
  111026. return(0);
  111027. }
  111028. bm->vb=vb;
  111029. /* look ahead for avg floater */
  111030. if(bm->avg_bitsper>0){
  111031. double slew=0.;
  111032. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111033. double slewlimit= 15./bi->slew_damp;
  111034. /* choosing a new floater:
  111035. if we're over target, we slew down
  111036. if we're under target, we slew up
  111037. choose slew as follows: look through packetblobs of this frame
  111038. and set slew as the first in the appropriate direction that
  111039. gives us the slew we want. This may mean no slew if delta is
  111040. already favorable.
  111041. Then limit slew to slew max */
  111042. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111043. while(choice>0 && this_bits>avg_target_bits &&
  111044. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111045. choice--;
  111046. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111047. }
  111048. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111049. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111050. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111051. choice++;
  111052. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111053. }
  111054. }
  111055. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111056. if(slew<-slewlimit)slew=-slewlimit;
  111057. if(slew>slewlimit)slew=slewlimit;
  111058. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111059. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111060. }
  111061. /* enforce min(if used) on the current floater (if used) */
  111062. if(bm->min_bitsper>0){
  111063. /* do we need to force the bitrate up? */
  111064. if(this_bits<min_target_bits){
  111065. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111066. choice++;
  111067. if(choice>=PACKETBLOBS)break;
  111068. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111069. }
  111070. }
  111071. }
  111072. /* enforce max (if used) on the current floater (if used) */
  111073. if(bm->max_bitsper>0){
  111074. /* do we need to force the bitrate down? */
  111075. if(this_bits>max_target_bits){
  111076. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111077. choice--;
  111078. if(choice<0)break;
  111079. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111080. }
  111081. }
  111082. }
  111083. /* Choice of packetblobs now made based on floater, and min/max
  111084. requirements. Now boundary check extreme choices */
  111085. if(choice<0){
  111086. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111087. frame will need to be truncated */
  111088. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111089. bm->choice=choice=0;
  111090. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111091. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111092. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111093. }
  111094. }else{
  111095. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111096. if(choice>=PACKETBLOBS)
  111097. choice=PACKETBLOBS-1;
  111098. bm->choice=choice;
  111099. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111100. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111101. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111102. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111103. }
  111104. /* now we have the final packet and the final packet size. Update statistics */
  111105. /* min and max reservoir */
  111106. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111107. if(max_target_bits>0 && this_bits>max_target_bits){
  111108. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111109. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111110. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111111. }else{
  111112. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111113. if(bm->minmax_reservoir>desired_fill){
  111114. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111115. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111116. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111117. }else{
  111118. bm->minmax_reservoir=desired_fill;
  111119. }
  111120. }else{
  111121. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111122. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111123. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111124. }else{
  111125. bm->minmax_reservoir=desired_fill;
  111126. }
  111127. }
  111128. }
  111129. }
  111130. /* avg reservoir */
  111131. if(bm->avg_bitsper>0){
  111132. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111133. bm->avg_reservoir+=this_bits-avg_target_bits;
  111134. }
  111135. return(0);
  111136. }
  111137. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111138. private_state *b=(private_state*)vd->backend_state;
  111139. bitrate_manager_state *bm=&b->bms;
  111140. vorbis_block *vb=bm->vb;
  111141. int choice=PACKETBLOBS/2;
  111142. if(!vb)return 0;
  111143. if(op){
  111144. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111145. if(vorbis_bitrate_managed(vb))
  111146. choice=bm->choice;
  111147. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111148. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111149. op->b_o_s=0;
  111150. op->e_o_s=vb->eofflag;
  111151. op->granulepos=vb->granulepos;
  111152. op->packetno=vb->sequence; /* for sake of completeness */
  111153. }
  111154. bm->vb=0;
  111155. return(1);
  111156. }
  111157. #endif
  111158. /*** End of inlined file: bitrate.c ***/
  111159. /*** Start of inlined file: block.c ***/
  111160. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111161. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111162. // tasks..
  111163. #if JUCE_MSVC
  111164. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111165. #endif
  111166. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111167. #if JUCE_USE_OGGVORBIS
  111168. #include <stdio.h>
  111169. #include <stdlib.h>
  111170. #include <string.h>
  111171. /*** Start of inlined file: window.h ***/
  111172. #ifndef _V_WINDOW_
  111173. #define _V_WINDOW_
  111174. extern float *_vorbis_window_get(int n);
  111175. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111176. int lW,int W,int nW);
  111177. #endif
  111178. /*** End of inlined file: window.h ***/
  111179. /*** Start of inlined file: lpc.h ***/
  111180. #ifndef _V_LPC_H_
  111181. #define _V_LPC_H_
  111182. /* simple linear scale LPC code */
  111183. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111184. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111185. float *data,long n);
  111186. #endif
  111187. /*** End of inlined file: lpc.h ***/
  111188. /* pcm accumulator examples (not exhaustive):
  111189. <-------------- lW ---------------->
  111190. <--------------- W ---------------->
  111191. : .....|..... _______________ |
  111192. : .''' | '''_--- | |\ |
  111193. :.....''' |_____--- '''......| | \_______|
  111194. :.................|__________________|_______|__|______|
  111195. |<------ Sl ------>| > Sr < |endW
  111196. |beginSl |endSl | |endSr
  111197. |beginW |endlW |beginSr
  111198. |< lW >|
  111199. <--------------- W ---------------->
  111200. | | .. ______________ |
  111201. | | ' `/ | ---_ |
  111202. |___.'___/`. | ---_____|
  111203. |_______|__|_______|_________________|
  111204. | >|Sl|< |<------ Sr ----->|endW
  111205. | | |endSl |beginSr |endSr
  111206. |beginW | |endlW
  111207. mult[0] |beginSl mult[n]
  111208. <-------------- lW ----------------->
  111209. |<--W-->|
  111210. : .............. ___ | |
  111211. : .''' |`/ \ | |
  111212. :.....''' |/`....\|...|
  111213. :.........................|___|___|___|
  111214. |Sl |Sr |endW
  111215. | | |endSr
  111216. | |beginSr
  111217. | |endSl
  111218. |beginSl
  111219. |beginW
  111220. */
  111221. /* block abstraction setup *********************************************/
  111222. #ifndef WORD_ALIGN
  111223. #define WORD_ALIGN 8
  111224. #endif
  111225. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111226. int i;
  111227. memset(vb,0,sizeof(*vb));
  111228. vb->vd=v;
  111229. vb->localalloc=0;
  111230. vb->localstore=NULL;
  111231. if(v->analysisp){
  111232. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111233. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111234. vbi->ampmax=-9999;
  111235. for(i=0;i<PACKETBLOBS;i++){
  111236. if(i==PACKETBLOBS/2){
  111237. vbi->packetblob[i]=&vb->opb;
  111238. }else{
  111239. vbi->packetblob[i]=
  111240. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111241. }
  111242. oggpack_writeinit(vbi->packetblob[i]);
  111243. }
  111244. }
  111245. return(0);
  111246. }
  111247. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111248. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111249. if(bytes+vb->localtop>vb->localalloc){
  111250. /* can't just _ogg_realloc... there are outstanding pointers */
  111251. if(vb->localstore){
  111252. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111253. vb->totaluse+=vb->localtop;
  111254. link->next=vb->reap;
  111255. link->ptr=vb->localstore;
  111256. vb->reap=link;
  111257. }
  111258. /* highly conservative */
  111259. vb->localalloc=bytes;
  111260. vb->localstore=_ogg_malloc(vb->localalloc);
  111261. vb->localtop=0;
  111262. }
  111263. {
  111264. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111265. vb->localtop+=bytes;
  111266. return ret;
  111267. }
  111268. }
  111269. /* reap the chain, pull the ripcord */
  111270. void _vorbis_block_ripcord(vorbis_block *vb){
  111271. /* reap the chain */
  111272. struct alloc_chain *reap=vb->reap;
  111273. while(reap){
  111274. struct alloc_chain *next=reap->next;
  111275. _ogg_free(reap->ptr);
  111276. memset(reap,0,sizeof(*reap));
  111277. _ogg_free(reap);
  111278. reap=next;
  111279. }
  111280. /* consolidate storage */
  111281. if(vb->totaluse){
  111282. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111283. vb->localalloc+=vb->totaluse;
  111284. vb->totaluse=0;
  111285. }
  111286. /* pull the ripcord */
  111287. vb->localtop=0;
  111288. vb->reap=NULL;
  111289. }
  111290. int vorbis_block_clear(vorbis_block *vb){
  111291. int i;
  111292. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111293. _vorbis_block_ripcord(vb);
  111294. if(vb->localstore)_ogg_free(vb->localstore);
  111295. if(vbi){
  111296. for(i=0;i<PACKETBLOBS;i++){
  111297. oggpack_writeclear(vbi->packetblob[i]);
  111298. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111299. }
  111300. _ogg_free(vbi);
  111301. }
  111302. memset(vb,0,sizeof(*vb));
  111303. return(0);
  111304. }
  111305. /* Analysis side code, but directly related to blocking. Thus it's
  111306. here and not in analysis.c (which is for analysis transforms only).
  111307. The init is here because some of it is shared */
  111308. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111309. int i;
  111310. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111311. private_state *b=NULL;
  111312. int hs;
  111313. if(ci==NULL) return 1;
  111314. hs=ci->halfrate_flag;
  111315. memset(v,0,sizeof(*v));
  111316. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111317. v->vi=vi;
  111318. b->modebits=ilog2(ci->modes);
  111319. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111320. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111321. /* MDCT is tranform 0 */
  111322. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111323. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111324. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111325. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111326. /* Vorbis I uses only window type 0 */
  111327. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111328. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111329. if(encp){ /* encode/decode differ here */
  111330. /* analysis always needs an fft */
  111331. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111332. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111333. /* finish the codebooks */
  111334. if(!ci->fullbooks){
  111335. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111336. for(i=0;i<ci->books;i++)
  111337. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111338. }
  111339. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111340. for(i=0;i<ci->psys;i++){
  111341. _vp_psy_init(b->psy+i,
  111342. ci->psy_param[i],
  111343. &ci->psy_g_param,
  111344. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111345. vi->rate);
  111346. }
  111347. v->analysisp=1;
  111348. }else{
  111349. /* finish the codebooks */
  111350. if(!ci->fullbooks){
  111351. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111352. for(i=0;i<ci->books;i++){
  111353. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111354. /* decode codebooks are now standalone after init */
  111355. vorbis_staticbook_destroy(ci->book_param[i]);
  111356. ci->book_param[i]=NULL;
  111357. }
  111358. }
  111359. }
  111360. /* initialize the storage vectors. blocksize[1] is small for encode,
  111361. but the correct size for decode */
  111362. v->pcm_storage=ci->blocksizes[1];
  111363. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111364. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111365. {
  111366. int i;
  111367. for(i=0;i<vi->channels;i++)
  111368. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111369. }
  111370. /* all 1 (large block) or 0 (small block) */
  111371. /* explicitly set for the sake of clarity */
  111372. v->lW=0; /* previous window size */
  111373. v->W=0; /* current window size */
  111374. /* all vector indexes */
  111375. v->centerW=ci->blocksizes[1]/2;
  111376. v->pcm_current=v->centerW;
  111377. /* initialize all the backend lookups */
  111378. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111379. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111380. for(i=0;i<ci->floors;i++)
  111381. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111382. look(v,ci->floor_param[i]);
  111383. for(i=0;i<ci->residues;i++)
  111384. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111385. look(v,ci->residue_param[i]);
  111386. return 0;
  111387. }
  111388. /* arbitrary settings and spec-mandated numbers get filled in here */
  111389. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111390. private_state *b=NULL;
  111391. if(_vds_shared_init(v,vi,1))return 1;
  111392. b=(private_state*)v->backend_state;
  111393. b->psy_g_look=_vp_global_look(vi);
  111394. /* Initialize the envelope state storage */
  111395. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111396. _ve_envelope_init(b->ve,vi);
  111397. vorbis_bitrate_init(vi,&b->bms);
  111398. /* compressed audio packets start after the headers
  111399. with sequence number 3 */
  111400. v->sequence=3;
  111401. return(0);
  111402. }
  111403. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111404. int i;
  111405. if(v){
  111406. vorbis_info *vi=v->vi;
  111407. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111408. private_state *b=(private_state*)v->backend_state;
  111409. if(b){
  111410. if(b->ve){
  111411. _ve_envelope_clear(b->ve);
  111412. _ogg_free(b->ve);
  111413. }
  111414. if(b->transform[0]){
  111415. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111416. _ogg_free(b->transform[0][0]);
  111417. _ogg_free(b->transform[0]);
  111418. }
  111419. if(b->transform[1]){
  111420. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111421. _ogg_free(b->transform[1][0]);
  111422. _ogg_free(b->transform[1]);
  111423. }
  111424. if(b->flr){
  111425. for(i=0;i<ci->floors;i++)
  111426. _floor_P[ci->floor_type[i]]->
  111427. free_look(b->flr[i]);
  111428. _ogg_free(b->flr);
  111429. }
  111430. if(b->residue){
  111431. for(i=0;i<ci->residues;i++)
  111432. _residue_P[ci->residue_type[i]]->
  111433. free_look(b->residue[i]);
  111434. _ogg_free(b->residue);
  111435. }
  111436. if(b->psy){
  111437. for(i=0;i<ci->psys;i++)
  111438. _vp_psy_clear(b->psy+i);
  111439. _ogg_free(b->psy);
  111440. }
  111441. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111442. vorbis_bitrate_clear(&b->bms);
  111443. drft_clear(&b->fft_look[0]);
  111444. drft_clear(&b->fft_look[1]);
  111445. }
  111446. if(v->pcm){
  111447. for(i=0;i<vi->channels;i++)
  111448. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111449. _ogg_free(v->pcm);
  111450. if(v->pcmret)_ogg_free(v->pcmret);
  111451. }
  111452. if(b){
  111453. /* free header, header1, header2 */
  111454. if(b->header)_ogg_free(b->header);
  111455. if(b->header1)_ogg_free(b->header1);
  111456. if(b->header2)_ogg_free(b->header2);
  111457. _ogg_free(b);
  111458. }
  111459. memset(v,0,sizeof(*v));
  111460. }
  111461. }
  111462. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111463. int i;
  111464. vorbis_info *vi=v->vi;
  111465. private_state *b=(private_state*)v->backend_state;
  111466. /* free header, header1, header2 */
  111467. if(b->header)_ogg_free(b->header);b->header=NULL;
  111468. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111469. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111470. /* Do we have enough storage space for the requested buffer? If not,
  111471. expand the PCM (and envelope) storage */
  111472. if(v->pcm_current+vals>=v->pcm_storage){
  111473. v->pcm_storage=v->pcm_current+vals*2;
  111474. for(i=0;i<vi->channels;i++){
  111475. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111476. }
  111477. }
  111478. for(i=0;i<vi->channels;i++)
  111479. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111480. return(v->pcmret);
  111481. }
  111482. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111483. int i;
  111484. int order=32;
  111485. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111486. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111487. long j;
  111488. v->preextrapolate=1;
  111489. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111490. for(i=0;i<v->vi->channels;i++){
  111491. /* need to run the extrapolation in reverse! */
  111492. for(j=0;j<v->pcm_current;j++)
  111493. work[j]=v->pcm[i][v->pcm_current-j-1];
  111494. /* prime as above */
  111495. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111496. /* run the predictor filter */
  111497. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111498. order,
  111499. work+v->pcm_current-v->centerW,
  111500. v->centerW);
  111501. for(j=0;j<v->pcm_current;j++)
  111502. v->pcm[i][v->pcm_current-j-1]=work[j];
  111503. }
  111504. }
  111505. }
  111506. /* call with val<=0 to set eof */
  111507. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111508. vorbis_info *vi=v->vi;
  111509. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111510. if(vals<=0){
  111511. int order=32;
  111512. int i;
  111513. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111514. /* if it wasn't done earlier (very short sample) */
  111515. if(!v->preextrapolate)
  111516. _preextrapolate_helper(v);
  111517. /* We're encoding the end of the stream. Just make sure we have
  111518. [at least] a few full blocks of zeroes at the end. */
  111519. /* actually, we don't want zeroes; that could drop a large
  111520. amplitude off a cliff, creating spread spectrum noise that will
  111521. suck to encode. Extrapolate for the sake of cleanliness. */
  111522. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111523. v->eofflag=v->pcm_current;
  111524. v->pcm_current+=ci->blocksizes[1]*3;
  111525. for(i=0;i<vi->channels;i++){
  111526. if(v->eofflag>order*2){
  111527. /* extrapolate with LPC to fill in */
  111528. long n;
  111529. /* make a predictor filter */
  111530. n=v->eofflag;
  111531. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111532. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111533. /* run the predictor filter */
  111534. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111535. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111536. }else{
  111537. /* not enough data to extrapolate (unlikely to happen due to
  111538. guarding the overlap, but bulletproof in case that
  111539. assumtion goes away). zeroes will do. */
  111540. memset(v->pcm[i]+v->eofflag,0,
  111541. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111542. }
  111543. }
  111544. }else{
  111545. if(v->pcm_current+vals>v->pcm_storage)
  111546. return(OV_EINVAL);
  111547. v->pcm_current+=vals;
  111548. /* we may want to reverse extrapolate the beginning of a stream
  111549. too... in case we're beginning on a cliff! */
  111550. /* clumsy, but simple. It only runs once, so simple is good. */
  111551. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111552. _preextrapolate_helper(v);
  111553. }
  111554. return(0);
  111555. }
  111556. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111557. the next block on which to continue analysis */
  111558. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111559. int i;
  111560. vorbis_info *vi=v->vi;
  111561. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111562. private_state *b=(private_state*)v->backend_state;
  111563. vorbis_look_psy_global *g=b->psy_g_look;
  111564. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111565. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111566. /* check to see if we're started... */
  111567. if(!v->preextrapolate)return(0);
  111568. /* check to see if we're done... */
  111569. if(v->eofflag==-1)return(0);
  111570. /* By our invariant, we have lW, W and centerW set. Search for
  111571. the next boundary so we can determine nW (the next window size)
  111572. which lets us compute the shape of the current block's window */
  111573. /* we do an envelope search even on a single blocksize; we may still
  111574. be throwing more bits at impulses, and envelope search handles
  111575. marking impulses too. */
  111576. {
  111577. long bp=_ve_envelope_search(v);
  111578. if(bp==-1){
  111579. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111580. full long block */
  111581. v->nW=0;
  111582. }else{
  111583. if(ci->blocksizes[0]==ci->blocksizes[1])
  111584. v->nW=0;
  111585. else
  111586. v->nW=bp;
  111587. }
  111588. }
  111589. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111590. {
  111591. /* center of next block + next block maximum right side. */
  111592. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111593. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111594. although this check is
  111595. less strict that the
  111596. _ve_envelope_search,
  111597. the search is not run
  111598. if we only use one
  111599. block size */
  111600. }
  111601. /* fill in the block. Note that for a short window, lW and nW are *short*
  111602. regardless of actual settings in the stream */
  111603. _vorbis_block_ripcord(vb);
  111604. vb->lW=v->lW;
  111605. vb->W=v->W;
  111606. vb->nW=v->nW;
  111607. if(v->W){
  111608. if(!v->lW || !v->nW){
  111609. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111610. /*fprintf(stderr,"-");*/
  111611. }else{
  111612. vbi->blocktype=BLOCKTYPE_LONG;
  111613. /*fprintf(stderr,"_");*/
  111614. }
  111615. }else{
  111616. if(_ve_envelope_mark(v)){
  111617. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111618. /*fprintf(stderr,"|");*/
  111619. }else{
  111620. vbi->blocktype=BLOCKTYPE_PADDING;
  111621. /*fprintf(stderr,".");*/
  111622. }
  111623. }
  111624. vb->vd=v;
  111625. vb->sequence=v->sequence++;
  111626. vb->granulepos=v->granulepos;
  111627. vb->pcmend=ci->blocksizes[v->W];
  111628. /* copy the vectors; this uses the local storage in vb */
  111629. /* this tracks 'strongest peak' for later psychoacoustics */
  111630. /* moved to the global psy state; clean this mess up */
  111631. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111632. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111633. vbi->ampmax=g->ampmax;
  111634. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111635. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111636. for(i=0;i<vi->channels;i++){
  111637. vbi->pcmdelay[i]=
  111638. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111639. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111640. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111641. /* before we added the delay
  111642. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111643. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111644. */
  111645. }
  111646. /* handle eof detection: eof==0 means that we've not yet received EOF
  111647. eof>0 marks the last 'real' sample in pcm[]
  111648. eof<0 'no more to do'; doesn't get here */
  111649. if(v->eofflag){
  111650. if(v->centerW>=v->eofflag){
  111651. v->eofflag=-1;
  111652. vb->eofflag=1;
  111653. return(1);
  111654. }
  111655. }
  111656. /* advance storage vectors and clean up */
  111657. {
  111658. int new_centerNext=ci->blocksizes[1]/2;
  111659. int movementW=centerNext-new_centerNext;
  111660. if(movementW>0){
  111661. _ve_envelope_shift(b->ve,movementW);
  111662. v->pcm_current-=movementW;
  111663. for(i=0;i<vi->channels;i++)
  111664. memmove(v->pcm[i],v->pcm[i]+movementW,
  111665. v->pcm_current*sizeof(*v->pcm[i]));
  111666. v->lW=v->W;
  111667. v->W=v->nW;
  111668. v->centerW=new_centerNext;
  111669. if(v->eofflag){
  111670. v->eofflag-=movementW;
  111671. if(v->eofflag<=0)v->eofflag=-1;
  111672. /* do not add padding to end of stream! */
  111673. if(v->centerW>=v->eofflag){
  111674. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111675. }else{
  111676. v->granulepos+=movementW;
  111677. }
  111678. }else{
  111679. v->granulepos+=movementW;
  111680. }
  111681. }
  111682. }
  111683. /* done */
  111684. return(1);
  111685. }
  111686. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111687. vorbis_info *vi=v->vi;
  111688. codec_setup_info *ci;
  111689. int hs;
  111690. if(!v->backend_state)return -1;
  111691. if(!vi)return -1;
  111692. ci=(codec_setup_info*) vi->codec_setup;
  111693. if(!ci)return -1;
  111694. hs=ci->halfrate_flag;
  111695. v->centerW=ci->blocksizes[1]>>(hs+1);
  111696. v->pcm_current=v->centerW>>hs;
  111697. v->pcm_returned=-1;
  111698. v->granulepos=-1;
  111699. v->sequence=-1;
  111700. v->eofflag=0;
  111701. ((private_state *)(v->backend_state))->sample_count=-1;
  111702. return(0);
  111703. }
  111704. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111705. if(_vds_shared_init(v,vi,0)) return 1;
  111706. vorbis_synthesis_restart(v);
  111707. return 0;
  111708. }
  111709. /* Unlike in analysis, the window is only partially applied for each
  111710. block. The time domain envelope is not yet handled at the point of
  111711. calling (as it relies on the previous block). */
  111712. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111713. vorbis_info *vi=v->vi;
  111714. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111715. private_state *b=(private_state*)v->backend_state;
  111716. int hs=ci->halfrate_flag;
  111717. int i,j;
  111718. if(!vb)return(OV_EINVAL);
  111719. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111720. v->lW=v->W;
  111721. v->W=vb->W;
  111722. v->nW=-1;
  111723. if((v->sequence==-1)||
  111724. (v->sequence+1 != vb->sequence)){
  111725. v->granulepos=-1; /* out of sequence; lose count */
  111726. b->sample_count=-1;
  111727. }
  111728. v->sequence=vb->sequence;
  111729. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111730. was called on block */
  111731. int n=ci->blocksizes[v->W]>>(hs+1);
  111732. int n0=ci->blocksizes[0]>>(hs+1);
  111733. int n1=ci->blocksizes[1]>>(hs+1);
  111734. int thisCenter;
  111735. int prevCenter;
  111736. v->glue_bits+=vb->glue_bits;
  111737. v->time_bits+=vb->time_bits;
  111738. v->floor_bits+=vb->floor_bits;
  111739. v->res_bits+=vb->res_bits;
  111740. if(v->centerW){
  111741. thisCenter=n1;
  111742. prevCenter=0;
  111743. }else{
  111744. thisCenter=0;
  111745. prevCenter=n1;
  111746. }
  111747. /* v->pcm is now used like a two-stage double buffer. We don't want
  111748. to have to constantly shift *or* adjust memory usage. Don't
  111749. accept a new block until the old is shifted out */
  111750. for(j=0;j<vi->channels;j++){
  111751. /* the overlap/add section */
  111752. if(v->lW){
  111753. if(v->W){
  111754. /* large/large */
  111755. float *w=_vorbis_window_get(b->window[1]-hs);
  111756. float *pcm=v->pcm[j]+prevCenter;
  111757. float *p=vb->pcm[j];
  111758. for(i=0;i<n1;i++)
  111759. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111760. }else{
  111761. /* large/small */
  111762. float *w=_vorbis_window_get(b->window[0]-hs);
  111763. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111764. float *p=vb->pcm[j];
  111765. for(i=0;i<n0;i++)
  111766. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111767. }
  111768. }else{
  111769. if(v->W){
  111770. /* small/large */
  111771. float *w=_vorbis_window_get(b->window[0]-hs);
  111772. float *pcm=v->pcm[j]+prevCenter;
  111773. float *p=vb->pcm[j]+n1/2-n0/2;
  111774. for(i=0;i<n0;i++)
  111775. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111776. for(;i<n1/2+n0/2;i++)
  111777. pcm[i]=p[i];
  111778. }else{
  111779. /* small/small */
  111780. float *w=_vorbis_window_get(b->window[0]-hs);
  111781. float *pcm=v->pcm[j]+prevCenter;
  111782. float *p=vb->pcm[j];
  111783. for(i=0;i<n0;i++)
  111784. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111785. }
  111786. }
  111787. /* the copy section */
  111788. {
  111789. float *pcm=v->pcm[j]+thisCenter;
  111790. float *p=vb->pcm[j]+n;
  111791. for(i=0;i<n;i++)
  111792. pcm[i]=p[i];
  111793. }
  111794. }
  111795. if(v->centerW)
  111796. v->centerW=0;
  111797. else
  111798. v->centerW=n1;
  111799. /* deal with initial packet state; we do this using the explicit
  111800. pcm_returned==-1 flag otherwise we're sensitive to first block
  111801. being short or long */
  111802. if(v->pcm_returned==-1){
  111803. v->pcm_returned=thisCenter;
  111804. v->pcm_current=thisCenter;
  111805. }else{
  111806. v->pcm_returned=prevCenter;
  111807. v->pcm_current=prevCenter+
  111808. ((ci->blocksizes[v->lW]/4+
  111809. ci->blocksizes[v->W]/4)>>hs);
  111810. }
  111811. }
  111812. /* track the frame number... This is for convenience, but also
  111813. making sure our last packet doesn't end with added padding. If
  111814. the last packet is partial, the number of samples we'll have to
  111815. return will be past the vb->granulepos.
  111816. This is not foolproof! It will be confused if we begin
  111817. decoding at the last page after a seek or hole. In that case,
  111818. we don't have a starting point to judge where the last frame
  111819. is. For this reason, vorbisfile will always try to make sure
  111820. it reads the last two marked pages in proper sequence */
  111821. if(b->sample_count==-1){
  111822. b->sample_count=0;
  111823. }else{
  111824. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111825. }
  111826. if(v->granulepos==-1){
  111827. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111828. v->granulepos=vb->granulepos;
  111829. /* is this a short page? */
  111830. if(b->sample_count>v->granulepos){
  111831. /* corner case; if this is both the first and last audio page,
  111832. then spec says the end is cut, not beginning */
  111833. if(vb->eofflag){
  111834. /* trim the end */
  111835. /* no preceeding granulepos; assume we started at zero (we'd
  111836. have to in a short single-page stream) */
  111837. /* granulepos could be -1 due to a seek, but that would result
  111838. in a long count, not short count */
  111839. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111840. }else{
  111841. /* trim the beginning */
  111842. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111843. if(v->pcm_returned>v->pcm_current)
  111844. v->pcm_returned=v->pcm_current;
  111845. }
  111846. }
  111847. }
  111848. }else{
  111849. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111850. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111851. if(v->granulepos>vb->granulepos){
  111852. long extra=v->granulepos-vb->granulepos;
  111853. if(extra)
  111854. if(vb->eofflag){
  111855. /* partial last frame. Strip the extra samples off */
  111856. v->pcm_current-=extra>>hs;
  111857. } /* else {Shouldn't happen *unless* the bitstream is out of
  111858. spec. Either way, believe the bitstream } */
  111859. } /* else {Shouldn't happen *unless* the bitstream is out of
  111860. spec. Either way, believe the bitstream } */
  111861. v->granulepos=vb->granulepos;
  111862. }
  111863. }
  111864. /* Update, cleanup */
  111865. if(vb->eofflag)v->eofflag=1;
  111866. return(0);
  111867. }
  111868. /* pcm==NULL indicates we just want the pending samples, no more */
  111869. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111870. vorbis_info *vi=v->vi;
  111871. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111872. if(pcm){
  111873. int i;
  111874. for(i=0;i<vi->channels;i++)
  111875. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111876. *pcm=v->pcmret;
  111877. }
  111878. return(v->pcm_current-v->pcm_returned);
  111879. }
  111880. return(0);
  111881. }
  111882. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111883. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111884. v->pcm_returned+=n;
  111885. return(0);
  111886. }
  111887. /* intended for use with a specific vorbisfile feature; we want access
  111888. to the [usually synthetic/postextrapolated] buffer and lapping at
  111889. the end of a decode cycle, specifically, a half-short-block worth.
  111890. This funtion works like pcmout above, except it will also expose
  111891. this implicit buffer data not normally decoded. */
  111892. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111893. vorbis_info *vi=v->vi;
  111894. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111895. int hs=ci->halfrate_flag;
  111896. int n=ci->blocksizes[v->W]>>(hs+1);
  111897. int n0=ci->blocksizes[0]>>(hs+1);
  111898. int n1=ci->blocksizes[1]>>(hs+1);
  111899. int i,j;
  111900. if(v->pcm_returned<0)return 0;
  111901. /* our returned data ends at pcm_returned; because the synthesis pcm
  111902. buffer is a two-fragment ring, that means our data block may be
  111903. fragmented by buffering, wrapping or a short block not filling
  111904. out a buffer. To simplify things, we unfragment if it's at all
  111905. possibly needed. Otherwise, we'd need to call lapout more than
  111906. once as well as hold additional dsp state. Opt for
  111907. simplicity. */
  111908. /* centerW was advanced by blockin; it would be the center of the
  111909. *next* block */
  111910. if(v->centerW==n1){
  111911. /* the data buffer wraps; swap the halves */
  111912. /* slow, sure, small */
  111913. for(j=0;j<vi->channels;j++){
  111914. float *p=v->pcm[j];
  111915. for(i=0;i<n1;i++){
  111916. float temp=p[i];
  111917. p[i]=p[i+n1];
  111918. p[i+n1]=temp;
  111919. }
  111920. }
  111921. v->pcm_current-=n1;
  111922. v->pcm_returned-=n1;
  111923. v->centerW=0;
  111924. }
  111925. /* solidify buffer into contiguous space */
  111926. if((v->lW^v->W)==1){
  111927. /* long/short or short/long */
  111928. for(j=0;j<vi->channels;j++){
  111929. float *s=v->pcm[j];
  111930. float *d=v->pcm[j]+(n1-n0)/2;
  111931. for(i=(n1+n0)/2-1;i>=0;--i)
  111932. d[i]=s[i];
  111933. }
  111934. v->pcm_returned+=(n1-n0)/2;
  111935. v->pcm_current+=(n1-n0)/2;
  111936. }else{
  111937. if(v->lW==0){
  111938. /* short/short */
  111939. for(j=0;j<vi->channels;j++){
  111940. float *s=v->pcm[j];
  111941. float *d=v->pcm[j]+n1-n0;
  111942. for(i=n0-1;i>=0;--i)
  111943. d[i]=s[i];
  111944. }
  111945. v->pcm_returned+=n1-n0;
  111946. v->pcm_current+=n1-n0;
  111947. }
  111948. }
  111949. if(pcm){
  111950. int i;
  111951. for(i=0;i<vi->channels;i++)
  111952. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111953. *pcm=v->pcmret;
  111954. }
  111955. return(n1+n-v->pcm_returned);
  111956. }
  111957. float *vorbis_window(vorbis_dsp_state *v,int W){
  111958. vorbis_info *vi=v->vi;
  111959. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111960. int hs=ci->halfrate_flag;
  111961. private_state *b=(private_state*)v->backend_state;
  111962. if(b->window[W]-1<0)return NULL;
  111963. return _vorbis_window_get(b->window[W]-hs);
  111964. }
  111965. #endif
  111966. /*** End of inlined file: block.c ***/
  111967. /*** Start of inlined file: codebook.c ***/
  111968. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111969. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111970. // tasks..
  111971. #if JUCE_MSVC
  111972. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111973. #endif
  111974. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111975. #if JUCE_USE_OGGVORBIS
  111976. #include <stdlib.h>
  111977. #include <string.h>
  111978. #include <math.h>
  111979. /* packs the given codebook into the bitstream **************************/
  111980. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111981. long i,j;
  111982. int ordered=0;
  111983. /* first the basic parameters */
  111984. oggpack_write(opb,0x564342,24);
  111985. oggpack_write(opb,c->dim,16);
  111986. oggpack_write(opb,c->entries,24);
  111987. /* pack the codewords. There are two packings; length ordered and
  111988. length random. Decide between the two now. */
  111989. for(i=1;i<c->entries;i++)
  111990. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111991. if(i==c->entries)ordered=1;
  111992. if(ordered){
  111993. /* length ordered. We only need to say how many codewords of
  111994. each length. The actual codewords are generated
  111995. deterministically */
  111996. long count=0;
  111997. oggpack_write(opb,1,1); /* ordered */
  111998. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111999. for(i=1;i<c->entries;i++){
  112000. long thisx=c->lengthlist[i];
  112001. long last=c->lengthlist[i-1];
  112002. if(thisx>last){
  112003. for(j=last;j<thisx;j++){
  112004. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112005. count=i;
  112006. }
  112007. }
  112008. }
  112009. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112010. }else{
  112011. /* length random. Again, we don't code the codeword itself, just
  112012. the length. This time, though, we have to encode each length */
  112013. oggpack_write(opb,0,1); /* unordered */
  112014. /* algortihmic mapping has use for 'unused entries', which we tag
  112015. here. The algorithmic mapping happens as usual, but the unused
  112016. entry has no codeword. */
  112017. for(i=0;i<c->entries;i++)
  112018. if(c->lengthlist[i]==0)break;
  112019. if(i==c->entries){
  112020. oggpack_write(opb,0,1); /* no unused entries */
  112021. for(i=0;i<c->entries;i++)
  112022. oggpack_write(opb,c->lengthlist[i]-1,5);
  112023. }else{
  112024. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112025. for(i=0;i<c->entries;i++){
  112026. if(c->lengthlist[i]==0){
  112027. oggpack_write(opb,0,1);
  112028. }else{
  112029. oggpack_write(opb,1,1);
  112030. oggpack_write(opb,c->lengthlist[i]-1,5);
  112031. }
  112032. }
  112033. }
  112034. }
  112035. /* is the entry number the desired return value, or do we have a
  112036. mapping? If we have a mapping, what type? */
  112037. oggpack_write(opb,c->maptype,4);
  112038. switch(c->maptype){
  112039. case 0:
  112040. /* no mapping */
  112041. break;
  112042. case 1:case 2:
  112043. /* implicitly populated value mapping */
  112044. /* explicitly populated value mapping */
  112045. if(!c->quantlist){
  112046. /* no quantlist? error */
  112047. return(-1);
  112048. }
  112049. /* values that define the dequantization */
  112050. oggpack_write(opb,c->q_min,32);
  112051. oggpack_write(opb,c->q_delta,32);
  112052. oggpack_write(opb,c->q_quant-1,4);
  112053. oggpack_write(opb,c->q_sequencep,1);
  112054. {
  112055. int quantvals;
  112056. switch(c->maptype){
  112057. case 1:
  112058. /* a single column of (c->entries/c->dim) quantized values for
  112059. building a full value list algorithmically (square lattice) */
  112060. quantvals=_book_maptype1_quantvals(c);
  112061. break;
  112062. case 2:
  112063. /* every value (c->entries*c->dim total) specified explicitly */
  112064. quantvals=c->entries*c->dim;
  112065. break;
  112066. default: /* NOT_REACHABLE */
  112067. quantvals=-1;
  112068. }
  112069. /* quantized values */
  112070. for(i=0;i<quantvals;i++)
  112071. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112072. }
  112073. break;
  112074. default:
  112075. /* error case; we don't have any other map types now */
  112076. return(-1);
  112077. }
  112078. return(0);
  112079. }
  112080. /* unpacks a codebook from the packet buffer into the codebook struct,
  112081. readies the codebook auxiliary structures for decode *************/
  112082. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112083. long i,j;
  112084. memset(s,0,sizeof(*s));
  112085. s->allocedp=1;
  112086. /* make sure alignment is correct */
  112087. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112088. /* first the basic parameters */
  112089. s->dim=oggpack_read(opb,16);
  112090. s->entries=oggpack_read(opb,24);
  112091. if(s->entries==-1)goto _eofout;
  112092. /* codeword ordering.... length ordered or unordered? */
  112093. switch((int)oggpack_read(opb,1)){
  112094. case 0:
  112095. /* unordered */
  112096. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112097. /* allocated but unused entries? */
  112098. if(oggpack_read(opb,1)){
  112099. /* yes, unused entries */
  112100. for(i=0;i<s->entries;i++){
  112101. if(oggpack_read(opb,1)){
  112102. long num=oggpack_read(opb,5);
  112103. if(num==-1)goto _eofout;
  112104. s->lengthlist[i]=num+1;
  112105. }else
  112106. s->lengthlist[i]=0;
  112107. }
  112108. }else{
  112109. /* all entries used; no tagging */
  112110. for(i=0;i<s->entries;i++){
  112111. long num=oggpack_read(opb,5);
  112112. if(num==-1)goto _eofout;
  112113. s->lengthlist[i]=num+1;
  112114. }
  112115. }
  112116. break;
  112117. case 1:
  112118. /* ordered */
  112119. {
  112120. long length=oggpack_read(opb,5)+1;
  112121. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112122. for(i=0;i<s->entries;){
  112123. long num=oggpack_read(opb,_ilog(s->entries-i));
  112124. if(num==-1)goto _eofout;
  112125. for(j=0;j<num && i<s->entries;j++,i++)
  112126. s->lengthlist[i]=length;
  112127. length++;
  112128. }
  112129. }
  112130. break;
  112131. default:
  112132. /* EOF */
  112133. return(-1);
  112134. }
  112135. /* Do we have a mapping to unpack? */
  112136. switch((s->maptype=oggpack_read(opb,4))){
  112137. case 0:
  112138. /* no mapping */
  112139. break;
  112140. case 1: case 2:
  112141. /* implicitly populated value mapping */
  112142. /* explicitly populated value mapping */
  112143. s->q_min=oggpack_read(opb,32);
  112144. s->q_delta=oggpack_read(opb,32);
  112145. s->q_quant=oggpack_read(opb,4)+1;
  112146. s->q_sequencep=oggpack_read(opb,1);
  112147. {
  112148. int quantvals=0;
  112149. switch(s->maptype){
  112150. case 1:
  112151. quantvals=_book_maptype1_quantvals(s);
  112152. break;
  112153. case 2:
  112154. quantvals=s->entries*s->dim;
  112155. break;
  112156. }
  112157. /* quantized values */
  112158. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112159. for(i=0;i<quantvals;i++)
  112160. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112161. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112162. }
  112163. break;
  112164. default:
  112165. goto _errout;
  112166. }
  112167. /* all set */
  112168. return(0);
  112169. _errout:
  112170. _eofout:
  112171. vorbis_staticbook_clear(s);
  112172. return(-1);
  112173. }
  112174. /* returns the number of bits ************************************************/
  112175. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112176. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112177. return(book->c->lengthlist[a]);
  112178. }
  112179. /* One the encode side, our vector writers are each designed for a
  112180. specific purpose, and the encoder is not flexible without modification:
  112181. The LSP vector coder uses a single stage nearest-match with no
  112182. interleave, so no step and no error return. This is specced by floor0
  112183. and doesn't change.
  112184. Residue0 encoding interleaves, uses multiple stages, and each stage
  112185. peels of a specific amount of resolution from a lattice (thus we want
  112186. to match by threshold, not nearest match). Residue doesn't *have* to
  112187. be encoded that way, but to change it, one will need to add more
  112188. infrastructure on the encode side (decode side is specced and simpler) */
  112189. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112190. /* returns entry number and *modifies a* to the quantization value *****/
  112191. int vorbis_book_errorv(codebook *book,float *a){
  112192. int dim=book->dim,k;
  112193. int best=_best(book,a,1);
  112194. for(k=0;k<dim;k++)
  112195. a[k]=(book->valuelist+best*dim)[k];
  112196. return(best);
  112197. }
  112198. /* returns the number of bits and *modifies a* to the quantization value *****/
  112199. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112200. int k,dim=book->dim;
  112201. for(k=0;k<dim;k++)
  112202. a[k]=(book->valuelist+best*dim)[k];
  112203. return(vorbis_book_encode(book,best,b));
  112204. }
  112205. /* the 'eliminate the decode tree' optimization actually requires the
  112206. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112207. (and one of the first places where carefully thought out design
  112208. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112209. to an MSb bitpacker), but not actually the huge hit it appears to
  112210. be. The first-stage decode table catches most words so that
  112211. bitreverse is not in the main execution path. */
  112212. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112213. int read=book->dec_maxlength;
  112214. long lo,hi;
  112215. long lok = oggpack_look(b,book->dec_firsttablen);
  112216. if (lok >= 0) {
  112217. long entry = book->dec_firsttable[lok];
  112218. if(entry&0x80000000UL){
  112219. lo=(entry>>15)&0x7fff;
  112220. hi=book->used_entries-(entry&0x7fff);
  112221. }else{
  112222. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112223. return(entry-1);
  112224. }
  112225. }else{
  112226. lo=0;
  112227. hi=book->used_entries;
  112228. }
  112229. lok = oggpack_look(b, read);
  112230. while(lok<0 && read>1)
  112231. lok = oggpack_look(b, --read);
  112232. if(lok<0)return -1;
  112233. /* bisect search for the codeword in the ordered list */
  112234. {
  112235. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112236. while(hi-lo>1){
  112237. long p=(hi-lo)>>1;
  112238. long test=book->codelist[lo+p]>testword;
  112239. lo+=p&(test-1);
  112240. hi-=p&(-test);
  112241. }
  112242. if(book->dec_codelengths[lo]<=read){
  112243. oggpack_adv(b, book->dec_codelengths[lo]);
  112244. return(lo);
  112245. }
  112246. }
  112247. oggpack_adv(b, read);
  112248. return(-1);
  112249. }
  112250. /* Decode side is specced and easier, because we don't need to find
  112251. matches using different criteria; we simply read and map. There are
  112252. two things we need to do 'depending':
  112253. We may need to support interleave. We don't really, but it's
  112254. convenient to do it here rather than rebuild the vector later.
  112255. Cascades may be additive or multiplicitive; this is not inherent in
  112256. the codebook, but set in the code using the codebook. Like
  112257. interleaving, it's easiest to do it here.
  112258. addmul==0 -> declarative (set the value)
  112259. addmul==1 -> additive
  112260. addmul==2 -> multiplicitive */
  112261. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112262. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112263. long packed_entry=decode_packed_entry_number(book,b);
  112264. if(packed_entry>=0)
  112265. return(book->dec_index[packed_entry]);
  112266. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112267. return(packed_entry);
  112268. }
  112269. /* returns 0 on OK or -1 on eof *************************************/
  112270. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112271. int step=n/book->dim;
  112272. long *entry = (long*)alloca(sizeof(*entry)*step);
  112273. float **t = (float**)alloca(sizeof(*t)*step);
  112274. int i,j,o;
  112275. for (i = 0; i < step; i++) {
  112276. entry[i]=decode_packed_entry_number(book,b);
  112277. if(entry[i]==-1)return(-1);
  112278. t[i] = book->valuelist+entry[i]*book->dim;
  112279. }
  112280. for(i=0,o=0;i<book->dim;i++,o+=step)
  112281. for (j=0;j<step;j++)
  112282. a[o+j]+=t[j][i];
  112283. return(0);
  112284. }
  112285. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112286. int i,j,entry;
  112287. float *t;
  112288. if(book->dim>8){
  112289. for(i=0;i<n;){
  112290. entry = decode_packed_entry_number(book,b);
  112291. if(entry==-1)return(-1);
  112292. t = book->valuelist+entry*book->dim;
  112293. for (j=0;j<book->dim;)
  112294. a[i++]+=t[j++];
  112295. }
  112296. }else{
  112297. for(i=0;i<n;){
  112298. entry = decode_packed_entry_number(book,b);
  112299. if(entry==-1)return(-1);
  112300. t = book->valuelist+entry*book->dim;
  112301. j=0;
  112302. switch((int)book->dim){
  112303. case 8:
  112304. a[i++]+=t[j++];
  112305. case 7:
  112306. a[i++]+=t[j++];
  112307. case 6:
  112308. a[i++]+=t[j++];
  112309. case 5:
  112310. a[i++]+=t[j++];
  112311. case 4:
  112312. a[i++]+=t[j++];
  112313. case 3:
  112314. a[i++]+=t[j++];
  112315. case 2:
  112316. a[i++]+=t[j++];
  112317. case 1:
  112318. a[i++]+=t[j++];
  112319. case 0:
  112320. break;
  112321. }
  112322. }
  112323. }
  112324. return(0);
  112325. }
  112326. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112327. int i,j,entry;
  112328. float *t;
  112329. for(i=0;i<n;){
  112330. entry = decode_packed_entry_number(book,b);
  112331. if(entry==-1)return(-1);
  112332. t = book->valuelist+entry*book->dim;
  112333. for (j=0;j<book->dim;)
  112334. a[i++]=t[j++];
  112335. }
  112336. return(0);
  112337. }
  112338. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112339. oggpack_buffer *b,int n){
  112340. long i,j,entry;
  112341. int chptr=0;
  112342. for(i=offset/ch;i<(offset+n)/ch;){
  112343. entry = decode_packed_entry_number(book,b);
  112344. if(entry==-1)return(-1);
  112345. {
  112346. const float *t = book->valuelist+entry*book->dim;
  112347. for (j=0;j<book->dim;j++){
  112348. a[chptr++][i]+=t[j];
  112349. if(chptr==ch){
  112350. chptr=0;
  112351. i++;
  112352. }
  112353. }
  112354. }
  112355. }
  112356. return(0);
  112357. }
  112358. #ifdef _V_SELFTEST
  112359. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112360. number of vectors through (keeping track of the quantized values),
  112361. and decode using the unpacked book. quantized version of in should
  112362. exactly equal out */
  112363. #include <stdio.h>
  112364. #include "vorbis/book/lsp20_0.vqh"
  112365. #include "vorbis/book/res0a_13.vqh"
  112366. #define TESTSIZE 40
  112367. float test1[TESTSIZE]={
  112368. 0.105939f,
  112369. 0.215373f,
  112370. 0.429117f,
  112371. 0.587974f,
  112372. 0.181173f,
  112373. 0.296583f,
  112374. 0.515707f,
  112375. 0.715261f,
  112376. 0.162327f,
  112377. 0.263834f,
  112378. 0.342876f,
  112379. 0.406025f,
  112380. 0.103571f,
  112381. 0.223561f,
  112382. 0.368513f,
  112383. 0.540313f,
  112384. 0.136672f,
  112385. 0.395882f,
  112386. 0.587183f,
  112387. 0.652476f,
  112388. 0.114338f,
  112389. 0.417300f,
  112390. 0.525486f,
  112391. 0.698679f,
  112392. 0.147492f,
  112393. 0.324481f,
  112394. 0.643089f,
  112395. 0.757582f,
  112396. 0.139556f,
  112397. 0.215795f,
  112398. 0.324559f,
  112399. 0.399387f,
  112400. 0.120236f,
  112401. 0.267420f,
  112402. 0.446940f,
  112403. 0.608760f,
  112404. 0.115587f,
  112405. 0.287234f,
  112406. 0.571081f,
  112407. 0.708603f,
  112408. };
  112409. float test3[TESTSIZE]={
  112410. 0,1,-2,3,4,-5,6,7,8,9,
  112411. 8,-2,7,-1,4,6,8,3,1,-9,
  112412. 10,11,12,13,14,15,26,17,18,19,
  112413. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112414. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112415. &_vq_book_res0a_13,NULL};
  112416. float *testvec[]={test1,test3};
  112417. int main(){
  112418. oggpack_buffer write;
  112419. oggpack_buffer read;
  112420. long ptr=0,i;
  112421. oggpack_writeinit(&write);
  112422. fprintf(stderr,"Testing codebook abstraction...:\n");
  112423. while(testlist[ptr]){
  112424. codebook c;
  112425. static_codebook s;
  112426. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112427. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112428. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112429. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112430. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112431. /* pack the codebook, write the testvector */
  112432. oggpack_reset(&write);
  112433. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112434. we can write */
  112435. vorbis_staticbook_pack(testlist[ptr],&write);
  112436. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112437. for(i=0;i<TESTSIZE;i+=c.dim){
  112438. int best=_best(&c,qv+i,1);
  112439. vorbis_book_encodev(&c,best,qv+i,&write);
  112440. }
  112441. vorbis_book_clear(&c);
  112442. fprintf(stderr,"OK.\n");
  112443. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112444. /* transfer the write data to a read buffer and unpack/read */
  112445. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112446. if(vorbis_staticbook_unpack(&read,&s)){
  112447. fprintf(stderr,"Error unpacking codebook.\n");
  112448. exit(1);
  112449. }
  112450. if(vorbis_book_init_decode(&c,&s)){
  112451. fprintf(stderr,"Error initializing codebook.\n");
  112452. exit(1);
  112453. }
  112454. for(i=0;i<TESTSIZE;i+=c.dim)
  112455. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112456. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112457. exit(1);
  112458. }
  112459. for(i=0;i<TESTSIZE;i++)
  112460. if(fabs(qv[i]-iv[i])>.000001){
  112461. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112462. iv[i],qv[i],i);
  112463. exit(1);
  112464. }
  112465. fprintf(stderr,"OK\n");
  112466. ptr++;
  112467. }
  112468. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112469. exit(0);
  112470. }
  112471. #endif
  112472. #endif
  112473. /*** End of inlined file: codebook.c ***/
  112474. /*** Start of inlined file: envelope.c ***/
  112475. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112476. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112477. // tasks..
  112478. #if JUCE_MSVC
  112479. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112480. #endif
  112481. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112482. #if JUCE_USE_OGGVORBIS
  112483. #include <stdlib.h>
  112484. #include <string.h>
  112485. #include <stdio.h>
  112486. #include <math.h>
  112487. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112488. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112489. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112490. int ch=vi->channels;
  112491. int i,j;
  112492. int n=e->winlength=128;
  112493. e->searchstep=64; /* not random */
  112494. e->minenergy=gi->preecho_minenergy;
  112495. e->ch=ch;
  112496. e->storage=128;
  112497. e->cursor=ci->blocksizes[1]/2;
  112498. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112499. mdct_init(&e->mdct,n);
  112500. for(i=0;i<n;i++){
  112501. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112502. e->mdct_win[i]*=e->mdct_win[i];
  112503. }
  112504. /* magic follows */
  112505. e->band[0].begin=2; e->band[0].end=4;
  112506. e->band[1].begin=4; e->band[1].end=5;
  112507. e->band[2].begin=6; e->band[2].end=6;
  112508. e->band[3].begin=9; e->band[3].end=8;
  112509. e->band[4].begin=13; e->band[4].end=8;
  112510. e->band[5].begin=17; e->band[5].end=8;
  112511. e->band[6].begin=22; e->band[6].end=8;
  112512. for(j=0;j<VE_BANDS;j++){
  112513. n=e->band[j].end;
  112514. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112515. for(i=0;i<n;i++){
  112516. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112517. e->band[j].total+=e->band[j].window[i];
  112518. }
  112519. e->band[j].total=1./e->band[j].total;
  112520. }
  112521. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112522. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112523. }
  112524. void _ve_envelope_clear(envelope_lookup *e){
  112525. int i;
  112526. mdct_clear(&e->mdct);
  112527. for(i=0;i<VE_BANDS;i++)
  112528. _ogg_free(e->band[i].window);
  112529. _ogg_free(e->mdct_win);
  112530. _ogg_free(e->filter);
  112531. _ogg_free(e->mark);
  112532. memset(e,0,sizeof(*e));
  112533. }
  112534. /* fairly straight threshhold-by-band based until we find something
  112535. that works better and isn't patented. */
  112536. static int _ve_amp(envelope_lookup *ve,
  112537. vorbis_info_psy_global *gi,
  112538. float *data,
  112539. envelope_band *bands,
  112540. envelope_filter_state *filters,
  112541. long pos){
  112542. long n=ve->winlength;
  112543. int ret=0;
  112544. long i,j;
  112545. float decay;
  112546. /* we want to have a 'minimum bar' for energy, else we're just
  112547. basing blocks on quantization noise that outweighs the signal
  112548. itself (for low power signals) */
  112549. float minV=ve->minenergy;
  112550. float *vec=(float*) alloca(n*sizeof(*vec));
  112551. /* stretch is used to gradually lengthen the number of windows
  112552. considered prevoius-to-potential-trigger */
  112553. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112554. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112555. if(penalty<0.f)penalty=0.f;
  112556. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112557. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112558. totalshift+pos*ve->searchstep);*/
  112559. /* window and transform */
  112560. for(i=0;i<n;i++)
  112561. vec[i]=data[i]*ve->mdct_win[i];
  112562. mdct_forward(&ve->mdct,vec,vec);
  112563. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112564. /* near-DC spreading function; this has nothing to do with
  112565. psychoacoustics, just sidelobe leakage and window size */
  112566. {
  112567. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112568. int ptr=filters->nearptr;
  112569. /* the accumulation is regularly refreshed from scratch to avoid
  112570. floating point creep */
  112571. if(ptr==0){
  112572. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112573. filters->nearDC_partialacc=temp;
  112574. }else{
  112575. decay=filters->nearDC_acc+=temp;
  112576. filters->nearDC_partialacc+=temp;
  112577. }
  112578. filters->nearDC_acc-=filters->nearDC[ptr];
  112579. filters->nearDC[ptr]=temp;
  112580. decay*=(1./(VE_NEARDC+1));
  112581. filters->nearptr++;
  112582. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112583. decay=todB(&decay)*.5-15.f;
  112584. }
  112585. /* perform spreading and limiting, also smooth the spectrum. yes,
  112586. the MDCT results in all real coefficients, but it still *behaves*
  112587. like real/imaginary pairs */
  112588. for(i=0;i<n/2;i+=2){
  112589. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112590. val=todB(&val)*.5f;
  112591. if(val<decay)val=decay;
  112592. if(val<minV)val=minV;
  112593. vec[i>>1]=val;
  112594. decay-=8.;
  112595. }
  112596. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112597. /* perform preecho/postecho triggering by band */
  112598. for(j=0;j<VE_BANDS;j++){
  112599. float acc=0.;
  112600. float valmax,valmin;
  112601. /* accumulate amplitude */
  112602. for(i=0;i<bands[j].end;i++)
  112603. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112604. acc*=bands[j].total;
  112605. /* convert amplitude to delta */
  112606. {
  112607. int p,thisx=filters[j].ampptr;
  112608. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112609. p=thisx;
  112610. p--;
  112611. if(p<0)p+=VE_AMP;
  112612. postmax=max(acc,filters[j].ampbuf[p]);
  112613. postmin=min(acc,filters[j].ampbuf[p]);
  112614. for(i=0;i<stretch;i++){
  112615. p--;
  112616. if(p<0)p+=VE_AMP;
  112617. premax=max(premax,filters[j].ampbuf[p]);
  112618. premin=min(premin,filters[j].ampbuf[p]);
  112619. }
  112620. valmin=postmin-premin;
  112621. valmax=postmax-premax;
  112622. /*filters[j].markers[pos]=valmax;*/
  112623. filters[j].ampbuf[thisx]=acc;
  112624. filters[j].ampptr++;
  112625. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112626. }
  112627. /* look at min/max, decide trigger */
  112628. if(valmax>gi->preecho_thresh[j]+penalty){
  112629. ret|=1;
  112630. ret|=4;
  112631. }
  112632. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112633. }
  112634. return(ret);
  112635. }
  112636. #if 0
  112637. static int seq=0;
  112638. static ogg_int64_t totalshift=-1024;
  112639. #endif
  112640. long _ve_envelope_search(vorbis_dsp_state *v){
  112641. vorbis_info *vi=v->vi;
  112642. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112643. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112644. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112645. long i,j;
  112646. int first=ve->current/ve->searchstep;
  112647. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112648. if(first<0)first=0;
  112649. /* make sure we have enough storage to match the PCM */
  112650. if(last+VE_WIN+VE_POST>ve->storage){
  112651. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112652. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112653. }
  112654. for(j=first;j<last;j++){
  112655. int ret=0;
  112656. ve->stretch++;
  112657. if(ve->stretch>VE_MAXSTRETCH*2)
  112658. ve->stretch=VE_MAXSTRETCH*2;
  112659. for(i=0;i<ve->ch;i++){
  112660. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112661. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112662. }
  112663. ve->mark[j+VE_POST]=0;
  112664. if(ret&1){
  112665. ve->mark[j]=1;
  112666. ve->mark[j+1]=1;
  112667. }
  112668. if(ret&2){
  112669. ve->mark[j]=1;
  112670. if(j>0)ve->mark[j-1]=1;
  112671. }
  112672. if(ret&4)ve->stretch=-1;
  112673. }
  112674. ve->current=last*ve->searchstep;
  112675. {
  112676. long centerW=v->centerW;
  112677. long testW=
  112678. centerW+
  112679. ci->blocksizes[v->W]/4+
  112680. ci->blocksizes[1]/2+
  112681. ci->blocksizes[0]/4;
  112682. j=ve->cursor;
  112683. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112684. working back one window */
  112685. if(j>=testW)return(1);
  112686. ve->cursor=j;
  112687. if(ve->mark[j/ve->searchstep]){
  112688. if(j>centerW){
  112689. #if 0
  112690. if(j>ve->curmark){
  112691. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112692. int l,m;
  112693. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112694. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112695. seq,
  112696. (totalshift+ve->cursor)/44100.,
  112697. (totalshift+j)/44100.);
  112698. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112699. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112700. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112701. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112702. for(m=0;m<VE_BANDS;m++){
  112703. char buf[80];
  112704. sprintf(buf,"delL%d",m);
  112705. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112706. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112707. }
  112708. for(m=0;m<VE_BANDS;m++){
  112709. char buf[80];
  112710. sprintf(buf,"delR%d",m);
  112711. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112712. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112713. }
  112714. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112715. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112716. seq++;
  112717. }
  112718. #endif
  112719. ve->curmark=j;
  112720. if(j>=testW)return(1);
  112721. return(0);
  112722. }
  112723. }
  112724. j+=ve->searchstep;
  112725. }
  112726. }
  112727. return(-1);
  112728. }
  112729. int _ve_envelope_mark(vorbis_dsp_state *v){
  112730. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112731. vorbis_info *vi=v->vi;
  112732. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112733. long centerW=v->centerW;
  112734. long beginW=centerW-ci->blocksizes[v->W]/4;
  112735. long endW=centerW+ci->blocksizes[v->W]/4;
  112736. if(v->W){
  112737. beginW-=ci->blocksizes[v->lW]/4;
  112738. endW+=ci->blocksizes[v->nW]/4;
  112739. }else{
  112740. beginW-=ci->blocksizes[0]/4;
  112741. endW+=ci->blocksizes[0]/4;
  112742. }
  112743. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112744. {
  112745. long first=beginW/ve->searchstep;
  112746. long last=endW/ve->searchstep;
  112747. long i;
  112748. for(i=first;i<last;i++)
  112749. if(ve->mark[i])return(1);
  112750. }
  112751. return(0);
  112752. }
  112753. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112754. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112755. ahead of ve->current */
  112756. int smallshift=shift/e->searchstep;
  112757. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112758. #if 0
  112759. for(i=0;i<VE_BANDS*e->ch;i++)
  112760. memmove(e->filter[i].markers,
  112761. e->filter[i].markers+smallshift,
  112762. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112763. totalshift+=shift;
  112764. #endif
  112765. e->current-=shift;
  112766. if(e->curmark>=0)
  112767. e->curmark-=shift;
  112768. e->cursor-=shift;
  112769. }
  112770. #endif
  112771. /*** End of inlined file: envelope.c ***/
  112772. /*** Start of inlined file: floor0.c ***/
  112773. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112774. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112775. // tasks..
  112776. #if JUCE_MSVC
  112777. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112778. #endif
  112779. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112780. #if JUCE_USE_OGGVORBIS
  112781. #include <stdlib.h>
  112782. #include <string.h>
  112783. #include <math.h>
  112784. /*** Start of inlined file: lsp.h ***/
  112785. #ifndef _V_LSP_H_
  112786. #define _V_LSP_H_
  112787. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112788. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112789. float *lsp,int m,
  112790. float amp,float ampoffset);
  112791. #endif
  112792. /*** End of inlined file: lsp.h ***/
  112793. #include <stdio.h>
  112794. typedef struct {
  112795. int ln;
  112796. int m;
  112797. int **linearmap;
  112798. int n[2];
  112799. vorbis_info_floor0 *vi;
  112800. long bits;
  112801. long frames;
  112802. } vorbis_look_floor0;
  112803. /***********************************************/
  112804. static void floor0_free_info(vorbis_info_floor *i){
  112805. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112806. if(info){
  112807. memset(info,0,sizeof(*info));
  112808. _ogg_free(info);
  112809. }
  112810. }
  112811. static void floor0_free_look(vorbis_look_floor *i){
  112812. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112813. if(look){
  112814. if(look->linearmap){
  112815. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112816. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112817. _ogg_free(look->linearmap);
  112818. }
  112819. memset(look,0,sizeof(*look));
  112820. _ogg_free(look);
  112821. }
  112822. }
  112823. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112824. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112825. int j;
  112826. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112827. info->order=oggpack_read(opb,8);
  112828. info->rate=oggpack_read(opb,16);
  112829. info->barkmap=oggpack_read(opb,16);
  112830. info->ampbits=oggpack_read(opb,6);
  112831. info->ampdB=oggpack_read(opb,8);
  112832. info->numbooks=oggpack_read(opb,4)+1;
  112833. if(info->order<1)goto err_out;
  112834. if(info->rate<1)goto err_out;
  112835. if(info->barkmap<1)goto err_out;
  112836. if(info->numbooks<1)goto err_out;
  112837. for(j=0;j<info->numbooks;j++){
  112838. info->books[j]=oggpack_read(opb,8);
  112839. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112840. }
  112841. return(info);
  112842. err_out:
  112843. floor0_free_info(info);
  112844. return(NULL);
  112845. }
  112846. /* initialize Bark scale and normalization lookups. We could do this
  112847. with static tables, but Vorbis allows a number of possible
  112848. combinations, so it's best to do it computationally.
  112849. The below is authoritative in terms of defining scale mapping.
  112850. Note that the scale depends on the sampling rate as well as the
  112851. linear block and mapping sizes */
  112852. static void floor0_map_lazy_init(vorbis_block *vb,
  112853. vorbis_info_floor *infoX,
  112854. vorbis_look_floor0 *look){
  112855. if(!look->linearmap[vb->W]){
  112856. vorbis_dsp_state *vd=vb->vd;
  112857. vorbis_info *vi=vd->vi;
  112858. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112859. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112860. int W=vb->W;
  112861. int n=ci->blocksizes[W]/2,j;
  112862. /* we choose a scaling constant so that:
  112863. floor(bark(rate/2-1)*C)=mapped-1
  112864. floor(bark(rate/2)*C)=mapped */
  112865. float scale=look->ln/toBARK(info->rate/2.f);
  112866. /* the mapping from a linear scale to a smaller bark scale is
  112867. straightforward. We do *not* make sure that the linear mapping
  112868. does not skip bark-scale bins; the decoder simply skips them and
  112869. the encoder may do what it wishes in filling them. They're
  112870. necessary in some mapping combinations to keep the scale spacing
  112871. accurate */
  112872. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112873. for(j=0;j<n;j++){
  112874. int val=floor( toBARK((info->rate/2.f)/n*j)
  112875. *scale); /* bark numbers represent band edges */
  112876. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112877. look->linearmap[W][j]=val;
  112878. }
  112879. look->linearmap[W][j]=-1;
  112880. look->n[W]=n;
  112881. }
  112882. }
  112883. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112884. vorbis_info_floor *i){
  112885. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112886. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112887. look->m=info->order;
  112888. look->ln=info->barkmap;
  112889. look->vi=info;
  112890. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112891. return look;
  112892. }
  112893. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112894. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112895. vorbis_info_floor0 *info=look->vi;
  112896. int j,k;
  112897. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112898. if(ampraw>0){ /* also handles the -1 out of data case */
  112899. long maxval=(1<<info->ampbits)-1;
  112900. float amp=(float)ampraw/maxval*info->ampdB;
  112901. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112902. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112903. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112904. codebook *b=ci->fullbooks+info->books[booknum];
  112905. float last=0.f;
  112906. /* the additional b->dim is a guard against any possible stack
  112907. smash; b->dim is provably more than we can overflow the
  112908. vector */
  112909. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112910. for(j=0;j<look->m;j+=b->dim)
  112911. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112912. for(j=0;j<look->m;){
  112913. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112914. last=lsp[j-1];
  112915. }
  112916. lsp[look->m]=amp;
  112917. return(lsp);
  112918. }
  112919. }
  112920. eop:
  112921. return(NULL);
  112922. }
  112923. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112924. void *memo,float *out){
  112925. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112926. vorbis_info_floor0 *info=look->vi;
  112927. floor0_map_lazy_init(vb,info,look);
  112928. if(memo){
  112929. float *lsp=(float *)memo;
  112930. float amp=lsp[look->m];
  112931. /* take the coefficients back to a spectral envelope curve */
  112932. vorbis_lsp_to_curve(out,
  112933. look->linearmap[vb->W],
  112934. look->n[vb->W],
  112935. look->ln,
  112936. lsp,look->m,amp,(float)info->ampdB);
  112937. return(1);
  112938. }
  112939. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112940. return(0);
  112941. }
  112942. /* export hooks */
  112943. vorbis_func_floor floor0_exportbundle={
  112944. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112945. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112946. };
  112947. #endif
  112948. /*** End of inlined file: floor0.c ***/
  112949. /*** Start of inlined file: floor1.c ***/
  112950. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112951. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112952. // tasks..
  112953. #if JUCE_MSVC
  112954. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112955. #endif
  112956. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112957. #if JUCE_USE_OGGVORBIS
  112958. #include <stdlib.h>
  112959. #include <string.h>
  112960. #include <math.h>
  112961. #include <stdio.h>
  112962. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112963. typedef struct {
  112964. int sorted_index[VIF_POSIT+2];
  112965. int forward_index[VIF_POSIT+2];
  112966. int reverse_index[VIF_POSIT+2];
  112967. int hineighbor[VIF_POSIT];
  112968. int loneighbor[VIF_POSIT];
  112969. int posts;
  112970. int n;
  112971. int quant_q;
  112972. vorbis_info_floor1 *vi;
  112973. long phrasebits;
  112974. long postbits;
  112975. long frames;
  112976. } vorbis_look_floor1;
  112977. typedef struct lsfit_acc{
  112978. long x0;
  112979. long x1;
  112980. long xa;
  112981. long ya;
  112982. long x2a;
  112983. long y2a;
  112984. long xya;
  112985. long an;
  112986. } lsfit_acc;
  112987. /***********************************************/
  112988. static void floor1_free_info(vorbis_info_floor *i){
  112989. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112990. if(info){
  112991. memset(info,0,sizeof(*info));
  112992. _ogg_free(info);
  112993. }
  112994. }
  112995. static void floor1_free_look(vorbis_look_floor *i){
  112996. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112997. if(look){
  112998. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112999. (float)look->phrasebits/look->frames,
  113000. (float)look->postbits/look->frames,
  113001. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113002. memset(look,0,sizeof(*look));
  113003. _ogg_free(look);
  113004. }
  113005. }
  113006. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113007. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113008. int j,k;
  113009. int count=0;
  113010. int rangebits;
  113011. int maxposit=info->postlist[1];
  113012. int maxclass=-1;
  113013. /* save out partitions */
  113014. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113015. for(j=0;j<info->partitions;j++){
  113016. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113017. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113018. }
  113019. /* save out partition classes */
  113020. for(j=0;j<maxclass+1;j++){
  113021. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113022. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113023. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113024. for(k=0;k<(1<<info->class_subs[j]);k++)
  113025. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113026. }
  113027. /* save out the post list */
  113028. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113029. oggpack_write(opb,ilog2(maxposit),4);
  113030. rangebits=ilog2(maxposit);
  113031. for(j=0,k=0;j<info->partitions;j++){
  113032. count+=info->class_dim[info->partitionclass[j]];
  113033. for(;k<count;k++)
  113034. oggpack_write(opb,info->postlist[k+2],rangebits);
  113035. }
  113036. }
  113037. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113038. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113039. int j,k,count=0,maxclass=-1,rangebits;
  113040. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113041. /* read partitions */
  113042. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113043. for(j=0;j<info->partitions;j++){
  113044. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113045. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113046. }
  113047. /* read partition classes */
  113048. for(j=0;j<maxclass+1;j++){
  113049. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113050. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113051. if(info->class_subs[j]<0)
  113052. goto err_out;
  113053. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113054. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113055. goto err_out;
  113056. for(k=0;k<(1<<info->class_subs[j]);k++){
  113057. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113058. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113059. goto err_out;
  113060. }
  113061. }
  113062. /* read the post list */
  113063. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113064. rangebits=oggpack_read(opb,4);
  113065. for(j=0,k=0;j<info->partitions;j++){
  113066. count+=info->class_dim[info->partitionclass[j]];
  113067. for(;k<count;k++){
  113068. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113069. if(t<0 || t>=(1<<rangebits))
  113070. goto err_out;
  113071. }
  113072. }
  113073. info->postlist[0]=0;
  113074. info->postlist[1]=1<<rangebits;
  113075. return(info);
  113076. err_out:
  113077. floor1_free_info(info);
  113078. return(NULL);
  113079. }
  113080. static int JUCE_CDECL icomp(const void *a,const void *b){
  113081. return(**(int **)a-**(int **)b);
  113082. }
  113083. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113084. vorbis_info_floor *in){
  113085. int *sortpointer[VIF_POSIT+2];
  113086. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113087. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113088. int i,j,n=0;
  113089. look->vi=info;
  113090. look->n=info->postlist[1];
  113091. /* we drop each position value in-between already decoded values,
  113092. and use linear interpolation to predict each new value past the
  113093. edges. The positions are read in the order of the position
  113094. list... we precompute the bounding positions in the lookup. Of
  113095. course, the neighbors can change (if a position is declined), but
  113096. this is an initial mapping */
  113097. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113098. n+=2;
  113099. look->posts=n;
  113100. /* also store a sorted position index */
  113101. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113102. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113103. /* points from sort order back to range number */
  113104. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113105. /* points from range order to sorted position */
  113106. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113107. /* we actually need the post values too */
  113108. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113109. /* quantize values to multiplier spec */
  113110. switch(info->mult){
  113111. case 1: /* 1024 -> 256 */
  113112. look->quant_q=256;
  113113. break;
  113114. case 2: /* 1024 -> 128 */
  113115. look->quant_q=128;
  113116. break;
  113117. case 3: /* 1024 -> 86 */
  113118. look->quant_q=86;
  113119. break;
  113120. case 4: /* 1024 -> 64 */
  113121. look->quant_q=64;
  113122. break;
  113123. }
  113124. /* discover our neighbors for decode where we don't use fit flags
  113125. (that would push the neighbors outward) */
  113126. for(i=0;i<n-2;i++){
  113127. int lo=0;
  113128. int hi=1;
  113129. int lx=0;
  113130. int hx=look->n;
  113131. int currentx=info->postlist[i+2];
  113132. for(j=0;j<i+2;j++){
  113133. int x=info->postlist[j];
  113134. if(x>lx && x<currentx){
  113135. lo=j;
  113136. lx=x;
  113137. }
  113138. if(x<hx && x>currentx){
  113139. hi=j;
  113140. hx=x;
  113141. }
  113142. }
  113143. look->loneighbor[i]=lo;
  113144. look->hineighbor[i]=hi;
  113145. }
  113146. return(look);
  113147. }
  113148. static int render_point(int x0,int x1,int y0,int y1,int x){
  113149. y0&=0x7fff; /* mask off flag */
  113150. y1&=0x7fff;
  113151. {
  113152. int dy=y1-y0;
  113153. int adx=x1-x0;
  113154. int ady=abs(dy);
  113155. int err=ady*(x-x0);
  113156. int off=err/adx;
  113157. if(dy<0)return(y0-off);
  113158. return(y0+off);
  113159. }
  113160. }
  113161. static int vorbis_dBquant(const float *x){
  113162. int i= *x*7.3142857f+1023.5f;
  113163. if(i>1023)return(1023);
  113164. if(i<0)return(0);
  113165. return i;
  113166. }
  113167. static float FLOOR1_fromdB_LOOKUP[256]={
  113168. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113169. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113170. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113171. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113172. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113173. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113174. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113175. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113176. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113177. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113178. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113179. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113180. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113181. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113182. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113183. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113184. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113185. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113186. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113187. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113188. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113189. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113190. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113191. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113192. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113193. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113194. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113195. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113196. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113197. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113198. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113199. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113200. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113201. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113202. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113203. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113204. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113205. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113206. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113207. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113208. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113209. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113210. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113211. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113212. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113213. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113214. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113215. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113216. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113217. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113218. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113219. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113220. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113221. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113222. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113223. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113224. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113225. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113226. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113227. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113228. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113229. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113230. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113231. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113232. };
  113233. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113234. int dy=y1-y0;
  113235. int adx=x1-x0;
  113236. int ady=abs(dy);
  113237. int base=dy/adx;
  113238. int sy=(dy<0?base-1:base+1);
  113239. int x=x0;
  113240. int y=y0;
  113241. int err=0;
  113242. ady-=abs(base*adx);
  113243. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113244. while(++x<x1){
  113245. err=err+ady;
  113246. if(err>=adx){
  113247. err-=adx;
  113248. y+=sy;
  113249. }else{
  113250. y+=base;
  113251. }
  113252. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113253. }
  113254. }
  113255. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113256. int dy=y1-y0;
  113257. int adx=x1-x0;
  113258. int ady=abs(dy);
  113259. int base=dy/adx;
  113260. int sy=(dy<0?base-1:base+1);
  113261. int x=x0;
  113262. int y=y0;
  113263. int err=0;
  113264. ady-=abs(base*adx);
  113265. d[x]=y;
  113266. while(++x<x1){
  113267. err=err+ady;
  113268. if(err>=adx){
  113269. err-=adx;
  113270. y+=sy;
  113271. }else{
  113272. y+=base;
  113273. }
  113274. d[x]=y;
  113275. }
  113276. }
  113277. /* the floor has already been filtered to only include relevant sections */
  113278. static int accumulate_fit(const float *flr,const float *mdct,
  113279. int x0, int x1,lsfit_acc *a,
  113280. int n,vorbis_info_floor1 *info){
  113281. long i;
  113282. 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;
  113283. memset(a,0,sizeof(*a));
  113284. a->x0=x0;
  113285. a->x1=x1;
  113286. if(x1>=n)x1=n-1;
  113287. for(i=x0;i<=x1;i++){
  113288. int quantized=vorbis_dBquant(flr+i);
  113289. if(quantized){
  113290. if(mdct[i]+info->twofitatten>=flr[i]){
  113291. xa += i;
  113292. ya += quantized;
  113293. x2a += i*i;
  113294. y2a += quantized*quantized;
  113295. xya += i*quantized;
  113296. na++;
  113297. }else{
  113298. xb += i;
  113299. yb += quantized;
  113300. x2b += i*i;
  113301. y2b += quantized*quantized;
  113302. xyb += i*quantized;
  113303. nb++;
  113304. }
  113305. }
  113306. }
  113307. xb+=xa;
  113308. yb+=ya;
  113309. x2b+=x2a;
  113310. y2b+=y2a;
  113311. xyb+=xya;
  113312. nb+=na;
  113313. /* weight toward the actually used frequencies if we meet the threshhold */
  113314. {
  113315. int weight=nb*info->twofitweight/(na+1);
  113316. a->xa=xa*weight+xb;
  113317. a->ya=ya*weight+yb;
  113318. a->x2a=x2a*weight+x2b;
  113319. a->y2a=y2a*weight+y2b;
  113320. a->xya=xya*weight+xyb;
  113321. a->an=na*weight+nb;
  113322. }
  113323. return(na);
  113324. }
  113325. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113326. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113327. long x0=a[0].x0;
  113328. long x1=a[fits-1].x1;
  113329. for(i=0;i<fits;i++){
  113330. x+=a[i].xa;
  113331. y+=a[i].ya;
  113332. x2+=a[i].x2a;
  113333. y2+=a[i].y2a;
  113334. xy+=a[i].xya;
  113335. an+=a[i].an;
  113336. }
  113337. if(*y0>=0){
  113338. x+= x0;
  113339. y+= *y0;
  113340. x2+= x0 * x0;
  113341. y2+= *y0 * *y0;
  113342. xy+= *y0 * x0;
  113343. an++;
  113344. }
  113345. if(*y1>=0){
  113346. x+= x1;
  113347. y+= *y1;
  113348. x2+= x1 * x1;
  113349. y2+= *y1 * *y1;
  113350. xy+= *y1 * x1;
  113351. an++;
  113352. }
  113353. if(an){
  113354. /* need 64 bit multiplies, which C doesn't give portably as int */
  113355. double fx=x;
  113356. double fy=y;
  113357. double fx2=x2;
  113358. double fxy=xy;
  113359. double denom=1./(an*fx2-fx*fx);
  113360. double a=(fy*fx2-fxy*fx)*denom;
  113361. double b=(an*fxy-fx*fy)*denom;
  113362. *y0=rint(a+b*x0);
  113363. *y1=rint(a+b*x1);
  113364. /* limit to our range! */
  113365. if(*y0>1023)*y0=1023;
  113366. if(*y1>1023)*y1=1023;
  113367. if(*y0<0)*y0=0;
  113368. if(*y1<0)*y1=0;
  113369. }else{
  113370. *y0=0;
  113371. *y1=0;
  113372. }
  113373. }
  113374. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113375. long y=0;
  113376. int i;
  113377. for(i=0;i<fits && y==0;i++)
  113378. y+=a[i].ya;
  113379. *y0=*y1=y;
  113380. }*/
  113381. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113382. const float *mdct,
  113383. vorbis_info_floor1 *info){
  113384. int dy=y1-y0;
  113385. int adx=x1-x0;
  113386. int ady=abs(dy);
  113387. int base=dy/adx;
  113388. int sy=(dy<0?base-1:base+1);
  113389. int x=x0;
  113390. int y=y0;
  113391. int err=0;
  113392. int val=vorbis_dBquant(mask+x);
  113393. int mse=0;
  113394. int n=0;
  113395. ady-=abs(base*adx);
  113396. mse=(y-val);
  113397. mse*=mse;
  113398. n++;
  113399. if(mdct[x]+info->twofitatten>=mask[x]){
  113400. if(y+info->maxover<val)return(1);
  113401. if(y-info->maxunder>val)return(1);
  113402. }
  113403. while(++x<x1){
  113404. err=err+ady;
  113405. if(err>=adx){
  113406. err-=adx;
  113407. y+=sy;
  113408. }else{
  113409. y+=base;
  113410. }
  113411. val=vorbis_dBquant(mask+x);
  113412. mse+=((y-val)*(y-val));
  113413. n++;
  113414. if(mdct[x]+info->twofitatten>=mask[x]){
  113415. if(val){
  113416. if(y+info->maxover<val)return(1);
  113417. if(y-info->maxunder>val)return(1);
  113418. }
  113419. }
  113420. }
  113421. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113422. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113423. if(mse/n>info->maxerr)return(1);
  113424. return(0);
  113425. }
  113426. static int post_Y(int *A,int *B,int pos){
  113427. if(A[pos]<0)
  113428. return B[pos];
  113429. if(B[pos]<0)
  113430. return A[pos];
  113431. return (A[pos]+B[pos])>>1;
  113432. }
  113433. int *floor1_fit(vorbis_block *vb,void *look_,
  113434. const float *logmdct, /* in */
  113435. const float *logmask){
  113436. long i,j;
  113437. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113438. vorbis_info_floor1 *info=look->vi;
  113439. long n=look->n;
  113440. long posts=look->posts;
  113441. long nonzero=0;
  113442. lsfit_acc fits[VIF_POSIT+1];
  113443. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113444. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113445. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113446. int hineighbor[VIF_POSIT+2];
  113447. int *output=NULL;
  113448. int memo[VIF_POSIT+2];
  113449. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113450. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113451. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113452. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113453. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113454. /* quantize the relevant floor points and collect them into line fit
  113455. structures (one per minimal division) at the same time */
  113456. if(posts==0){
  113457. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113458. }else{
  113459. for(i=0;i<posts-1;i++)
  113460. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113461. look->sorted_index[i+1],fits+i,
  113462. n,info);
  113463. }
  113464. if(nonzero){
  113465. /* start by fitting the implicit base case.... */
  113466. int y0=-200;
  113467. int y1=-200;
  113468. fit_line(fits,posts-1,&y0,&y1);
  113469. fit_valueA[0]=y0;
  113470. fit_valueB[0]=y0;
  113471. fit_valueB[1]=y1;
  113472. fit_valueA[1]=y1;
  113473. /* Non degenerate case */
  113474. /* start progressive splitting. This is a greedy, non-optimal
  113475. algorithm, but simple and close enough to the best
  113476. answer. */
  113477. for(i=2;i<posts;i++){
  113478. int sortpos=look->reverse_index[i];
  113479. int ln=loneighbor[sortpos];
  113480. int hn=hineighbor[sortpos];
  113481. /* eliminate repeat searches of a particular range with a memo */
  113482. if(memo[ln]!=hn){
  113483. /* haven't performed this error search yet */
  113484. int lsortpos=look->reverse_index[ln];
  113485. int hsortpos=look->reverse_index[hn];
  113486. memo[ln]=hn;
  113487. {
  113488. /* A note: we want to bound/minimize *local*, not global, error */
  113489. int lx=info->postlist[ln];
  113490. int hx=info->postlist[hn];
  113491. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113492. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113493. if(ly==-1 || hy==-1){
  113494. exit(1);
  113495. }
  113496. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113497. /* outside error bounds/begin search area. Split it. */
  113498. int ly0=-200;
  113499. int ly1=-200;
  113500. int hy0=-200;
  113501. int hy1=-200;
  113502. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113503. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113504. /* store new edge values */
  113505. fit_valueB[ln]=ly0;
  113506. if(ln==0)fit_valueA[ln]=ly0;
  113507. fit_valueA[i]=ly1;
  113508. fit_valueB[i]=hy0;
  113509. fit_valueA[hn]=hy1;
  113510. if(hn==1)fit_valueB[hn]=hy1;
  113511. if(ly1>=0 || hy0>=0){
  113512. /* store new neighbor values */
  113513. for(j=sortpos-1;j>=0;j--)
  113514. if(hineighbor[j]==hn)
  113515. hineighbor[j]=i;
  113516. else
  113517. break;
  113518. for(j=sortpos+1;j<posts;j++)
  113519. if(loneighbor[j]==ln)
  113520. loneighbor[j]=i;
  113521. else
  113522. break;
  113523. }
  113524. }else{
  113525. fit_valueA[i]=-200;
  113526. fit_valueB[i]=-200;
  113527. }
  113528. }
  113529. }
  113530. }
  113531. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113532. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113533. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113534. /* fill in posts marked as not using a fit; we will zero
  113535. back out to 'unused' when encoding them so long as curve
  113536. interpolation doesn't force them into use */
  113537. for(i=2;i<posts;i++){
  113538. int ln=look->loneighbor[i-2];
  113539. int hn=look->hineighbor[i-2];
  113540. int x0=info->postlist[ln];
  113541. int x1=info->postlist[hn];
  113542. int y0=output[ln];
  113543. int y1=output[hn];
  113544. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113545. int vx=post_Y(fit_valueA,fit_valueB,i);
  113546. if(vx>=0 && predicted!=vx){
  113547. output[i]=vx;
  113548. }else{
  113549. output[i]= predicted|0x8000;
  113550. }
  113551. }
  113552. }
  113553. return(output);
  113554. }
  113555. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113556. int *A,int *B,
  113557. int del){
  113558. long i;
  113559. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113560. long posts=look->posts;
  113561. int *output=NULL;
  113562. if(A && B){
  113563. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113564. for(i=0;i<posts;i++){
  113565. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113566. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113567. }
  113568. }
  113569. return(output);
  113570. }
  113571. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113572. void*look_,
  113573. int *post,int *ilogmask){
  113574. long i,j;
  113575. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113576. vorbis_info_floor1 *info=look->vi;
  113577. long posts=look->posts;
  113578. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113579. int out[VIF_POSIT+2];
  113580. static_codebook **sbooks=ci->book_param;
  113581. codebook *books=ci->fullbooks;
  113582. static long seq=0;
  113583. /* quantize values to multiplier spec */
  113584. if(post){
  113585. for(i=0;i<posts;i++){
  113586. int val=post[i]&0x7fff;
  113587. switch(info->mult){
  113588. case 1: /* 1024 -> 256 */
  113589. val>>=2;
  113590. break;
  113591. case 2: /* 1024 -> 128 */
  113592. val>>=3;
  113593. break;
  113594. case 3: /* 1024 -> 86 */
  113595. val/=12;
  113596. break;
  113597. case 4: /* 1024 -> 64 */
  113598. val>>=4;
  113599. break;
  113600. }
  113601. post[i]=val | (post[i]&0x8000);
  113602. }
  113603. out[0]=post[0];
  113604. out[1]=post[1];
  113605. /* find prediction values for each post and subtract them */
  113606. for(i=2;i<posts;i++){
  113607. int ln=look->loneighbor[i-2];
  113608. int hn=look->hineighbor[i-2];
  113609. int x0=info->postlist[ln];
  113610. int x1=info->postlist[hn];
  113611. int y0=post[ln];
  113612. int y1=post[hn];
  113613. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113614. if((post[i]&0x8000) || (predicted==post[i])){
  113615. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113616. in interpolation */
  113617. out[i]=0;
  113618. }else{
  113619. int headroom=(look->quant_q-predicted<predicted?
  113620. look->quant_q-predicted:predicted);
  113621. int val=post[i]-predicted;
  113622. /* at this point the 'deviation' value is in the range +/- max
  113623. range, but the real, unique range can always be mapped to
  113624. only [0-maxrange). So we want to wrap the deviation into
  113625. this limited range, but do it in the way that least screws
  113626. an essentially gaussian probability distribution. */
  113627. if(val<0)
  113628. if(val<-headroom)
  113629. val=headroom-val-1;
  113630. else
  113631. val=-1-(val<<1);
  113632. else
  113633. if(val>=headroom)
  113634. val= val+headroom;
  113635. else
  113636. val<<=1;
  113637. out[i]=val;
  113638. post[ln]&=0x7fff;
  113639. post[hn]&=0x7fff;
  113640. }
  113641. }
  113642. /* we have everything we need. pack it out */
  113643. /* mark nontrivial floor */
  113644. oggpack_write(opb,1,1);
  113645. /* beginning/end post */
  113646. look->frames++;
  113647. look->postbits+=ilog(look->quant_q-1)*2;
  113648. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113649. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113650. /* partition by partition */
  113651. for(i=0,j=2;i<info->partitions;i++){
  113652. int classx=info->partitionclass[i];
  113653. int cdim=info->class_dim[classx];
  113654. int csubbits=info->class_subs[classx];
  113655. int csub=1<<csubbits;
  113656. int bookas[8]={0,0,0,0,0,0,0,0};
  113657. int cval=0;
  113658. int cshift=0;
  113659. int k,l;
  113660. /* generate the partition's first stage cascade value */
  113661. if(csubbits){
  113662. int maxval[8];
  113663. for(k=0;k<csub;k++){
  113664. int booknum=info->class_subbook[classx][k];
  113665. if(booknum<0){
  113666. maxval[k]=1;
  113667. }else{
  113668. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113669. }
  113670. }
  113671. for(k=0;k<cdim;k++){
  113672. for(l=0;l<csub;l++){
  113673. int val=out[j+k];
  113674. if(val<maxval[l]){
  113675. bookas[k]=l;
  113676. break;
  113677. }
  113678. }
  113679. cval|= bookas[k]<<cshift;
  113680. cshift+=csubbits;
  113681. }
  113682. /* write it */
  113683. look->phrasebits+=
  113684. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113685. #ifdef TRAIN_FLOOR1
  113686. {
  113687. FILE *of;
  113688. char buffer[80];
  113689. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113690. vb->pcmend/2,posts-2,class);
  113691. of=fopen(buffer,"a");
  113692. fprintf(of,"%d\n",cval);
  113693. fclose(of);
  113694. }
  113695. #endif
  113696. }
  113697. /* write post values */
  113698. for(k=0;k<cdim;k++){
  113699. int book=info->class_subbook[classx][bookas[k]];
  113700. if(book>=0){
  113701. /* hack to allow training with 'bad' books */
  113702. if(out[j+k]<(books+book)->entries)
  113703. look->postbits+=vorbis_book_encode(books+book,
  113704. out[j+k],opb);
  113705. /*else
  113706. fprintf(stderr,"+!");*/
  113707. #ifdef TRAIN_FLOOR1
  113708. {
  113709. FILE *of;
  113710. char buffer[80];
  113711. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113712. vb->pcmend/2,posts-2,class,bookas[k]);
  113713. of=fopen(buffer,"a");
  113714. fprintf(of,"%d\n",out[j+k]);
  113715. fclose(of);
  113716. }
  113717. #endif
  113718. }
  113719. }
  113720. j+=cdim;
  113721. }
  113722. {
  113723. /* generate quantized floor equivalent to what we'd unpack in decode */
  113724. /* render the lines */
  113725. int hx=0;
  113726. int lx=0;
  113727. int ly=post[0]*info->mult;
  113728. for(j=1;j<look->posts;j++){
  113729. int current=look->forward_index[j];
  113730. int hy=post[current]&0x7fff;
  113731. if(hy==post[current]){
  113732. hy*=info->mult;
  113733. hx=info->postlist[current];
  113734. render_line0(lx,hx,ly,hy,ilogmask);
  113735. lx=hx;
  113736. ly=hy;
  113737. }
  113738. }
  113739. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113740. seq++;
  113741. return(1);
  113742. }
  113743. }else{
  113744. oggpack_write(opb,0,1);
  113745. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113746. seq++;
  113747. return(0);
  113748. }
  113749. }
  113750. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113751. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113752. vorbis_info_floor1 *info=look->vi;
  113753. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113754. int i,j,k;
  113755. codebook *books=ci->fullbooks;
  113756. /* unpack wrapped/predicted values from stream */
  113757. if(oggpack_read(&vb->opb,1)==1){
  113758. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113759. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113760. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113761. /* partition by partition */
  113762. for(i=0,j=2;i<info->partitions;i++){
  113763. int classx=info->partitionclass[i];
  113764. int cdim=info->class_dim[classx];
  113765. int csubbits=info->class_subs[classx];
  113766. int csub=1<<csubbits;
  113767. int cval=0;
  113768. /* decode the partition's first stage cascade value */
  113769. if(csubbits){
  113770. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113771. if(cval==-1)goto eop;
  113772. }
  113773. for(k=0;k<cdim;k++){
  113774. int book=info->class_subbook[classx][cval&(csub-1)];
  113775. cval>>=csubbits;
  113776. if(book>=0){
  113777. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113778. goto eop;
  113779. }else{
  113780. fit_value[j+k]=0;
  113781. }
  113782. }
  113783. j+=cdim;
  113784. }
  113785. /* unwrap positive values and reconsitute via linear interpolation */
  113786. for(i=2;i<look->posts;i++){
  113787. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113788. info->postlist[look->hineighbor[i-2]],
  113789. fit_value[look->loneighbor[i-2]],
  113790. fit_value[look->hineighbor[i-2]],
  113791. info->postlist[i]);
  113792. int hiroom=look->quant_q-predicted;
  113793. int loroom=predicted;
  113794. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113795. int val=fit_value[i];
  113796. if(val){
  113797. if(val>=room){
  113798. if(hiroom>loroom){
  113799. val = val-loroom;
  113800. }else{
  113801. val = -1-(val-hiroom);
  113802. }
  113803. }else{
  113804. if(val&1){
  113805. val= -((val+1)>>1);
  113806. }else{
  113807. val>>=1;
  113808. }
  113809. }
  113810. fit_value[i]=val+predicted;
  113811. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113812. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113813. }else{
  113814. fit_value[i]=predicted|0x8000;
  113815. }
  113816. }
  113817. return(fit_value);
  113818. }
  113819. eop:
  113820. return(NULL);
  113821. }
  113822. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113823. float *out){
  113824. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113825. vorbis_info_floor1 *info=look->vi;
  113826. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113827. int n=ci->blocksizes[vb->W]/2;
  113828. int j;
  113829. if(memo){
  113830. /* render the lines */
  113831. int *fit_value=(int *)memo;
  113832. int hx=0;
  113833. int lx=0;
  113834. int ly=fit_value[0]*info->mult;
  113835. for(j=1;j<look->posts;j++){
  113836. int current=look->forward_index[j];
  113837. int hy=fit_value[current]&0x7fff;
  113838. if(hy==fit_value[current]){
  113839. hy*=info->mult;
  113840. hx=info->postlist[current];
  113841. render_line(lx,hx,ly,hy,out);
  113842. lx=hx;
  113843. ly=hy;
  113844. }
  113845. }
  113846. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113847. return(1);
  113848. }
  113849. memset(out,0,sizeof(*out)*n);
  113850. return(0);
  113851. }
  113852. /* export hooks */
  113853. vorbis_func_floor floor1_exportbundle={
  113854. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113855. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113856. };
  113857. #endif
  113858. /*** End of inlined file: floor1.c ***/
  113859. /*** Start of inlined file: info.c ***/
  113860. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113861. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113862. // tasks..
  113863. #if JUCE_MSVC
  113864. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113865. #endif
  113866. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113867. #if JUCE_USE_OGGVORBIS
  113868. /* general handling of the header and the vorbis_info structure (and
  113869. substructures) */
  113870. #include <stdlib.h>
  113871. #include <string.h>
  113872. #include <ctype.h>
  113873. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113874. while(bytes--){
  113875. oggpack_write(o,*s++,8);
  113876. }
  113877. }
  113878. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113879. while(bytes--){
  113880. *buf++=oggpack_read(o,8);
  113881. }
  113882. }
  113883. void vorbis_comment_init(vorbis_comment *vc){
  113884. memset(vc,0,sizeof(*vc));
  113885. }
  113886. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113887. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113888. (vc->comments+2)*sizeof(*vc->user_comments));
  113889. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113890. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113891. vc->comment_lengths[vc->comments]=strlen(comment);
  113892. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113893. strcpy(vc->user_comments[vc->comments], comment);
  113894. vc->comments++;
  113895. vc->user_comments[vc->comments]=NULL;
  113896. }
  113897. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113898. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113899. strcpy(comment, tag);
  113900. strcat(comment, "=");
  113901. strcat(comment, contents);
  113902. vorbis_comment_add(vc, comment);
  113903. }
  113904. /* This is more or less the same as strncasecmp - but that doesn't exist
  113905. * everywhere, and this is a fairly trivial function, so we include it */
  113906. static int tagcompare(const char *s1, const char *s2, int n){
  113907. int c=0;
  113908. while(c < n){
  113909. if(toupper(s1[c]) != toupper(s2[c]))
  113910. return !0;
  113911. c++;
  113912. }
  113913. return 0;
  113914. }
  113915. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113916. long i;
  113917. int found = 0;
  113918. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113919. char *fulltag = (char*)alloca(taglen+ 1);
  113920. strcpy(fulltag, tag);
  113921. strcat(fulltag, "=");
  113922. for(i=0;i<vc->comments;i++){
  113923. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113924. if(count == found)
  113925. /* We return a pointer to the data, not a copy */
  113926. return vc->user_comments[i] + taglen;
  113927. else
  113928. found++;
  113929. }
  113930. }
  113931. return NULL; /* didn't find anything */
  113932. }
  113933. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113934. int i,count=0;
  113935. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113936. char *fulltag = (char*)alloca(taglen+1);
  113937. strcpy(fulltag,tag);
  113938. strcat(fulltag, "=");
  113939. for(i=0;i<vc->comments;i++){
  113940. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113941. count++;
  113942. }
  113943. return count;
  113944. }
  113945. void vorbis_comment_clear(vorbis_comment *vc){
  113946. if(vc){
  113947. long i;
  113948. for(i=0;i<vc->comments;i++)
  113949. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113950. if(vc->user_comments)_ogg_free(vc->user_comments);
  113951. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113952. if(vc->vendor)_ogg_free(vc->vendor);
  113953. }
  113954. memset(vc,0,sizeof(*vc));
  113955. }
  113956. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113957. They may be equal, but short will never ge greater than long */
  113958. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113959. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113960. return ci ? ci->blocksizes[zo] : -1;
  113961. }
  113962. /* used by synthesis, which has a full, alloced vi */
  113963. void vorbis_info_init(vorbis_info *vi){
  113964. memset(vi,0,sizeof(*vi));
  113965. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113966. }
  113967. void vorbis_info_clear(vorbis_info *vi){
  113968. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113969. int i;
  113970. if(ci){
  113971. for(i=0;i<ci->modes;i++)
  113972. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113973. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113974. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113975. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113976. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113977. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113978. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113979. for(i=0;i<ci->books;i++){
  113980. if(ci->book_param[i]){
  113981. /* knows if the book was not alloced */
  113982. vorbis_staticbook_destroy(ci->book_param[i]);
  113983. }
  113984. if(ci->fullbooks)
  113985. vorbis_book_clear(ci->fullbooks+i);
  113986. }
  113987. if(ci->fullbooks)
  113988. _ogg_free(ci->fullbooks);
  113989. for(i=0;i<ci->psys;i++)
  113990. _vi_psy_free(ci->psy_param[i]);
  113991. _ogg_free(ci);
  113992. }
  113993. memset(vi,0,sizeof(*vi));
  113994. }
  113995. /* Header packing/unpacking ********************************************/
  113996. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113997. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113998. if(!ci)return(OV_EFAULT);
  113999. vi->version=oggpack_read(opb,32);
  114000. if(vi->version!=0)return(OV_EVERSION);
  114001. vi->channels=oggpack_read(opb,8);
  114002. vi->rate=oggpack_read(opb,32);
  114003. vi->bitrate_upper=oggpack_read(opb,32);
  114004. vi->bitrate_nominal=oggpack_read(opb,32);
  114005. vi->bitrate_lower=oggpack_read(opb,32);
  114006. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114007. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114008. if(vi->rate<1)goto err_out;
  114009. if(vi->channels<1)goto err_out;
  114010. if(ci->blocksizes[0]<8)goto err_out;
  114011. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114012. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114013. return(0);
  114014. err_out:
  114015. vorbis_info_clear(vi);
  114016. return(OV_EBADHEADER);
  114017. }
  114018. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114019. int i;
  114020. int vendorlen=oggpack_read(opb,32);
  114021. if(vendorlen<0)goto err_out;
  114022. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114023. _v_readstring(opb,vc->vendor,vendorlen);
  114024. vc->comments=oggpack_read(opb,32);
  114025. if(vc->comments<0)goto err_out;
  114026. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114027. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114028. for(i=0;i<vc->comments;i++){
  114029. int len=oggpack_read(opb,32);
  114030. if(len<0)goto err_out;
  114031. vc->comment_lengths[i]=len;
  114032. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114033. _v_readstring(opb,vc->user_comments[i],len);
  114034. }
  114035. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114036. return(0);
  114037. err_out:
  114038. vorbis_comment_clear(vc);
  114039. return(OV_EBADHEADER);
  114040. }
  114041. /* all of the real encoding details are here. The modes, books,
  114042. everything */
  114043. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114044. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114045. int i;
  114046. if(!ci)return(OV_EFAULT);
  114047. /* codebooks */
  114048. ci->books=oggpack_read(opb,8)+1;
  114049. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114050. for(i=0;i<ci->books;i++){
  114051. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114052. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114053. }
  114054. /* time backend settings; hooks are unused */
  114055. {
  114056. int times=oggpack_read(opb,6)+1;
  114057. for(i=0;i<times;i++){
  114058. int test=oggpack_read(opb,16);
  114059. if(test<0 || test>=VI_TIMEB)goto err_out;
  114060. }
  114061. }
  114062. /* floor backend settings */
  114063. ci->floors=oggpack_read(opb,6)+1;
  114064. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114065. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114066. for(i=0;i<ci->floors;i++){
  114067. ci->floor_type[i]=oggpack_read(opb,16);
  114068. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114069. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114070. if(!ci->floor_param[i])goto err_out;
  114071. }
  114072. /* residue backend settings */
  114073. ci->residues=oggpack_read(opb,6)+1;
  114074. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114075. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114076. for(i=0;i<ci->residues;i++){
  114077. ci->residue_type[i]=oggpack_read(opb,16);
  114078. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114079. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114080. if(!ci->residue_param[i])goto err_out;
  114081. }
  114082. /* map backend settings */
  114083. ci->maps=oggpack_read(opb,6)+1;
  114084. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114085. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114086. for(i=0;i<ci->maps;i++){
  114087. ci->map_type[i]=oggpack_read(opb,16);
  114088. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114089. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114090. if(!ci->map_param[i])goto err_out;
  114091. }
  114092. /* mode settings */
  114093. ci->modes=oggpack_read(opb,6)+1;
  114094. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114095. for(i=0;i<ci->modes;i++){
  114096. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114097. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114098. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114099. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114100. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114101. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114102. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114103. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114104. }
  114105. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114106. return(0);
  114107. err_out:
  114108. vorbis_info_clear(vi);
  114109. return(OV_EBADHEADER);
  114110. }
  114111. /* The Vorbis header is in three packets; the initial small packet in
  114112. the first page that identifies basic parameters, a second packet
  114113. with bitstream comments and a third packet that holds the
  114114. codebook. */
  114115. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114116. oggpack_buffer opb;
  114117. if(op){
  114118. oggpack_readinit(&opb,op->packet,op->bytes);
  114119. /* Which of the three types of header is this? */
  114120. /* Also verify header-ness, vorbis */
  114121. {
  114122. char buffer[6];
  114123. int packtype=oggpack_read(&opb,8);
  114124. memset(buffer,0,6);
  114125. _v_readstring(&opb,buffer,6);
  114126. if(memcmp(buffer,"vorbis",6)){
  114127. /* not a vorbis header */
  114128. return(OV_ENOTVORBIS);
  114129. }
  114130. switch(packtype){
  114131. case 0x01: /* least significant *bit* is read first */
  114132. if(!op->b_o_s){
  114133. /* Not the initial packet */
  114134. return(OV_EBADHEADER);
  114135. }
  114136. if(vi->rate!=0){
  114137. /* previously initialized info header */
  114138. return(OV_EBADHEADER);
  114139. }
  114140. return(_vorbis_unpack_info(vi,&opb));
  114141. case 0x03: /* least significant *bit* is read first */
  114142. if(vi->rate==0){
  114143. /* um... we didn't get the initial header */
  114144. return(OV_EBADHEADER);
  114145. }
  114146. return(_vorbis_unpack_comment(vc,&opb));
  114147. case 0x05: /* least significant *bit* is read first */
  114148. if(vi->rate==0 || vc->vendor==NULL){
  114149. /* um... we didn;t get the initial header or comments yet */
  114150. return(OV_EBADHEADER);
  114151. }
  114152. return(_vorbis_unpack_books(vi,&opb));
  114153. default:
  114154. /* Not a valid vorbis header type */
  114155. return(OV_EBADHEADER);
  114156. break;
  114157. }
  114158. }
  114159. }
  114160. return(OV_EBADHEADER);
  114161. }
  114162. /* pack side **********************************************************/
  114163. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114164. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114165. if(!ci)return(OV_EFAULT);
  114166. /* preamble */
  114167. oggpack_write(opb,0x01,8);
  114168. _v_writestring(opb,"vorbis", 6);
  114169. /* basic information about the stream */
  114170. oggpack_write(opb,0x00,32);
  114171. oggpack_write(opb,vi->channels,8);
  114172. oggpack_write(opb,vi->rate,32);
  114173. oggpack_write(opb,vi->bitrate_upper,32);
  114174. oggpack_write(opb,vi->bitrate_nominal,32);
  114175. oggpack_write(opb,vi->bitrate_lower,32);
  114176. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114177. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114178. oggpack_write(opb,1,1);
  114179. return(0);
  114180. }
  114181. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114182. char temp[]="Xiph.Org libVorbis I 20050304";
  114183. int bytes = strlen(temp);
  114184. /* preamble */
  114185. oggpack_write(opb,0x03,8);
  114186. _v_writestring(opb,"vorbis", 6);
  114187. /* vendor */
  114188. oggpack_write(opb,bytes,32);
  114189. _v_writestring(opb,temp, bytes);
  114190. /* comments */
  114191. oggpack_write(opb,vc->comments,32);
  114192. if(vc->comments){
  114193. int i;
  114194. for(i=0;i<vc->comments;i++){
  114195. if(vc->user_comments[i]){
  114196. oggpack_write(opb,vc->comment_lengths[i],32);
  114197. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114198. }else{
  114199. oggpack_write(opb,0,32);
  114200. }
  114201. }
  114202. }
  114203. oggpack_write(opb,1,1);
  114204. return(0);
  114205. }
  114206. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114207. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114208. int i;
  114209. if(!ci)return(OV_EFAULT);
  114210. oggpack_write(opb,0x05,8);
  114211. _v_writestring(opb,"vorbis", 6);
  114212. /* books */
  114213. oggpack_write(opb,ci->books-1,8);
  114214. for(i=0;i<ci->books;i++)
  114215. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114216. /* times; hook placeholders */
  114217. oggpack_write(opb,0,6);
  114218. oggpack_write(opb,0,16);
  114219. /* floors */
  114220. oggpack_write(opb,ci->floors-1,6);
  114221. for(i=0;i<ci->floors;i++){
  114222. oggpack_write(opb,ci->floor_type[i],16);
  114223. if(_floor_P[ci->floor_type[i]]->pack)
  114224. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114225. else
  114226. goto err_out;
  114227. }
  114228. /* residues */
  114229. oggpack_write(opb,ci->residues-1,6);
  114230. for(i=0;i<ci->residues;i++){
  114231. oggpack_write(opb,ci->residue_type[i],16);
  114232. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114233. }
  114234. /* maps */
  114235. oggpack_write(opb,ci->maps-1,6);
  114236. for(i=0;i<ci->maps;i++){
  114237. oggpack_write(opb,ci->map_type[i],16);
  114238. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114239. }
  114240. /* modes */
  114241. oggpack_write(opb,ci->modes-1,6);
  114242. for(i=0;i<ci->modes;i++){
  114243. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114244. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114245. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114246. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114247. }
  114248. oggpack_write(opb,1,1);
  114249. return(0);
  114250. err_out:
  114251. return(-1);
  114252. }
  114253. int vorbis_commentheader_out(vorbis_comment *vc,
  114254. ogg_packet *op){
  114255. oggpack_buffer opb;
  114256. oggpack_writeinit(&opb);
  114257. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114258. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114259. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114260. op->bytes=oggpack_bytes(&opb);
  114261. op->b_o_s=0;
  114262. op->e_o_s=0;
  114263. op->granulepos=0;
  114264. op->packetno=1;
  114265. return 0;
  114266. }
  114267. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114268. vorbis_comment *vc,
  114269. ogg_packet *op,
  114270. ogg_packet *op_comm,
  114271. ogg_packet *op_code){
  114272. int ret=OV_EIMPL;
  114273. vorbis_info *vi=v->vi;
  114274. oggpack_buffer opb;
  114275. private_state *b=(private_state*)v->backend_state;
  114276. if(!b){
  114277. ret=OV_EFAULT;
  114278. goto err_out;
  114279. }
  114280. /* first header packet **********************************************/
  114281. oggpack_writeinit(&opb);
  114282. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114283. /* build the packet */
  114284. if(b->header)_ogg_free(b->header);
  114285. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114286. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114287. op->packet=b->header;
  114288. op->bytes=oggpack_bytes(&opb);
  114289. op->b_o_s=1;
  114290. op->e_o_s=0;
  114291. op->granulepos=0;
  114292. op->packetno=0;
  114293. /* second header packet (comments) **********************************/
  114294. oggpack_reset(&opb);
  114295. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114296. if(b->header1)_ogg_free(b->header1);
  114297. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114298. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114299. op_comm->packet=b->header1;
  114300. op_comm->bytes=oggpack_bytes(&opb);
  114301. op_comm->b_o_s=0;
  114302. op_comm->e_o_s=0;
  114303. op_comm->granulepos=0;
  114304. op_comm->packetno=1;
  114305. /* third header packet (modes/codebooks) ****************************/
  114306. oggpack_reset(&opb);
  114307. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114308. if(b->header2)_ogg_free(b->header2);
  114309. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114310. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114311. op_code->packet=b->header2;
  114312. op_code->bytes=oggpack_bytes(&opb);
  114313. op_code->b_o_s=0;
  114314. op_code->e_o_s=0;
  114315. op_code->granulepos=0;
  114316. op_code->packetno=2;
  114317. oggpack_writeclear(&opb);
  114318. return(0);
  114319. err_out:
  114320. oggpack_writeclear(&opb);
  114321. memset(op,0,sizeof(*op));
  114322. memset(op_comm,0,sizeof(*op_comm));
  114323. memset(op_code,0,sizeof(*op_code));
  114324. if(b->header)_ogg_free(b->header);
  114325. if(b->header1)_ogg_free(b->header1);
  114326. if(b->header2)_ogg_free(b->header2);
  114327. b->header=NULL;
  114328. b->header1=NULL;
  114329. b->header2=NULL;
  114330. return(ret);
  114331. }
  114332. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114333. if(granulepos>=0)
  114334. return((double)granulepos/v->vi->rate);
  114335. return(-1);
  114336. }
  114337. #endif
  114338. /*** End of inlined file: info.c ***/
  114339. /*** Start of inlined file: lpc.c ***/
  114340. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114341. are derived from code written by Jutta Degener and Carsten Bormann;
  114342. thus we include their copyright below. The entirety of this file
  114343. is freely redistributable on the condition that both of these
  114344. copyright notices are preserved without modification. */
  114345. /* Preserved Copyright: *********************************************/
  114346. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114347. Technische Universita"t Berlin
  114348. Any use of this software is permitted provided that this notice is not
  114349. removed and that neither the authors nor the Technische Universita"t
  114350. Berlin are deemed to have made any representations as to the
  114351. suitability of this software for any purpose nor are held responsible
  114352. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114353. THIS SOFTWARE.
  114354. As a matter of courtesy, the authors request to be informed about uses
  114355. this software has found, about bugs in this software, and about any
  114356. improvements that may be of general interest.
  114357. Berlin, 28.11.1994
  114358. Jutta Degener
  114359. Carsten Bormann
  114360. *********************************************************************/
  114361. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114362. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114363. // tasks..
  114364. #if JUCE_MSVC
  114365. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114366. #endif
  114367. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114368. #if JUCE_USE_OGGVORBIS
  114369. #include <stdlib.h>
  114370. #include <string.h>
  114371. #include <math.h>
  114372. /* Autocorrelation LPC coeff generation algorithm invented by
  114373. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114374. /* Input : n elements of time doamin data
  114375. Output: m lpc coefficients, excitation energy */
  114376. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114377. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114378. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114379. double error;
  114380. int i,j;
  114381. /* autocorrelation, p+1 lag coefficients */
  114382. j=m+1;
  114383. while(j--){
  114384. double d=0; /* double needed for accumulator depth */
  114385. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114386. aut[j]=d;
  114387. }
  114388. /* Generate lpc coefficients from autocorr values */
  114389. error=aut[0];
  114390. for(i=0;i<m;i++){
  114391. double r= -aut[i+1];
  114392. if(error==0){
  114393. memset(lpci,0,m*sizeof(*lpci));
  114394. return 0;
  114395. }
  114396. /* Sum up this iteration's reflection coefficient; note that in
  114397. Vorbis we don't save it. If anyone wants to recycle this code
  114398. and needs reflection coefficients, save the results of 'r' from
  114399. each iteration. */
  114400. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114401. r/=error;
  114402. /* Update LPC coefficients and total error */
  114403. lpc[i]=r;
  114404. for(j=0;j<i/2;j++){
  114405. double tmp=lpc[j];
  114406. lpc[j]+=r*lpc[i-1-j];
  114407. lpc[i-1-j]+=r*tmp;
  114408. }
  114409. if(i%2)lpc[j]+=lpc[j]*r;
  114410. error*=1.f-r*r;
  114411. }
  114412. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114413. /* we need the error value to know how big an impulse to hit the
  114414. filter with later */
  114415. return error;
  114416. }
  114417. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114418. float *data,long n){
  114419. /* in: coeff[0...m-1] LPC coefficients
  114420. prime[0...m-1] initial values (allocated size of n+m-1)
  114421. out: data[0...n-1] data samples */
  114422. long i,j,o,p;
  114423. float y;
  114424. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114425. if(!prime)
  114426. for(i=0;i<m;i++)
  114427. work[i]=0.f;
  114428. else
  114429. for(i=0;i<m;i++)
  114430. work[i]=prime[i];
  114431. for(i=0;i<n;i++){
  114432. y=0;
  114433. o=i;
  114434. p=m;
  114435. for(j=0;j<m;j++)
  114436. y-=work[o++]*coeff[--p];
  114437. data[i]=work[o]=y;
  114438. }
  114439. }
  114440. #endif
  114441. /*** End of inlined file: lpc.c ***/
  114442. /*** Start of inlined file: lsp.c ***/
  114443. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114444. an iterative root polisher (CACM algorithm 283). It *is* possible
  114445. to confuse this algorithm into not converging; that should only
  114446. happen with absurdly closely spaced roots (very sharp peaks in the
  114447. LPC f response) which in turn should be impossible in our use of
  114448. the code. If this *does* happen anyway, it's a bug in the floor
  114449. finder; find the cause of the confusion (probably a single bin
  114450. spike or accidental near-float-limit resolution problems) and
  114451. correct it. */
  114452. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114453. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114454. // tasks..
  114455. #if JUCE_MSVC
  114456. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114457. #endif
  114458. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114459. #if JUCE_USE_OGGVORBIS
  114460. #include <math.h>
  114461. #include <string.h>
  114462. #include <stdlib.h>
  114463. /*** Start of inlined file: lookup.h ***/
  114464. #ifndef _V_LOOKUP_H_
  114465. #ifdef FLOAT_LOOKUP
  114466. extern float vorbis_coslook(float a);
  114467. extern float vorbis_invsqlook(float a);
  114468. extern float vorbis_invsq2explook(int a);
  114469. extern float vorbis_fromdBlook(float a);
  114470. #endif
  114471. #ifdef INT_LOOKUP
  114472. extern long vorbis_invsqlook_i(long a,long e);
  114473. extern long vorbis_coslook_i(long a);
  114474. extern float vorbis_fromdBlook_i(long a);
  114475. #endif
  114476. #endif
  114477. /*** End of inlined file: lookup.h ***/
  114478. /* three possible LSP to f curve functions; the exact computation
  114479. (float), a lookup based float implementation, and an integer
  114480. implementation. The float lookup is likely the optimal choice on
  114481. any machine with an FPU. The integer implementation is *not* fixed
  114482. point (due to the need for a large dynamic range and thus a
  114483. seperately tracked exponent) and thus much more complex than the
  114484. relatively simple float implementations. It's mostly for future
  114485. work on a fully fixed point implementation for processors like the
  114486. ARM family. */
  114487. /* undefine both for the 'old' but more precise implementation */
  114488. #define FLOAT_LOOKUP
  114489. #undef INT_LOOKUP
  114490. #ifdef FLOAT_LOOKUP
  114491. /*** Start of inlined file: lookup.c ***/
  114492. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114493. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114494. // tasks..
  114495. #if JUCE_MSVC
  114496. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114497. #endif
  114498. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114499. #if JUCE_USE_OGGVORBIS
  114500. #include <math.h>
  114501. /*** Start of inlined file: lookup.h ***/
  114502. #ifndef _V_LOOKUP_H_
  114503. #ifdef FLOAT_LOOKUP
  114504. extern float vorbis_coslook(float a);
  114505. extern float vorbis_invsqlook(float a);
  114506. extern float vorbis_invsq2explook(int a);
  114507. extern float vorbis_fromdBlook(float a);
  114508. #endif
  114509. #ifdef INT_LOOKUP
  114510. extern long vorbis_invsqlook_i(long a,long e);
  114511. extern long vorbis_coslook_i(long a);
  114512. extern float vorbis_fromdBlook_i(long a);
  114513. #endif
  114514. #endif
  114515. /*** End of inlined file: lookup.h ***/
  114516. /*** Start of inlined file: lookup_data.h ***/
  114517. #ifndef _V_LOOKUP_DATA_H_
  114518. #ifdef FLOAT_LOOKUP
  114519. #define COS_LOOKUP_SZ 128
  114520. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114521. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114522. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114523. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114524. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114525. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114526. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114527. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114528. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114529. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114530. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114531. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114532. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114533. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114534. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114535. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114536. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114537. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114538. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114539. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114540. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114541. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114542. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114543. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114544. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114545. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114546. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114547. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114548. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114549. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114550. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114551. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114552. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114553. -1.0000000000000f,
  114554. };
  114555. #define INVSQ_LOOKUP_SZ 32
  114556. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114557. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114558. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114559. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114560. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114561. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114562. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114563. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114564. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114565. 1.000000000000f,
  114566. };
  114567. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114568. #define INVSQ2EXP_LOOKUP_MAX 32
  114569. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114570. INVSQ2EXP_LOOKUP_MIN+1]={
  114571. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114572. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114573. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114574. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114575. 256.f, 181.019336f, 128.f, 90.50966799f,
  114576. 64.f, 45.254834f, 32.f, 22.627417f,
  114577. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114578. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114579. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114580. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114581. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114582. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114583. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114584. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114585. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114586. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114587. 1.525878906e-05f,
  114588. };
  114589. #endif
  114590. #define FROMdB_LOOKUP_SZ 35
  114591. #define FROMdB2_LOOKUP_SZ 32
  114592. #define FROMdB_SHIFT 5
  114593. #define FROMdB2_SHIFT 3
  114594. #define FROMdB2_MASK 31
  114595. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114596. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114597. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114598. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114599. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114600. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114601. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114602. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114603. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114604. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114605. };
  114606. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114607. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114608. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114609. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114610. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114611. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114612. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114613. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114614. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114615. };
  114616. #ifdef INT_LOOKUP
  114617. #define INVSQ_LOOKUP_I_SHIFT 10
  114618. #define INVSQ_LOOKUP_I_MASK 1023
  114619. static long INVSQ_LOOKUP_I[64+1]={
  114620. 92682l, 91966l, 91267l, 90583l,
  114621. 89915l, 89261l, 88621l, 87995l,
  114622. 87381l, 86781l, 86192l, 85616l,
  114623. 85051l, 84497l, 83953l, 83420l,
  114624. 82897l, 82384l, 81880l, 81385l,
  114625. 80899l, 80422l, 79953l, 79492l,
  114626. 79039l, 78594l, 78156l, 77726l,
  114627. 77302l, 76885l, 76475l, 76072l,
  114628. 75674l, 75283l, 74898l, 74519l,
  114629. 74146l, 73778l, 73415l, 73058l,
  114630. 72706l, 72359l, 72016l, 71679l,
  114631. 71347l, 71019l, 70695l, 70376l,
  114632. 70061l, 69750l, 69444l, 69141l,
  114633. 68842l, 68548l, 68256l, 67969l,
  114634. 67685l, 67405l, 67128l, 66855l,
  114635. 66585l, 66318l, 66054l, 65794l,
  114636. 65536l,
  114637. };
  114638. #define COS_LOOKUP_I_SHIFT 9
  114639. #define COS_LOOKUP_I_MASK 511
  114640. #define COS_LOOKUP_I_SZ 128
  114641. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114642. 16384l, 16379l, 16364l, 16340l,
  114643. 16305l, 16261l, 16207l, 16143l,
  114644. 16069l, 15986l, 15893l, 15791l,
  114645. 15679l, 15557l, 15426l, 15286l,
  114646. 15137l, 14978l, 14811l, 14635l,
  114647. 14449l, 14256l, 14053l, 13842l,
  114648. 13623l, 13395l, 13160l, 12916l,
  114649. 12665l, 12406l, 12140l, 11866l,
  114650. 11585l, 11297l, 11003l, 10702l,
  114651. 10394l, 10080l, 9760l, 9434l,
  114652. 9102l, 8765l, 8423l, 8076l,
  114653. 7723l, 7366l, 7005l, 6639l,
  114654. 6270l, 5897l, 5520l, 5139l,
  114655. 4756l, 4370l, 3981l, 3590l,
  114656. 3196l, 2801l, 2404l, 2006l,
  114657. 1606l, 1205l, 804l, 402l,
  114658. 0l, -401l, -803l, -1204l,
  114659. -1605l, -2005l, -2403l, -2800l,
  114660. -3195l, -3589l, -3980l, -4369l,
  114661. -4755l, -5138l, -5519l, -5896l,
  114662. -6269l, -6638l, -7004l, -7365l,
  114663. -7722l, -8075l, -8422l, -8764l,
  114664. -9101l, -9433l, -9759l, -10079l,
  114665. -10393l, -10701l, -11002l, -11296l,
  114666. -11584l, -11865l, -12139l, -12405l,
  114667. -12664l, -12915l, -13159l, -13394l,
  114668. -13622l, -13841l, -14052l, -14255l,
  114669. -14448l, -14634l, -14810l, -14977l,
  114670. -15136l, -15285l, -15425l, -15556l,
  114671. -15678l, -15790l, -15892l, -15985l,
  114672. -16068l, -16142l, -16206l, -16260l,
  114673. -16304l, -16339l, -16363l, -16378l,
  114674. -16383l,
  114675. };
  114676. #endif
  114677. #endif
  114678. /*** End of inlined file: lookup_data.h ***/
  114679. #ifdef FLOAT_LOOKUP
  114680. /* interpolated lookup based cos function, domain 0 to PI only */
  114681. float vorbis_coslook(float a){
  114682. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114683. int i=vorbis_ftoi(d-.5);
  114684. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114685. }
  114686. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114687. float vorbis_invsqlook(float a){
  114688. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114689. int i=vorbis_ftoi(d-.5f);
  114690. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114691. }
  114692. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114693. float vorbis_invsq2explook(int a){
  114694. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114695. }
  114696. #include <stdio.h>
  114697. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114698. float vorbis_fromdBlook(float a){
  114699. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114700. return (i<0)?1.f:
  114701. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114702. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114703. }
  114704. #endif
  114705. #ifdef INT_LOOKUP
  114706. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114707. 16.16 format
  114708. returns in m.8 format */
  114709. long vorbis_invsqlook_i(long a,long e){
  114710. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114711. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114712. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114713. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114714. d)>>16); /* result 1.16 */
  114715. e+=32;
  114716. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114717. e=(e>>1)-8;
  114718. return(val>>e);
  114719. }
  114720. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114721. /* a is in n.12 format */
  114722. float vorbis_fromdBlook_i(long a){
  114723. int i=(-a)>>(12-FROMdB2_SHIFT);
  114724. return (i<0)?1.f:
  114725. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114726. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114727. }
  114728. /* interpolated lookup based cos function, domain 0 to PI only */
  114729. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114730. long vorbis_coslook_i(long a){
  114731. int i=a>>COS_LOOKUP_I_SHIFT;
  114732. int d=a&COS_LOOKUP_I_MASK;
  114733. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114734. COS_LOOKUP_I_SHIFT);
  114735. }
  114736. #endif
  114737. #endif
  114738. /*** End of inlined file: lookup.c ***/
  114739. /* catch this in the build system; we #include for
  114740. compilers (like gcc) that can't inline across
  114741. modules */
  114742. /* side effect: changes *lsp to cosines of lsp */
  114743. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114744. float amp,float ampoffset){
  114745. int i;
  114746. float wdel=M_PI/ln;
  114747. vorbis_fpu_control fpu;
  114748. (void) fpu; // to avoid an unused variable warning
  114749. vorbis_fpu_setround(&fpu);
  114750. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114751. i=0;
  114752. while(i<n){
  114753. int k=map[i];
  114754. int qexp;
  114755. float p=.7071067812f;
  114756. float q=.7071067812f;
  114757. float w=vorbis_coslook(wdel*k);
  114758. float *ftmp=lsp;
  114759. int c=m>>1;
  114760. do{
  114761. q*=ftmp[0]-w;
  114762. p*=ftmp[1]-w;
  114763. ftmp+=2;
  114764. }while(--c);
  114765. if(m&1){
  114766. /* odd order filter; slightly assymetric */
  114767. /* the last coefficient */
  114768. q*=ftmp[0]-w;
  114769. q*=q;
  114770. p*=p*(1.f-w*w);
  114771. }else{
  114772. /* even order filter; still symmetric */
  114773. q*=q*(1.f+w);
  114774. p*=p*(1.f-w);
  114775. }
  114776. q=frexp(p+q,&qexp);
  114777. q=vorbis_fromdBlook(amp*
  114778. vorbis_invsqlook(q)*
  114779. vorbis_invsq2explook(qexp+m)-
  114780. ampoffset);
  114781. do{
  114782. curve[i++]*=q;
  114783. }while(map[i]==k);
  114784. }
  114785. vorbis_fpu_restore(fpu);
  114786. }
  114787. #else
  114788. #ifdef INT_LOOKUP
  114789. /*** Start of inlined file: lookup.c ***/
  114790. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114791. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114792. // tasks..
  114793. #if JUCE_MSVC
  114794. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114795. #endif
  114796. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114797. #if JUCE_USE_OGGVORBIS
  114798. #include <math.h>
  114799. /*** Start of inlined file: lookup.h ***/
  114800. #ifndef _V_LOOKUP_H_
  114801. #ifdef FLOAT_LOOKUP
  114802. extern float vorbis_coslook(float a);
  114803. extern float vorbis_invsqlook(float a);
  114804. extern float vorbis_invsq2explook(int a);
  114805. extern float vorbis_fromdBlook(float a);
  114806. #endif
  114807. #ifdef INT_LOOKUP
  114808. extern long vorbis_invsqlook_i(long a,long e);
  114809. extern long vorbis_coslook_i(long a);
  114810. extern float vorbis_fromdBlook_i(long a);
  114811. #endif
  114812. #endif
  114813. /*** End of inlined file: lookup.h ***/
  114814. /*** Start of inlined file: lookup_data.h ***/
  114815. #ifndef _V_LOOKUP_DATA_H_
  114816. #ifdef FLOAT_LOOKUP
  114817. #define COS_LOOKUP_SZ 128
  114818. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114819. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114820. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114821. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114822. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114823. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114824. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114825. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114826. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114827. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114828. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114829. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114830. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114831. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114832. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114833. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114834. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114835. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114836. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114837. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114838. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114839. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114840. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114841. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114842. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114843. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114844. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114845. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114846. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114847. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114848. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114849. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114850. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114851. -1.0000000000000f,
  114852. };
  114853. #define INVSQ_LOOKUP_SZ 32
  114854. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114855. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114856. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114857. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114858. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114859. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114860. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114861. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114862. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114863. 1.000000000000f,
  114864. };
  114865. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114866. #define INVSQ2EXP_LOOKUP_MAX 32
  114867. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114868. INVSQ2EXP_LOOKUP_MIN+1]={
  114869. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114870. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114871. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114872. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114873. 256.f, 181.019336f, 128.f, 90.50966799f,
  114874. 64.f, 45.254834f, 32.f, 22.627417f,
  114875. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114876. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114877. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114878. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114879. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114880. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114881. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114882. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114883. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114884. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114885. 1.525878906e-05f,
  114886. };
  114887. #endif
  114888. #define FROMdB_LOOKUP_SZ 35
  114889. #define FROMdB2_LOOKUP_SZ 32
  114890. #define FROMdB_SHIFT 5
  114891. #define FROMdB2_SHIFT 3
  114892. #define FROMdB2_MASK 31
  114893. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114894. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114895. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114896. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114897. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114898. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114899. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114900. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114901. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114902. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114903. };
  114904. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114905. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114906. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114907. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114908. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114909. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114910. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114911. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114912. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114913. };
  114914. #ifdef INT_LOOKUP
  114915. #define INVSQ_LOOKUP_I_SHIFT 10
  114916. #define INVSQ_LOOKUP_I_MASK 1023
  114917. static long INVSQ_LOOKUP_I[64+1]={
  114918. 92682l, 91966l, 91267l, 90583l,
  114919. 89915l, 89261l, 88621l, 87995l,
  114920. 87381l, 86781l, 86192l, 85616l,
  114921. 85051l, 84497l, 83953l, 83420l,
  114922. 82897l, 82384l, 81880l, 81385l,
  114923. 80899l, 80422l, 79953l, 79492l,
  114924. 79039l, 78594l, 78156l, 77726l,
  114925. 77302l, 76885l, 76475l, 76072l,
  114926. 75674l, 75283l, 74898l, 74519l,
  114927. 74146l, 73778l, 73415l, 73058l,
  114928. 72706l, 72359l, 72016l, 71679l,
  114929. 71347l, 71019l, 70695l, 70376l,
  114930. 70061l, 69750l, 69444l, 69141l,
  114931. 68842l, 68548l, 68256l, 67969l,
  114932. 67685l, 67405l, 67128l, 66855l,
  114933. 66585l, 66318l, 66054l, 65794l,
  114934. 65536l,
  114935. };
  114936. #define COS_LOOKUP_I_SHIFT 9
  114937. #define COS_LOOKUP_I_MASK 511
  114938. #define COS_LOOKUP_I_SZ 128
  114939. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114940. 16384l, 16379l, 16364l, 16340l,
  114941. 16305l, 16261l, 16207l, 16143l,
  114942. 16069l, 15986l, 15893l, 15791l,
  114943. 15679l, 15557l, 15426l, 15286l,
  114944. 15137l, 14978l, 14811l, 14635l,
  114945. 14449l, 14256l, 14053l, 13842l,
  114946. 13623l, 13395l, 13160l, 12916l,
  114947. 12665l, 12406l, 12140l, 11866l,
  114948. 11585l, 11297l, 11003l, 10702l,
  114949. 10394l, 10080l, 9760l, 9434l,
  114950. 9102l, 8765l, 8423l, 8076l,
  114951. 7723l, 7366l, 7005l, 6639l,
  114952. 6270l, 5897l, 5520l, 5139l,
  114953. 4756l, 4370l, 3981l, 3590l,
  114954. 3196l, 2801l, 2404l, 2006l,
  114955. 1606l, 1205l, 804l, 402l,
  114956. 0l, -401l, -803l, -1204l,
  114957. -1605l, -2005l, -2403l, -2800l,
  114958. -3195l, -3589l, -3980l, -4369l,
  114959. -4755l, -5138l, -5519l, -5896l,
  114960. -6269l, -6638l, -7004l, -7365l,
  114961. -7722l, -8075l, -8422l, -8764l,
  114962. -9101l, -9433l, -9759l, -10079l,
  114963. -10393l, -10701l, -11002l, -11296l,
  114964. -11584l, -11865l, -12139l, -12405l,
  114965. -12664l, -12915l, -13159l, -13394l,
  114966. -13622l, -13841l, -14052l, -14255l,
  114967. -14448l, -14634l, -14810l, -14977l,
  114968. -15136l, -15285l, -15425l, -15556l,
  114969. -15678l, -15790l, -15892l, -15985l,
  114970. -16068l, -16142l, -16206l, -16260l,
  114971. -16304l, -16339l, -16363l, -16378l,
  114972. -16383l,
  114973. };
  114974. #endif
  114975. #endif
  114976. /*** End of inlined file: lookup_data.h ***/
  114977. #ifdef FLOAT_LOOKUP
  114978. /* interpolated lookup based cos function, domain 0 to PI only */
  114979. float vorbis_coslook(float a){
  114980. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114981. int i=vorbis_ftoi(d-.5);
  114982. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114983. }
  114984. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114985. float vorbis_invsqlook(float a){
  114986. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114987. int i=vorbis_ftoi(d-.5f);
  114988. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114989. }
  114990. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114991. float vorbis_invsq2explook(int a){
  114992. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114993. }
  114994. #include <stdio.h>
  114995. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114996. float vorbis_fromdBlook(float a){
  114997. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114998. return (i<0)?1.f:
  114999. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115000. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115001. }
  115002. #endif
  115003. #ifdef INT_LOOKUP
  115004. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115005. 16.16 format
  115006. returns in m.8 format */
  115007. long vorbis_invsqlook_i(long a,long e){
  115008. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115009. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115010. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115011. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115012. d)>>16); /* result 1.16 */
  115013. e+=32;
  115014. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115015. e=(e>>1)-8;
  115016. return(val>>e);
  115017. }
  115018. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115019. /* a is in n.12 format */
  115020. float vorbis_fromdBlook_i(long a){
  115021. int i=(-a)>>(12-FROMdB2_SHIFT);
  115022. return (i<0)?1.f:
  115023. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115024. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115025. }
  115026. /* interpolated lookup based cos function, domain 0 to PI only */
  115027. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115028. long vorbis_coslook_i(long a){
  115029. int i=a>>COS_LOOKUP_I_SHIFT;
  115030. int d=a&COS_LOOKUP_I_MASK;
  115031. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115032. COS_LOOKUP_I_SHIFT);
  115033. }
  115034. #endif
  115035. #endif
  115036. /*** End of inlined file: lookup.c ***/
  115037. /* catch this in the build system; we #include for
  115038. compilers (like gcc) that can't inline across
  115039. modules */
  115040. static int MLOOP_1[64]={
  115041. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115042. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115043. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115044. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115045. };
  115046. static int MLOOP_2[64]={
  115047. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115048. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115049. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115050. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115051. };
  115052. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115053. /* side effect: changes *lsp to cosines of lsp */
  115054. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115055. float amp,float ampoffset){
  115056. /* 0 <= m < 256 */
  115057. /* set up for using all int later */
  115058. int i;
  115059. int ampoffseti=rint(ampoffset*4096.f);
  115060. int ampi=rint(amp*16.f);
  115061. long *ilsp=alloca(m*sizeof(*ilsp));
  115062. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115063. i=0;
  115064. while(i<n){
  115065. int j,k=map[i];
  115066. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115067. unsigned long qi=46341;
  115068. int qexp=0,shift;
  115069. long wi=vorbis_coslook_i(k*65536/ln);
  115070. qi*=labs(ilsp[0]-wi);
  115071. pi*=labs(ilsp[1]-wi);
  115072. for(j=3;j<m;j+=2){
  115073. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115074. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115075. shift=MLOOP_3[(pi|qi)>>16];
  115076. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115077. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115078. qexp+=shift;
  115079. }
  115080. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115081. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115082. shift=MLOOP_3[(pi|qi)>>16];
  115083. /* pi,qi normalized collectively, both tracked using qexp */
  115084. if(m&1){
  115085. /* odd order filter; slightly assymetric */
  115086. /* the last coefficient */
  115087. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115088. pi=(pi>>shift)<<14;
  115089. qexp+=shift;
  115090. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115091. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115092. shift=MLOOP_3[(pi|qi)>>16];
  115093. pi>>=shift;
  115094. qi>>=shift;
  115095. qexp+=shift-14*((m+1)>>1);
  115096. pi=((pi*pi)>>16);
  115097. qi=((qi*qi)>>16);
  115098. qexp=qexp*2+m;
  115099. pi*=(1<<14)-((wi*wi)>>14);
  115100. qi+=pi>>14;
  115101. }else{
  115102. /* even order filter; still symmetric */
  115103. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115104. worth tracking step by step */
  115105. pi>>=shift;
  115106. qi>>=shift;
  115107. qexp+=shift-7*m;
  115108. pi=((pi*pi)>>16);
  115109. qi=((qi*qi)>>16);
  115110. qexp=qexp*2+m;
  115111. pi*=(1<<14)-wi;
  115112. qi*=(1<<14)+wi;
  115113. qi=(qi+pi)>>14;
  115114. }
  115115. /* we've let the normalization drift because it wasn't important;
  115116. however, for the lookup, things must be normalized again. We
  115117. need at most one right shift or a number of left shifts */
  115118. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115119. qi>>=1; qexp++;
  115120. }else
  115121. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115122. qi<<=1; qexp--;
  115123. }
  115124. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115125. vorbis_invsqlook_i(qi,qexp)-
  115126. /* m.8, m+n<=8 */
  115127. ampoffseti); /* 8.12[0] */
  115128. curve[i]*=amp;
  115129. while(map[++i]==k)curve[i]*=amp;
  115130. }
  115131. }
  115132. #else
  115133. /* old, nonoptimized but simple version for any poor sap who needs to
  115134. figure out what the hell this code does, or wants the other
  115135. fraction of a dB precision */
  115136. /* side effect: changes *lsp to cosines of lsp */
  115137. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115138. float amp,float ampoffset){
  115139. int i;
  115140. float wdel=M_PI/ln;
  115141. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115142. i=0;
  115143. while(i<n){
  115144. int j,k=map[i];
  115145. float p=.5f;
  115146. float q=.5f;
  115147. float w=2.f*cos(wdel*k);
  115148. for(j=1;j<m;j+=2){
  115149. q *= w-lsp[j-1];
  115150. p *= w-lsp[j];
  115151. }
  115152. if(j==m){
  115153. /* odd order filter; slightly assymetric */
  115154. /* the last coefficient */
  115155. q*=w-lsp[j-1];
  115156. p*=p*(4.f-w*w);
  115157. q*=q;
  115158. }else{
  115159. /* even order filter; still symmetric */
  115160. p*=p*(2.f-w);
  115161. q*=q*(2.f+w);
  115162. }
  115163. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115164. curve[i]*=q;
  115165. while(map[++i]==k)curve[i]*=q;
  115166. }
  115167. }
  115168. #endif
  115169. #endif
  115170. static void cheby(float *g, int ord) {
  115171. int i, j;
  115172. g[0] *= .5f;
  115173. for(i=2; i<= ord; i++) {
  115174. for(j=ord; j >= i; j--) {
  115175. g[j-2] -= g[j];
  115176. g[j] += g[j];
  115177. }
  115178. }
  115179. }
  115180. static int JUCE_CDECL comp(const void *a,const void *b){
  115181. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115182. }
  115183. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115184. but there are root sets for which it gets into limit cycles
  115185. (exacerbated by zero suppression) and fails. We can't afford to
  115186. fail, even if the failure is 1 in 100,000,000, so we now use
  115187. Laguerre and later polish with Newton-Raphson (which can then
  115188. afford to fail) */
  115189. #define EPSILON 10e-7
  115190. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115191. int i,m;
  115192. double lastdelta=0.f;
  115193. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115194. for(i=0;i<=ord;i++)defl[i]=a[i];
  115195. for(m=ord;m>0;m--){
  115196. double newx=0.f,delta;
  115197. /* iterate a root */
  115198. while(1){
  115199. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115200. /* eval the polynomial and its first two derivatives */
  115201. for(i=m;i>0;i--){
  115202. ppp = newx*ppp + pp;
  115203. pp = newx*pp + p;
  115204. p = newx*p + defl[i-1];
  115205. }
  115206. /* Laguerre's method */
  115207. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115208. if(denom<0)
  115209. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115210. if(pp>0){
  115211. denom = pp + sqrt(denom);
  115212. if(denom<EPSILON)denom=EPSILON;
  115213. }else{
  115214. denom = pp - sqrt(denom);
  115215. if(denom>-(EPSILON))denom=-(EPSILON);
  115216. }
  115217. delta = m*p/denom;
  115218. newx -= delta;
  115219. if(delta<0.f)delta*=-1;
  115220. if(fabs(delta/newx)<10e-12)break;
  115221. lastdelta=delta;
  115222. }
  115223. r[m-1]=newx;
  115224. /* forward deflation */
  115225. for(i=m;i>0;i--)
  115226. defl[i-1]+=newx*defl[i];
  115227. defl++;
  115228. }
  115229. return(0);
  115230. }
  115231. /* for spit-and-polish only */
  115232. static int Newton_Raphson(float *a,int ord,float *r){
  115233. int i, k, count=0;
  115234. double error=1.f;
  115235. double *root=(double*)alloca(ord*sizeof(*root));
  115236. for(i=0; i<ord;i++) root[i] = r[i];
  115237. while(error>1e-20){
  115238. error=0;
  115239. for(i=0; i<ord; i++) { /* Update each point. */
  115240. double pp=0.,delta;
  115241. double rooti=root[i];
  115242. double p=a[ord];
  115243. for(k=ord-1; k>= 0; k--) {
  115244. pp= pp* rooti + p;
  115245. p = p * rooti + a[k];
  115246. }
  115247. delta = p/pp;
  115248. root[i] -= delta;
  115249. error+= delta*delta;
  115250. }
  115251. if(count>40)return(-1);
  115252. count++;
  115253. }
  115254. /* Replaced the original bubble sort with a real sort. With your
  115255. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115256. for(i=0; i<ord;i++) r[i] = root[i];
  115257. return(0);
  115258. }
  115259. /* Convert lpc coefficients to lsp coefficients */
  115260. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115261. int order2=(m+1)>>1;
  115262. int g1_order,g2_order;
  115263. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115264. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115265. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115266. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115267. int i;
  115268. /* even and odd are slightly different base cases */
  115269. g1_order=(m+1)>>1;
  115270. g2_order=(m) >>1;
  115271. /* Compute the lengths of the x polynomials. */
  115272. /* Compute the first half of K & R F1 & F2 polynomials. */
  115273. /* Compute half of the symmetric and antisymmetric polynomials. */
  115274. /* Remove the roots at +1 and -1. */
  115275. g1[g1_order] = 1.f;
  115276. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115277. g2[g2_order] = 1.f;
  115278. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115279. if(g1_order>g2_order){
  115280. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115281. }else{
  115282. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115283. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115284. }
  115285. /* Convert into polynomials in cos(alpha) */
  115286. cheby(g1,g1_order);
  115287. cheby(g2,g2_order);
  115288. /* Find the roots of the 2 even polynomials.*/
  115289. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115290. Laguerre_With_Deflation(g2,g2_order,g2r))
  115291. return(-1);
  115292. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115293. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115294. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115295. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115296. for(i=0;i<g1_order;i++)
  115297. lsp[i*2] = acos(g1r[i]);
  115298. for(i=0;i<g2_order;i++)
  115299. lsp[i*2+1] = acos(g2r[i]);
  115300. return(0);
  115301. }
  115302. #endif
  115303. /*** End of inlined file: lsp.c ***/
  115304. /*** Start of inlined file: mapping0.c ***/
  115305. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115306. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115307. // tasks..
  115308. #if JUCE_MSVC
  115309. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115310. #endif
  115311. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115312. #if JUCE_USE_OGGVORBIS
  115313. #include <stdlib.h>
  115314. #include <stdio.h>
  115315. #include <string.h>
  115316. #include <math.h>
  115317. /* simplistic, wasteful way of doing this (unique lookup for each
  115318. mode/submapping); there should be a central repository for
  115319. identical lookups. That will require minor work, so I'm putting it
  115320. off as low priority.
  115321. Why a lookup for each backend in a given mode? Because the
  115322. blocksize is set by the mode, and low backend lookups may require
  115323. parameters from other areas of the mode/mapping */
  115324. static void mapping0_free_info(vorbis_info_mapping *i){
  115325. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115326. if(info){
  115327. memset(info,0,sizeof(*info));
  115328. _ogg_free(info);
  115329. }
  115330. }
  115331. static int ilog3(unsigned int v){
  115332. int ret=0;
  115333. if(v)--v;
  115334. while(v){
  115335. ret++;
  115336. v>>=1;
  115337. }
  115338. return(ret);
  115339. }
  115340. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115341. oggpack_buffer *opb){
  115342. int i;
  115343. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115344. /* another 'we meant to do it this way' hack... up to beta 4, we
  115345. packed 4 binary zeros here to signify one submapping in use. We
  115346. now redefine that to mean four bitflags that indicate use of
  115347. deeper features; bit0:submappings, bit1:coupling,
  115348. bit2,3:reserved. This is backward compatable with all actual uses
  115349. of the beta code. */
  115350. if(info->submaps>1){
  115351. oggpack_write(opb,1,1);
  115352. oggpack_write(opb,info->submaps-1,4);
  115353. }else
  115354. oggpack_write(opb,0,1);
  115355. if(info->coupling_steps>0){
  115356. oggpack_write(opb,1,1);
  115357. oggpack_write(opb,info->coupling_steps-1,8);
  115358. for(i=0;i<info->coupling_steps;i++){
  115359. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115360. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115361. }
  115362. }else
  115363. oggpack_write(opb,0,1);
  115364. oggpack_write(opb,0,2); /* 2,3:reserved */
  115365. /* we don't write the channel submappings if we only have one... */
  115366. if(info->submaps>1){
  115367. for(i=0;i<vi->channels;i++)
  115368. oggpack_write(opb,info->chmuxlist[i],4);
  115369. }
  115370. for(i=0;i<info->submaps;i++){
  115371. oggpack_write(opb,0,8); /* time submap unused */
  115372. oggpack_write(opb,info->floorsubmap[i],8);
  115373. oggpack_write(opb,info->residuesubmap[i],8);
  115374. }
  115375. }
  115376. /* also responsible for range checking */
  115377. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115378. int i;
  115379. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115380. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115381. memset(info,0,sizeof(*info));
  115382. if(oggpack_read(opb,1))
  115383. info->submaps=oggpack_read(opb,4)+1;
  115384. else
  115385. info->submaps=1;
  115386. if(oggpack_read(opb,1)){
  115387. info->coupling_steps=oggpack_read(opb,8)+1;
  115388. for(i=0;i<info->coupling_steps;i++){
  115389. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115390. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115391. if(testM<0 ||
  115392. testA<0 ||
  115393. testM==testA ||
  115394. testM>=vi->channels ||
  115395. testA>=vi->channels) goto err_out;
  115396. }
  115397. }
  115398. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115399. if(info->submaps>1){
  115400. for(i=0;i<vi->channels;i++){
  115401. info->chmuxlist[i]=oggpack_read(opb,4);
  115402. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115403. }
  115404. }
  115405. for(i=0;i<info->submaps;i++){
  115406. oggpack_read(opb,8); /* time submap unused */
  115407. info->floorsubmap[i]=oggpack_read(opb,8);
  115408. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115409. info->residuesubmap[i]=oggpack_read(opb,8);
  115410. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115411. }
  115412. return info;
  115413. err_out:
  115414. mapping0_free_info(info);
  115415. return(NULL);
  115416. }
  115417. #if 0
  115418. static long seq=0;
  115419. static ogg_int64_t total=0;
  115420. static float FLOOR1_fromdB_LOOKUP[256]={
  115421. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115422. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115423. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115424. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115425. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115426. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115427. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115428. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115429. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115430. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115431. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115432. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115433. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115434. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115435. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115436. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115437. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115438. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115439. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115440. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115441. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115442. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115443. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115444. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115445. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115446. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115447. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115448. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115449. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115450. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115451. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115452. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115453. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115454. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115455. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115456. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115457. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115458. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115459. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115460. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115461. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115462. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115463. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115464. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115465. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115466. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115467. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115468. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115469. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115470. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115471. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115472. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115473. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115474. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115475. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115476. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115477. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115478. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115479. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115480. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115481. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115482. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115483. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115484. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115485. };
  115486. #endif
  115487. extern int *floor1_fit(vorbis_block *vb,void *look,
  115488. const float *logmdct, /* in */
  115489. const float *logmask);
  115490. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115491. int *A,int *B,
  115492. int del);
  115493. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115494. void*look,
  115495. int *post,int *ilogmask);
  115496. static int mapping0_forward(vorbis_block *vb){
  115497. vorbis_dsp_state *vd=vb->vd;
  115498. vorbis_info *vi=vd->vi;
  115499. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115500. private_state *b=(private_state*)vb->vd->backend_state;
  115501. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115502. int n=vb->pcmend;
  115503. int i,j,k;
  115504. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115505. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115506. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115507. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115508. float global_ampmax=vbi->ampmax;
  115509. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115510. int blocktype=vbi->blocktype;
  115511. int modenumber=vb->W;
  115512. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115513. vorbis_look_psy *psy_look=
  115514. b->psy+blocktype+(vb->W?2:0);
  115515. vb->mode=modenumber;
  115516. for(i=0;i<vi->channels;i++){
  115517. float scale=4.f/n;
  115518. float scale_dB;
  115519. float *pcm =vb->pcm[i];
  115520. float *logfft =pcm;
  115521. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115522. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115523. todB estimation used on IEEE 754
  115524. compliant machines had a bug that
  115525. returned dB values about a third
  115526. of a decibel too high. The bug
  115527. was harmless because tunings
  115528. implicitly took that into
  115529. account. However, fixing the bug
  115530. in the estimator requires
  115531. changing all the tunings as well.
  115532. For now, it's easier to sync
  115533. things back up here, and
  115534. recalibrate the tunings in the
  115535. next major model upgrade. */
  115536. #if 0
  115537. if(vi->channels==2)
  115538. if(i==0)
  115539. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115540. else
  115541. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115542. #endif
  115543. /* window the PCM data */
  115544. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115545. #if 0
  115546. if(vi->channels==2)
  115547. if(i==0)
  115548. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115549. else
  115550. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115551. #endif
  115552. /* transform the PCM data */
  115553. /* only MDCT right now.... */
  115554. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115555. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115556. drft_forward(&b->fft_look[vb->W],pcm);
  115557. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115558. original todB estimation used on
  115559. IEEE 754 compliant machines had a
  115560. bug that returned dB values about
  115561. a third of a decibel too high.
  115562. The bug was harmless because
  115563. tunings implicitly took that into
  115564. account. However, fixing the bug
  115565. in the estimator requires
  115566. changing all the tunings as well.
  115567. For now, it's easier to sync
  115568. things back up here, and
  115569. recalibrate the tunings in the
  115570. next major model upgrade. */
  115571. local_ampmax[i]=logfft[0];
  115572. for(j=1;j<n-1;j+=2){
  115573. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115574. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115575. .345 is a hack; the original todB
  115576. estimation used on IEEE 754
  115577. compliant machines had a bug that
  115578. returned dB values about a third
  115579. of a decibel too high. The bug
  115580. was harmless because tunings
  115581. implicitly took that into
  115582. account. However, fixing the bug
  115583. in the estimator requires
  115584. changing all the tunings as well.
  115585. For now, it's easier to sync
  115586. things back up here, and
  115587. recalibrate the tunings in the
  115588. next major model upgrade. */
  115589. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115590. }
  115591. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115592. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115593. #if 0
  115594. if(vi->channels==2){
  115595. if(i==0){
  115596. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115597. }else{
  115598. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115599. }
  115600. }
  115601. #endif
  115602. }
  115603. {
  115604. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115605. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115606. for(i=0;i<vi->channels;i++){
  115607. /* the encoder setup assumes that all the modes used by any
  115608. specific bitrate tweaking use the same floor */
  115609. int submap=info->chmuxlist[i];
  115610. /* the following makes things clearer to *me* anyway */
  115611. float *mdct =gmdct[i];
  115612. float *logfft =vb->pcm[i];
  115613. float *logmdct =logfft+n/2;
  115614. float *logmask =logfft;
  115615. vb->mode=modenumber;
  115616. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115617. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115618. for(j=0;j<n/2;j++)
  115619. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115620. todB estimation used on IEEE 754
  115621. compliant machines had a bug that
  115622. returned dB values about a third
  115623. of a decibel too high. The bug
  115624. was harmless because tunings
  115625. implicitly took that into
  115626. account. However, fixing the bug
  115627. in the estimator requires
  115628. changing all the tunings as well.
  115629. For now, it's easier to sync
  115630. things back up here, and
  115631. recalibrate the tunings in the
  115632. next major model upgrade. */
  115633. #if 0
  115634. if(vi->channels==2){
  115635. if(i==0)
  115636. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115637. else
  115638. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115639. }else{
  115640. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115641. }
  115642. #endif
  115643. /* first step; noise masking. Not only does 'noise masking'
  115644. give us curves from which we can decide how much resolution
  115645. to give noise parts of the spectrum, it also implicitly hands
  115646. us a tonality estimate (the larger the value in the
  115647. 'noise_depth' vector, the more tonal that area is) */
  115648. _vp_noisemask(psy_look,
  115649. logmdct,
  115650. noise); /* noise does not have by-frequency offset
  115651. bias applied yet */
  115652. #if 0
  115653. if(vi->channels==2){
  115654. if(i==0)
  115655. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115656. else
  115657. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115658. }
  115659. #endif
  115660. /* second step: 'all the other crap'; all the stuff that isn't
  115661. computed/fit for bitrate management goes in the second psy
  115662. vector. This includes tone masking, peak limiting and ATH */
  115663. _vp_tonemask(psy_look,
  115664. logfft,
  115665. tone,
  115666. global_ampmax,
  115667. local_ampmax[i]);
  115668. #if 0
  115669. if(vi->channels==2){
  115670. if(i==0)
  115671. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115672. else
  115673. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115674. }
  115675. #endif
  115676. /* third step; we offset the noise vectors, overlay tone
  115677. masking. We then do a floor1-specific line fit. If we're
  115678. performing bitrate management, the line fit is performed
  115679. multiple times for up/down tweakage on demand. */
  115680. #if 0
  115681. {
  115682. float aotuv[psy_look->n];
  115683. #endif
  115684. _vp_offset_and_mix(psy_look,
  115685. noise,
  115686. tone,
  115687. 1,
  115688. logmask,
  115689. mdct,
  115690. logmdct);
  115691. #if 0
  115692. if(vi->channels==2){
  115693. if(i==0)
  115694. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115695. else
  115696. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115697. }
  115698. }
  115699. #endif
  115700. #if 0
  115701. if(vi->channels==2){
  115702. if(i==0)
  115703. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115704. else
  115705. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115706. }
  115707. #endif
  115708. /* this algorithm is hardwired to floor 1 for now; abort out if
  115709. we're *not* floor1. This won't happen unless someone has
  115710. broken the encode setup lib. Guard it anyway. */
  115711. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115712. floor_posts[i][PACKETBLOBS/2]=
  115713. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115714. logmdct,
  115715. logmask);
  115716. /* are we managing bitrate? If so, perform two more fits for
  115717. later rate tweaking (fits represent hi/lo) */
  115718. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115719. /* higher rate by way of lower noise curve */
  115720. _vp_offset_and_mix(psy_look,
  115721. noise,
  115722. tone,
  115723. 2,
  115724. logmask,
  115725. mdct,
  115726. logmdct);
  115727. #if 0
  115728. if(vi->channels==2){
  115729. if(i==0)
  115730. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115731. else
  115732. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115733. }
  115734. #endif
  115735. floor_posts[i][PACKETBLOBS-1]=
  115736. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115737. logmdct,
  115738. logmask);
  115739. /* lower rate by way of higher noise curve */
  115740. _vp_offset_and_mix(psy_look,
  115741. noise,
  115742. tone,
  115743. 0,
  115744. logmask,
  115745. mdct,
  115746. logmdct);
  115747. #if 0
  115748. if(vi->channels==2)
  115749. if(i==0)
  115750. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115751. else
  115752. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115753. #endif
  115754. floor_posts[i][0]=
  115755. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115756. logmdct,
  115757. logmask);
  115758. /* we also interpolate a range of intermediate curves for
  115759. intermediate rates */
  115760. for(k=1;k<PACKETBLOBS/2;k++)
  115761. floor_posts[i][k]=
  115762. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115763. floor_posts[i][0],
  115764. floor_posts[i][PACKETBLOBS/2],
  115765. k*65536/(PACKETBLOBS/2));
  115766. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115767. floor_posts[i][k]=
  115768. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115769. floor_posts[i][PACKETBLOBS/2],
  115770. floor_posts[i][PACKETBLOBS-1],
  115771. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115772. }
  115773. }
  115774. }
  115775. vbi->ampmax=global_ampmax;
  115776. /*
  115777. the next phases are performed once for vbr-only and PACKETBLOB
  115778. times for bitrate managed modes.
  115779. 1) encode actual mode being used
  115780. 2) encode the floor for each channel, compute coded mask curve/res
  115781. 3) normalize and couple.
  115782. 4) encode residue
  115783. 5) save packet bytes to the packetblob vector
  115784. */
  115785. /* iterate over the many masking curve fits we've created */
  115786. {
  115787. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115788. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115789. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115790. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115791. float **mag_memo;
  115792. int **mag_sort;
  115793. if(info->coupling_steps){
  115794. mag_memo=_vp_quantize_couple_memo(vb,
  115795. &ci->psy_g_param,
  115796. psy_look,
  115797. info,
  115798. gmdct);
  115799. mag_sort=_vp_quantize_couple_sort(vb,
  115800. psy_look,
  115801. info,
  115802. mag_memo);
  115803. hf_reduction(&ci->psy_g_param,
  115804. psy_look,
  115805. info,
  115806. mag_memo);
  115807. }
  115808. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115809. if(psy_look->vi->normal_channel_p){
  115810. for(i=0;i<vi->channels;i++){
  115811. float *mdct =gmdct[i];
  115812. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115813. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115814. }
  115815. }
  115816. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115817. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115818. k++){
  115819. oggpack_buffer *opb=vbi->packetblob[k];
  115820. /* start out our new packet blob with packet type and mode */
  115821. /* Encode the packet type */
  115822. oggpack_write(opb,0,1);
  115823. /* Encode the modenumber */
  115824. /* Encode frame mode, pre,post windowsize, then dispatch */
  115825. oggpack_write(opb,modenumber,b->modebits);
  115826. if(vb->W){
  115827. oggpack_write(opb,vb->lW,1);
  115828. oggpack_write(opb,vb->nW,1);
  115829. }
  115830. /* encode floor, compute masking curve, sep out residue */
  115831. for(i=0;i<vi->channels;i++){
  115832. int submap=info->chmuxlist[i];
  115833. float *mdct =gmdct[i];
  115834. float *res =vb->pcm[i];
  115835. int *ilogmask=ilogmaskch[i]=
  115836. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115837. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115838. floor_posts[i][k],
  115839. ilogmask);
  115840. #if 0
  115841. {
  115842. char buf[80];
  115843. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115844. float work[n/2];
  115845. for(j=0;j<n/2;j++)
  115846. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115847. _analysis_output(buf,seq,work,n/2,1,1,0);
  115848. }
  115849. #endif
  115850. _vp_remove_floor(psy_look,
  115851. mdct,
  115852. ilogmask,
  115853. res,
  115854. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115855. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115856. #if 0
  115857. {
  115858. char buf[80];
  115859. float work[n/2];
  115860. for(j=0;j<n/2;j++)
  115861. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115862. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115863. _analysis_output(buf,seq,work,n/2,1,1,0);
  115864. }
  115865. #endif
  115866. }
  115867. /* our iteration is now based on masking curve, not prequant and
  115868. coupling. Only one prequant/coupling step */
  115869. /* quantize/couple */
  115870. /* incomplete implementation that assumes the tree is all depth
  115871. one, or no tree at all */
  115872. if(info->coupling_steps){
  115873. _vp_couple(k,
  115874. &ci->psy_g_param,
  115875. psy_look,
  115876. info,
  115877. vb->pcm,
  115878. mag_memo,
  115879. mag_sort,
  115880. ilogmaskch,
  115881. nonzero,
  115882. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115883. }
  115884. /* classify and encode by submap */
  115885. for(i=0;i<info->submaps;i++){
  115886. int ch_in_bundle=0;
  115887. long **classifications;
  115888. int resnum=info->residuesubmap[i];
  115889. for(j=0;j<vi->channels;j++){
  115890. if(info->chmuxlist[j]==i){
  115891. zerobundle[ch_in_bundle]=0;
  115892. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115893. res_bundle[ch_in_bundle]=vb->pcm[j];
  115894. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115895. }
  115896. }
  115897. classifications=_residue_P[ci->residue_type[resnum]]->
  115898. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115899. _residue_P[ci->residue_type[resnum]]->
  115900. forward(opb,vb,b->residue[resnum],
  115901. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115902. }
  115903. /* ok, done encoding. Next protopacket. */
  115904. }
  115905. }
  115906. #if 0
  115907. seq++;
  115908. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115909. #endif
  115910. return(0);
  115911. }
  115912. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115913. vorbis_dsp_state *vd=vb->vd;
  115914. vorbis_info *vi=vd->vi;
  115915. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115916. private_state *b=(private_state*)vd->backend_state;
  115917. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115918. int i,j;
  115919. long n=vb->pcmend=ci->blocksizes[vb->W];
  115920. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115921. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115922. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115923. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115924. /* recover the spectral envelope; store it in the PCM vector for now */
  115925. for(i=0;i<vi->channels;i++){
  115926. int submap=info->chmuxlist[i];
  115927. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115928. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115929. if(floormemo[i])
  115930. nonzero[i]=1;
  115931. else
  115932. nonzero[i]=0;
  115933. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115934. }
  115935. /* channel coupling can 'dirty' the nonzero listing */
  115936. for(i=0;i<info->coupling_steps;i++){
  115937. if(nonzero[info->coupling_mag[i]] ||
  115938. nonzero[info->coupling_ang[i]]){
  115939. nonzero[info->coupling_mag[i]]=1;
  115940. nonzero[info->coupling_ang[i]]=1;
  115941. }
  115942. }
  115943. /* recover the residue into our working vectors */
  115944. for(i=0;i<info->submaps;i++){
  115945. int ch_in_bundle=0;
  115946. for(j=0;j<vi->channels;j++){
  115947. if(info->chmuxlist[j]==i){
  115948. if(nonzero[j])
  115949. zerobundle[ch_in_bundle]=1;
  115950. else
  115951. zerobundle[ch_in_bundle]=0;
  115952. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115953. }
  115954. }
  115955. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115956. inverse(vb,b->residue[info->residuesubmap[i]],
  115957. pcmbundle,zerobundle,ch_in_bundle);
  115958. }
  115959. /* channel coupling */
  115960. for(i=info->coupling_steps-1;i>=0;i--){
  115961. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115962. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115963. for(j=0;j<n/2;j++){
  115964. float mag=pcmM[j];
  115965. float ang=pcmA[j];
  115966. if(mag>0)
  115967. if(ang>0){
  115968. pcmM[j]=mag;
  115969. pcmA[j]=mag-ang;
  115970. }else{
  115971. pcmA[j]=mag;
  115972. pcmM[j]=mag+ang;
  115973. }
  115974. else
  115975. if(ang>0){
  115976. pcmM[j]=mag;
  115977. pcmA[j]=mag+ang;
  115978. }else{
  115979. pcmA[j]=mag;
  115980. pcmM[j]=mag-ang;
  115981. }
  115982. }
  115983. }
  115984. /* compute and apply spectral envelope */
  115985. for(i=0;i<vi->channels;i++){
  115986. float *pcm=vb->pcm[i];
  115987. int submap=info->chmuxlist[i];
  115988. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115989. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115990. floormemo[i],pcm);
  115991. }
  115992. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115993. /* only MDCT right now.... */
  115994. for(i=0;i<vi->channels;i++){
  115995. float *pcm=vb->pcm[i];
  115996. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115997. }
  115998. /* all done! */
  115999. return(0);
  116000. }
  116001. /* export hooks */
  116002. vorbis_func_mapping mapping0_exportbundle={
  116003. &mapping0_pack,
  116004. &mapping0_unpack,
  116005. &mapping0_free_info,
  116006. &mapping0_forward,
  116007. &mapping0_inverse
  116008. };
  116009. #endif
  116010. /*** End of inlined file: mapping0.c ***/
  116011. /*** Start of inlined file: mdct.c ***/
  116012. /* this can also be run as an integer transform by uncommenting a
  116013. define in mdct.h; the integerization is a first pass and although
  116014. it's likely stable for Vorbis, the dynamic range is constrained and
  116015. roundoff isn't done (so it's noisy). Consider it functional, but
  116016. only a starting point. There's no point on a machine with an FPU */
  116017. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116018. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116019. // tasks..
  116020. #if JUCE_MSVC
  116021. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116022. #endif
  116023. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116024. #if JUCE_USE_OGGVORBIS
  116025. #include <stdio.h>
  116026. #include <stdlib.h>
  116027. #include <string.h>
  116028. #include <math.h>
  116029. /* build lookups for trig functions; also pre-figure scaling and
  116030. some window function algebra. */
  116031. void mdct_init(mdct_lookup *lookup,int n){
  116032. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116033. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116034. int i;
  116035. int n2=n>>1;
  116036. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116037. lookup->n=n;
  116038. lookup->trig=T;
  116039. lookup->bitrev=bitrev;
  116040. /* trig lookups... */
  116041. for(i=0;i<n/4;i++){
  116042. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116043. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116044. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116045. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116046. }
  116047. for(i=0;i<n/8;i++){
  116048. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116049. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116050. }
  116051. /* bitreverse lookup... */
  116052. {
  116053. int mask=(1<<(log2n-1))-1,i,j;
  116054. int msb=1<<(log2n-2);
  116055. for(i=0;i<n/8;i++){
  116056. int acc=0;
  116057. for(j=0;msb>>j;j++)
  116058. if((msb>>j)&i)acc|=1<<j;
  116059. bitrev[i*2]=((~acc)&mask)-1;
  116060. bitrev[i*2+1]=acc;
  116061. }
  116062. }
  116063. lookup->scale=FLOAT_CONV(4.f/n);
  116064. }
  116065. /* 8 point butterfly (in place, 4 register) */
  116066. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116067. REG_TYPE r0 = x[6] + x[2];
  116068. REG_TYPE r1 = x[6] - x[2];
  116069. REG_TYPE r2 = x[4] + x[0];
  116070. REG_TYPE r3 = x[4] - x[0];
  116071. x[6] = r0 + r2;
  116072. x[4] = r0 - r2;
  116073. r0 = x[5] - x[1];
  116074. r2 = x[7] - x[3];
  116075. x[0] = r1 + r0;
  116076. x[2] = r1 - r0;
  116077. r0 = x[5] + x[1];
  116078. r1 = x[7] + x[3];
  116079. x[3] = r2 + r3;
  116080. x[1] = r2 - r3;
  116081. x[7] = r1 + r0;
  116082. x[5] = r1 - r0;
  116083. }
  116084. /* 16 point butterfly (in place, 4 register) */
  116085. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116086. REG_TYPE r0 = x[1] - x[9];
  116087. REG_TYPE r1 = x[0] - x[8];
  116088. x[8] += x[0];
  116089. x[9] += x[1];
  116090. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116091. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116092. r0 = x[3] - x[11];
  116093. r1 = x[10] - x[2];
  116094. x[10] += x[2];
  116095. x[11] += x[3];
  116096. x[2] = r0;
  116097. x[3] = r1;
  116098. r0 = x[12] - x[4];
  116099. r1 = x[13] - x[5];
  116100. x[12] += x[4];
  116101. x[13] += x[5];
  116102. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116103. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116104. r0 = x[14] - x[6];
  116105. r1 = x[15] - x[7];
  116106. x[14] += x[6];
  116107. x[15] += x[7];
  116108. x[6] = r0;
  116109. x[7] = r1;
  116110. mdct_butterfly_8(x);
  116111. mdct_butterfly_8(x+8);
  116112. }
  116113. /* 32 point butterfly (in place, 4 register) */
  116114. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116115. REG_TYPE r0 = x[30] - x[14];
  116116. REG_TYPE r1 = x[31] - x[15];
  116117. x[30] += x[14];
  116118. x[31] += x[15];
  116119. x[14] = r0;
  116120. x[15] = r1;
  116121. r0 = x[28] - x[12];
  116122. r1 = x[29] - x[13];
  116123. x[28] += x[12];
  116124. x[29] += x[13];
  116125. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116126. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116127. r0 = x[26] - x[10];
  116128. r1 = x[27] - x[11];
  116129. x[26] += x[10];
  116130. x[27] += x[11];
  116131. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116132. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116133. r0 = x[24] - x[8];
  116134. r1 = x[25] - x[9];
  116135. x[24] += x[8];
  116136. x[25] += x[9];
  116137. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116138. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116139. r0 = x[22] - x[6];
  116140. r1 = x[7] - x[23];
  116141. x[22] += x[6];
  116142. x[23] += x[7];
  116143. x[6] = r1;
  116144. x[7] = r0;
  116145. r0 = x[4] - x[20];
  116146. r1 = x[5] - x[21];
  116147. x[20] += x[4];
  116148. x[21] += x[5];
  116149. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116150. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116151. r0 = x[2] - x[18];
  116152. r1 = x[3] - x[19];
  116153. x[18] += x[2];
  116154. x[19] += x[3];
  116155. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116156. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116157. r0 = x[0] - x[16];
  116158. r1 = x[1] - x[17];
  116159. x[16] += x[0];
  116160. x[17] += x[1];
  116161. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116162. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116163. mdct_butterfly_16(x);
  116164. mdct_butterfly_16(x+16);
  116165. }
  116166. /* N point first stage butterfly (in place, 2 register) */
  116167. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116168. DATA_TYPE *x,
  116169. int points){
  116170. DATA_TYPE *x1 = x + points - 8;
  116171. DATA_TYPE *x2 = x + (points>>1) - 8;
  116172. REG_TYPE r0;
  116173. REG_TYPE r1;
  116174. do{
  116175. r0 = x1[6] - x2[6];
  116176. r1 = x1[7] - x2[7];
  116177. x1[6] += x2[6];
  116178. x1[7] += x2[7];
  116179. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116180. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116181. r0 = x1[4] - x2[4];
  116182. r1 = x1[5] - x2[5];
  116183. x1[4] += x2[4];
  116184. x1[5] += x2[5];
  116185. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116186. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116187. r0 = x1[2] - x2[2];
  116188. r1 = x1[3] - x2[3];
  116189. x1[2] += x2[2];
  116190. x1[3] += x2[3];
  116191. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116192. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116193. r0 = x1[0] - x2[0];
  116194. r1 = x1[1] - x2[1];
  116195. x1[0] += x2[0];
  116196. x1[1] += x2[1];
  116197. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116198. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116199. x1-=8;
  116200. x2-=8;
  116201. T+=16;
  116202. }while(x2>=x);
  116203. }
  116204. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116205. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116206. DATA_TYPE *x,
  116207. int points,
  116208. int trigint){
  116209. DATA_TYPE *x1 = x + points - 8;
  116210. DATA_TYPE *x2 = x + (points>>1) - 8;
  116211. REG_TYPE r0;
  116212. REG_TYPE r1;
  116213. do{
  116214. r0 = x1[6] - x2[6];
  116215. r1 = x1[7] - x2[7];
  116216. x1[6] += x2[6];
  116217. x1[7] += x2[7];
  116218. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116219. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116220. T+=trigint;
  116221. r0 = x1[4] - x2[4];
  116222. r1 = x1[5] - x2[5];
  116223. x1[4] += x2[4];
  116224. x1[5] += x2[5];
  116225. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116226. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116227. T+=trigint;
  116228. r0 = x1[2] - x2[2];
  116229. r1 = x1[3] - x2[3];
  116230. x1[2] += x2[2];
  116231. x1[3] += x2[3];
  116232. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116233. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116234. T+=trigint;
  116235. r0 = x1[0] - x2[0];
  116236. r1 = x1[1] - x2[1];
  116237. x1[0] += x2[0];
  116238. x1[1] += x2[1];
  116239. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116240. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116241. T+=trigint;
  116242. x1-=8;
  116243. x2-=8;
  116244. }while(x2>=x);
  116245. }
  116246. STIN void mdct_butterflies(mdct_lookup *init,
  116247. DATA_TYPE *x,
  116248. int points){
  116249. DATA_TYPE *T=init->trig;
  116250. int stages=init->log2n-5;
  116251. int i,j;
  116252. if(--stages>0){
  116253. mdct_butterfly_first(T,x,points);
  116254. }
  116255. for(i=1;--stages>0;i++){
  116256. for(j=0;j<(1<<i);j++)
  116257. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116258. }
  116259. for(j=0;j<points;j+=32)
  116260. mdct_butterfly_32(x+j);
  116261. }
  116262. void mdct_clear(mdct_lookup *l){
  116263. if(l){
  116264. if(l->trig)_ogg_free(l->trig);
  116265. if(l->bitrev)_ogg_free(l->bitrev);
  116266. memset(l,0,sizeof(*l));
  116267. }
  116268. }
  116269. STIN void mdct_bitreverse(mdct_lookup *init,
  116270. DATA_TYPE *x){
  116271. int n = init->n;
  116272. int *bit = init->bitrev;
  116273. DATA_TYPE *w0 = x;
  116274. DATA_TYPE *w1 = x = w0+(n>>1);
  116275. DATA_TYPE *T = init->trig+n;
  116276. do{
  116277. DATA_TYPE *x0 = x+bit[0];
  116278. DATA_TYPE *x1 = x+bit[1];
  116279. REG_TYPE r0 = x0[1] - x1[1];
  116280. REG_TYPE r1 = x0[0] + x1[0];
  116281. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116282. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116283. w1 -= 4;
  116284. r0 = HALVE(x0[1] + x1[1]);
  116285. r1 = HALVE(x0[0] - x1[0]);
  116286. w0[0] = r0 + r2;
  116287. w1[2] = r0 - r2;
  116288. w0[1] = r1 + r3;
  116289. w1[3] = r3 - r1;
  116290. x0 = x+bit[2];
  116291. x1 = x+bit[3];
  116292. r0 = x0[1] - x1[1];
  116293. r1 = x0[0] + x1[0];
  116294. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116295. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116296. r0 = HALVE(x0[1] + x1[1]);
  116297. r1 = HALVE(x0[0] - x1[0]);
  116298. w0[2] = r0 + r2;
  116299. w1[0] = r0 - r2;
  116300. w0[3] = r1 + r3;
  116301. w1[1] = r3 - r1;
  116302. T += 4;
  116303. bit += 4;
  116304. w0 += 4;
  116305. }while(w0<w1);
  116306. }
  116307. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116308. int n=init->n;
  116309. int n2=n>>1;
  116310. int n4=n>>2;
  116311. /* rotate */
  116312. DATA_TYPE *iX = in+n2-7;
  116313. DATA_TYPE *oX = out+n2+n4;
  116314. DATA_TYPE *T = init->trig+n4;
  116315. do{
  116316. oX -= 4;
  116317. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116318. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116319. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116320. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116321. iX -= 8;
  116322. T += 4;
  116323. }while(iX>=in);
  116324. iX = in+n2-8;
  116325. oX = out+n2+n4;
  116326. T = init->trig+n4;
  116327. do{
  116328. T -= 4;
  116329. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116330. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116331. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116332. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116333. iX -= 8;
  116334. oX += 4;
  116335. }while(iX>=in);
  116336. mdct_butterflies(init,out+n2,n2);
  116337. mdct_bitreverse(init,out);
  116338. /* roatate + window */
  116339. {
  116340. DATA_TYPE *oX1=out+n2+n4;
  116341. DATA_TYPE *oX2=out+n2+n4;
  116342. DATA_TYPE *iX =out;
  116343. T =init->trig+n2;
  116344. do{
  116345. oX1-=4;
  116346. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116347. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116348. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116349. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116350. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116351. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116352. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116353. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116354. oX2+=4;
  116355. iX += 8;
  116356. T += 8;
  116357. }while(iX<oX1);
  116358. iX=out+n2+n4;
  116359. oX1=out+n4;
  116360. oX2=oX1;
  116361. do{
  116362. oX1-=4;
  116363. iX-=4;
  116364. oX2[0] = -(oX1[3] = iX[3]);
  116365. oX2[1] = -(oX1[2] = iX[2]);
  116366. oX2[2] = -(oX1[1] = iX[1]);
  116367. oX2[3] = -(oX1[0] = iX[0]);
  116368. oX2+=4;
  116369. }while(oX2<iX);
  116370. iX=out+n2+n4;
  116371. oX1=out+n2+n4;
  116372. oX2=out+n2;
  116373. do{
  116374. oX1-=4;
  116375. oX1[0]= iX[3];
  116376. oX1[1]= iX[2];
  116377. oX1[2]= iX[1];
  116378. oX1[3]= iX[0];
  116379. iX+=4;
  116380. }while(oX1>oX2);
  116381. }
  116382. }
  116383. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116384. int n=init->n;
  116385. int n2=n>>1;
  116386. int n4=n>>2;
  116387. int n8=n>>3;
  116388. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116389. DATA_TYPE *w2=w+n2;
  116390. /* rotate */
  116391. /* window + rotate + step 1 */
  116392. REG_TYPE r0;
  116393. REG_TYPE r1;
  116394. DATA_TYPE *x0=in+n2+n4;
  116395. DATA_TYPE *x1=x0+1;
  116396. DATA_TYPE *T=init->trig+n2;
  116397. int i=0;
  116398. for(i=0;i<n8;i+=2){
  116399. x0 -=4;
  116400. T-=2;
  116401. r0= x0[2] + x1[0];
  116402. r1= x0[0] + x1[2];
  116403. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116404. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116405. x1 +=4;
  116406. }
  116407. x1=in+1;
  116408. for(;i<n2-n8;i+=2){
  116409. T-=2;
  116410. x0 -=4;
  116411. r0= x0[2] - x1[0];
  116412. r1= x0[0] - x1[2];
  116413. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116414. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116415. x1 +=4;
  116416. }
  116417. x0=in+n;
  116418. for(;i<n2;i+=2){
  116419. T-=2;
  116420. x0 -=4;
  116421. r0= -x0[2] - x1[0];
  116422. r1= -x0[0] - x1[2];
  116423. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116424. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116425. x1 +=4;
  116426. }
  116427. mdct_butterflies(init,w+n2,n2);
  116428. mdct_bitreverse(init,w);
  116429. /* roatate + window */
  116430. T=init->trig+n2;
  116431. x0=out+n2;
  116432. for(i=0;i<n4;i++){
  116433. x0--;
  116434. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116435. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116436. w+=2;
  116437. T+=2;
  116438. }
  116439. }
  116440. #endif
  116441. /*** End of inlined file: mdct.c ***/
  116442. /*** Start of inlined file: psy.c ***/
  116443. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116444. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116445. // tasks..
  116446. #if JUCE_MSVC
  116447. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116448. #endif
  116449. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116450. #if JUCE_USE_OGGVORBIS
  116451. #include <stdlib.h>
  116452. #include <math.h>
  116453. #include <string.h>
  116454. /*** Start of inlined file: masking.h ***/
  116455. #ifndef _V_MASKING_H_
  116456. #define _V_MASKING_H_
  116457. /* more detailed ATH; the bass if flat to save stressing the floor
  116458. overly for only a bin or two of savings. */
  116459. #define MAX_ATH 88
  116460. static float ATH[]={
  116461. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116462. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116463. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116464. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116465. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116466. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116467. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116468. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116469. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116470. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116471. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116472. };
  116473. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116474. replaced by an empirically collected data set. The previously
  116475. published values were, far too often, simply on crack. */
  116476. #define EHMER_OFFSET 16
  116477. #define EHMER_MAX 56
  116478. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116479. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116480. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116481. for collection of these curves) */
  116482. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116483. /* 62.5 Hz */
  116484. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116485. -60, -60, -60, -60, -62, -62, -65, -73,
  116486. -69, -68, -68, -67, -70, -70, -72, -74,
  116487. -75, -79, -79, -80, -83, -88, -93, -100,
  116488. -110, -999, -999, -999, -999, -999, -999, -999,
  116489. -999, -999, -999, -999, -999, -999, -999, -999,
  116490. -999, -999, -999, -999, -999, -999, -999, -999},
  116491. { -48, -48, -48, -48, -48, -48, -48, -48,
  116492. -48, -48, -48, -48, -48, -53, -61, -66,
  116493. -66, -68, -67, -70, -76, -76, -72, -73,
  116494. -75, -76, -78, -79, -83, -88, -93, -100,
  116495. -110, -999, -999, -999, -999, -999, -999, -999,
  116496. -999, -999, -999, -999, -999, -999, -999, -999,
  116497. -999, -999, -999, -999, -999, -999, -999, -999},
  116498. { -37, -37, -37, -37, -37, -37, -37, -37,
  116499. -38, -40, -42, -46, -48, -53, -55, -62,
  116500. -65, -58, -56, -56, -61, -60, -65, -67,
  116501. -69, -71, -77, -77, -78, -80, -82, -84,
  116502. -88, -93, -98, -106, -112, -999, -999, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999},
  116505. { -25, -25, -25, -25, -25, -25, -25, -25,
  116506. -25, -26, -27, -29, -32, -38, -48, -52,
  116507. -52, -50, -48, -48, -51, -52, -54, -60,
  116508. -67, -67, -66, -68, -69, -73, -73, -76,
  116509. -80, -81, -81, -85, -85, -86, -88, -93,
  116510. -100, -110, -999, -999, -999, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -999, -999, -999},
  116512. { -16, -16, -16, -16, -16, -16, -16, -16,
  116513. -17, -19, -20, -22, -26, -28, -31, -40,
  116514. -47, -39, -39, -40, -42, -43, -47, -51,
  116515. -57, -52, -55, -55, -60, -58, -62, -63,
  116516. -70, -67, -69, -72, -73, -77, -80, -82,
  116517. -83, -87, -90, -94, -98, -104, -115, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999},
  116519. { -8, -8, -8, -8, -8, -8, -8, -8,
  116520. -8, -8, -10, -11, -15, -19, -25, -30,
  116521. -34, -31, -30, -31, -29, -32, -35, -42,
  116522. -48, -42, -44, -46, -50, -50, -51, -52,
  116523. -59, -54, -55, -55, -58, -62, -63, -66,
  116524. -72, -73, -76, -75, -78, -80, -80, -81,
  116525. -84, -88, -90, -94, -98, -101, -106, -110}},
  116526. /* 88Hz */
  116527. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116528. -66, -66, -66, -66, -66, -67, -67, -67,
  116529. -76, -72, -71, -74, -76, -76, -75, -78,
  116530. -79, -79, -81, -83, -86, -89, -93, -97,
  116531. -100, -105, -110, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999},
  116534. { -47, -47, -47, -47, -47, -47, -47, -47,
  116535. -47, -47, -47, -48, -51, -55, -59, -66,
  116536. -66, -66, -67, -66, -68, -69, -70, -74,
  116537. -79, -77, -77, -78, -80, -81, -82, -84,
  116538. -86, -88, -91, -95, -100, -108, -116, -999,
  116539. -999, -999, -999, -999, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999},
  116541. { -36, -36, -36, -36, -36, -36, -36, -36,
  116542. -36, -37, -37, -41, -44, -48, -51, -58,
  116543. -62, -60, -57, -59, -59, -60, -63, -65,
  116544. -72, -71, -70, -72, -74, -77, -76, -78,
  116545. -81, -81, -80, -83, -86, -91, -96, -100,
  116546. -105, -110, -999, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999},
  116548. { -28, -28, -28, -28, -28, -28, -28, -28,
  116549. -28, -30, -32, -32, -33, -35, -41, -49,
  116550. -50, -49, -47, -48, -48, -52, -51, -57,
  116551. -65, -61, -59, -61, -64, -69, -70, -74,
  116552. -77, -77, -78, -81, -84, -85, -87, -90,
  116553. -92, -96, -100, -107, -112, -999, -999, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999},
  116555. { -19, -19, -19, -19, -19, -19, -19, -19,
  116556. -20, -21, -23, -27, -30, -35, -36, -41,
  116557. -46, -44, -42, -40, -41, -41, -43, -48,
  116558. -55, -53, -52, -53, -56, -59, -58, -60,
  116559. -67, -66, -69, -71, -72, -75, -79, -81,
  116560. -84, -87, -90, -93, -97, -101, -107, -114,
  116561. -999, -999, -999, -999, -999, -999, -999, -999},
  116562. { -9, -9, -9, -9, -9, -9, -9, -9,
  116563. -11, -12, -12, -15, -16, -20, -23, -30,
  116564. -37, -34, -33, -34, -31, -32, -32, -38,
  116565. -47, -44, -41, -40, -47, -49, -46, -46,
  116566. -58, -50, -50, -54, -58, -62, -64, -67,
  116567. -67, -70, -72, -76, -79, -83, -87, -91,
  116568. -96, -100, -104, -110, -999, -999, -999, -999}},
  116569. /* 125 Hz */
  116570. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116571. -62, -62, -63, -64, -66, -67, -66, -68,
  116572. -75, -72, -76, -75, -76, -78, -79, -82,
  116573. -84, -85, -90, -94, -101, -110, -999, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999},
  116577. { -59, -59, -59, -59, -59, -59, -59, -59,
  116578. -59, -59, -59, -60, -60, -61, -63, -66,
  116579. -71, -68, -70, -70, -71, -72, -72, -75,
  116580. -81, -78, -79, -82, -83, -86, -90, -97,
  116581. -103, -113, -999, -999, -999, -999, -999, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999},
  116584. { -53, -53, -53, -53, -53, -53, -53, -53,
  116585. -53, -54, -55, -57, -56, -57, -55, -61,
  116586. -65, -60, -60, -62, -63, -63, -66, -68,
  116587. -74, -73, -75, -75, -78, -80, -80, -82,
  116588. -85, -90, -96, -101, -108, -999, -999, -999,
  116589. -999, -999, -999, -999, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999},
  116591. { -46, -46, -46, -46, -46, -46, -46, -46,
  116592. -46, -46, -47, -47, -47, -47, -48, -51,
  116593. -57, -51, -49, -50, -51, -53, -54, -59,
  116594. -66, -60, -62, -67, -67, -70, -72, -75,
  116595. -76, -78, -81, -85, -88, -94, -97, -104,
  116596. -112, -999, -999, -999, -999, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999},
  116598. { -36, -36, -36, -36, -36, -36, -36, -36,
  116599. -39, -41, -42, -42, -39, -38, -41, -43,
  116600. -52, -44, -40, -39, -37, -37, -40, -47,
  116601. -54, -50, -48, -50, -55, -61, -59, -62,
  116602. -66, -66, -66, -69, -69, -73, -74, -74,
  116603. -75, -77, -79, -82, -87, -91, -95, -100,
  116604. -108, -115, -999, -999, -999, -999, -999, -999},
  116605. { -28, -26, -24, -22, -20, -20, -23, -29,
  116606. -30, -31, -28, -27, -28, -28, -28, -35,
  116607. -40, -33, -32, -29, -30, -30, -30, -37,
  116608. -45, -41, -37, -38, -45, -47, -47, -48,
  116609. -53, -49, -48, -50, -49, -49, -51, -52,
  116610. -58, -56, -57, -56, -60, -61, -62, -70,
  116611. -72, -74, -78, -83, -88, -93, -100, -106}},
  116612. /* 177 Hz */
  116613. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116614. -999, -110, -105, -100, -95, -91, -87, -83,
  116615. -80, -78, -76, -78, -78, -81, -83, -85,
  116616. -86, -85, -86, -87, -90, -97, -107, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999},
  116620. {-999, -999, -999, -110, -105, -100, -95, -90,
  116621. -85, -81, -77, -73, -70, -67, -67, -68,
  116622. -75, -73, -70, -69, -70, -72, -75, -79,
  116623. -84, -83, -84, -86, -88, -89, -89, -93,
  116624. -98, -105, -112, -999, -999, -999, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. {-105, -100, -95, -90, -85, -80, -76, -71,
  116628. -68, -68, -65, -63, -63, -62, -62, -64,
  116629. -65, -64, -61, -62, -63, -64, -66, -68,
  116630. -73, -73, -74, -75, -76, -81, -83, -85,
  116631. -88, -89, -92, -95, -100, -108, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999},
  116634. { -80, -75, -71, -68, -65, -63, -62, -61,
  116635. -61, -61, -61, -59, -56, -57, -53, -50,
  116636. -58, -52, -50, -50, -52, -53, -54, -58,
  116637. -67, -63, -67, -68, -72, -75, -78, -80,
  116638. -81, -81, -82, -85, -89, -90, -93, -97,
  116639. -101, -107, -114, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999},
  116641. { -65, -61, -59, -57, -56, -55, -55, -56,
  116642. -56, -57, -55, -53, -52, -47, -44, -44,
  116643. -50, -44, -41, -39, -39, -42, -40, -46,
  116644. -51, -49, -50, -53, -54, -63, -60, -61,
  116645. -62, -66, -66, -66, -70, -73, -74, -75,
  116646. -76, -75, -79, -85, -89, -91, -96, -102,
  116647. -110, -999, -999, -999, -999, -999, -999, -999},
  116648. { -52, -50, -49, -49, -48, -48, -48, -49,
  116649. -50, -50, -49, -46, -43, -39, -35, -33,
  116650. -38, -36, -32, -29, -32, -32, -32, -35,
  116651. -44, -39, -38, -38, -46, -50, -45, -46,
  116652. -53, -50, -50, -50, -54, -54, -53, -53,
  116653. -56, -57, -59, -66, -70, -72, -74, -79,
  116654. -83, -85, -90, -97, -114, -999, -999, -999}},
  116655. /* 250 Hz */
  116656. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116657. -100, -95, -90, -86, -80, -75, -75, -79,
  116658. -80, -79, -80, -81, -82, -88, -95, -103,
  116659. -110, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. {-999, -999, -999, -999, -108, -103, -98, -93,
  116664. -88, -83, -79, -78, -75, -71, -67, -68,
  116665. -73, -73, -72, -73, -75, -77, -80, -82,
  116666. -88, -93, -100, -107, -114, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. {-999, -999, -999, -110, -105, -101, -96, -90,
  116671. -86, -81, -77, -73, -69, -66, -61, -62,
  116672. -66, -64, -62, -65, -66, -70, -72, -76,
  116673. -81, -80, -84, -90, -95, -102, -110, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999},
  116677. {-999, -999, -999, -107, -103, -97, -92, -88,
  116678. -83, -79, -74, -70, -66, -59, -53, -58,
  116679. -62, -55, -54, -54, -54, -58, -61, -62,
  116680. -72, -70, -72, -75, -78, -80, -81, -80,
  116681. -83, -83, -88, -93, -100, -107, -115, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999},
  116684. {-999, -999, -999, -105, -100, -95, -90, -85,
  116685. -80, -75, -70, -66, -62, -56, -48, -44,
  116686. -48, -46, -46, -43, -46, -48, -48, -51,
  116687. -58, -58, -59, -60, -62, -62, -61, -61,
  116688. -65, -64, -65, -68, -70, -74, -75, -78,
  116689. -81, -86, -95, -110, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999},
  116691. {-999, -999, -105, -100, -95, -90, -85, -80,
  116692. -75, -70, -65, -61, -55, -49, -39, -33,
  116693. -40, -35, -32, -38, -40, -33, -35, -37,
  116694. -46, -41, -45, -44, -46, -42, -45, -46,
  116695. -52, -50, -50, -50, -54, -54, -55, -57,
  116696. -62, -64, -66, -68, -70, -76, -81, -90,
  116697. -100, -110, -999, -999, -999, -999, -999, -999}},
  116698. /* 354 hz */
  116699. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116700. -105, -98, -90, -85, -82, -83, -80, -78,
  116701. -84, -79, -80, -83, -87, -89, -91, -93,
  116702. -99, -106, -117, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  116708. -74, -72, -74, -77, -80, -82, -85, -87,
  116709. -92, -89, -91, -95, -100, -106, -112, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999},
  116713. {-999, -999, -999, -999, -999, -999, -999, -999,
  116714. -105, -98, -90, -83, -75, -71, -63, -64,
  116715. -67, -62, -64, -67, -70, -73, -77, -81,
  116716. -84, -83, -85, -89, -90, -93, -98, -104,
  116717. -109, -114, -999, -999, -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. -103, -96, -88, -81, -75, -68, -58, -54,
  116722. -56, -54, -56, -56, -58, -60, -63, -66,
  116723. -74, -69, -72, -72, -75, -74, -77, -81,
  116724. -81, -82, -84, -87, -93, -96, -99, -104,
  116725. -110, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999},
  116727. {-999, -999, -999, -999, -999, -108, -102, -96,
  116728. -91, -85, -80, -74, -68, -60, -51, -46,
  116729. -48, -46, -43, -45, -47, -47, -49, -48,
  116730. -56, -53, -55, -58, -57, -63, -58, -60,
  116731. -66, -64, -67, -70, -70, -74, -77, -84,
  116732. -86, -89, -91, -93, -94, -101, -109, -118,
  116733. -999, -999, -999, -999, -999, -999, -999, -999},
  116734. {-999, -999, -999, -108, -103, -98, -93, -88,
  116735. -83, -78, -73, -68, -60, -53, -44, -35,
  116736. -38, -38, -34, -34, -36, -40, -41, -44,
  116737. -51, -45, -46, -47, -46, -54, -50, -49,
  116738. -50, -50, -50, -51, -54, -57, -58, -60,
  116739. -66, -66, -66, -64, -65, -68, -77, -82,
  116740. -87, -95, -110, -999, -999, -999, -999, -999}},
  116741. /* 500 Hz */
  116742. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116743. -107, -102, -97, -92, -87, -83, -78, -75,
  116744. -82, -79, -83, -85, -89, -92, -95, -98,
  116745. -101, -105, -109, -113, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999},
  116749. {-999, -999, -999, -999, -999, -999, -999, -106,
  116750. -100, -95, -90, -86, -81, -78, -74, -69,
  116751. -74, -74, -76, -79, -83, -84, -86, -89,
  116752. -92, -97, -93, -100, -103, -107, -110, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999},
  116756. {-999, -999, -999, -999, -999, -999, -106, -100,
  116757. -95, -90, -87, -83, -80, -75, -69, -60,
  116758. -66, -66, -68, -70, -74, -78, -79, -81,
  116759. -81, -83, -84, -87, -93, -96, -99, -103,
  116760. -107, -110, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999},
  116763. {-999, -999, -999, -999, -999, -108, -103, -98,
  116764. -93, -89, -85, -82, -78, -71, -62, -55,
  116765. -58, -58, -54, -54, -55, -59, -61, -62,
  116766. -70, -66, -66, -67, -70, -72, -75, -78,
  116767. -84, -84, -84, -88, -91, -90, -95, -98,
  116768. -102, -103, -106, -110, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999},
  116770. {-999, -999, -999, -999, -108, -103, -98, -94,
  116771. -90, -87, -82, -79, -73, -67, -58, -47,
  116772. -50, -45, -41, -45, -48, -44, -44, -49,
  116773. -54, -51, -48, -47, -49, -50, -51, -57,
  116774. -58, -60, -63, -69, -70, -69, -71, -74,
  116775. -78, -82, -90, -95, -101, -105, -110, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999},
  116777. {-999, -999, -999, -105, -101, -97, -93, -90,
  116778. -85, -80, -77, -72, -65, -56, -48, -37,
  116779. -40, -36, -34, -40, -50, -47, -38, -41,
  116780. -47, -38, -35, -39, -38, -43, -40, -45,
  116781. -50, -45, -44, -47, -50, -55, -48, -48,
  116782. -52, -66, -70, -76, -82, -90, -97, -105,
  116783. -110, -999, -999, -999, -999, -999, -999, -999}},
  116784. /* 707 Hz */
  116785. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116786. -999, -108, -103, -98, -93, -86, -79, -76,
  116787. -83, -81, -85, -87, -89, -93, -98, -102,
  116788. -107, -112, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999},
  116792. {-999, -999, -999, -999, -999, -999, -999, -999,
  116793. -999, -108, -103, -98, -93, -86, -79, -71,
  116794. -77, -74, -77, -79, -81, -84, -85, -90,
  116795. -92, -93, -92, -98, -101, -108, -112, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999},
  116799. {-999, -999, -999, -999, -999, -999, -999, -999,
  116800. -108, -103, -98, -93, -87, -78, -68, -65,
  116801. -66, -62, -65, -67, -70, -73, -75, -78,
  116802. -82, -82, -83, -84, -91, -93, -98, -102,
  116803. -106, -110, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999},
  116806. {-999, -999, -999, -999, -999, -999, -999, -999,
  116807. -105, -100, -95, -90, -82, -74, -62, -57,
  116808. -58, -56, -51, -52, -52, -54, -54, -58,
  116809. -66, -59, -60, -63, -66, -69, -73, -79,
  116810. -83, -84, -80, -81, -81, -82, -88, -92,
  116811. -98, -105, -113, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999},
  116813. {-999, -999, -999, -999, -999, -999, -999, -107,
  116814. -102, -97, -92, -84, -79, -69, -57, -47,
  116815. -52, -47, -44, -45, -50, -52, -42, -42,
  116816. -53, -43, -43, -48, -51, -56, -55, -52,
  116817. -57, -59, -61, -62, -67, -71, -78, -83,
  116818. -86, -94, -98, -103, -110, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999},
  116820. {-999, -999, -999, -999, -999, -999, -105, -100,
  116821. -95, -90, -84, -78, -70, -61, -51, -41,
  116822. -40, -38, -40, -46, -52, -51, -41, -40,
  116823. -46, -40, -38, -38, -41, -46, -41, -46,
  116824. -47, -43, -43, -45, -41, -45, -56, -67,
  116825. -68, -83, -87, -90, -95, -102, -107, -113,
  116826. -999, -999, -999, -999, -999, -999, -999, -999}},
  116827. /* 1000 Hz */
  116828. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -109, -105, -101, -96, -91, -84, -77,
  116830. -82, -82, -85, -89, -94, -100, -106, -110,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999},
  116835. {-999, -999, -999, -999, -999, -999, -999, -999,
  116836. -999, -106, -103, -98, -92, -85, -80, -71,
  116837. -75, -72, -76, -80, -84, -86, -89, -93,
  116838. -100, -107, -113, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999},
  116842. {-999, -999, -999, -999, -999, -999, -999, -107,
  116843. -104, -101, -97, -92, -88, -84, -80, -64,
  116844. -66, -63, -64, -66, -69, -73, -77, -83,
  116845. -83, -86, -91, -98, -104, -111, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999},
  116849. {-999, -999, -999, -999, -999, -999, -999, -107,
  116850. -104, -101, -97, -92, -90, -84, -74, -57,
  116851. -58, -52, -55, -54, -50, -52, -50, -52,
  116852. -63, -62, -69, -76, -77, -78, -78, -79,
  116853. -82, -88, -94, -100, -106, -111, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999},
  116856. {-999, -999, -999, -999, -999, -999, -106, -102,
  116857. -98, -95, -90, -85, -83, -78, -70, -50,
  116858. -50, -41, -44, -49, -47, -50, -50, -44,
  116859. -55, -46, -47, -48, -48, -54, -49, -49,
  116860. -58, -62, -71, -81, -87, -92, -97, -102,
  116861. -108, -114, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999},
  116863. {-999, -999, -999, -999, -999, -999, -106, -102,
  116864. -98, -95, -90, -85, -83, -78, -70, -45,
  116865. -43, -41, -47, -50, -51, -50, -49, -45,
  116866. -47, -41, -44, -41, -39, -43, -38, -37,
  116867. -40, -41, -44, -50, -58, -65, -73, -79,
  116868. -85, -92, -97, -101, -105, -109, -113, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999}},
  116870. /* 1414 Hz */
  116871. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -999, -999, -107, -100, -95, -87, -81,
  116873. -85, -83, -88, -93, -100, -107, -114, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999},
  116878. {-999, -999, -999, -999, -999, -999, -999, -999,
  116879. -999, -999, -107, -101, -95, -88, -83, -76,
  116880. -73, -72, -79, -84, -90, -95, -100, -105,
  116881. -110, -115, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999},
  116885. {-999, -999, -999, -999, -999, -999, -999, -999,
  116886. -999, -999, -104, -98, -92, -87, -81, -70,
  116887. -65, -62, -67, -71, -74, -80, -85, -91,
  116888. -95, -99, -103, -108, -111, -114, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999},
  116892. {-999, -999, -999, -999, -999, -999, -999, -999,
  116893. -999, -999, -103, -97, -90, -85, -76, -60,
  116894. -56, -54, -60, -62, -61, -56, -63, -65,
  116895. -73, -74, -77, -75, -78, -81, -86, -87,
  116896. -88, -91, -94, -98, -103, -110, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999},
  116899. {-999, -999, -999, -999, -999, -999, -999, -105,
  116900. -100, -97, -92, -86, -81, -79, -70, -57,
  116901. -51, -47, -51, -58, -60, -56, -53, -50,
  116902. -58, -52, -50, -50, -53, -55, -64, -69,
  116903. -71, -85, -82, -78, -81, -85, -95, -102,
  116904. -112, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999},
  116906. {-999, -999, -999, -999, -999, -999, -999, -105,
  116907. -100, -97, -92, -85, -83, -79, -72, -49,
  116908. -40, -43, -43, -54, -56, -51, -50, -40,
  116909. -43, -38, -36, -35, -37, -38, -37, -44,
  116910. -54, -60, -57, -60, -70, -75, -84, -92,
  116911. -103, -112, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999}},
  116913. /* 2000 Hz */
  116914. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -999, -110, -102, -95, -89, -82,
  116916. -83, -84, -90, -92, -99, -107, -113, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -999, -999, -999, -999},
  116921. {-999, -999, -999, -999, -999, -999, -999, -999,
  116922. -999, -999, -107, -101, -95, -89, -83, -72,
  116923. -74, -78, -85, -88, -88, -90, -92, -98,
  116924. -105, -111, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999},
  116928. {-999, -999, -999, -999, -999, -999, -999, -999,
  116929. -999, -109, -103, -97, -93, -87, -81, -70,
  116930. -70, -67, -75, -73, -76, -79, -81, -83,
  116931. -88, -89, -97, -103, -110, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999},
  116935. {-999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -107, -100, -94, -88, -83, -75, -63,
  116937. -59, -59, -63, -66, -60, -62, -67, -67,
  116938. -77, -76, -81, -88, -86, -92, -96, -102,
  116939. -109, -116, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999},
  116942. {-999, -999, -999, -999, -999, -999, -999, -999,
  116943. -999, -105, -98, -92, -86, -81, -73, -56,
  116944. -52, -47, -55, -60, -58, -52, -51, -45,
  116945. -49, -50, -53, -54, -61, -71, -70, -69,
  116946. -78, -79, -87, -90, -96, -104, -112, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999},
  116949. {-999, -999, -999, -999, -999, -999, -999, -999,
  116950. -999, -103, -96, -90, -86, -78, -70, -51,
  116951. -42, -47, -48, -55, -54, -54, -53, -42,
  116952. -35, -28, -33, -38, -37, -44, -47, -49,
  116953. -54, -63, -68, -78, -82, -89, -94, -99,
  116954. -104, -109, -114, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999}},
  116956. /* 2828 Hz */
  116957. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -999, -110, -100, -90, -79,
  116959. -85, -81, -82, -82, -89, -94, -99, -103,
  116960. -109, -115, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999},
  116964. {-999, -999, -999, -999, -999, -999, -999, -999,
  116965. -999, -999, -999, -999, -105, -97, -85, -72,
  116966. -74, -70, -70, -70, -76, -85, -91, -93,
  116967. -97, -103, -109, -115, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999},
  116971. {-999, -999, -999, -999, -999, -999, -999, -999,
  116972. -999, -999, -999, -999, -112, -93, -81, -68,
  116973. -62, -60, -60, -57, -63, -70, -77, -82,
  116974. -90, -93, -98, -104, -109, -113, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999},
  116978. {-999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -999, -999, -113, -100, -93, -84, -63,
  116980. -58, -48, -53, -54, -52, -52, -57, -64,
  116981. -66, -76, -83, -81, -85, -85, -90, -95,
  116982. -98, -101, -103, -106, -108, -111, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999},
  116985. {-999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -999, -999, -105, -95, -86, -74, -53,
  116987. -50, -38, -43, -49, -43, -42, -39, -39,
  116988. -46, -52, -57, -56, -72, -69, -74, -81,
  116989. -87, -92, -94, -97, -99, -102, -105, -108,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999},
  116992. {-999, -999, -999, -999, -999, -999, -999, -999,
  116993. -999, -999, -108, -99, -90, -76, -66, -45,
  116994. -43, -41, -44, -47, -43, -47, -40, -30,
  116995. -31, -31, -39, -33, -40, -41, -43, -53,
  116996. -59, -70, -73, -77, -79, -82, -84, -87,
  116997. -999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999}},
  116999. /* 4000 Hz */
  117000. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -999, -110, -91, -76,
  117002. -75, -85, -93, -98, -104, -110, -999, -999,
  117003. -999, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999},
  117007. {-999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -999, -110, -91, -70,
  117009. -70, -75, -86, -89, -94, -98, -101, -106,
  117010. -110, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999},
  117014. {-999, -999, -999, -999, -999, -999, -999, -999,
  117015. -999, -999, -999, -999, -110, -95, -80, -60,
  117016. -65, -64, -74, -83, -88, -91, -95, -99,
  117017. -103, -107, -110, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999},
  117021. {-999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -999, -110, -95, -80, -58,
  117023. -55, -49, -66, -68, -71, -78, -78, -80,
  117024. -88, -85, -89, -97, -100, -105, -110, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999},
  117028. {-999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -999, -999, -110, -95, -80, -53,
  117030. -52, -41, -59, -59, -49, -58, -56, -63,
  117031. -86, -79, -90, -93, -98, -103, -107, -112,
  117032. -999, -999, -999, -999, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999},
  117035. {-999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -999, -110, -97, -91, -73, -45,
  117037. -40, -33, -53, -61, -49, -54, -50, -50,
  117038. -60, -52, -67, -74, -81, -92, -96, -100,
  117039. -105, -110, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999}},
  117042. /* 5657 Hz */
  117043. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -113, -106, -99, -92, -77,
  117045. -80, -88, -97, -106, -115, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999},
  117050. {-999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -999, -116, -109, -102, -95, -89, -74,
  117052. -72, -88, -87, -95, -102, -109, -116, -999,
  117053. -999, -999, -999, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999},
  117057. {-999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -999, -116, -109, -102, -95, -89, -75,
  117059. -66, -74, -77, -78, -86, -87, -90, -96,
  117060. -105, -115, -999, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999,
  117062. -999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -999, -999, -999},
  117064. {-999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -115, -108, -101, -94, -88, -66,
  117066. -56, -61, -70, -65, -78, -72, -83, -84,
  117067. -93, -98, -105, -110, -999, -999, -999, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999,
  117069. -999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999},
  117071. {-999, -999, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -110, -105, -95, -89, -82, -57,
  117073. -52, -52, -59, -56, -59, -58, -69, -67,
  117074. -88, -82, -82, -89, -94, -100, -108, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999},
  117078. {-999, -999, -999, -999, -999, -999, -999, -999,
  117079. -999, -110, -101, -96, -90, -83, -77, -54,
  117080. -43, -38, -50, -48, -52, -48, -42, -42,
  117081. -51, -52, -53, -59, -65, -71, -78, -85,
  117082. -95, -999, -999, -999, -999, -999, -999, -999,
  117083. -999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999}},
  117085. /* 8000 Hz */
  117086. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -999, -999, -120, -105, -86, -68,
  117088. -78, -79, -90, -100, -110, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -999, -999, -999, -999},
  117093. {-999, -999, -999, -999, -999, -999, -999, -999,
  117094. -999, -999, -999, -999, -120, -105, -86, -66,
  117095. -73, -77, -88, -96, -105, -115, -999, -999,
  117096. -999, -999, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -999, -999, -999, -999},
  117100. {-999, -999, -999, -999, -999, -999, -999, -999,
  117101. -999, -999, -999, -120, -105, -92, -80, -61,
  117102. -64, -68, -80, -87, -92, -100, -110, -999,
  117103. -999, -999, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999,
  117105. -999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -999, -999, -999, -999},
  117107. {-999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -999, -120, -104, -91, -79, -52,
  117109. -60, -54, -64, -69, -77, -80, -82, -84,
  117110. -85, -87, -88, -90, -999, -999, -999, -999,
  117111. -999, -999, -999, -999, -999, -999, -999, -999,
  117112. -999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -999, -999, -999, -999, -999, -999},
  117114. {-999, -999, -999, -999, -999, -999, -999, -999,
  117115. -999, -999, -999, -118, -100, -87, -77, -49,
  117116. -50, -44, -58, -61, -61, -67, -65, -62,
  117117. -62, -62, -65, -68, -999, -999, -999, -999,
  117118. -999, -999, -999, -999, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -999, -999, -999, -999, -999, -999},
  117121. {-999, -999, -999, -999, -999, -999, -999, -999,
  117122. -999, -999, -999, -115, -98, -84, -62, -49,
  117123. -44, -38, -46, -49, -49, -46, -39, -37,
  117124. -39, -40, -42, -43, -999, -999, -999, -999,
  117125. -999, -999, -999, -999, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -999, -999, -999, -999, -999, -999}},
  117128. /* 11314 Hz */
  117129. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -999, -110, -88, -74,
  117131. -77, -82, -82, -85, -90, -94, -99, -104,
  117132. -999, -999, -999, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999},
  117136. {-999, -999, -999, -999, -999, -999, -999, -999,
  117137. -999, -999, -999, -999, -999, -110, -88, -66,
  117138. -70, -81, -80, -81, -84, -88, -91, -93,
  117139. -999, -999, -999, -999, -999, -999, -999, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -999, -999, -999, -999, -999},
  117143. {-999, -999, -999, -999, -999, -999, -999, -999,
  117144. -999, -999, -999, -999, -999, -110, -88, -61,
  117145. -63, -70, -71, -74, -77, -80, -83, -85,
  117146. -999, -999, -999, -999, -999, -999, -999, -999,
  117147. -999, -999, -999, -999, -999, -999, -999, -999,
  117148. -999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -999, -999, -999, -999, -999},
  117150. {-999, -999, -999, -999, -999, -999, -999, -999,
  117151. -999, -999, -999, -999, -999, -110, -86, -62,
  117152. -63, -62, -62, -58, -52, -50, -50, -52,
  117153. -54, -999, -999, -999, -999, -999, -999, -999,
  117154. -999, -999, -999, -999, -999, -999, -999, -999,
  117155. -999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -999, -999, -999, -999, -999},
  117157. {-999, -999, -999, -999, -999, -999, -999, -999,
  117158. -999, -999, -999, -999, -118, -108, -84, -53,
  117159. -50, -50, -50, -55, -47, -45, -40, -40,
  117160. -40, -999, -999, -999, -999, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999,
  117162. -999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -999, -999, -999, -999, -999},
  117164. {-999, -999, -999, -999, -999, -999, -999, -999,
  117165. -999, -999, -999, -999, -118, -100, -73, -43,
  117166. -37, -42, -43, -53, -38, -37, -35, -35,
  117167. -38, -999, -999, -999, -999, -999, -999, -999,
  117168. -999, -999, -999, -999, -999, -999, -999, -999,
  117169. -999, -999, -999, -999, -999, -999, -999, -999,
  117170. -999, -999, -999, -999, -999, -999, -999, -999}},
  117171. /* 16000 Hz */
  117172. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117173. -999, -999, -999, -110, -100, -91, -84, -74,
  117174. -80, -80, -80, -80, -80, -999, -999, -999,
  117175. -999, -999, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -999, -999, -999,
  117177. -999, -999, -999, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -999, -999, -999, -999, -999},
  117179. {-999, -999, -999, -999, -999, -999, -999, -999,
  117180. -999, -999, -999, -110, -100, -91, -84, -74,
  117181. -68, -68, -68, -68, -68, -999, -999, -999,
  117182. -999, -999, -999, -999, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -999, -999, -999,
  117184. -999, -999, -999, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -999, -999, -999, -999, -999},
  117186. {-999, -999, -999, -999, -999, -999, -999, -999,
  117187. -999, -999, -999, -110, -100, -86, -78, -70,
  117188. -60, -45, -30, -21, -999, -999, -999, -999,
  117189. -999, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999,
  117191. -999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -999, -999, -999},
  117193. {-999, -999, -999, -999, -999, -999, -999, -999,
  117194. -999, -999, -999, -110, -100, -87, -78, -67,
  117195. -48, -38, -29, -21, -999, -999, -999, -999,
  117196. -999, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -999, -999, -999, -999,
  117198. -999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -999, -999, -999, -999},
  117200. {-999, -999, -999, -999, -999, -999, -999, -999,
  117201. -999, -999, -999, -110, -100, -86, -69, -56,
  117202. -45, -35, -33, -29, -999, -999, -999, -999,
  117203. -999, -999, -999, -999, -999, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999,
  117205. -999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -999, -999, -999, -999},
  117207. {-999, -999, -999, -999, -999, -999, -999, -999,
  117208. -999, -999, -999, -110, -100, -83, -71, -48,
  117209. -27, -38, -37, -34, -999, -999, -999, -999,
  117210. -999, -999, -999, -999, -999, -999, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999,
  117212. -999, -999, -999, -999, -999, -999, -999, -999,
  117213. -999, -999, -999, -999, -999, -999, -999, -999}}
  117214. };
  117215. #endif
  117216. /*** End of inlined file: masking.h ***/
  117217. #define NEGINF -9999.f
  117218. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117219. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117220. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117221. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117222. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117223. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117224. look->channels=vi->channels;
  117225. look->ampmax=-9999.;
  117226. look->gi=gi;
  117227. return(look);
  117228. }
  117229. void _vp_global_free(vorbis_look_psy_global *look){
  117230. if(look){
  117231. memset(look,0,sizeof(*look));
  117232. _ogg_free(look);
  117233. }
  117234. }
  117235. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117236. if(i){
  117237. memset(i,0,sizeof(*i));
  117238. _ogg_free(i);
  117239. }
  117240. }
  117241. void _vi_psy_free(vorbis_info_psy *i){
  117242. if(i){
  117243. memset(i,0,sizeof(*i));
  117244. _ogg_free(i);
  117245. }
  117246. }
  117247. static void min_curve(float *c,
  117248. float *c2){
  117249. int i;
  117250. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117251. }
  117252. static void max_curve(float *c,
  117253. float *c2){
  117254. int i;
  117255. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117256. }
  117257. static void attenuate_curve(float *c,float att){
  117258. int i;
  117259. for(i=0;i<EHMER_MAX;i++)
  117260. c[i]+=att;
  117261. }
  117262. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117263. float center_boost, float center_decay_rate){
  117264. int i,j,k,m;
  117265. float ath[EHMER_MAX];
  117266. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117267. float athc[P_LEVELS][EHMER_MAX];
  117268. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117269. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117270. memset(workc,0,sizeof(workc));
  117271. for(i=0;i<P_BANDS;i++){
  117272. /* we add back in the ATH to avoid low level curves falling off to
  117273. -infinity and unnecessarily cutting off high level curves in the
  117274. curve limiting (last step). */
  117275. /* A half-band's settings must be valid over the whole band, and
  117276. it's better to mask too little than too much */
  117277. int ath_offset=i*4;
  117278. for(j=0;j<EHMER_MAX;j++){
  117279. float min=999.;
  117280. for(k=0;k<4;k++)
  117281. if(j+k+ath_offset<MAX_ATH){
  117282. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117283. }else{
  117284. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117285. }
  117286. ath[j]=min;
  117287. }
  117288. /* copy curves into working space, replicate the 50dB curve to 30
  117289. and 40, replicate the 100dB curve to 110 */
  117290. for(j=0;j<6;j++)
  117291. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117292. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117293. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117294. /* apply centered curve boost/decay */
  117295. for(j=0;j<P_LEVELS;j++){
  117296. for(k=0;k<EHMER_MAX;k++){
  117297. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117298. if(adj<0. && center_boost>0)adj=0.;
  117299. if(adj>0. && center_boost<0)adj=0.;
  117300. workc[i][j][k]+=adj;
  117301. }
  117302. }
  117303. /* normalize curves so the driving amplitude is 0dB */
  117304. /* make temp curves with the ATH overlayed */
  117305. for(j=0;j<P_LEVELS;j++){
  117306. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117307. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117308. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117309. max_curve(athc[j],workc[i][j]);
  117310. }
  117311. /* Now limit the louder curves.
  117312. the idea is this: We don't know what the playback attenuation
  117313. will be; 0dB SL moves every time the user twiddles the volume
  117314. knob. So that means we have to use a single 'most pessimal' curve
  117315. for all masking amplitudes, right? Wrong. The *loudest* sound
  117316. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117317. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117318. etc... */
  117319. for(j=1;j<P_LEVELS;j++){
  117320. min_curve(athc[j],athc[j-1]);
  117321. min_curve(workc[i][j],athc[j]);
  117322. }
  117323. }
  117324. for(i=0;i<P_BANDS;i++){
  117325. int hi_curve,lo_curve,bin;
  117326. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117327. /* low frequency curves are measured with greater resolution than
  117328. the MDCT/FFT will actually give us; we want the curve applied
  117329. to the tone data to be pessimistic and thus apply the minimum
  117330. masking possible for a given bin. That means that a single bin
  117331. could span more than one octave and that the curve will be a
  117332. composite of multiple octaves. It also may mean that a single
  117333. bin may span > an eighth of an octave and that the eighth
  117334. octave values may also be composited. */
  117335. /* which octave curves will we be compositing? */
  117336. bin=floor(fromOC(i*.5)/binHz);
  117337. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117338. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117339. if(lo_curve>i)lo_curve=i;
  117340. if(lo_curve<0)lo_curve=0;
  117341. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117342. for(m=0;m<P_LEVELS;m++){
  117343. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117344. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117345. /* render the curve into bins, then pull values back into curve.
  117346. The point is that any inherent subsampling aliasing results in
  117347. a safe minimum */
  117348. for(k=lo_curve;k<=hi_curve;k++){
  117349. int l=0;
  117350. for(j=0;j<EHMER_MAX;j++){
  117351. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117352. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117353. if(lo_bin<0)lo_bin=0;
  117354. if(lo_bin>n)lo_bin=n;
  117355. if(lo_bin<l)l=lo_bin;
  117356. if(hi_bin<0)hi_bin=0;
  117357. if(hi_bin>n)hi_bin=n;
  117358. for(;l<hi_bin && l<n;l++)
  117359. if(brute_buffer[l]>workc[k][m][j])
  117360. brute_buffer[l]=workc[k][m][j];
  117361. }
  117362. for(;l<n;l++)
  117363. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117364. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117365. }
  117366. /* be equally paranoid about being valid up to next half ocatve */
  117367. if(i+1<P_BANDS){
  117368. int l=0;
  117369. k=i+1;
  117370. for(j=0;j<EHMER_MAX;j++){
  117371. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117372. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117373. if(lo_bin<0)lo_bin=0;
  117374. if(lo_bin>n)lo_bin=n;
  117375. if(lo_bin<l)l=lo_bin;
  117376. if(hi_bin<0)hi_bin=0;
  117377. if(hi_bin>n)hi_bin=n;
  117378. for(;l<hi_bin && l<n;l++)
  117379. if(brute_buffer[l]>workc[k][m][j])
  117380. brute_buffer[l]=workc[k][m][j];
  117381. }
  117382. for(;l<n;l++)
  117383. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117384. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117385. }
  117386. for(j=0;j<EHMER_MAX;j++){
  117387. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117388. if(bin<0){
  117389. ret[i][m][j+2]=-999.;
  117390. }else{
  117391. if(bin>=n){
  117392. ret[i][m][j+2]=-999.;
  117393. }else{
  117394. ret[i][m][j+2]=brute_buffer[bin];
  117395. }
  117396. }
  117397. }
  117398. /* add fenceposts */
  117399. for(j=0;j<EHMER_OFFSET;j++)
  117400. if(ret[i][m][j+2]>-200.f)break;
  117401. ret[i][m][0]=j;
  117402. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117403. if(ret[i][m][j+2]>-200.f)
  117404. break;
  117405. ret[i][m][1]=j;
  117406. }
  117407. }
  117408. return(ret);
  117409. }
  117410. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117411. vorbis_info_psy_global *gi,int n,long rate){
  117412. long i,j,lo=-99,hi=1;
  117413. long maxoc;
  117414. memset(p,0,sizeof(*p));
  117415. p->eighth_octave_lines=gi->eighth_octave_lines;
  117416. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117417. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117418. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117419. p->total_octave_lines=maxoc-p->firstoc+1;
  117420. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117421. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117422. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117423. p->vi=vi;
  117424. p->n=n;
  117425. p->rate=rate;
  117426. /* AoTuV HF weighting */
  117427. p->m_val = 1.;
  117428. if(rate < 26000) p->m_val = 0;
  117429. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117430. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117431. /* set up the lookups for a given blocksize and sample rate */
  117432. for(i=0,j=0;i<MAX_ATH-1;i++){
  117433. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117434. float base=ATH[i];
  117435. if(j<endpos){
  117436. float delta=(ATH[i+1]-base)/(endpos-j);
  117437. for(;j<endpos && j<n;j++){
  117438. p->ath[j]=base+100.;
  117439. base+=delta;
  117440. }
  117441. }
  117442. }
  117443. for(i=0;i<n;i++){
  117444. float bark=toBARK(rate/(2*n)*i);
  117445. for(;lo+vi->noisewindowlomin<i &&
  117446. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117447. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117448. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117449. p->bark[i]=((lo-1)<<16)+(hi-1);
  117450. }
  117451. for(i=0;i<n;i++)
  117452. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117453. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117454. vi->tone_centerboost,vi->tone_decay);
  117455. /* set up rolling noise median */
  117456. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117457. for(i=0;i<P_NOISECURVES;i++)
  117458. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117459. for(i=0;i<n;i++){
  117460. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117461. int inthalfoc;
  117462. float del;
  117463. if(halfoc<0)halfoc=0;
  117464. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117465. inthalfoc=(int)halfoc;
  117466. del=halfoc-inthalfoc;
  117467. for(j=0;j<P_NOISECURVES;j++)
  117468. p->noiseoffset[j][i]=
  117469. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117470. p->vi->noiseoff[j][inthalfoc+1]*del;
  117471. }
  117472. #if 0
  117473. {
  117474. static int ls=0;
  117475. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117476. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117477. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117478. }
  117479. #endif
  117480. }
  117481. void _vp_psy_clear(vorbis_look_psy *p){
  117482. int i,j;
  117483. if(p){
  117484. if(p->ath)_ogg_free(p->ath);
  117485. if(p->octave)_ogg_free(p->octave);
  117486. if(p->bark)_ogg_free(p->bark);
  117487. if(p->tonecurves){
  117488. for(i=0;i<P_BANDS;i++){
  117489. for(j=0;j<P_LEVELS;j++){
  117490. _ogg_free(p->tonecurves[i][j]);
  117491. }
  117492. _ogg_free(p->tonecurves[i]);
  117493. }
  117494. _ogg_free(p->tonecurves);
  117495. }
  117496. if(p->noiseoffset){
  117497. for(i=0;i<P_NOISECURVES;i++){
  117498. _ogg_free(p->noiseoffset[i]);
  117499. }
  117500. _ogg_free(p->noiseoffset);
  117501. }
  117502. memset(p,0,sizeof(*p));
  117503. }
  117504. }
  117505. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117506. static void seed_curve(float *seed,
  117507. const float **curves,
  117508. float amp,
  117509. int oc, int n,
  117510. int linesper,float dBoffset){
  117511. int i,post1;
  117512. int seedptr;
  117513. const float *posts,*curve;
  117514. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117515. choice=max(choice,0);
  117516. choice=min(choice,P_LEVELS-1);
  117517. posts=curves[choice];
  117518. curve=posts+2;
  117519. post1=(int)posts[1];
  117520. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117521. for(i=posts[0];i<post1;i++){
  117522. if(seedptr>0){
  117523. float lin=amp+curve[i];
  117524. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117525. }
  117526. seedptr+=linesper;
  117527. if(seedptr>=n)break;
  117528. }
  117529. }
  117530. static void seed_loop(vorbis_look_psy *p,
  117531. const float ***curves,
  117532. const float *f,
  117533. const float *flr,
  117534. float *seed,
  117535. float specmax){
  117536. vorbis_info_psy *vi=p->vi;
  117537. long n=p->n,i;
  117538. float dBoffset=vi->max_curve_dB-specmax;
  117539. /* prime the working vector with peak values */
  117540. for(i=0;i<n;i++){
  117541. float max=f[i];
  117542. long oc=p->octave[i];
  117543. while(i+1<n && p->octave[i+1]==oc){
  117544. i++;
  117545. if(f[i]>max)max=f[i];
  117546. }
  117547. if(max+6.f>flr[i]){
  117548. oc=oc>>p->shiftoc;
  117549. if(oc>=P_BANDS)oc=P_BANDS-1;
  117550. if(oc<0)oc=0;
  117551. seed_curve(seed,
  117552. curves[oc],
  117553. max,
  117554. p->octave[i]-p->firstoc,
  117555. p->total_octave_lines,
  117556. p->eighth_octave_lines,
  117557. dBoffset);
  117558. }
  117559. }
  117560. }
  117561. static void seed_chase(float *seeds, int linesper, long n){
  117562. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117563. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117564. long stack=0;
  117565. long pos=0;
  117566. long i;
  117567. for(i=0;i<n;i++){
  117568. if(stack<2){
  117569. posstack[stack]=i;
  117570. ampstack[stack++]=seeds[i];
  117571. }else{
  117572. while(1){
  117573. if(seeds[i]<ampstack[stack-1]){
  117574. posstack[stack]=i;
  117575. ampstack[stack++]=seeds[i];
  117576. break;
  117577. }else{
  117578. if(i<posstack[stack-1]+linesper){
  117579. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117580. i<posstack[stack-2]+linesper){
  117581. /* we completely overlap, making stack-1 irrelevant. pop it */
  117582. stack--;
  117583. continue;
  117584. }
  117585. }
  117586. posstack[stack]=i;
  117587. ampstack[stack++]=seeds[i];
  117588. break;
  117589. }
  117590. }
  117591. }
  117592. }
  117593. /* the stack now contains only the positions that are relevant. Scan
  117594. 'em straight through */
  117595. for(i=0;i<stack;i++){
  117596. long endpos;
  117597. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117598. endpos=posstack[i+1];
  117599. }else{
  117600. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117601. discarded in short frames */
  117602. }
  117603. if(endpos>n)endpos=n;
  117604. for(;pos<endpos;pos++)
  117605. seeds[pos]=ampstack[i];
  117606. }
  117607. /* there. Linear time. I now remember this was on a problem set I
  117608. had in Grad Skool... I didn't solve it at the time ;-) */
  117609. }
  117610. /* bleaugh, this is more complicated than it needs to be */
  117611. #include<stdio.h>
  117612. static void max_seeds(vorbis_look_psy *p,
  117613. float *seed,
  117614. float *flr){
  117615. long n=p->total_octave_lines;
  117616. int linesper=p->eighth_octave_lines;
  117617. long linpos=0;
  117618. long pos;
  117619. seed_chase(seed,linesper,n); /* for masking */
  117620. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117621. while(linpos+1<p->n){
  117622. float minV=seed[pos];
  117623. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117624. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117625. while(pos+1<=end){
  117626. pos++;
  117627. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117628. minV=seed[pos];
  117629. }
  117630. end=pos+p->firstoc;
  117631. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117632. if(flr[linpos]<minV)flr[linpos]=minV;
  117633. }
  117634. {
  117635. float minV=seed[p->total_octave_lines-1];
  117636. for(;linpos<p->n;linpos++)
  117637. if(flr[linpos]<minV)flr[linpos]=minV;
  117638. }
  117639. }
  117640. static void bark_noise_hybridmp(int n,const long *b,
  117641. const float *f,
  117642. float *noise,
  117643. const float offset,
  117644. const int fixed){
  117645. float *N=(float*) alloca(n*sizeof(*N));
  117646. float *X=(float*) alloca(n*sizeof(*N));
  117647. float *XX=(float*) alloca(n*sizeof(*N));
  117648. float *Y=(float*) alloca(n*sizeof(*N));
  117649. float *XY=(float*) alloca(n*sizeof(*N));
  117650. float tN, tX, tXX, tY, tXY;
  117651. int i;
  117652. int lo, hi;
  117653. float R, A, B, D;
  117654. float w, x, y;
  117655. tN = tX = tXX = tY = tXY = 0.f;
  117656. y = f[0] + offset;
  117657. if (y < 1.f) y = 1.f;
  117658. w = y * y * .5;
  117659. tN += w;
  117660. tX += w;
  117661. tY += w * y;
  117662. N[0] = tN;
  117663. X[0] = tX;
  117664. XX[0] = tXX;
  117665. Y[0] = tY;
  117666. XY[0] = tXY;
  117667. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117668. y = f[i] + offset;
  117669. if (y < 1.f) y = 1.f;
  117670. w = y * y;
  117671. tN += w;
  117672. tX += w * x;
  117673. tXX += w * x * x;
  117674. tY += w * y;
  117675. tXY += w * x * y;
  117676. N[i] = tN;
  117677. X[i] = tX;
  117678. XX[i] = tXX;
  117679. Y[i] = tY;
  117680. XY[i] = tXY;
  117681. }
  117682. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117683. lo = b[i] >> 16;
  117684. if( lo>=0 ) break;
  117685. hi = b[i] & 0xffff;
  117686. tN = N[hi] + N[-lo];
  117687. tX = X[hi] - X[-lo];
  117688. tXX = XX[hi] + XX[-lo];
  117689. tY = Y[hi] + Y[-lo];
  117690. tXY = XY[hi] - XY[-lo];
  117691. A = tY * tXX - tX * tXY;
  117692. B = tN * tXY - tX * tY;
  117693. D = tN * tXX - tX * tX;
  117694. R = (A + x * B) / D;
  117695. if (R < 0.f)
  117696. R = 0.f;
  117697. noise[i] = R - offset;
  117698. }
  117699. for ( ;; i++, x += 1.f) {
  117700. lo = b[i] >> 16;
  117701. hi = b[i] & 0xffff;
  117702. if(hi>=n)break;
  117703. tN = N[hi] - N[lo];
  117704. tX = X[hi] - X[lo];
  117705. tXX = XX[hi] - XX[lo];
  117706. tY = Y[hi] - Y[lo];
  117707. tXY = XY[hi] - XY[lo];
  117708. A = tY * tXX - tX * tXY;
  117709. B = tN * tXY - tX * tY;
  117710. D = tN * tXX - tX * tX;
  117711. R = (A + x * B) / D;
  117712. if (R < 0.f) R = 0.f;
  117713. noise[i] = R - offset;
  117714. }
  117715. for ( ; i < n; i++, x += 1.f) {
  117716. R = (A + x * B) / D;
  117717. if (R < 0.f) R = 0.f;
  117718. noise[i] = R - offset;
  117719. }
  117720. if (fixed <= 0) return;
  117721. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117722. hi = i + fixed / 2;
  117723. lo = hi - fixed;
  117724. if(lo>=0)break;
  117725. tN = N[hi] + N[-lo];
  117726. tX = X[hi] - X[-lo];
  117727. tXX = XX[hi] + XX[-lo];
  117728. tY = Y[hi] + Y[-lo];
  117729. tXY = XY[hi] - XY[-lo];
  117730. A = tY * tXX - tX * tXY;
  117731. B = tN * tXY - tX * tY;
  117732. D = tN * tXX - tX * tX;
  117733. R = (A + x * B) / D;
  117734. if (R - offset < noise[i]) noise[i] = R - offset;
  117735. }
  117736. for ( ;; i++, x += 1.f) {
  117737. hi = i + fixed / 2;
  117738. lo = hi - fixed;
  117739. if(hi>=n)break;
  117740. tN = N[hi] - N[lo];
  117741. tX = X[hi] - X[lo];
  117742. tXX = XX[hi] - XX[lo];
  117743. tY = Y[hi] - Y[lo];
  117744. tXY = XY[hi] - XY[lo];
  117745. A = tY * tXX - tX * tXY;
  117746. B = tN * tXY - tX * tY;
  117747. D = tN * tXX - tX * tX;
  117748. R = (A + x * B) / D;
  117749. if (R - offset < noise[i]) noise[i] = R - offset;
  117750. }
  117751. for ( ; i < n; i++, x += 1.f) {
  117752. R = (A + x * B) / D;
  117753. if (R - offset < noise[i]) noise[i] = R - offset;
  117754. }
  117755. }
  117756. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117757. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117758. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117759. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117760. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117761. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117762. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117763. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117764. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117765. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117766. 973377.F, 913981.F, 858210.F, 805842.F,
  117767. 756669.F, 710497.F, 667142.F, 626433.F,
  117768. 588208.F, 552316.F, 518613.F, 486967.F,
  117769. 457252.F, 429351.F, 403152.F, 378551.F,
  117770. 355452.F, 333762.F, 313396.F, 294273.F,
  117771. 276316.F, 259455.F, 243623.F, 228757.F,
  117772. 214798.F, 201691.F, 189384.F, 177828.F,
  117773. 166977.F, 156788.F, 147221.F, 138237.F,
  117774. 129802.F, 121881.F, 114444.F, 107461.F,
  117775. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117776. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117777. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117778. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117779. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117780. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117781. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117782. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117783. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117784. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117785. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117786. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117787. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117788. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117789. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117790. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117791. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117792. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117793. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117794. 842.910F, 791.475F, 743.179F, 697.830F,
  117795. 655.249F, 615.265F, 577.722F, 542.469F,
  117796. 509.367F, 478.286F, 449.101F, 421.696F,
  117797. 395.964F, 371.803F, 349.115F, 327.812F,
  117798. 307.809F, 289.026F, 271.390F, 254.830F,
  117799. 239.280F, 224.679F, 210.969F, 198.096F,
  117800. 186.008F, 174.658F, 164.000F, 153.993F,
  117801. 144.596F, 135.773F, 127.488F, 119.708F,
  117802. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117803. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117804. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117805. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117806. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117807. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117808. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117809. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117810. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117811. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117812. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117813. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117814. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117815. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117816. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117817. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117818. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117819. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117820. 1.20790F, 1.13419F, 1.06499F, 1.F
  117821. };
  117822. void _vp_remove_floor(vorbis_look_psy *p,
  117823. float *mdct,
  117824. int *codedflr,
  117825. float *residue,
  117826. int sliding_lowpass){
  117827. int i,n=p->n;
  117828. if(sliding_lowpass>n)sliding_lowpass=n;
  117829. for(i=0;i<sliding_lowpass;i++){
  117830. residue[i]=
  117831. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117832. }
  117833. for(;i<n;i++)
  117834. residue[i]=0.;
  117835. }
  117836. void _vp_noisemask(vorbis_look_psy *p,
  117837. float *logmdct,
  117838. float *logmask){
  117839. int i,n=p->n;
  117840. float *work=(float*) alloca(n*sizeof(*work));
  117841. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117842. 140.,-1);
  117843. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117844. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117845. p->vi->noisewindowfixed);
  117846. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117847. #if 0
  117848. {
  117849. static int seq=0;
  117850. float work2[n];
  117851. for(i=0;i<n;i++){
  117852. work2[i]=logmask[i]+work[i];
  117853. }
  117854. if(seq&1)
  117855. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117856. else
  117857. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117858. if(seq&1)
  117859. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117860. else
  117861. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117862. seq++;
  117863. }
  117864. #endif
  117865. for(i=0;i<n;i++){
  117866. int dB=logmask[i]+.5;
  117867. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117868. if(dB<0)dB=0;
  117869. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117870. }
  117871. }
  117872. void _vp_tonemask(vorbis_look_psy *p,
  117873. float *logfft,
  117874. float *logmask,
  117875. float global_specmax,
  117876. float local_specmax){
  117877. int i,n=p->n;
  117878. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117879. float att=local_specmax+p->vi->ath_adjatt;
  117880. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117881. /* set the ATH (floating below localmax, not global max by a
  117882. specified att) */
  117883. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117884. for(i=0;i<n;i++)
  117885. logmask[i]=p->ath[i]+att;
  117886. /* tone masking */
  117887. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117888. max_seeds(p,seed,logmask);
  117889. }
  117890. void _vp_offset_and_mix(vorbis_look_psy *p,
  117891. float *noise,
  117892. float *tone,
  117893. int offset_select,
  117894. float *logmask,
  117895. float *mdct,
  117896. float *logmdct){
  117897. int i,n=p->n;
  117898. float de, coeffi, cx;/* AoTuV */
  117899. float toneatt=p->vi->tone_masteratt[offset_select];
  117900. cx = p->m_val;
  117901. for(i=0;i<n;i++){
  117902. float val= noise[i]+p->noiseoffset[offset_select][i];
  117903. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117904. logmask[i]=max(val,tone[i]+toneatt);
  117905. /* AoTuV */
  117906. /** @ M1 **
  117907. The following codes improve a noise problem.
  117908. A fundamental idea uses the value of masking and carries out
  117909. the relative compensation of the MDCT.
  117910. However, this code is not perfect and all noise problems cannot be solved.
  117911. by Aoyumi @ 2004/04/18
  117912. */
  117913. if(offset_select == 1) {
  117914. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117915. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117916. if(val > coeffi){
  117917. /* mdct value is > -17.2 dB below floor */
  117918. de = 1.0-((val-coeffi)*0.005*cx);
  117919. /* pro-rated attenuation:
  117920. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117921. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117922. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117923. etc... */
  117924. if(de < 0) de = 0.0001;
  117925. }else
  117926. /* mdct value is <= -17.2 dB below floor */
  117927. de = 1.0-((val-coeffi)*0.0003*cx);
  117928. /* pro-rated attenuation:
  117929. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117930. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117931. etc... */
  117932. mdct[i] *= de;
  117933. }
  117934. }
  117935. }
  117936. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117937. vorbis_info *vi=vd->vi;
  117938. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117939. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117940. int n=ci->blocksizes[vd->W]/2;
  117941. float secs=(float)n/vi->rate;
  117942. amp+=secs*gi->ampmax_att_per_sec;
  117943. if(amp<-9999)amp=-9999;
  117944. return(amp);
  117945. }
  117946. static void couple_lossless(float A, float B,
  117947. float *qA, float *qB){
  117948. int test1=fabs(*qA)>fabs(*qB);
  117949. test1-= fabs(*qA)<fabs(*qB);
  117950. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117951. if(test1==1){
  117952. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117953. }else{
  117954. float temp=*qB;
  117955. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117956. *qA=temp;
  117957. }
  117958. if(*qB>fabs(*qA)*1.9999f){
  117959. *qB= -fabs(*qA)*2.f;
  117960. *qA= -*qA;
  117961. }
  117962. }
  117963. static float hypot_lookup[32]={
  117964. -0.009935, -0.011245, -0.012726, -0.014397,
  117965. -0.016282, -0.018407, -0.020800, -0.023494,
  117966. -0.026522, -0.029923, -0.033737, -0.038010,
  117967. -0.042787, -0.048121, -0.054064, -0.060671,
  117968. -0.068000, -0.076109, -0.085054, -0.094892,
  117969. -0.105675, -0.117451, -0.130260, -0.144134,
  117970. -0.159093, -0.175146, -0.192286, -0.210490,
  117971. -0.229718, -0.249913, -0.271001, -0.292893};
  117972. static void precomputed_couple_point(float premag,
  117973. int floorA,int floorB,
  117974. float *mag, float *ang){
  117975. int test=(floorA>floorB)-1;
  117976. int offset=31-abs(floorA-floorB);
  117977. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117978. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117979. *mag=premag*floormag;
  117980. *ang=0.f;
  117981. }
  117982. /* just like below, this is currently set up to only do
  117983. single-step-depth coupling. Otherwise, we'd have to do more
  117984. copying (which will be inevitable later) */
  117985. /* doing the real circular magnitude calculation is audibly superior
  117986. to (A+B)/sqrt(2) */
  117987. static float dipole_hypot(float a, float b){
  117988. if(a>0.){
  117989. if(b>0.)return sqrt(a*a+b*b);
  117990. if(a>-b)return sqrt(a*a-b*b);
  117991. return -sqrt(b*b-a*a);
  117992. }
  117993. if(b<0.)return -sqrt(a*a+b*b);
  117994. if(-a>b)return -sqrt(a*a-b*b);
  117995. return sqrt(b*b-a*a);
  117996. }
  117997. static float round_hypot(float a, float b){
  117998. if(a>0.){
  117999. if(b>0.)return sqrt(a*a+b*b);
  118000. if(a>-b)return sqrt(a*a+b*b);
  118001. return -sqrt(b*b+a*a);
  118002. }
  118003. if(b<0.)return -sqrt(a*a+b*b);
  118004. if(-a>b)return -sqrt(a*a+b*b);
  118005. return sqrt(b*b+a*a);
  118006. }
  118007. /* revert to round hypot for now */
  118008. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118009. vorbis_info_psy_global *g,
  118010. vorbis_look_psy *p,
  118011. vorbis_info_mapping0 *vi,
  118012. float **mdct){
  118013. int i,j,n=p->n;
  118014. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118015. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118016. for(i=0;i<vi->coupling_steps;i++){
  118017. float *mdctM=mdct[vi->coupling_mag[i]];
  118018. float *mdctA=mdct[vi->coupling_ang[i]];
  118019. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118020. for(j=0;j<limit;j++)
  118021. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118022. for(;j<n;j++)
  118023. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118024. }
  118025. return(ret);
  118026. }
  118027. /* this is for per-channel noise normalization */
  118028. static int JUCE_CDECL apsort(const void *a, const void *b){
  118029. float f1=fabs(**(float**)a);
  118030. float f2=fabs(**(float**)b);
  118031. return (f1<f2)-(f1>f2);
  118032. }
  118033. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118034. vorbis_look_psy *p,
  118035. vorbis_info_mapping0 *vi,
  118036. float **mags){
  118037. if(p->vi->normal_point_p){
  118038. int i,j,k,n=p->n;
  118039. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118040. int partition=p->vi->normal_partition;
  118041. float **work=(float**) alloca(sizeof(*work)*partition);
  118042. for(i=0;i<vi->coupling_steps;i++){
  118043. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118044. for(j=0;j<n;j+=partition){
  118045. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118046. qsort(work,partition,sizeof(*work),apsort);
  118047. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118048. }
  118049. }
  118050. return(ret);
  118051. }
  118052. return(NULL);
  118053. }
  118054. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118055. float *magnitudes,int *sortedindex){
  118056. int i,j,n=p->n;
  118057. vorbis_info_psy *vi=p->vi;
  118058. int partition=vi->normal_partition;
  118059. float **work=(float**) alloca(sizeof(*work)*partition);
  118060. int start=vi->normal_start;
  118061. for(j=start;j<n;j+=partition){
  118062. if(j+partition>n)partition=n-j;
  118063. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118064. qsort(work,partition,sizeof(*work),apsort);
  118065. for(i=0;i<partition;i++){
  118066. sortedindex[i+j-start]=work[i]-magnitudes;
  118067. }
  118068. }
  118069. }
  118070. void _vp_noise_normalize(vorbis_look_psy *p,
  118071. float *in,float *out,int *sortedindex){
  118072. int flag=0,i,j=0,n=p->n;
  118073. vorbis_info_psy *vi=p->vi;
  118074. int partition=vi->normal_partition;
  118075. int start=vi->normal_start;
  118076. if(start>n)start=n;
  118077. if(vi->normal_channel_p){
  118078. for(;j<start;j++)
  118079. out[j]=rint(in[j]);
  118080. for(;j+partition<=n;j+=partition){
  118081. float acc=0.;
  118082. int k;
  118083. for(i=j;i<j+partition;i++)
  118084. acc+=in[i]*in[i];
  118085. for(i=0;i<partition;i++){
  118086. k=sortedindex[i+j-start];
  118087. if(in[k]*in[k]>=.25f){
  118088. out[k]=rint(in[k]);
  118089. acc-=in[k]*in[k];
  118090. flag=1;
  118091. }else{
  118092. if(acc<vi->normal_thresh)break;
  118093. out[k]=unitnorm(in[k]);
  118094. acc-=1.;
  118095. }
  118096. }
  118097. for(;i<partition;i++){
  118098. k=sortedindex[i+j-start];
  118099. out[k]=0.;
  118100. }
  118101. }
  118102. }
  118103. for(;j<n;j++)
  118104. out[j]=rint(in[j]);
  118105. }
  118106. void _vp_couple(int blobno,
  118107. vorbis_info_psy_global *g,
  118108. vorbis_look_psy *p,
  118109. vorbis_info_mapping0 *vi,
  118110. float **res,
  118111. float **mag_memo,
  118112. int **mag_sort,
  118113. int **ifloor,
  118114. int *nonzero,
  118115. int sliding_lowpass){
  118116. int i,j,k,n=p->n;
  118117. /* perform any requested channel coupling */
  118118. /* point stereo can only be used in a first stage (in this encoder)
  118119. because of the dependency on floor lookups */
  118120. for(i=0;i<vi->coupling_steps;i++){
  118121. /* once we're doing multistage coupling in which a channel goes
  118122. through more than one coupling step, the floor vector
  118123. magnitudes will also have to be recalculated an propogated
  118124. along with PCM. Right now, we're not (that will wait until 5.1
  118125. most likely), so the code isn't here yet. The memory management
  118126. here is all assuming single depth couplings anyway. */
  118127. /* make sure coupling a zero and a nonzero channel results in two
  118128. nonzero channels. */
  118129. if(nonzero[vi->coupling_mag[i]] ||
  118130. nonzero[vi->coupling_ang[i]]){
  118131. float *rM=res[vi->coupling_mag[i]];
  118132. float *rA=res[vi->coupling_ang[i]];
  118133. float *qM=rM+n;
  118134. float *qA=rA+n;
  118135. int *floorM=ifloor[vi->coupling_mag[i]];
  118136. int *floorA=ifloor[vi->coupling_ang[i]];
  118137. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118138. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118139. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118140. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118141. int pointlimit=limit;
  118142. nonzero[vi->coupling_mag[i]]=1;
  118143. nonzero[vi->coupling_ang[i]]=1;
  118144. /* The threshold of a stereo is changed with the size of n */
  118145. if(n > 1000)
  118146. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118147. for(j=0;j<p->n;j+=partition){
  118148. float acc=0.f;
  118149. for(k=0;k<partition;k++){
  118150. int l=k+j;
  118151. if(l<sliding_lowpass){
  118152. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118153. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118154. precomputed_couple_point(mag_memo[i][l],
  118155. floorM[l],floorA[l],
  118156. qM+l,qA+l);
  118157. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118158. }else{
  118159. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118160. }
  118161. }else{
  118162. qM[l]=0.;
  118163. qA[l]=0.;
  118164. }
  118165. }
  118166. if(p->vi->normal_point_p){
  118167. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118168. int l=mag_sort[i][j+k];
  118169. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118170. qM[l]=unitnorm(qM[l]);
  118171. acc-=1.f;
  118172. }
  118173. }
  118174. }
  118175. }
  118176. }
  118177. }
  118178. }
  118179. /* AoTuV */
  118180. /** @ M2 **
  118181. The boost problem by the combination of noise normalization and point stereo is eased.
  118182. However, this is a temporary patch.
  118183. by Aoyumi @ 2004/04/18
  118184. */
  118185. void hf_reduction(vorbis_info_psy_global *g,
  118186. vorbis_look_psy *p,
  118187. vorbis_info_mapping0 *vi,
  118188. float **mdct){
  118189. int i,j,n=p->n, de=0.3*p->m_val;
  118190. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118191. for(i=0; i<vi->coupling_steps; i++){
  118192. /* for(j=start; j<limit; j++){} // ???*/
  118193. for(j=limit; j<n; j++)
  118194. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118195. }
  118196. }
  118197. #endif
  118198. /*** End of inlined file: psy.c ***/
  118199. /*** Start of inlined file: registry.c ***/
  118200. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118201. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118202. // tasks..
  118203. #if JUCE_MSVC
  118204. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118205. #endif
  118206. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118207. #if JUCE_USE_OGGVORBIS
  118208. /* seems like major overkill now; the backend numbers will grow into
  118209. the infrastructure soon enough */
  118210. extern vorbis_func_floor floor0_exportbundle;
  118211. extern vorbis_func_floor floor1_exportbundle;
  118212. extern vorbis_func_residue residue0_exportbundle;
  118213. extern vorbis_func_residue residue1_exportbundle;
  118214. extern vorbis_func_residue residue2_exportbundle;
  118215. extern vorbis_func_mapping mapping0_exportbundle;
  118216. vorbis_func_floor *_floor_P[]={
  118217. &floor0_exportbundle,
  118218. &floor1_exportbundle,
  118219. };
  118220. vorbis_func_residue *_residue_P[]={
  118221. &residue0_exportbundle,
  118222. &residue1_exportbundle,
  118223. &residue2_exportbundle,
  118224. };
  118225. vorbis_func_mapping *_mapping_P[]={
  118226. &mapping0_exportbundle,
  118227. };
  118228. #endif
  118229. /*** End of inlined file: registry.c ***/
  118230. /*** Start of inlined file: res0.c ***/
  118231. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118232. encode/decode loops are coded for clarity and performance is not
  118233. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118234. it's slow. */
  118235. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118236. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118237. // tasks..
  118238. #if JUCE_MSVC
  118239. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118240. #endif
  118241. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118242. #if JUCE_USE_OGGVORBIS
  118243. #include <stdlib.h>
  118244. #include <string.h>
  118245. #include <math.h>
  118246. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118247. #include <stdio.h>
  118248. #endif
  118249. typedef struct {
  118250. vorbis_info_residue0 *info;
  118251. int parts;
  118252. int stages;
  118253. codebook *fullbooks;
  118254. codebook *phrasebook;
  118255. codebook ***partbooks;
  118256. int partvals;
  118257. int **decodemap;
  118258. long postbits;
  118259. long phrasebits;
  118260. long frames;
  118261. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118262. int train_seq;
  118263. long *training_data[8][64];
  118264. float training_max[8][64];
  118265. float training_min[8][64];
  118266. float tmin;
  118267. float tmax;
  118268. #endif
  118269. } vorbis_look_residue0;
  118270. void res0_free_info(vorbis_info_residue *i){
  118271. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118272. if(info){
  118273. memset(info,0,sizeof(*info));
  118274. _ogg_free(info);
  118275. }
  118276. }
  118277. void res0_free_look(vorbis_look_residue *i){
  118278. int j;
  118279. if(i){
  118280. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118281. #ifdef TRAIN_RES
  118282. {
  118283. int j,k,l;
  118284. for(j=0;j<look->parts;j++){
  118285. /*fprintf(stderr,"partition %d: ",j);*/
  118286. for(k=0;k<8;k++)
  118287. if(look->training_data[k][j]){
  118288. char buffer[80];
  118289. FILE *of;
  118290. codebook *statebook=look->partbooks[j][k];
  118291. /* long and short into the same bucket by current convention */
  118292. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118293. of=fopen(buffer,"a");
  118294. for(l=0;l<statebook->entries;l++)
  118295. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118296. fclose(of);
  118297. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118298. look->training_min[k][j],look->training_max[k][j]);*/
  118299. _ogg_free(look->training_data[k][j]);
  118300. look->training_data[k][j]=NULL;
  118301. }
  118302. /*fprintf(stderr,"\n");*/
  118303. }
  118304. }
  118305. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118306. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118307. (float)look->phrasebits/look->frames,
  118308. (float)look->postbits/look->frames,
  118309. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118310. #endif
  118311. /*vorbis_info_residue0 *info=look->info;
  118312. fprintf(stderr,
  118313. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118314. "(%g/frame) \n",look->frames,look->phrasebits,
  118315. look->resbitsflat,
  118316. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118317. for(j=0;j<look->parts;j++){
  118318. long acc=0;
  118319. fprintf(stderr,"\t[%d] == ",j);
  118320. for(k=0;k<look->stages;k++)
  118321. if((info->secondstages[j]>>k)&1){
  118322. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118323. acc+=look->resbits[j][k];
  118324. }
  118325. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118326. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118327. }
  118328. fprintf(stderr,"\n");*/
  118329. for(j=0;j<look->parts;j++)
  118330. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118331. _ogg_free(look->partbooks);
  118332. for(j=0;j<look->partvals;j++)
  118333. _ogg_free(look->decodemap[j]);
  118334. _ogg_free(look->decodemap);
  118335. memset(look,0,sizeof(*look));
  118336. _ogg_free(look);
  118337. }
  118338. }
  118339. static int icount(unsigned int v){
  118340. int ret=0;
  118341. while(v){
  118342. ret+=v&1;
  118343. v>>=1;
  118344. }
  118345. return(ret);
  118346. }
  118347. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118348. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118349. int j,acc=0;
  118350. oggpack_write(opb,info->begin,24);
  118351. oggpack_write(opb,info->end,24);
  118352. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118353. code with a partitioned book */
  118354. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118355. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118356. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118357. bitmask of one indicates this partition class has bits to write
  118358. this pass */
  118359. for(j=0;j<info->partitions;j++){
  118360. if(ilog(info->secondstages[j])>3){
  118361. /* yes, this is a minor hack due to not thinking ahead */
  118362. oggpack_write(opb,info->secondstages[j],3);
  118363. oggpack_write(opb,1,1);
  118364. oggpack_write(opb,info->secondstages[j]>>3,5);
  118365. }else
  118366. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118367. acc+=icount(info->secondstages[j]);
  118368. }
  118369. for(j=0;j<acc;j++)
  118370. oggpack_write(opb,info->booklist[j],8);
  118371. }
  118372. /* vorbis_info is for range checking */
  118373. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118374. int j,acc=0;
  118375. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118376. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118377. info->begin=oggpack_read(opb,24);
  118378. info->end=oggpack_read(opb,24);
  118379. info->grouping=oggpack_read(opb,24)+1;
  118380. info->partitions=oggpack_read(opb,6)+1;
  118381. info->groupbook=oggpack_read(opb,8);
  118382. for(j=0;j<info->partitions;j++){
  118383. int cascade=oggpack_read(opb,3);
  118384. if(oggpack_read(opb,1))
  118385. cascade|=(oggpack_read(opb,5)<<3);
  118386. info->secondstages[j]=cascade;
  118387. acc+=icount(cascade);
  118388. }
  118389. for(j=0;j<acc;j++)
  118390. info->booklist[j]=oggpack_read(opb,8);
  118391. if(info->groupbook>=ci->books)goto errout;
  118392. for(j=0;j<acc;j++)
  118393. if(info->booklist[j]>=ci->books)goto errout;
  118394. return(info);
  118395. errout:
  118396. res0_free_info(info);
  118397. return(NULL);
  118398. }
  118399. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118400. vorbis_info_residue *vr){
  118401. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118402. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118403. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118404. int j,k,acc=0;
  118405. int dim;
  118406. int maxstage=0;
  118407. look->info=info;
  118408. look->parts=info->partitions;
  118409. look->fullbooks=ci->fullbooks;
  118410. look->phrasebook=ci->fullbooks+info->groupbook;
  118411. dim=look->phrasebook->dim;
  118412. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118413. for(j=0;j<look->parts;j++){
  118414. int stages=ilog(info->secondstages[j]);
  118415. if(stages){
  118416. if(stages>maxstage)maxstage=stages;
  118417. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118418. for(k=0;k<stages;k++)
  118419. if(info->secondstages[j]&(1<<k)){
  118420. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118421. #ifdef TRAIN_RES
  118422. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118423. sizeof(***look->training_data));
  118424. #endif
  118425. }
  118426. }
  118427. }
  118428. look->partvals=rint(pow((float)look->parts,(float)dim));
  118429. look->stages=maxstage;
  118430. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118431. for(j=0;j<look->partvals;j++){
  118432. long val=j;
  118433. long mult=look->partvals/look->parts;
  118434. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118435. for(k=0;k<dim;k++){
  118436. long deco=val/mult;
  118437. val-=deco*mult;
  118438. mult/=look->parts;
  118439. look->decodemap[j][k]=deco;
  118440. }
  118441. }
  118442. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118443. {
  118444. static int train_seq=0;
  118445. look->train_seq=train_seq++;
  118446. }
  118447. #endif
  118448. return(look);
  118449. }
  118450. /* break an abstraction and copy some code for performance purposes */
  118451. static int local_book_besterror(codebook *book,float *a){
  118452. int dim=book->dim,i,k,o;
  118453. int best=0;
  118454. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118455. /* find the quant val of each scalar */
  118456. for(k=0,o=dim;k<dim;++k){
  118457. float val=a[--o];
  118458. i=tt->threshvals>>1;
  118459. if(val<tt->quantthresh[i]){
  118460. if(val<tt->quantthresh[i-1]){
  118461. for(--i;i>0;--i)
  118462. if(val>=tt->quantthresh[i-1])
  118463. break;
  118464. }
  118465. }else{
  118466. for(++i;i<tt->threshvals-1;++i)
  118467. if(val<tt->quantthresh[i])break;
  118468. }
  118469. best=(best*tt->quantvals)+tt->quantmap[i];
  118470. }
  118471. /* regular lattices are easy :-) */
  118472. if(book->c->lengthlist[best]<=0){
  118473. const static_codebook *c=book->c;
  118474. int i,j;
  118475. float bestf=0.f;
  118476. float *e=book->valuelist;
  118477. best=-1;
  118478. for(i=0;i<book->entries;i++){
  118479. if(c->lengthlist[i]>0){
  118480. float thisx=0.f;
  118481. for(j=0;j<dim;j++){
  118482. float val=(e[j]-a[j]);
  118483. thisx+=val*val;
  118484. }
  118485. if(best==-1 || thisx<bestf){
  118486. bestf=thisx;
  118487. best=i;
  118488. }
  118489. }
  118490. e+=dim;
  118491. }
  118492. }
  118493. {
  118494. float *ptr=book->valuelist+best*dim;
  118495. for(i=0;i<dim;i++)
  118496. *a++ -= *ptr++;
  118497. }
  118498. return(best);
  118499. }
  118500. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118501. codebook *book,long *acc){
  118502. int i,bits=0;
  118503. int dim=book->dim;
  118504. int step=n/dim;
  118505. for(i=0;i<step;i++){
  118506. int entry=local_book_besterror(book,vec+i*dim);
  118507. #ifdef TRAIN_RES
  118508. acc[entry]++;
  118509. #endif
  118510. bits+=vorbis_book_encode(book,entry,opb);
  118511. }
  118512. return(bits);
  118513. }
  118514. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118515. float **in,int ch){
  118516. long i,j,k;
  118517. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118518. vorbis_info_residue0 *info=look->info;
  118519. /* move all this setup out later */
  118520. int samples_per_partition=info->grouping;
  118521. int possible_partitions=info->partitions;
  118522. int n=info->end-info->begin;
  118523. int partvals=n/samples_per_partition;
  118524. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118525. float scale=100./samples_per_partition;
  118526. /* we find the partition type for each partition of each
  118527. channel. We'll go back and do the interleaved encoding in a
  118528. bit. For now, clarity */
  118529. for(i=0;i<ch;i++){
  118530. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118531. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118532. }
  118533. for(i=0;i<partvals;i++){
  118534. int offset=i*samples_per_partition+info->begin;
  118535. for(j=0;j<ch;j++){
  118536. float max=0.;
  118537. float ent=0.;
  118538. for(k=0;k<samples_per_partition;k++){
  118539. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118540. ent+=fabs(rint(in[j][offset+k]));
  118541. }
  118542. ent*=scale;
  118543. for(k=0;k<possible_partitions-1;k++)
  118544. if(max<=info->classmetric1[k] &&
  118545. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118546. break;
  118547. partword[j][i]=k;
  118548. }
  118549. }
  118550. #ifdef TRAIN_RESAUX
  118551. {
  118552. FILE *of;
  118553. char buffer[80];
  118554. for(i=0;i<ch;i++){
  118555. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118556. of=fopen(buffer,"a");
  118557. for(j=0;j<partvals;j++)
  118558. fprintf(of,"%ld, ",partword[i][j]);
  118559. fprintf(of,"\n");
  118560. fclose(of);
  118561. }
  118562. }
  118563. #endif
  118564. look->frames++;
  118565. return(partword);
  118566. }
  118567. /* designed for stereo or other modes where the partition size is an
  118568. integer multiple of the number of channels encoded in the current
  118569. submap */
  118570. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118571. int ch){
  118572. long i,j,k,l;
  118573. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118574. vorbis_info_residue0 *info=look->info;
  118575. /* move all this setup out later */
  118576. int samples_per_partition=info->grouping;
  118577. int possible_partitions=info->partitions;
  118578. int n=info->end-info->begin;
  118579. int partvals=n/samples_per_partition;
  118580. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118581. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118582. FILE *of;
  118583. char buffer[80];
  118584. #endif
  118585. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118586. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118587. for(i=0,l=info->begin/ch;i<partvals;i++){
  118588. float magmax=0.f;
  118589. float angmax=0.f;
  118590. for(j=0;j<samples_per_partition;j+=ch){
  118591. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118592. for(k=1;k<ch;k++)
  118593. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118594. l++;
  118595. }
  118596. for(j=0;j<possible_partitions-1;j++)
  118597. if(magmax<=info->classmetric1[j] &&
  118598. angmax<=info->classmetric2[j])
  118599. break;
  118600. partword[0][i]=j;
  118601. }
  118602. #ifdef TRAIN_RESAUX
  118603. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118604. of=fopen(buffer,"a");
  118605. for(i=0;i<partvals;i++)
  118606. fprintf(of,"%ld, ",partword[0][i]);
  118607. fprintf(of,"\n");
  118608. fclose(of);
  118609. #endif
  118610. look->frames++;
  118611. return(partword);
  118612. }
  118613. static int _01forward(oggpack_buffer *opb,
  118614. vorbis_block *vb,vorbis_look_residue *vl,
  118615. float **in,int ch,
  118616. long **partword,
  118617. int (*encode)(oggpack_buffer *,float *,int,
  118618. codebook *,long *)){
  118619. long i,j,k,s;
  118620. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118621. vorbis_info_residue0 *info=look->info;
  118622. /* move all this setup out later */
  118623. int samples_per_partition=info->grouping;
  118624. int possible_partitions=info->partitions;
  118625. int partitions_per_word=look->phrasebook->dim;
  118626. int n=info->end-info->begin;
  118627. int partvals=n/samples_per_partition;
  118628. long resbits[128];
  118629. long resvals[128];
  118630. #ifdef TRAIN_RES
  118631. for(i=0;i<ch;i++)
  118632. for(j=info->begin;j<info->end;j++){
  118633. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118634. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118635. }
  118636. #endif
  118637. memset(resbits,0,sizeof(resbits));
  118638. memset(resvals,0,sizeof(resvals));
  118639. /* we code the partition words for each channel, then the residual
  118640. words for a partition per channel until we've written all the
  118641. residual words for that partition word. Then write the next
  118642. partition channel words... */
  118643. for(s=0;s<look->stages;s++){
  118644. for(i=0;i<partvals;){
  118645. /* first we encode a partition codeword for each channel */
  118646. if(s==0){
  118647. for(j=0;j<ch;j++){
  118648. long val=partword[j][i];
  118649. for(k=1;k<partitions_per_word;k++){
  118650. val*=possible_partitions;
  118651. if(i+k<partvals)
  118652. val+=partword[j][i+k];
  118653. }
  118654. /* training hack */
  118655. if(val<look->phrasebook->entries)
  118656. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118657. #if 0 /*def TRAIN_RES*/
  118658. else
  118659. fprintf(stderr,"!");
  118660. #endif
  118661. }
  118662. }
  118663. /* now we encode interleaved residual values for the partitions */
  118664. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118665. long offset=i*samples_per_partition+info->begin;
  118666. for(j=0;j<ch;j++){
  118667. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118668. if(info->secondstages[partword[j][i]]&(1<<s)){
  118669. codebook *statebook=look->partbooks[partword[j][i]][s];
  118670. if(statebook){
  118671. int ret;
  118672. long *accumulator=NULL;
  118673. #ifdef TRAIN_RES
  118674. accumulator=look->training_data[s][partword[j][i]];
  118675. {
  118676. int l;
  118677. float *samples=in[j]+offset;
  118678. for(l=0;l<samples_per_partition;l++){
  118679. if(samples[l]<look->training_min[s][partword[j][i]])
  118680. look->training_min[s][partword[j][i]]=samples[l];
  118681. if(samples[l]>look->training_max[s][partword[j][i]])
  118682. look->training_max[s][partword[j][i]]=samples[l];
  118683. }
  118684. }
  118685. #endif
  118686. ret=encode(opb,in[j]+offset,samples_per_partition,
  118687. statebook,accumulator);
  118688. look->postbits+=ret;
  118689. resbits[partword[j][i]]+=ret;
  118690. }
  118691. }
  118692. }
  118693. }
  118694. }
  118695. }
  118696. /*{
  118697. long total=0;
  118698. long totalbits=0;
  118699. fprintf(stderr,"%d :: ",vb->mode);
  118700. for(k=0;k<possible_partitions;k++){
  118701. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118702. total+=resvals[k];
  118703. totalbits+=resbits[k];
  118704. }
  118705. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118706. }*/
  118707. return(0);
  118708. }
  118709. /* a truncated packet here just means 'stop working'; it's not an error */
  118710. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118711. float **in,int ch,
  118712. long (*decodepart)(codebook *, float *,
  118713. oggpack_buffer *,int)){
  118714. long i,j,k,l,s;
  118715. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118716. vorbis_info_residue0 *info=look->info;
  118717. /* move all this setup out later */
  118718. int samples_per_partition=info->grouping;
  118719. int partitions_per_word=look->phrasebook->dim;
  118720. int n=info->end-info->begin;
  118721. int partvals=n/samples_per_partition;
  118722. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118723. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118724. for(j=0;j<ch;j++)
  118725. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118726. for(s=0;s<look->stages;s++){
  118727. /* each loop decodes on partition codeword containing
  118728. partitions_pre_word partitions */
  118729. for(i=0,l=0;i<partvals;l++){
  118730. if(s==0){
  118731. /* fetch the partition word for each channel */
  118732. for(j=0;j<ch;j++){
  118733. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118734. if(temp==-1)goto eopbreak;
  118735. partword[j][l]=look->decodemap[temp];
  118736. if(partword[j][l]==NULL)goto errout;
  118737. }
  118738. }
  118739. /* now we decode residual values for the partitions */
  118740. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118741. for(j=0;j<ch;j++){
  118742. long offset=info->begin+i*samples_per_partition;
  118743. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118744. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118745. if(stagebook){
  118746. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118747. samples_per_partition)==-1)goto eopbreak;
  118748. }
  118749. }
  118750. }
  118751. }
  118752. }
  118753. errout:
  118754. eopbreak:
  118755. return(0);
  118756. }
  118757. #if 0
  118758. /* residue 0 and 1 are just slight variants of one another. 0 is
  118759. interleaved, 1 is not */
  118760. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118761. float **in,int *nonzero,int ch){
  118762. /* we encode only the nonzero parts of a bundle */
  118763. int i,used=0;
  118764. for(i=0;i<ch;i++)
  118765. if(nonzero[i])
  118766. in[used++]=in[i];
  118767. if(used)
  118768. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118769. return(_01class(vb,vl,in,used));
  118770. else
  118771. return(0);
  118772. }
  118773. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118774. float **in,float **out,int *nonzero,int ch,
  118775. long **partword){
  118776. /* we encode only the nonzero parts of a bundle */
  118777. int i,j,used=0,n=vb->pcmend/2;
  118778. for(i=0;i<ch;i++)
  118779. if(nonzero[i]){
  118780. if(out)
  118781. for(j=0;j<n;j++)
  118782. out[i][j]+=in[i][j];
  118783. in[used++]=in[i];
  118784. }
  118785. if(used){
  118786. int ret=_01forward(vb,vl,in,used,partword,
  118787. _interleaved_encodepart);
  118788. if(out){
  118789. used=0;
  118790. for(i=0;i<ch;i++)
  118791. if(nonzero[i]){
  118792. for(j=0;j<n;j++)
  118793. out[i][j]-=in[used][j];
  118794. used++;
  118795. }
  118796. }
  118797. return(ret);
  118798. }else{
  118799. return(0);
  118800. }
  118801. }
  118802. #endif
  118803. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118804. float **in,int *nonzero,int ch){
  118805. int i,used=0;
  118806. for(i=0;i<ch;i++)
  118807. if(nonzero[i])
  118808. in[used++]=in[i];
  118809. if(used)
  118810. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118811. else
  118812. return(0);
  118813. }
  118814. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118815. float **in,float **out,int *nonzero,int ch,
  118816. long **partword){
  118817. int i,j,used=0,n=vb->pcmend/2;
  118818. for(i=0;i<ch;i++)
  118819. if(nonzero[i]){
  118820. if(out)
  118821. for(j=0;j<n;j++)
  118822. out[i][j]+=in[i][j];
  118823. in[used++]=in[i];
  118824. }
  118825. if(used){
  118826. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118827. if(out){
  118828. used=0;
  118829. for(i=0;i<ch;i++)
  118830. if(nonzero[i]){
  118831. for(j=0;j<n;j++)
  118832. out[i][j]-=in[used][j];
  118833. used++;
  118834. }
  118835. }
  118836. return(ret);
  118837. }else{
  118838. return(0);
  118839. }
  118840. }
  118841. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118842. float **in,int *nonzero,int ch){
  118843. int i,used=0;
  118844. for(i=0;i<ch;i++)
  118845. if(nonzero[i])
  118846. in[used++]=in[i];
  118847. if(used)
  118848. return(_01class(vb,vl,in,used));
  118849. else
  118850. return(0);
  118851. }
  118852. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118853. float **in,int *nonzero,int ch){
  118854. int i,used=0;
  118855. for(i=0;i<ch;i++)
  118856. if(nonzero[i])
  118857. in[used++]=in[i];
  118858. if(used)
  118859. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118860. else
  118861. return(0);
  118862. }
  118863. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118864. float **in,int *nonzero,int ch){
  118865. int i,used=0;
  118866. for(i=0;i<ch;i++)
  118867. if(nonzero[i])used++;
  118868. if(used)
  118869. return(_2class(vb,vl,in,ch));
  118870. else
  118871. return(0);
  118872. }
  118873. /* res2 is slightly more different; all the channels are interleaved
  118874. into a single vector and encoded. */
  118875. int res2_forward(oggpack_buffer *opb,
  118876. vorbis_block *vb,vorbis_look_residue *vl,
  118877. float **in,float **out,int *nonzero,int ch,
  118878. long **partword){
  118879. long i,j,k,n=vb->pcmend/2,used=0;
  118880. /* don't duplicate the code; use a working vector hack for now and
  118881. reshape ourselves into a single channel res1 */
  118882. /* ugly; reallocs for each coupling pass :-( */
  118883. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118884. for(i=0;i<ch;i++){
  118885. float *pcm=in[i];
  118886. if(nonzero[i])used++;
  118887. for(j=0,k=i;j<n;j++,k+=ch)
  118888. work[k]=pcm[j];
  118889. }
  118890. if(used){
  118891. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118892. /* update the sofar vector */
  118893. if(out){
  118894. for(i=0;i<ch;i++){
  118895. float *pcm=in[i];
  118896. float *sofar=out[i];
  118897. for(j=0,k=i;j<n;j++,k+=ch)
  118898. sofar[j]+=pcm[j]-work[k];
  118899. }
  118900. }
  118901. return(ret);
  118902. }else{
  118903. return(0);
  118904. }
  118905. }
  118906. /* duplicate code here as speed is somewhat more important */
  118907. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118908. float **in,int *nonzero,int ch){
  118909. long i,k,l,s;
  118910. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118911. vorbis_info_residue0 *info=look->info;
  118912. /* move all this setup out later */
  118913. int samples_per_partition=info->grouping;
  118914. int partitions_per_word=look->phrasebook->dim;
  118915. int n=info->end-info->begin;
  118916. int partvals=n/samples_per_partition;
  118917. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118918. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118919. for(i=0;i<ch;i++)if(nonzero[i])break;
  118920. if(i==ch)return(0); /* no nonzero vectors */
  118921. for(s=0;s<look->stages;s++){
  118922. for(i=0,l=0;i<partvals;l++){
  118923. if(s==0){
  118924. /* fetch the partition word */
  118925. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118926. if(temp==-1)goto eopbreak;
  118927. partword[l]=look->decodemap[temp];
  118928. if(partword[l]==NULL)goto errout;
  118929. }
  118930. /* now we decode residual values for the partitions */
  118931. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118932. if(info->secondstages[partword[l][k]]&(1<<s)){
  118933. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118934. if(stagebook){
  118935. if(vorbis_book_decodevv_add(stagebook,in,
  118936. i*samples_per_partition+info->begin,ch,
  118937. &vb->opb,samples_per_partition)==-1)
  118938. goto eopbreak;
  118939. }
  118940. }
  118941. }
  118942. }
  118943. errout:
  118944. eopbreak:
  118945. return(0);
  118946. }
  118947. vorbis_func_residue residue0_exportbundle={
  118948. NULL,
  118949. &res0_unpack,
  118950. &res0_look,
  118951. &res0_free_info,
  118952. &res0_free_look,
  118953. NULL,
  118954. NULL,
  118955. &res0_inverse
  118956. };
  118957. vorbis_func_residue residue1_exportbundle={
  118958. &res0_pack,
  118959. &res0_unpack,
  118960. &res0_look,
  118961. &res0_free_info,
  118962. &res0_free_look,
  118963. &res1_class,
  118964. &res1_forward,
  118965. &res1_inverse
  118966. };
  118967. vorbis_func_residue residue2_exportbundle={
  118968. &res0_pack,
  118969. &res0_unpack,
  118970. &res0_look,
  118971. &res0_free_info,
  118972. &res0_free_look,
  118973. &res2_class,
  118974. &res2_forward,
  118975. &res2_inverse
  118976. };
  118977. #endif
  118978. /*** End of inlined file: res0.c ***/
  118979. /*** Start of inlined file: sharedbook.c ***/
  118980. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118981. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118982. // tasks..
  118983. #if JUCE_MSVC
  118984. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118985. #endif
  118986. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118987. #if JUCE_USE_OGGVORBIS
  118988. #include <stdlib.h>
  118989. #include <math.h>
  118990. #include <string.h>
  118991. /**** pack/unpack helpers ******************************************/
  118992. int _ilog(unsigned int v){
  118993. int ret=0;
  118994. while(v){
  118995. ret++;
  118996. v>>=1;
  118997. }
  118998. return(ret);
  118999. }
  119000. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119001. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119002. Why not IEEE? It's just not that important here. */
  119003. #define VQ_FEXP 10
  119004. #define VQ_FMAN 21
  119005. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119006. /* doesn't currently guard under/overflow */
  119007. long _float32_pack(float val){
  119008. int sign=0;
  119009. long exp;
  119010. long mant;
  119011. if(val<0){
  119012. sign=0x80000000;
  119013. val= -val;
  119014. }
  119015. exp= floor(log(val)/log(2.f));
  119016. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119017. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119018. return(sign|exp|mant);
  119019. }
  119020. float _float32_unpack(long val){
  119021. double mant=val&0x1fffff;
  119022. int sign=val&0x80000000;
  119023. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119024. if(sign)mant= -mant;
  119025. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119026. }
  119027. /* given a list of word lengths, generate a list of codewords. Works
  119028. for length ordered or unordered, always assigns the lowest valued
  119029. codewords first. Extended to handle unused entries (length 0) */
  119030. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119031. long i,j,count=0;
  119032. ogg_uint32_t marker[33];
  119033. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119034. memset(marker,0,sizeof(marker));
  119035. for(i=0;i<n;i++){
  119036. long length=l[i];
  119037. if(length>0){
  119038. ogg_uint32_t entry=marker[length];
  119039. /* when we claim a node for an entry, we also claim the nodes
  119040. below it (pruning off the imagined tree that may have dangled
  119041. from it) as well as blocking the use of any nodes directly
  119042. above for leaves */
  119043. /* update ourself */
  119044. if(length<32 && (entry>>length)){
  119045. /* error condition; the lengths must specify an overpopulated tree */
  119046. _ogg_free(r);
  119047. return(NULL);
  119048. }
  119049. r[count++]=entry;
  119050. /* Look to see if the next shorter marker points to the node
  119051. above. if so, update it and repeat. */
  119052. {
  119053. for(j=length;j>0;j--){
  119054. if(marker[j]&1){
  119055. /* have to jump branches */
  119056. if(j==1)
  119057. marker[1]++;
  119058. else
  119059. marker[j]=marker[j-1]<<1;
  119060. break; /* invariant says next upper marker would already
  119061. have been moved if it was on the same path */
  119062. }
  119063. marker[j]++;
  119064. }
  119065. }
  119066. /* prune the tree; the implicit invariant says all the longer
  119067. markers were dangling from our just-taken node. Dangle them
  119068. from our *new* node. */
  119069. for(j=length+1;j<33;j++)
  119070. if((marker[j]>>1) == entry){
  119071. entry=marker[j];
  119072. marker[j]=marker[j-1]<<1;
  119073. }else
  119074. break;
  119075. }else
  119076. if(sparsecount==0)count++;
  119077. }
  119078. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119079. endian */
  119080. for(i=0,count=0;i<n;i++){
  119081. ogg_uint32_t temp=0;
  119082. for(j=0;j<l[i];j++){
  119083. temp<<=1;
  119084. temp|=(r[count]>>j)&1;
  119085. }
  119086. if(sparsecount){
  119087. if(l[i])
  119088. r[count++]=temp;
  119089. }else
  119090. r[count++]=temp;
  119091. }
  119092. return(r);
  119093. }
  119094. /* there might be a straightforward one-line way to do the below
  119095. that's portable and totally safe against roundoff, but I haven't
  119096. thought of it. Therefore, we opt on the side of caution */
  119097. long _book_maptype1_quantvals(const static_codebook *b){
  119098. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119099. /* the above *should* be reliable, but we'll not assume that FP is
  119100. ever reliable when bitstream sync is at stake; verify via integer
  119101. means that vals really is the greatest value of dim for which
  119102. vals^b->bim <= b->entries */
  119103. /* treat the above as an initial guess */
  119104. while(1){
  119105. long acc=1;
  119106. long acc1=1;
  119107. int i;
  119108. for(i=0;i<b->dim;i++){
  119109. acc*=vals;
  119110. acc1*=vals+1;
  119111. }
  119112. if(acc<=b->entries && acc1>b->entries){
  119113. return(vals);
  119114. }else{
  119115. if(acc>b->entries){
  119116. vals--;
  119117. }else{
  119118. vals++;
  119119. }
  119120. }
  119121. }
  119122. }
  119123. /* unpack the quantized list of values for encode/decode ***********/
  119124. /* we need to deal with two map types: in map type 1, the values are
  119125. generated algorithmically (each column of the vector counts through
  119126. the values in the quant vector). in map type 2, all the values came
  119127. in in an explicit list. Both value lists must be unpacked */
  119128. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119129. long j,k,count=0;
  119130. if(b->maptype==1 || b->maptype==2){
  119131. int quantvals;
  119132. float mindel=_float32_unpack(b->q_min);
  119133. float delta=_float32_unpack(b->q_delta);
  119134. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119135. /* maptype 1 and 2 both use a quantized value vector, but
  119136. different sizes */
  119137. switch(b->maptype){
  119138. case 1:
  119139. /* most of the time, entries%dimensions == 0, but we need to be
  119140. well defined. We define that the possible vales at each
  119141. scalar is values == entries/dim. If entries%dim != 0, we'll
  119142. have 'too few' values (values*dim<entries), which means that
  119143. we'll have 'left over' entries; left over entries use zeroed
  119144. values (and are wasted). So don't generate codebooks like
  119145. that */
  119146. quantvals=_book_maptype1_quantvals(b);
  119147. for(j=0;j<b->entries;j++){
  119148. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119149. float last=0.f;
  119150. int indexdiv=1;
  119151. for(k=0;k<b->dim;k++){
  119152. int index= (j/indexdiv)%quantvals;
  119153. float val=b->quantlist[index];
  119154. val=fabs(val)*delta+mindel+last;
  119155. if(b->q_sequencep)last=val;
  119156. if(sparsemap)
  119157. r[sparsemap[count]*b->dim+k]=val;
  119158. else
  119159. r[count*b->dim+k]=val;
  119160. indexdiv*=quantvals;
  119161. }
  119162. count++;
  119163. }
  119164. }
  119165. break;
  119166. case 2:
  119167. for(j=0;j<b->entries;j++){
  119168. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119169. float last=0.f;
  119170. for(k=0;k<b->dim;k++){
  119171. float val=b->quantlist[j*b->dim+k];
  119172. val=fabs(val)*delta+mindel+last;
  119173. if(b->q_sequencep)last=val;
  119174. if(sparsemap)
  119175. r[sparsemap[count]*b->dim+k]=val;
  119176. else
  119177. r[count*b->dim+k]=val;
  119178. }
  119179. count++;
  119180. }
  119181. }
  119182. break;
  119183. }
  119184. return(r);
  119185. }
  119186. return(NULL);
  119187. }
  119188. void vorbis_staticbook_clear(static_codebook *b){
  119189. if(b->allocedp){
  119190. if(b->quantlist)_ogg_free(b->quantlist);
  119191. if(b->lengthlist)_ogg_free(b->lengthlist);
  119192. if(b->nearest_tree){
  119193. _ogg_free(b->nearest_tree->ptr0);
  119194. _ogg_free(b->nearest_tree->ptr1);
  119195. _ogg_free(b->nearest_tree->p);
  119196. _ogg_free(b->nearest_tree->q);
  119197. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119198. _ogg_free(b->nearest_tree);
  119199. }
  119200. if(b->thresh_tree){
  119201. _ogg_free(b->thresh_tree->quantthresh);
  119202. _ogg_free(b->thresh_tree->quantmap);
  119203. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119204. _ogg_free(b->thresh_tree);
  119205. }
  119206. memset(b,0,sizeof(*b));
  119207. }
  119208. }
  119209. void vorbis_staticbook_destroy(static_codebook *b){
  119210. if(b->allocedp){
  119211. vorbis_staticbook_clear(b);
  119212. _ogg_free(b);
  119213. }
  119214. }
  119215. void vorbis_book_clear(codebook *b){
  119216. /* static book is not cleared; we're likely called on the lookup and
  119217. the static codebook belongs to the info struct */
  119218. if(b->valuelist)_ogg_free(b->valuelist);
  119219. if(b->codelist)_ogg_free(b->codelist);
  119220. if(b->dec_index)_ogg_free(b->dec_index);
  119221. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119222. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119223. memset(b,0,sizeof(*b));
  119224. }
  119225. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119226. memset(c,0,sizeof(*c));
  119227. c->c=s;
  119228. c->entries=s->entries;
  119229. c->used_entries=s->entries;
  119230. c->dim=s->dim;
  119231. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119232. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119233. return(0);
  119234. }
  119235. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119236. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119237. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119238. }
  119239. /* decode codebook arrangement is more heavily optimized than encode */
  119240. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119241. int i,j,n=0,tabn;
  119242. int *sortindex;
  119243. memset(c,0,sizeof(*c));
  119244. /* count actually used entries */
  119245. for(i=0;i<s->entries;i++)
  119246. if(s->lengthlist[i]>0)
  119247. n++;
  119248. c->entries=s->entries;
  119249. c->used_entries=n;
  119250. c->dim=s->dim;
  119251. /* two different remappings go on here.
  119252. First, we collapse the likely sparse codebook down only to
  119253. actually represented values/words. This collapsing needs to be
  119254. indexed as map-valueless books are used to encode original entry
  119255. positions as integers.
  119256. Second, we reorder all vectors, including the entry index above,
  119257. by sorted bitreversed codeword to allow treeless decode. */
  119258. {
  119259. /* perform sort */
  119260. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119261. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119262. if(codes==NULL)goto err_out;
  119263. for(i=0;i<n;i++){
  119264. codes[i]=ogg_bitreverse(codes[i]);
  119265. codep[i]=codes+i;
  119266. }
  119267. qsort(codep,n,sizeof(*codep),sort32a);
  119268. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119269. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119270. /* the index is a reverse index */
  119271. for(i=0;i<n;i++){
  119272. int position=codep[i]-codes;
  119273. sortindex[position]=i;
  119274. }
  119275. for(i=0;i<n;i++)
  119276. c->codelist[sortindex[i]]=codes[i];
  119277. _ogg_free(codes);
  119278. }
  119279. c->valuelist=_book_unquantize(s,n,sortindex);
  119280. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119281. for(n=0,i=0;i<s->entries;i++)
  119282. if(s->lengthlist[i]>0)
  119283. c->dec_index[sortindex[n++]]=i;
  119284. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119285. for(n=0,i=0;i<s->entries;i++)
  119286. if(s->lengthlist[i]>0)
  119287. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119288. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119289. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119290. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119291. tabn=1<<c->dec_firsttablen;
  119292. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119293. c->dec_maxlength=0;
  119294. for(i=0;i<n;i++){
  119295. if(c->dec_maxlength<c->dec_codelengths[i])
  119296. c->dec_maxlength=c->dec_codelengths[i];
  119297. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119298. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119299. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119300. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119301. }
  119302. }
  119303. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119304. hints for the non-direct-hits */
  119305. {
  119306. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119307. long lo=0,hi=0;
  119308. for(i=0;i<tabn;i++){
  119309. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119310. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119311. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119312. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119313. /* we only actually have 15 bits per hint to play with here.
  119314. In order to overflow gracefully (nothing breaks, efficiency
  119315. just drops), encode as the difference from the extremes. */
  119316. {
  119317. unsigned long loval=lo;
  119318. unsigned long hival=n-hi;
  119319. if(loval>0x7fff)loval=0x7fff;
  119320. if(hival>0x7fff)hival=0x7fff;
  119321. c->dec_firsttable[ogg_bitreverse(word)]=
  119322. 0x80000000UL | (loval<<15) | hival;
  119323. }
  119324. }
  119325. }
  119326. }
  119327. return(0);
  119328. err_out:
  119329. vorbis_book_clear(c);
  119330. return(-1);
  119331. }
  119332. static float _dist(int el,float *ref, float *b,int step){
  119333. int i;
  119334. float acc=0.f;
  119335. for(i=0;i<el;i++){
  119336. float val=(ref[i]-b[i*step]);
  119337. acc+=val*val;
  119338. }
  119339. return(acc);
  119340. }
  119341. int _best(codebook *book, float *a, int step){
  119342. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119343. #if 0
  119344. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119345. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119346. #endif
  119347. int dim=book->dim;
  119348. int k,o;
  119349. /*int savebest=-1;
  119350. float saverr;*/
  119351. /* do we have a threshhold encode hint? */
  119352. if(tt){
  119353. int index=0,i;
  119354. /* find the quant val of each scalar */
  119355. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119356. i=tt->threshvals>>1;
  119357. if(a[o]<tt->quantthresh[i]){
  119358. for(;i>0;i--)
  119359. if(a[o]>=tt->quantthresh[i-1])
  119360. break;
  119361. }else{
  119362. for(i++;i<tt->threshvals-1;i++)
  119363. if(a[o]<tt->quantthresh[i])break;
  119364. }
  119365. index=(index*tt->quantvals)+tt->quantmap[i];
  119366. }
  119367. /* regular lattices are easy :-) */
  119368. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119369. use a decision tree after all
  119370. and fall through*/
  119371. return(index);
  119372. }
  119373. #if 0
  119374. /* do we have a pigeonhole encode hint? */
  119375. if(pt){
  119376. const static_codebook *c=book->c;
  119377. int i,besti=-1;
  119378. float best=0.f;
  119379. int entry=0;
  119380. /* dealing with sequentialness is a pain in the ass */
  119381. if(c->q_sequencep){
  119382. int pv;
  119383. long mul=1;
  119384. float qlast=0;
  119385. for(k=0,o=0;k<dim;k++,o+=step){
  119386. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119387. if(pv<0 || pv>=pt->mapentries)break;
  119388. entry+=pt->pigeonmap[pv]*mul;
  119389. mul*=pt->quantvals;
  119390. qlast+=pv*pt->del+pt->min;
  119391. }
  119392. }else{
  119393. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119394. int pv=(int)((a[o]-pt->min)/pt->del);
  119395. if(pv<0 || pv>=pt->mapentries)break;
  119396. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119397. }
  119398. }
  119399. /* must be within the pigeonholable range; if we quant outside (or
  119400. in an entry that we define no list for), brute force it */
  119401. if(k==dim && pt->fitlength[entry]){
  119402. /* search the abbreviated list */
  119403. long *list=pt->fitlist+pt->fitmap[entry];
  119404. for(i=0;i<pt->fitlength[entry];i++){
  119405. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119406. if(besti==-1 || this<best){
  119407. best=this;
  119408. besti=list[i];
  119409. }
  119410. }
  119411. return(besti);
  119412. }
  119413. }
  119414. if(nt){
  119415. /* optimized using the decision tree */
  119416. while(1){
  119417. float c=0.f;
  119418. float *p=book->valuelist+nt->p[ptr];
  119419. float *q=book->valuelist+nt->q[ptr];
  119420. for(k=0,o=0;k<dim;k++,o+=step)
  119421. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119422. if(c>0.f) /* in A */
  119423. ptr= -nt->ptr0[ptr];
  119424. else /* in B */
  119425. ptr= -nt->ptr1[ptr];
  119426. if(ptr<=0)break;
  119427. }
  119428. return(-ptr);
  119429. }
  119430. #endif
  119431. /* brute force it! */
  119432. {
  119433. const static_codebook *c=book->c;
  119434. int i,besti=-1;
  119435. float best=0.f;
  119436. float *e=book->valuelist;
  119437. for(i=0;i<book->entries;i++){
  119438. if(c->lengthlist[i]>0){
  119439. float thisx=_dist(dim,e,a,step);
  119440. if(besti==-1 || thisx<best){
  119441. best=thisx;
  119442. besti=i;
  119443. }
  119444. }
  119445. e+=dim;
  119446. }
  119447. /*if(savebest!=-1 && savebest!=besti){
  119448. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119449. "original:");
  119450. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119451. fprintf(stderr,"\n"
  119452. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119453. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119454. (book->valuelist+savebest*dim)[i]);
  119455. fprintf(stderr,"\n"
  119456. "bruteforce (entry %d, err %g):",besti,best);
  119457. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119458. (book->valuelist+besti*dim)[i]);
  119459. fprintf(stderr,"\n");
  119460. }*/
  119461. return(besti);
  119462. }
  119463. }
  119464. long vorbis_book_codeword(codebook *book,int entry){
  119465. if(book->c) /* only use with encode; decode optimizations are
  119466. allowed to break this */
  119467. return book->codelist[entry];
  119468. return -1;
  119469. }
  119470. long vorbis_book_codelen(codebook *book,int entry){
  119471. if(book->c) /* only use with encode; decode optimizations are
  119472. allowed to break this */
  119473. return book->c->lengthlist[entry];
  119474. return -1;
  119475. }
  119476. #ifdef _V_SELFTEST
  119477. /* Unit tests of the dequantizer; this stuff will be OK
  119478. cross-platform, I simply want to be sure that special mapping cases
  119479. actually work properly; a bug could go unnoticed for a while */
  119480. #include <stdio.h>
  119481. /* cases:
  119482. no mapping
  119483. full, explicit mapping
  119484. algorithmic mapping
  119485. nonsequential
  119486. sequential
  119487. */
  119488. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119489. static long partial_quantlist1[]={0,7,2};
  119490. /* no mapping */
  119491. static_codebook test1={
  119492. 4,16,
  119493. NULL,
  119494. 0,
  119495. 0,0,0,0,
  119496. NULL,
  119497. NULL,NULL
  119498. };
  119499. static float *test1_result=NULL;
  119500. /* linear, full mapping, nonsequential */
  119501. static_codebook test2={
  119502. 4,3,
  119503. NULL,
  119504. 2,
  119505. -533200896,1611661312,4,0,
  119506. full_quantlist1,
  119507. NULL,NULL
  119508. };
  119509. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119510. /* linear, full mapping, sequential */
  119511. static_codebook test3={
  119512. 4,3,
  119513. NULL,
  119514. 2,
  119515. -533200896,1611661312,4,1,
  119516. full_quantlist1,
  119517. NULL,NULL
  119518. };
  119519. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119520. /* linear, algorithmic mapping, nonsequential */
  119521. static_codebook test4={
  119522. 3,27,
  119523. NULL,
  119524. 1,
  119525. -533200896,1611661312,4,0,
  119526. partial_quantlist1,
  119527. NULL,NULL
  119528. };
  119529. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119530. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119531. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119532. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119533. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119534. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119535. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119536. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119537. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119538. /* linear, algorithmic mapping, sequential */
  119539. static_codebook test5={
  119540. 3,27,
  119541. NULL,
  119542. 1,
  119543. -533200896,1611661312,4,1,
  119544. partial_quantlist1,
  119545. NULL,NULL
  119546. };
  119547. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119548. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119549. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119550. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119551. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119552. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119553. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119554. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119555. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119556. void run_test(static_codebook *b,float *comp){
  119557. float *out=_book_unquantize(b,b->entries,NULL);
  119558. int i;
  119559. if(comp){
  119560. if(!out){
  119561. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119562. exit(1);
  119563. }
  119564. for(i=0;i<b->entries*b->dim;i++)
  119565. if(fabs(out[i]-comp[i])>.0001){
  119566. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119567. "position %d, %g != %g\n",i,out[i],comp[i]);
  119568. exit(1);
  119569. }
  119570. }else{
  119571. if(out){
  119572. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119573. " correct result should have been NULL\n");
  119574. exit(1);
  119575. }
  119576. }
  119577. }
  119578. int main(){
  119579. /* run the nine dequant tests, and compare to the hand-rolled results */
  119580. fprintf(stderr,"Dequant test 1... ");
  119581. run_test(&test1,test1_result);
  119582. fprintf(stderr,"OK\nDequant test 2... ");
  119583. run_test(&test2,test2_result);
  119584. fprintf(stderr,"OK\nDequant test 3... ");
  119585. run_test(&test3,test3_result);
  119586. fprintf(stderr,"OK\nDequant test 4... ");
  119587. run_test(&test4,test4_result);
  119588. fprintf(stderr,"OK\nDequant test 5... ");
  119589. run_test(&test5,test5_result);
  119590. fprintf(stderr,"OK\n\n");
  119591. return(0);
  119592. }
  119593. #endif
  119594. #endif
  119595. /*** End of inlined file: sharedbook.c ***/
  119596. /*** Start of inlined file: smallft.c ***/
  119597. /* FFT implementation from OggSquish, minus cosine transforms,
  119598. * minus all but radix 2/4 case. In Vorbis we only need this
  119599. * cut-down version.
  119600. *
  119601. * To do more than just power-of-two sized vectors, see the full
  119602. * version I wrote for NetLib.
  119603. *
  119604. * Note that the packing is a little strange; rather than the FFT r/i
  119605. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119606. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119607. * FORTRAN version
  119608. */
  119609. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119610. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119611. // tasks..
  119612. #if JUCE_MSVC
  119613. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119614. #endif
  119615. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119616. #if JUCE_USE_OGGVORBIS
  119617. #include <stdlib.h>
  119618. #include <string.h>
  119619. #include <math.h>
  119620. static void drfti1(int n, float *wa, int *ifac){
  119621. static int ntryh[4] = { 4,2,3,5 };
  119622. static float tpi = 6.28318530717958648f;
  119623. float arg,argh,argld,fi;
  119624. int ntry=0,i,j=-1;
  119625. int k1, l1, l2, ib;
  119626. int ld, ii, ip, is, nq, nr;
  119627. int ido, ipm, nfm1;
  119628. int nl=n;
  119629. int nf=0;
  119630. L101:
  119631. j++;
  119632. if (j < 4)
  119633. ntry=ntryh[j];
  119634. else
  119635. ntry+=2;
  119636. L104:
  119637. nq=nl/ntry;
  119638. nr=nl-ntry*nq;
  119639. if (nr!=0) goto L101;
  119640. nf++;
  119641. ifac[nf+1]=ntry;
  119642. nl=nq;
  119643. if(ntry!=2)goto L107;
  119644. if(nf==1)goto L107;
  119645. for (i=1;i<nf;i++){
  119646. ib=nf-i+1;
  119647. ifac[ib+1]=ifac[ib];
  119648. }
  119649. ifac[2] = 2;
  119650. L107:
  119651. if(nl!=1)goto L104;
  119652. ifac[0]=n;
  119653. ifac[1]=nf;
  119654. argh=tpi/n;
  119655. is=0;
  119656. nfm1=nf-1;
  119657. l1=1;
  119658. if(nfm1==0)return;
  119659. for (k1=0;k1<nfm1;k1++){
  119660. ip=ifac[k1+2];
  119661. ld=0;
  119662. l2=l1*ip;
  119663. ido=n/l2;
  119664. ipm=ip-1;
  119665. for (j=0;j<ipm;j++){
  119666. ld+=l1;
  119667. i=is;
  119668. argld=(float)ld*argh;
  119669. fi=0.f;
  119670. for (ii=2;ii<ido;ii+=2){
  119671. fi+=1.f;
  119672. arg=fi*argld;
  119673. wa[i++]=cos(arg);
  119674. wa[i++]=sin(arg);
  119675. }
  119676. is+=ido;
  119677. }
  119678. l1=l2;
  119679. }
  119680. }
  119681. static void fdrffti(int n, float *wsave, int *ifac){
  119682. if (n == 1) return;
  119683. drfti1(n, wsave+n, ifac);
  119684. }
  119685. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119686. int i,k;
  119687. float ti2,tr2;
  119688. int t0,t1,t2,t3,t4,t5,t6;
  119689. t1=0;
  119690. t0=(t2=l1*ido);
  119691. t3=ido<<1;
  119692. for(k=0;k<l1;k++){
  119693. ch[t1<<1]=cc[t1]+cc[t2];
  119694. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119695. t1+=ido;
  119696. t2+=ido;
  119697. }
  119698. if(ido<2)return;
  119699. if(ido==2)goto L105;
  119700. t1=0;
  119701. t2=t0;
  119702. for(k=0;k<l1;k++){
  119703. t3=t2;
  119704. t4=(t1<<1)+(ido<<1);
  119705. t5=t1;
  119706. t6=t1+t1;
  119707. for(i=2;i<ido;i+=2){
  119708. t3+=2;
  119709. t4-=2;
  119710. t5+=2;
  119711. t6+=2;
  119712. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119713. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119714. ch[t6]=cc[t5]+ti2;
  119715. ch[t4]=ti2-cc[t5];
  119716. ch[t6-1]=cc[t5-1]+tr2;
  119717. ch[t4-1]=cc[t5-1]-tr2;
  119718. }
  119719. t1+=ido;
  119720. t2+=ido;
  119721. }
  119722. if(ido%2==1)return;
  119723. L105:
  119724. t3=(t2=(t1=ido)-1);
  119725. t2+=t0;
  119726. for(k=0;k<l1;k++){
  119727. ch[t1]=-cc[t2];
  119728. ch[t1-1]=cc[t3];
  119729. t1+=ido<<1;
  119730. t2+=ido;
  119731. t3+=ido;
  119732. }
  119733. }
  119734. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119735. float *wa2,float *wa3){
  119736. static float hsqt2 = .70710678118654752f;
  119737. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119738. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119739. t0=l1*ido;
  119740. t1=t0;
  119741. t4=t1<<1;
  119742. t2=t1+(t1<<1);
  119743. t3=0;
  119744. for(k=0;k<l1;k++){
  119745. tr1=cc[t1]+cc[t2];
  119746. tr2=cc[t3]+cc[t4];
  119747. ch[t5=t3<<2]=tr1+tr2;
  119748. ch[(ido<<2)+t5-1]=tr2-tr1;
  119749. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119750. ch[t5]=cc[t2]-cc[t1];
  119751. t1+=ido;
  119752. t2+=ido;
  119753. t3+=ido;
  119754. t4+=ido;
  119755. }
  119756. if(ido<2)return;
  119757. if(ido==2)goto L105;
  119758. t1=0;
  119759. for(k=0;k<l1;k++){
  119760. t2=t1;
  119761. t4=t1<<2;
  119762. t5=(t6=ido<<1)+t4;
  119763. for(i=2;i<ido;i+=2){
  119764. t3=(t2+=2);
  119765. t4+=2;
  119766. t5-=2;
  119767. t3+=t0;
  119768. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119769. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119770. t3+=t0;
  119771. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119772. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119773. t3+=t0;
  119774. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119775. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119776. tr1=cr2+cr4;
  119777. tr4=cr4-cr2;
  119778. ti1=ci2+ci4;
  119779. ti4=ci2-ci4;
  119780. ti2=cc[t2]+ci3;
  119781. ti3=cc[t2]-ci3;
  119782. tr2=cc[t2-1]+cr3;
  119783. tr3=cc[t2-1]-cr3;
  119784. ch[t4-1]=tr1+tr2;
  119785. ch[t4]=ti1+ti2;
  119786. ch[t5-1]=tr3-ti4;
  119787. ch[t5]=tr4-ti3;
  119788. ch[t4+t6-1]=ti4+tr3;
  119789. ch[t4+t6]=tr4+ti3;
  119790. ch[t5+t6-1]=tr2-tr1;
  119791. ch[t5+t6]=ti1-ti2;
  119792. }
  119793. t1+=ido;
  119794. }
  119795. if(ido&1)return;
  119796. L105:
  119797. t2=(t1=t0+ido-1)+(t0<<1);
  119798. t3=ido<<2;
  119799. t4=ido;
  119800. t5=ido<<1;
  119801. t6=ido;
  119802. for(k=0;k<l1;k++){
  119803. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119804. tr1=hsqt2*(cc[t1]-cc[t2]);
  119805. ch[t4-1]=tr1+cc[t6-1];
  119806. ch[t4+t5-1]=cc[t6-1]-tr1;
  119807. ch[t4]=ti1-cc[t1+t0];
  119808. ch[t4+t5]=ti1+cc[t1+t0];
  119809. t1+=ido;
  119810. t2+=ido;
  119811. t4+=t3;
  119812. t6+=ido;
  119813. }
  119814. }
  119815. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119816. float *c2,float *ch,float *ch2,float *wa){
  119817. static float tpi=6.283185307179586f;
  119818. int idij,ipph,i,j,k,l,ic,ik,is;
  119819. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119820. float dc2,ai1,ai2,ar1,ar2,ds2;
  119821. int nbd;
  119822. float dcp,arg,dsp,ar1h,ar2h;
  119823. int idp2,ipp2;
  119824. arg=tpi/(float)ip;
  119825. dcp=cos(arg);
  119826. dsp=sin(arg);
  119827. ipph=(ip+1)>>1;
  119828. ipp2=ip;
  119829. idp2=ido;
  119830. nbd=(ido-1)>>1;
  119831. t0=l1*ido;
  119832. t10=ip*ido;
  119833. if(ido==1)goto L119;
  119834. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119835. t1=0;
  119836. for(j=1;j<ip;j++){
  119837. t1+=t0;
  119838. t2=t1;
  119839. for(k=0;k<l1;k++){
  119840. ch[t2]=c1[t2];
  119841. t2+=ido;
  119842. }
  119843. }
  119844. is=-ido;
  119845. t1=0;
  119846. if(nbd>l1){
  119847. for(j=1;j<ip;j++){
  119848. t1+=t0;
  119849. is+=ido;
  119850. t2= -ido+t1;
  119851. for(k=0;k<l1;k++){
  119852. idij=is-1;
  119853. t2+=ido;
  119854. t3=t2;
  119855. for(i=2;i<ido;i+=2){
  119856. idij+=2;
  119857. t3+=2;
  119858. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119859. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119860. }
  119861. }
  119862. }
  119863. }else{
  119864. for(j=1;j<ip;j++){
  119865. is+=ido;
  119866. idij=is-1;
  119867. t1+=t0;
  119868. t2=t1;
  119869. for(i=2;i<ido;i+=2){
  119870. idij+=2;
  119871. t2+=2;
  119872. t3=t2;
  119873. for(k=0;k<l1;k++){
  119874. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119875. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119876. t3+=ido;
  119877. }
  119878. }
  119879. }
  119880. }
  119881. t1=0;
  119882. t2=ipp2*t0;
  119883. if(nbd<l1){
  119884. for(j=1;j<ipph;j++){
  119885. t1+=t0;
  119886. t2-=t0;
  119887. t3=t1;
  119888. t4=t2;
  119889. for(i=2;i<ido;i+=2){
  119890. t3+=2;
  119891. t4+=2;
  119892. t5=t3-ido;
  119893. t6=t4-ido;
  119894. for(k=0;k<l1;k++){
  119895. t5+=ido;
  119896. t6+=ido;
  119897. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119898. c1[t6-1]=ch[t5]-ch[t6];
  119899. c1[t5]=ch[t5]+ch[t6];
  119900. c1[t6]=ch[t6-1]-ch[t5-1];
  119901. }
  119902. }
  119903. }
  119904. }else{
  119905. for(j=1;j<ipph;j++){
  119906. t1+=t0;
  119907. t2-=t0;
  119908. t3=t1;
  119909. t4=t2;
  119910. for(k=0;k<l1;k++){
  119911. t5=t3;
  119912. t6=t4;
  119913. for(i=2;i<ido;i+=2){
  119914. t5+=2;
  119915. t6+=2;
  119916. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119917. c1[t6-1]=ch[t5]-ch[t6];
  119918. c1[t5]=ch[t5]+ch[t6];
  119919. c1[t6]=ch[t6-1]-ch[t5-1];
  119920. }
  119921. t3+=ido;
  119922. t4+=ido;
  119923. }
  119924. }
  119925. }
  119926. L119:
  119927. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119928. t1=0;
  119929. t2=ipp2*idl1;
  119930. for(j=1;j<ipph;j++){
  119931. t1+=t0;
  119932. t2-=t0;
  119933. t3=t1-ido;
  119934. t4=t2-ido;
  119935. for(k=0;k<l1;k++){
  119936. t3+=ido;
  119937. t4+=ido;
  119938. c1[t3]=ch[t3]+ch[t4];
  119939. c1[t4]=ch[t4]-ch[t3];
  119940. }
  119941. }
  119942. ar1=1.f;
  119943. ai1=0.f;
  119944. t1=0;
  119945. t2=ipp2*idl1;
  119946. t3=(ip-1)*idl1;
  119947. for(l=1;l<ipph;l++){
  119948. t1+=idl1;
  119949. t2-=idl1;
  119950. ar1h=dcp*ar1-dsp*ai1;
  119951. ai1=dcp*ai1+dsp*ar1;
  119952. ar1=ar1h;
  119953. t4=t1;
  119954. t5=t2;
  119955. t6=t3;
  119956. t7=idl1;
  119957. for(ik=0;ik<idl1;ik++){
  119958. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119959. ch2[t5++]=ai1*c2[t6++];
  119960. }
  119961. dc2=ar1;
  119962. ds2=ai1;
  119963. ar2=ar1;
  119964. ai2=ai1;
  119965. t4=idl1;
  119966. t5=(ipp2-1)*idl1;
  119967. for(j=2;j<ipph;j++){
  119968. t4+=idl1;
  119969. t5-=idl1;
  119970. ar2h=dc2*ar2-ds2*ai2;
  119971. ai2=dc2*ai2+ds2*ar2;
  119972. ar2=ar2h;
  119973. t6=t1;
  119974. t7=t2;
  119975. t8=t4;
  119976. t9=t5;
  119977. for(ik=0;ik<idl1;ik++){
  119978. ch2[t6++]+=ar2*c2[t8++];
  119979. ch2[t7++]+=ai2*c2[t9++];
  119980. }
  119981. }
  119982. }
  119983. t1=0;
  119984. for(j=1;j<ipph;j++){
  119985. t1+=idl1;
  119986. t2=t1;
  119987. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119988. }
  119989. if(ido<l1)goto L132;
  119990. t1=0;
  119991. t2=0;
  119992. for(k=0;k<l1;k++){
  119993. t3=t1;
  119994. t4=t2;
  119995. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119996. t1+=ido;
  119997. t2+=t10;
  119998. }
  119999. goto L135;
  120000. L132:
  120001. for(i=0;i<ido;i++){
  120002. t1=i;
  120003. t2=i;
  120004. for(k=0;k<l1;k++){
  120005. cc[t2]=ch[t1];
  120006. t1+=ido;
  120007. t2+=t10;
  120008. }
  120009. }
  120010. L135:
  120011. t1=0;
  120012. t2=ido<<1;
  120013. t3=0;
  120014. t4=ipp2*t0;
  120015. for(j=1;j<ipph;j++){
  120016. t1+=t2;
  120017. t3+=t0;
  120018. t4-=t0;
  120019. t5=t1;
  120020. t6=t3;
  120021. t7=t4;
  120022. for(k=0;k<l1;k++){
  120023. cc[t5-1]=ch[t6];
  120024. cc[t5]=ch[t7];
  120025. t5+=t10;
  120026. t6+=ido;
  120027. t7+=ido;
  120028. }
  120029. }
  120030. if(ido==1)return;
  120031. if(nbd<l1)goto L141;
  120032. t1=-ido;
  120033. t3=0;
  120034. t4=0;
  120035. t5=ipp2*t0;
  120036. for(j=1;j<ipph;j++){
  120037. t1+=t2;
  120038. t3+=t2;
  120039. t4+=t0;
  120040. t5-=t0;
  120041. t6=t1;
  120042. t7=t3;
  120043. t8=t4;
  120044. t9=t5;
  120045. for(k=0;k<l1;k++){
  120046. for(i=2;i<ido;i+=2){
  120047. ic=idp2-i;
  120048. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120049. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120050. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120051. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120052. }
  120053. t6+=t10;
  120054. t7+=t10;
  120055. t8+=ido;
  120056. t9+=ido;
  120057. }
  120058. }
  120059. return;
  120060. L141:
  120061. t1=-ido;
  120062. t3=0;
  120063. t4=0;
  120064. t5=ipp2*t0;
  120065. for(j=1;j<ipph;j++){
  120066. t1+=t2;
  120067. t3+=t2;
  120068. t4+=t0;
  120069. t5-=t0;
  120070. for(i=2;i<ido;i+=2){
  120071. t6=idp2+t1-i;
  120072. t7=i+t3;
  120073. t8=i+t4;
  120074. t9=i+t5;
  120075. for(k=0;k<l1;k++){
  120076. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120077. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120078. cc[t7]=ch[t8]+ch[t9];
  120079. cc[t6]=ch[t9]-ch[t8];
  120080. t6+=t10;
  120081. t7+=t10;
  120082. t8+=ido;
  120083. t9+=ido;
  120084. }
  120085. }
  120086. }
  120087. }
  120088. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120089. int i,k1,l1,l2;
  120090. int na,kh,nf;
  120091. int ip,iw,ido,idl1,ix2,ix3;
  120092. nf=ifac[1];
  120093. na=1;
  120094. l2=n;
  120095. iw=n;
  120096. for(k1=0;k1<nf;k1++){
  120097. kh=nf-k1;
  120098. ip=ifac[kh+1];
  120099. l1=l2/ip;
  120100. ido=n/l2;
  120101. idl1=ido*l1;
  120102. iw-=(ip-1)*ido;
  120103. na=1-na;
  120104. if(ip!=4)goto L102;
  120105. ix2=iw+ido;
  120106. ix3=ix2+ido;
  120107. if(na!=0)
  120108. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120109. else
  120110. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120111. goto L110;
  120112. L102:
  120113. if(ip!=2)goto L104;
  120114. if(na!=0)goto L103;
  120115. dradf2(ido,l1,c,ch,wa+iw-1);
  120116. goto L110;
  120117. L103:
  120118. dradf2(ido,l1,ch,c,wa+iw-1);
  120119. goto L110;
  120120. L104:
  120121. if(ido==1)na=1-na;
  120122. if(na!=0)goto L109;
  120123. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120124. na=1;
  120125. goto L110;
  120126. L109:
  120127. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120128. na=0;
  120129. L110:
  120130. l2=l1;
  120131. }
  120132. if(na==1)return;
  120133. for(i=0;i<n;i++)c[i]=ch[i];
  120134. }
  120135. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120136. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120137. float ti2,tr2;
  120138. t0=l1*ido;
  120139. t1=0;
  120140. t2=0;
  120141. t3=(ido<<1)-1;
  120142. for(k=0;k<l1;k++){
  120143. ch[t1]=cc[t2]+cc[t3+t2];
  120144. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120145. t2=(t1+=ido)<<1;
  120146. }
  120147. if(ido<2)return;
  120148. if(ido==2)goto L105;
  120149. t1=0;
  120150. t2=0;
  120151. for(k=0;k<l1;k++){
  120152. t3=t1;
  120153. t5=(t4=t2)+(ido<<1);
  120154. t6=t0+t1;
  120155. for(i=2;i<ido;i+=2){
  120156. t3+=2;
  120157. t4+=2;
  120158. t5-=2;
  120159. t6+=2;
  120160. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120161. tr2=cc[t4-1]-cc[t5-1];
  120162. ch[t3]=cc[t4]-cc[t5];
  120163. ti2=cc[t4]+cc[t5];
  120164. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120165. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120166. }
  120167. t2=(t1+=ido)<<1;
  120168. }
  120169. if(ido%2==1)return;
  120170. L105:
  120171. t1=ido-1;
  120172. t2=ido-1;
  120173. for(k=0;k<l1;k++){
  120174. ch[t1]=cc[t2]+cc[t2];
  120175. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120176. t1+=ido;
  120177. t2+=ido<<1;
  120178. }
  120179. }
  120180. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120181. float *wa2){
  120182. static float taur = -.5f;
  120183. static float taui = .8660254037844386f;
  120184. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120185. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120186. t0=l1*ido;
  120187. t1=0;
  120188. t2=t0<<1;
  120189. t3=ido<<1;
  120190. t4=ido+(ido<<1);
  120191. t5=0;
  120192. for(k=0;k<l1;k++){
  120193. tr2=cc[t3-1]+cc[t3-1];
  120194. cr2=cc[t5]+(taur*tr2);
  120195. ch[t1]=cc[t5]+tr2;
  120196. ci3=taui*(cc[t3]+cc[t3]);
  120197. ch[t1+t0]=cr2-ci3;
  120198. ch[t1+t2]=cr2+ci3;
  120199. t1+=ido;
  120200. t3+=t4;
  120201. t5+=t4;
  120202. }
  120203. if(ido==1)return;
  120204. t1=0;
  120205. t3=ido<<1;
  120206. for(k=0;k<l1;k++){
  120207. t7=t1+(t1<<1);
  120208. t6=(t5=t7+t3);
  120209. t8=t1;
  120210. t10=(t9=t1+t0)+t0;
  120211. for(i=2;i<ido;i+=2){
  120212. t5+=2;
  120213. t6-=2;
  120214. t7+=2;
  120215. t8+=2;
  120216. t9+=2;
  120217. t10+=2;
  120218. tr2=cc[t5-1]+cc[t6-1];
  120219. cr2=cc[t7-1]+(taur*tr2);
  120220. ch[t8-1]=cc[t7-1]+tr2;
  120221. ti2=cc[t5]-cc[t6];
  120222. ci2=cc[t7]+(taur*ti2);
  120223. ch[t8]=cc[t7]+ti2;
  120224. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120225. ci3=taui*(cc[t5]+cc[t6]);
  120226. dr2=cr2-ci3;
  120227. dr3=cr2+ci3;
  120228. di2=ci2+cr3;
  120229. di3=ci2-cr3;
  120230. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120231. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120232. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120233. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120234. }
  120235. t1+=ido;
  120236. }
  120237. }
  120238. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120239. float *wa2,float *wa3){
  120240. static float sqrt2=1.414213562373095f;
  120241. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120242. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120243. t0=l1*ido;
  120244. t1=0;
  120245. t2=ido<<2;
  120246. t3=0;
  120247. t6=ido<<1;
  120248. for(k=0;k<l1;k++){
  120249. t4=t3+t6;
  120250. t5=t1;
  120251. tr3=cc[t4-1]+cc[t4-1];
  120252. tr4=cc[t4]+cc[t4];
  120253. tr1=cc[t3]-cc[(t4+=t6)-1];
  120254. tr2=cc[t3]+cc[t4-1];
  120255. ch[t5]=tr2+tr3;
  120256. ch[t5+=t0]=tr1-tr4;
  120257. ch[t5+=t0]=tr2-tr3;
  120258. ch[t5+=t0]=tr1+tr4;
  120259. t1+=ido;
  120260. t3+=t2;
  120261. }
  120262. if(ido<2)return;
  120263. if(ido==2)goto L105;
  120264. t1=0;
  120265. for(k=0;k<l1;k++){
  120266. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120267. t7=t1;
  120268. for(i=2;i<ido;i+=2){
  120269. t2+=2;
  120270. t3+=2;
  120271. t4-=2;
  120272. t5-=2;
  120273. t7+=2;
  120274. ti1=cc[t2]+cc[t5];
  120275. ti2=cc[t2]-cc[t5];
  120276. ti3=cc[t3]-cc[t4];
  120277. tr4=cc[t3]+cc[t4];
  120278. tr1=cc[t2-1]-cc[t5-1];
  120279. tr2=cc[t2-1]+cc[t5-1];
  120280. ti4=cc[t3-1]-cc[t4-1];
  120281. tr3=cc[t3-1]+cc[t4-1];
  120282. ch[t7-1]=tr2+tr3;
  120283. cr3=tr2-tr3;
  120284. ch[t7]=ti2+ti3;
  120285. ci3=ti2-ti3;
  120286. cr2=tr1-tr4;
  120287. cr4=tr1+tr4;
  120288. ci2=ti1+ti4;
  120289. ci4=ti1-ti4;
  120290. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120291. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120292. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120293. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120294. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120295. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120296. }
  120297. t1+=ido;
  120298. }
  120299. if(ido%2 == 1)return;
  120300. L105:
  120301. t1=ido;
  120302. t2=ido<<2;
  120303. t3=ido-1;
  120304. t4=ido+(ido<<1);
  120305. for(k=0;k<l1;k++){
  120306. t5=t3;
  120307. ti1=cc[t1]+cc[t4];
  120308. ti2=cc[t4]-cc[t1];
  120309. tr1=cc[t1-1]-cc[t4-1];
  120310. tr2=cc[t1-1]+cc[t4-1];
  120311. ch[t5]=tr2+tr2;
  120312. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120313. ch[t5+=t0]=ti2+ti2;
  120314. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120315. t3+=ido;
  120316. t1+=t2;
  120317. t4+=t2;
  120318. }
  120319. }
  120320. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120321. float *c2,float *ch,float *ch2,float *wa){
  120322. static float tpi=6.283185307179586f;
  120323. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120324. t11,t12;
  120325. float dc2,ai1,ai2,ar1,ar2,ds2;
  120326. int nbd;
  120327. float dcp,arg,dsp,ar1h,ar2h;
  120328. int ipp2;
  120329. t10=ip*ido;
  120330. t0=l1*ido;
  120331. arg=tpi/(float)ip;
  120332. dcp=cos(arg);
  120333. dsp=sin(arg);
  120334. nbd=(ido-1)>>1;
  120335. ipp2=ip;
  120336. ipph=(ip+1)>>1;
  120337. if(ido<l1)goto L103;
  120338. t1=0;
  120339. t2=0;
  120340. for(k=0;k<l1;k++){
  120341. t3=t1;
  120342. t4=t2;
  120343. for(i=0;i<ido;i++){
  120344. ch[t3]=cc[t4];
  120345. t3++;
  120346. t4++;
  120347. }
  120348. t1+=ido;
  120349. t2+=t10;
  120350. }
  120351. goto L106;
  120352. L103:
  120353. t1=0;
  120354. for(i=0;i<ido;i++){
  120355. t2=t1;
  120356. t3=t1;
  120357. for(k=0;k<l1;k++){
  120358. ch[t2]=cc[t3];
  120359. t2+=ido;
  120360. t3+=t10;
  120361. }
  120362. t1++;
  120363. }
  120364. L106:
  120365. t1=0;
  120366. t2=ipp2*t0;
  120367. t7=(t5=ido<<1);
  120368. for(j=1;j<ipph;j++){
  120369. t1+=t0;
  120370. t2-=t0;
  120371. t3=t1;
  120372. t4=t2;
  120373. t6=t5;
  120374. for(k=0;k<l1;k++){
  120375. ch[t3]=cc[t6-1]+cc[t6-1];
  120376. ch[t4]=cc[t6]+cc[t6];
  120377. t3+=ido;
  120378. t4+=ido;
  120379. t6+=t10;
  120380. }
  120381. t5+=t7;
  120382. }
  120383. if (ido == 1)goto L116;
  120384. if(nbd<l1)goto L112;
  120385. t1=0;
  120386. t2=ipp2*t0;
  120387. t7=0;
  120388. for(j=1;j<ipph;j++){
  120389. t1+=t0;
  120390. t2-=t0;
  120391. t3=t1;
  120392. t4=t2;
  120393. t7+=(ido<<1);
  120394. t8=t7;
  120395. for(k=0;k<l1;k++){
  120396. t5=t3;
  120397. t6=t4;
  120398. t9=t8;
  120399. t11=t8;
  120400. for(i=2;i<ido;i+=2){
  120401. t5+=2;
  120402. t6+=2;
  120403. t9+=2;
  120404. t11-=2;
  120405. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120406. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120407. ch[t5]=cc[t9]-cc[t11];
  120408. ch[t6]=cc[t9]+cc[t11];
  120409. }
  120410. t3+=ido;
  120411. t4+=ido;
  120412. t8+=t10;
  120413. }
  120414. }
  120415. goto L116;
  120416. L112:
  120417. t1=0;
  120418. t2=ipp2*t0;
  120419. t7=0;
  120420. for(j=1;j<ipph;j++){
  120421. t1+=t0;
  120422. t2-=t0;
  120423. t3=t1;
  120424. t4=t2;
  120425. t7+=(ido<<1);
  120426. t8=t7;
  120427. t9=t7;
  120428. for(i=2;i<ido;i+=2){
  120429. t3+=2;
  120430. t4+=2;
  120431. t8+=2;
  120432. t9-=2;
  120433. t5=t3;
  120434. t6=t4;
  120435. t11=t8;
  120436. t12=t9;
  120437. for(k=0;k<l1;k++){
  120438. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120439. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120440. ch[t5]=cc[t11]-cc[t12];
  120441. ch[t6]=cc[t11]+cc[t12];
  120442. t5+=ido;
  120443. t6+=ido;
  120444. t11+=t10;
  120445. t12+=t10;
  120446. }
  120447. }
  120448. }
  120449. L116:
  120450. ar1=1.f;
  120451. ai1=0.f;
  120452. t1=0;
  120453. t9=(t2=ipp2*idl1);
  120454. t3=(ip-1)*idl1;
  120455. for(l=1;l<ipph;l++){
  120456. t1+=idl1;
  120457. t2-=idl1;
  120458. ar1h=dcp*ar1-dsp*ai1;
  120459. ai1=dcp*ai1+dsp*ar1;
  120460. ar1=ar1h;
  120461. t4=t1;
  120462. t5=t2;
  120463. t6=0;
  120464. t7=idl1;
  120465. t8=t3;
  120466. for(ik=0;ik<idl1;ik++){
  120467. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120468. c2[t5++]=ai1*ch2[t8++];
  120469. }
  120470. dc2=ar1;
  120471. ds2=ai1;
  120472. ar2=ar1;
  120473. ai2=ai1;
  120474. t6=idl1;
  120475. t7=t9-idl1;
  120476. for(j=2;j<ipph;j++){
  120477. t6+=idl1;
  120478. t7-=idl1;
  120479. ar2h=dc2*ar2-ds2*ai2;
  120480. ai2=dc2*ai2+ds2*ar2;
  120481. ar2=ar2h;
  120482. t4=t1;
  120483. t5=t2;
  120484. t11=t6;
  120485. t12=t7;
  120486. for(ik=0;ik<idl1;ik++){
  120487. c2[t4++]+=ar2*ch2[t11++];
  120488. c2[t5++]+=ai2*ch2[t12++];
  120489. }
  120490. }
  120491. }
  120492. t1=0;
  120493. for(j=1;j<ipph;j++){
  120494. t1+=idl1;
  120495. t2=t1;
  120496. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120497. }
  120498. t1=0;
  120499. t2=ipp2*t0;
  120500. for(j=1;j<ipph;j++){
  120501. t1+=t0;
  120502. t2-=t0;
  120503. t3=t1;
  120504. t4=t2;
  120505. for(k=0;k<l1;k++){
  120506. ch[t3]=c1[t3]-c1[t4];
  120507. ch[t4]=c1[t3]+c1[t4];
  120508. t3+=ido;
  120509. t4+=ido;
  120510. }
  120511. }
  120512. if(ido==1)goto L132;
  120513. if(nbd<l1)goto L128;
  120514. t1=0;
  120515. t2=ipp2*t0;
  120516. for(j=1;j<ipph;j++){
  120517. t1+=t0;
  120518. t2-=t0;
  120519. t3=t1;
  120520. t4=t2;
  120521. for(k=0;k<l1;k++){
  120522. t5=t3;
  120523. t6=t4;
  120524. for(i=2;i<ido;i+=2){
  120525. t5+=2;
  120526. t6+=2;
  120527. ch[t5-1]=c1[t5-1]-c1[t6];
  120528. ch[t6-1]=c1[t5-1]+c1[t6];
  120529. ch[t5]=c1[t5]+c1[t6-1];
  120530. ch[t6]=c1[t5]-c1[t6-1];
  120531. }
  120532. t3+=ido;
  120533. t4+=ido;
  120534. }
  120535. }
  120536. goto L132;
  120537. L128:
  120538. t1=0;
  120539. t2=ipp2*t0;
  120540. for(j=1;j<ipph;j++){
  120541. t1+=t0;
  120542. t2-=t0;
  120543. t3=t1;
  120544. t4=t2;
  120545. for(i=2;i<ido;i+=2){
  120546. t3+=2;
  120547. t4+=2;
  120548. t5=t3;
  120549. t6=t4;
  120550. for(k=0;k<l1;k++){
  120551. ch[t5-1]=c1[t5-1]-c1[t6];
  120552. ch[t6-1]=c1[t5-1]+c1[t6];
  120553. ch[t5]=c1[t5]+c1[t6-1];
  120554. ch[t6]=c1[t5]-c1[t6-1];
  120555. t5+=ido;
  120556. t6+=ido;
  120557. }
  120558. }
  120559. }
  120560. L132:
  120561. if(ido==1)return;
  120562. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120563. t1=0;
  120564. for(j=1;j<ip;j++){
  120565. t2=(t1+=t0);
  120566. for(k=0;k<l1;k++){
  120567. c1[t2]=ch[t2];
  120568. t2+=ido;
  120569. }
  120570. }
  120571. if(nbd>l1)goto L139;
  120572. is= -ido-1;
  120573. t1=0;
  120574. for(j=1;j<ip;j++){
  120575. is+=ido;
  120576. t1+=t0;
  120577. idij=is;
  120578. t2=t1;
  120579. for(i=2;i<ido;i+=2){
  120580. t2+=2;
  120581. idij+=2;
  120582. t3=t2;
  120583. for(k=0;k<l1;k++){
  120584. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120585. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120586. t3+=ido;
  120587. }
  120588. }
  120589. }
  120590. return;
  120591. L139:
  120592. is= -ido-1;
  120593. t1=0;
  120594. for(j=1;j<ip;j++){
  120595. is+=ido;
  120596. t1+=t0;
  120597. t2=t1;
  120598. for(k=0;k<l1;k++){
  120599. idij=is;
  120600. t3=t2;
  120601. for(i=2;i<ido;i+=2){
  120602. idij+=2;
  120603. t3+=2;
  120604. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120605. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120606. }
  120607. t2+=ido;
  120608. }
  120609. }
  120610. }
  120611. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120612. int i,k1,l1,l2;
  120613. int na;
  120614. int nf,ip,iw,ix2,ix3,ido,idl1;
  120615. nf=ifac[1];
  120616. na=0;
  120617. l1=1;
  120618. iw=1;
  120619. for(k1=0;k1<nf;k1++){
  120620. ip=ifac[k1 + 2];
  120621. l2=ip*l1;
  120622. ido=n/l2;
  120623. idl1=ido*l1;
  120624. if(ip!=4)goto L103;
  120625. ix2=iw+ido;
  120626. ix3=ix2+ido;
  120627. if(na!=0)
  120628. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120629. else
  120630. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120631. na=1-na;
  120632. goto L115;
  120633. L103:
  120634. if(ip!=2)goto L106;
  120635. if(na!=0)
  120636. dradb2(ido,l1,ch,c,wa+iw-1);
  120637. else
  120638. dradb2(ido,l1,c,ch,wa+iw-1);
  120639. na=1-na;
  120640. goto L115;
  120641. L106:
  120642. if(ip!=3)goto L109;
  120643. ix2=iw+ido;
  120644. if(na!=0)
  120645. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120646. else
  120647. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120648. na=1-na;
  120649. goto L115;
  120650. L109:
  120651. /* The radix five case can be translated later..... */
  120652. /* if(ip!=5)goto L112;
  120653. ix2=iw+ido;
  120654. ix3=ix2+ido;
  120655. ix4=ix3+ido;
  120656. if(na!=0)
  120657. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120658. else
  120659. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120660. na=1-na;
  120661. goto L115;
  120662. L112:*/
  120663. if(na!=0)
  120664. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120665. else
  120666. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120667. if(ido==1)na=1-na;
  120668. L115:
  120669. l1=l2;
  120670. iw+=(ip-1)*ido;
  120671. }
  120672. if(na==0)return;
  120673. for(i=0;i<n;i++)c[i]=ch[i];
  120674. }
  120675. void drft_forward(drft_lookup *l,float *data){
  120676. if(l->n==1)return;
  120677. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120678. }
  120679. void drft_backward(drft_lookup *l,float *data){
  120680. if (l->n==1)return;
  120681. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120682. }
  120683. void drft_init(drft_lookup *l,int n){
  120684. l->n=n;
  120685. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120686. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120687. fdrffti(n, l->trigcache, l->splitcache);
  120688. }
  120689. void drft_clear(drft_lookup *l){
  120690. if(l){
  120691. if(l->trigcache)_ogg_free(l->trigcache);
  120692. if(l->splitcache)_ogg_free(l->splitcache);
  120693. memset(l,0,sizeof(*l));
  120694. }
  120695. }
  120696. #endif
  120697. /*** End of inlined file: smallft.c ***/
  120698. /*** Start of inlined file: synthesis.c ***/
  120699. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120700. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120701. // tasks..
  120702. #if JUCE_MSVC
  120703. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120704. #endif
  120705. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120706. #if JUCE_USE_OGGVORBIS
  120707. #include <stdio.h>
  120708. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120709. vorbis_dsp_state *vd=vb->vd;
  120710. private_state *b=(private_state*)vd->backend_state;
  120711. vorbis_info *vi=vd->vi;
  120712. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120713. oggpack_buffer *opb=&vb->opb;
  120714. int type,mode,i;
  120715. /* first things first. Make sure decode is ready */
  120716. _vorbis_block_ripcord(vb);
  120717. oggpack_readinit(opb,op->packet,op->bytes);
  120718. /* Check the packet type */
  120719. if(oggpack_read(opb,1)!=0){
  120720. /* Oops. This is not an audio data packet */
  120721. return(OV_ENOTAUDIO);
  120722. }
  120723. /* read our mode and pre/post windowsize */
  120724. mode=oggpack_read(opb,b->modebits);
  120725. if(mode==-1)return(OV_EBADPACKET);
  120726. vb->mode=mode;
  120727. vb->W=ci->mode_param[mode]->blockflag;
  120728. if(vb->W){
  120729. /* this doesn;t get mapped through mode selection as it's used
  120730. only for window selection */
  120731. vb->lW=oggpack_read(opb,1);
  120732. vb->nW=oggpack_read(opb,1);
  120733. if(vb->nW==-1) return(OV_EBADPACKET);
  120734. }else{
  120735. vb->lW=0;
  120736. vb->nW=0;
  120737. }
  120738. /* more setup */
  120739. vb->granulepos=op->granulepos;
  120740. vb->sequence=op->packetno;
  120741. vb->eofflag=op->e_o_s;
  120742. /* alloc pcm passback storage */
  120743. vb->pcmend=ci->blocksizes[vb->W];
  120744. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120745. for(i=0;i<vi->channels;i++)
  120746. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120747. /* unpack_header enforces range checking */
  120748. type=ci->map_type[ci->mode_param[mode]->mapping];
  120749. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120750. mapping]));
  120751. }
  120752. /* used to track pcm position without actually performing decode.
  120753. Useful for sequential 'fast forward' */
  120754. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120755. vorbis_dsp_state *vd=vb->vd;
  120756. private_state *b=(private_state*)vd->backend_state;
  120757. vorbis_info *vi=vd->vi;
  120758. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120759. oggpack_buffer *opb=&vb->opb;
  120760. int mode;
  120761. /* first things first. Make sure decode is ready */
  120762. _vorbis_block_ripcord(vb);
  120763. oggpack_readinit(opb,op->packet,op->bytes);
  120764. /* Check the packet type */
  120765. if(oggpack_read(opb,1)!=0){
  120766. /* Oops. This is not an audio data packet */
  120767. return(OV_ENOTAUDIO);
  120768. }
  120769. /* read our mode and pre/post windowsize */
  120770. mode=oggpack_read(opb,b->modebits);
  120771. if(mode==-1)return(OV_EBADPACKET);
  120772. vb->mode=mode;
  120773. vb->W=ci->mode_param[mode]->blockflag;
  120774. if(vb->W){
  120775. vb->lW=oggpack_read(opb,1);
  120776. vb->nW=oggpack_read(opb,1);
  120777. if(vb->nW==-1) return(OV_EBADPACKET);
  120778. }else{
  120779. vb->lW=0;
  120780. vb->nW=0;
  120781. }
  120782. /* more setup */
  120783. vb->granulepos=op->granulepos;
  120784. vb->sequence=op->packetno;
  120785. vb->eofflag=op->e_o_s;
  120786. /* no pcm */
  120787. vb->pcmend=0;
  120788. vb->pcm=NULL;
  120789. return(0);
  120790. }
  120791. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120792. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120793. oggpack_buffer opb;
  120794. int mode;
  120795. oggpack_readinit(&opb,op->packet,op->bytes);
  120796. /* Check the packet type */
  120797. if(oggpack_read(&opb,1)!=0){
  120798. /* Oops. This is not an audio data packet */
  120799. return(OV_ENOTAUDIO);
  120800. }
  120801. {
  120802. int modebits=0;
  120803. int v=ci->modes;
  120804. while(v>1){
  120805. modebits++;
  120806. v>>=1;
  120807. }
  120808. /* read our mode and pre/post windowsize */
  120809. mode=oggpack_read(&opb,modebits);
  120810. }
  120811. if(mode==-1)return(OV_EBADPACKET);
  120812. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120813. }
  120814. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120815. /* set / clear half-sample-rate mode */
  120816. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120817. /* right now, our MDCT can't handle < 64 sample windows. */
  120818. if(ci->blocksizes[0]<=64 && flag)return -1;
  120819. ci->halfrate_flag=(flag?1:0);
  120820. return 0;
  120821. }
  120822. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120823. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120824. return ci->halfrate_flag;
  120825. }
  120826. #endif
  120827. /*** End of inlined file: synthesis.c ***/
  120828. /*** Start of inlined file: vorbisenc.c ***/
  120829. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120830. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120831. // tasks..
  120832. #if JUCE_MSVC
  120833. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120834. #endif
  120835. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120836. #if JUCE_USE_OGGVORBIS
  120837. #include <stdlib.h>
  120838. #include <string.h>
  120839. #include <math.h>
  120840. /* careful with this; it's using static array sizing to make managing
  120841. all the modes a little less annoying. If we use a residue backend
  120842. with > 12 partition types, or a different division of iteration,
  120843. this needs to be updated. */
  120844. typedef struct {
  120845. static_codebook *books[12][3];
  120846. } static_bookblock;
  120847. typedef struct {
  120848. int res_type;
  120849. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120850. vorbis_info_residue0 *res;
  120851. static_codebook *book_aux;
  120852. static_codebook *book_aux_managed;
  120853. static_bookblock *books_base;
  120854. static_bookblock *books_base_managed;
  120855. } vorbis_residue_template;
  120856. typedef struct {
  120857. vorbis_info_mapping0 *map;
  120858. vorbis_residue_template *res;
  120859. } vorbis_mapping_template;
  120860. typedef struct vp_adjblock{
  120861. int block[P_BANDS];
  120862. } vp_adjblock;
  120863. typedef struct {
  120864. int data[NOISE_COMPAND_LEVELS];
  120865. } compandblock;
  120866. /* high level configuration information for setting things up
  120867. step-by-step with the detailed vorbis_encode_ctl interface.
  120868. There's a fair amount of redundancy such that interactive setup
  120869. does not directly deal with any vorbis_info or codec_setup_info
  120870. initialization; it's all stored (until full init) in this highlevel
  120871. setup, then flushed out to the real codec setup structs later. */
  120872. typedef struct {
  120873. int att[P_NOISECURVES];
  120874. float boost;
  120875. float decay;
  120876. } att3;
  120877. typedef struct { int data[P_NOISECURVES]; } adj3;
  120878. typedef struct {
  120879. int pre[PACKETBLOBS];
  120880. int post[PACKETBLOBS];
  120881. float kHz[PACKETBLOBS];
  120882. float lowpasskHz[PACKETBLOBS];
  120883. } adj_stereo;
  120884. typedef struct {
  120885. int lo;
  120886. int hi;
  120887. int fixed;
  120888. } noiseguard;
  120889. typedef struct {
  120890. int data[P_NOISECURVES][17];
  120891. } noise3;
  120892. typedef struct {
  120893. int mappings;
  120894. double *rate_mapping;
  120895. double *quality_mapping;
  120896. int coupling_restriction;
  120897. long samplerate_min_restriction;
  120898. long samplerate_max_restriction;
  120899. int *blocksize_short;
  120900. int *blocksize_long;
  120901. att3 *psy_tone_masteratt;
  120902. int *psy_tone_0dB;
  120903. int *psy_tone_dBsuppress;
  120904. vp_adjblock *psy_tone_adj_impulse;
  120905. vp_adjblock *psy_tone_adj_long;
  120906. vp_adjblock *psy_tone_adj_other;
  120907. noiseguard *psy_noiseguards;
  120908. noise3 *psy_noise_bias_impulse;
  120909. noise3 *psy_noise_bias_padding;
  120910. noise3 *psy_noise_bias_trans;
  120911. noise3 *psy_noise_bias_long;
  120912. int *psy_noise_dBsuppress;
  120913. compandblock *psy_noise_compand;
  120914. double *psy_noise_compand_short_mapping;
  120915. double *psy_noise_compand_long_mapping;
  120916. int *psy_noise_normal_start[2];
  120917. int *psy_noise_normal_partition[2];
  120918. double *psy_noise_normal_thresh;
  120919. int *psy_ath_float;
  120920. int *psy_ath_abs;
  120921. double *psy_lowpass;
  120922. vorbis_info_psy_global *global_params;
  120923. double *global_mapping;
  120924. adj_stereo *stereo_modes;
  120925. static_codebook ***floor_books;
  120926. vorbis_info_floor1 *floor_params;
  120927. int *floor_short_mapping;
  120928. int *floor_long_mapping;
  120929. vorbis_mapping_template *maps;
  120930. } ve_setup_data_template;
  120931. /* a few static coder conventions */
  120932. static vorbis_info_mode _mode_template[2]={
  120933. {0,0,0,0},
  120934. {1,0,0,1}
  120935. };
  120936. static vorbis_info_mapping0 _map_nominal[2]={
  120937. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120938. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120939. };
  120940. /*** Start of inlined file: setup_44.h ***/
  120941. /*** Start of inlined file: floor_all.h ***/
  120942. /*** Start of inlined file: floor_books.h ***/
  120943. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120944. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120945. };
  120946. static static_codebook _huff_book_line_256x7_0sub1 = {
  120947. 1, 9,
  120948. _huff_lengthlist_line_256x7_0sub1,
  120949. 0, 0, 0, 0, 0,
  120950. NULL,
  120951. NULL,
  120952. NULL,
  120953. NULL,
  120954. 0
  120955. };
  120956. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120958. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120959. };
  120960. static static_codebook _huff_book_line_256x7_0sub2 = {
  120961. 1, 25,
  120962. _huff_lengthlist_line_256x7_0sub2,
  120963. 0, 0, 0, 0, 0,
  120964. NULL,
  120965. NULL,
  120966. NULL,
  120967. NULL,
  120968. 0
  120969. };
  120970. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120973. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120974. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120975. };
  120976. static static_codebook _huff_book_line_256x7_0sub3 = {
  120977. 1, 64,
  120978. _huff_lengthlist_line_256x7_0sub3,
  120979. 0, 0, 0, 0, 0,
  120980. NULL,
  120981. NULL,
  120982. NULL,
  120983. NULL,
  120984. 0
  120985. };
  120986. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120987. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120988. };
  120989. static static_codebook _huff_book_line_256x7_1sub1 = {
  120990. 1, 9,
  120991. _huff_lengthlist_line_256x7_1sub1,
  120992. 0, 0, 0, 0, 0,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. NULL,
  120997. 0
  120998. };
  120999. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121001. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121002. };
  121003. static static_codebook _huff_book_line_256x7_1sub2 = {
  121004. 1, 25,
  121005. _huff_lengthlist_line_256x7_1sub2,
  121006. 0, 0, 0, 0, 0,
  121007. NULL,
  121008. NULL,
  121009. NULL,
  121010. NULL,
  121011. 0
  121012. };
  121013. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121016. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121017. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121018. };
  121019. static static_codebook _huff_book_line_256x7_1sub3 = {
  121020. 1, 64,
  121021. _huff_lengthlist_line_256x7_1sub3,
  121022. 0, 0, 0, 0, 0,
  121023. NULL,
  121024. NULL,
  121025. NULL,
  121026. NULL,
  121027. 0
  121028. };
  121029. static long _huff_lengthlist_line_256x7_class0[] = {
  121030. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121031. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121032. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121033. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121034. };
  121035. static static_codebook _huff_book_line_256x7_class0 = {
  121036. 1, 64,
  121037. _huff_lengthlist_line_256x7_class0,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_256x7_class1[] = {
  121046. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121047. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121048. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121049. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121050. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121051. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121052. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121053. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121054. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121055. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121056. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121057. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121058. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121059. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121060. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121061. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121062. };
  121063. static static_codebook _huff_book_line_256x7_class1 = {
  121064. 1, 256,
  121065. _huff_lengthlist_line_256x7_class1,
  121066. 0, 0, 0, 0, 0,
  121067. NULL,
  121068. NULL,
  121069. NULL,
  121070. NULL,
  121071. 0
  121072. };
  121073. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121074. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121075. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121076. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121077. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121078. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121079. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121080. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121081. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121082. };
  121083. static static_codebook _huff_book_line_512x17_0sub0 = {
  121084. 1, 128,
  121085. _huff_lengthlist_line_512x17_0sub0,
  121086. 0, 0, 0, 0, 0,
  121087. NULL,
  121088. NULL,
  121089. NULL,
  121090. NULL,
  121091. 0
  121092. };
  121093. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121094. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121095. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121096. };
  121097. static static_codebook _huff_book_line_512x17_1sub0 = {
  121098. 1, 32,
  121099. _huff_lengthlist_line_512x17_1sub0,
  121100. 0, 0, 0, 0, 0,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. NULL,
  121105. 0
  121106. };
  121107. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121110. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121111. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121112. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121113. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121114. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121115. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121116. };
  121117. static static_codebook _huff_book_line_512x17_1sub1 = {
  121118. 1, 128,
  121119. _huff_lengthlist_line_512x17_1sub1,
  121120. 0, 0, 0, 0, 0,
  121121. NULL,
  121122. NULL,
  121123. NULL,
  121124. NULL,
  121125. 0
  121126. };
  121127. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121128. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121129. 5, 3,
  121130. };
  121131. static static_codebook _huff_book_line_512x17_2sub1 = {
  121132. 1, 18,
  121133. _huff_lengthlist_line_512x17_2sub1,
  121134. 0, 0, 0, 0, 0,
  121135. NULL,
  121136. NULL,
  121137. NULL,
  121138. NULL,
  121139. 0
  121140. };
  121141. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121143. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121144. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121145. 9, 8,
  121146. };
  121147. static static_codebook _huff_book_line_512x17_2sub2 = {
  121148. 1, 50,
  121149. _huff_lengthlist_line_512x17_2sub2,
  121150. 0, 0, 0, 0, 0,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. NULL,
  121155. 0
  121156. };
  121157. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121162. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121163. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121164. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121166. };
  121167. static static_codebook _huff_book_line_512x17_2sub3 = {
  121168. 1, 128,
  121169. _huff_lengthlist_line_512x17_2sub3,
  121170. 0, 0, 0, 0, 0,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. NULL,
  121175. 0
  121176. };
  121177. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121178. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121179. 5, 5,
  121180. };
  121181. static static_codebook _huff_book_line_512x17_3sub1 = {
  121182. 1, 18,
  121183. _huff_lengthlist_line_512x17_3sub1,
  121184. 0, 0, 0, 0, 0,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. NULL,
  121189. 0
  121190. };
  121191. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121194. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121195. 11,14,
  121196. };
  121197. static static_codebook _huff_book_line_512x17_3sub2 = {
  121198. 1, 50,
  121199. _huff_lengthlist_line_512x17_3sub2,
  121200. 0, 0, 0, 0, 0,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. NULL,
  121205. 0
  121206. };
  121207. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121211. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121212. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121213. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121214. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121215. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121216. };
  121217. static static_codebook _huff_book_line_512x17_3sub3 = {
  121218. 1, 128,
  121219. _huff_lengthlist_line_512x17_3sub3,
  121220. 0, 0, 0, 0, 0,
  121221. NULL,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. 0
  121226. };
  121227. static long _huff_lengthlist_line_512x17_class1[] = {
  121228. 1, 2, 3, 6, 5, 4, 7, 7,
  121229. };
  121230. static static_codebook _huff_book_line_512x17_class1 = {
  121231. 1, 8,
  121232. _huff_lengthlist_line_512x17_class1,
  121233. 0, 0, 0, 0, 0,
  121234. NULL,
  121235. NULL,
  121236. NULL,
  121237. NULL,
  121238. 0
  121239. };
  121240. static long _huff_lengthlist_line_512x17_class2[] = {
  121241. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121242. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121243. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121244. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121245. };
  121246. static static_codebook _huff_book_line_512x17_class2 = {
  121247. 1, 64,
  121248. _huff_lengthlist_line_512x17_class2,
  121249. 0, 0, 0, 0, 0,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. NULL,
  121254. 0
  121255. };
  121256. static long _huff_lengthlist_line_512x17_class3[] = {
  121257. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121258. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121259. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121260. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121261. };
  121262. static static_codebook _huff_book_line_512x17_class3 = {
  121263. 1, 64,
  121264. _huff_lengthlist_line_512x17_class3,
  121265. 0, 0, 0, 0, 0,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. NULL,
  121270. 0
  121271. };
  121272. static long _huff_lengthlist_line_128x4_class0[] = {
  121273. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121274. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121275. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121276. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121277. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121278. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121279. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121280. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121281. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121282. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121283. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121284. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121285. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121286. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121287. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121288. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121289. };
  121290. static static_codebook _huff_book_line_128x4_class0 = {
  121291. 1, 256,
  121292. _huff_lengthlist_line_128x4_class0,
  121293. 0, 0, 0, 0, 0,
  121294. NULL,
  121295. NULL,
  121296. NULL,
  121297. NULL,
  121298. 0
  121299. };
  121300. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121301. 2, 2, 2, 2,
  121302. };
  121303. static static_codebook _huff_book_line_128x4_0sub0 = {
  121304. 1, 4,
  121305. _huff_lengthlist_line_128x4_0sub0,
  121306. 0, 0, 0, 0, 0,
  121307. NULL,
  121308. NULL,
  121309. NULL,
  121310. NULL,
  121311. 0
  121312. };
  121313. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121314. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121315. };
  121316. static static_codebook _huff_book_line_128x4_0sub1 = {
  121317. 1, 10,
  121318. _huff_lengthlist_line_128x4_0sub1,
  121319. 0, 0, 0, 0, 0,
  121320. NULL,
  121321. NULL,
  121322. NULL,
  121323. NULL,
  121324. 0
  121325. };
  121326. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121328. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121329. };
  121330. static static_codebook _huff_book_line_128x4_0sub2 = {
  121331. 1, 25,
  121332. _huff_lengthlist_line_128x4_0sub2,
  121333. 0, 0, 0, 0, 0,
  121334. NULL,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. 0
  121339. };
  121340. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121343. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121344. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121345. };
  121346. static static_codebook _huff_book_line_128x4_0sub3 = {
  121347. 1, 64,
  121348. _huff_lengthlist_line_128x4_0sub3,
  121349. 0, 0, 0, 0, 0,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. NULL,
  121354. 0
  121355. };
  121356. static long _huff_lengthlist_line_256x4_class0[] = {
  121357. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121358. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121359. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121360. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121361. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121362. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121363. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121364. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121365. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121366. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121367. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121368. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121369. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121370. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121371. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121372. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121373. };
  121374. static static_codebook _huff_book_line_256x4_class0 = {
  121375. 1, 256,
  121376. _huff_lengthlist_line_256x4_class0,
  121377. 0, 0, 0, 0, 0,
  121378. NULL,
  121379. NULL,
  121380. NULL,
  121381. NULL,
  121382. 0
  121383. };
  121384. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121385. 2, 2, 2, 2,
  121386. };
  121387. static static_codebook _huff_book_line_256x4_0sub0 = {
  121388. 1, 4,
  121389. _huff_lengthlist_line_256x4_0sub0,
  121390. 0, 0, 0, 0, 0,
  121391. NULL,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121398. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121399. };
  121400. static static_codebook _huff_book_line_256x4_0sub1 = {
  121401. 1, 10,
  121402. _huff_lengthlist_line_256x4_0sub1,
  121403. 0, 0, 0, 0, 0,
  121404. NULL,
  121405. NULL,
  121406. NULL,
  121407. NULL,
  121408. 0
  121409. };
  121410. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121412. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121413. };
  121414. static static_codebook _huff_book_line_256x4_0sub2 = {
  121415. 1, 25,
  121416. _huff_lengthlist_line_256x4_0sub2,
  121417. 0, 0, 0, 0, 0,
  121418. NULL,
  121419. NULL,
  121420. NULL,
  121421. NULL,
  121422. 0
  121423. };
  121424. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121427. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121428. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121429. };
  121430. static static_codebook _huff_book_line_256x4_0sub3 = {
  121431. 1, 64,
  121432. _huff_lengthlist_line_256x4_0sub3,
  121433. 0, 0, 0, 0, 0,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. 0
  121439. };
  121440. static long _huff_lengthlist_line_128x7_class0[] = {
  121441. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121442. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121443. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121444. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121445. };
  121446. static static_codebook _huff_book_line_128x7_class0 = {
  121447. 1, 64,
  121448. _huff_lengthlist_line_128x7_class0,
  121449. 0, 0, 0, 0, 0,
  121450. NULL,
  121451. NULL,
  121452. NULL,
  121453. NULL,
  121454. 0
  121455. };
  121456. static long _huff_lengthlist_line_128x7_class1[] = {
  121457. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121458. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121459. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121460. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121461. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121462. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121463. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121464. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121465. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121466. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121467. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121468. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121469. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121470. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121471. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121472. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121473. };
  121474. static static_codebook _huff_book_line_128x7_class1 = {
  121475. 1, 256,
  121476. _huff_lengthlist_line_128x7_class1,
  121477. 0, 0, 0, 0, 0,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. NULL,
  121482. 0
  121483. };
  121484. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121485. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121486. };
  121487. static static_codebook _huff_book_line_128x7_0sub1 = {
  121488. 1, 9,
  121489. _huff_lengthlist_line_128x7_0sub1,
  121490. 0, 0, 0, 0, 0,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. NULL,
  121495. 0
  121496. };
  121497. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121499. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121500. };
  121501. static static_codebook _huff_book_line_128x7_0sub2 = {
  121502. 1, 25,
  121503. _huff_lengthlist_line_128x7_0sub2,
  121504. 0, 0, 0, 0, 0,
  121505. NULL,
  121506. NULL,
  121507. NULL,
  121508. NULL,
  121509. 0
  121510. };
  121511. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121514. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121515. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121516. };
  121517. static static_codebook _huff_book_line_128x7_0sub3 = {
  121518. 1, 64,
  121519. _huff_lengthlist_line_128x7_0sub3,
  121520. 0, 0, 0, 0, 0,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. NULL,
  121525. 0
  121526. };
  121527. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121528. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121529. };
  121530. static static_codebook _huff_book_line_128x7_1sub1 = {
  121531. 1, 9,
  121532. _huff_lengthlist_line_128x7_1sub1,
  121533. 0, 0, 0, 0, 0,
  121534. NULL,
  121535. NULL,
  121536. NULL,
  121537. NULL,
  121538. 0
  121539. };
  121540. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121542. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121543. };
  121544. static static_codebook _huff_book_line_128x7_1sub2 = {
  121545. 1, 25,
  121546. _huff_lengthlist_line_128x7_1sub2,
  121547. 0, 0, 0, 0, 0,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. NULL,
  121552. 0
  121553. };
  121554. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121557. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121558. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121559. };
  121560. static static_codebook _huff_book_line_128x7_1sub3 = {
  121561. 1, 64,
  121562. _huff_lengthlist_line_128x7_1sub3,
  121563. 0, 0, 0, 0, 0,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. NULL,
  121568. 0
  121569. };
  121570. static long _huff_lengthlist_line_128x11_class1[] = {
  121571. 1, 6, 3, 7, 2, 4, 5, 7,
  121572. };
  121573. static static_codebook _huff_book_line_128x11_class1 = {
  121574. 1, 8,
  121575. _huff_lengthlist_line_128x11_class1,
  121576. 0, 0, 0, 0, 0,
  121577. NULL,
  121578. NULL,
  121579. NULL,
  121580. NULL,
  121581. 0
  121582. };
  121583. static long _huff_lengthlist_line_128x11_class2[] = {
  121584. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121585. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121586. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121587. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121588. };
  121589. static static_codebook _huff_book_line_128x11_class2 = {
  121590. 1, 64,
  121591. _huff_lengthlist_line_128x11_class2,
  121592. 0, 0, 0, 0, 0,
  121593. NULL,
  121594. NULL,
  121595. NULL,
  121596. NULL,
  121597. 0
  121598. };
  121599. static long _huff_lengthlist_line_128x11_class3[] = {
  121600. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121601. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121602. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121603. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121604. };
  121605. static static_codebook _huff_book_line_128x11_class3 = {
  121606. 1, 64,
  121607. _huff_lengthlist_line_128x11_class3,
  121608. 0, 0, 0, 0, 0,
  121609. NULL,
  121610. NULL,
  121611. NULL,
  121612. NULL,
  121613. 0
  121614. };
  121615. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121616. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121617. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121618. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121619. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121620. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121621. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121622. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121623. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121624. };
  121625. static static_codebook _huff_book_line_128x11_0sub0 = {
  121626. 1, 128,
  121627. _huff_lengthlist_line_128x11_0sub0,
  121628. 0, 0, 0, 0, 0,
  121629. NULL,
  121630. NULL,
  121631. NULL,
  121632. NULL,
  121633. 0
  121634. };
  121635. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121636. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121637. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121638. };
  121639. static static_codebook _huff_book_line_128x11_1sub0 = {
  121640. 1, 32,
  121641. _huff_lengthlist_line_128x11_1sub0,
  121642. 0, 0, 0, 0, 0,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. NULL,
  121647. 0
  121648. };
  121649. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121653. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121654. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121655. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121656. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121657. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121658. };
  121659. static static_codebook _huff_book_line_128x11_1sub1 = {
  121660. 1, 128,
  121661. _huff_lengthlist_line_128x11_1sub1,
  121662. 0, 0, 0, 0, 0,
  121663. NULL,
  121664. NULL,
  121665. NULL,
  121666. NULL,
  121667. 0
  121668. };
  121669. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121670. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121671. 5, 5,
  121672. };
  121673. static static_codebook _huff_book_line_128x11_2sub1 = {
  121674. 1, 18,
  121675. _huff_lengthlist_line_128x11_2sub1,
  121676. 0, 0, 0, 0, 0,
  121677. NULL,
  121678. NULL,
  121679. NULL,
  121680. NULL,
  121681. 0
  121682. };
  121683. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121686. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121687. 8,11,
  121688. };
  121689. static static_codebook _huff_book_line_128x11_2sub2 = {
  121690. 1, 50,
  121691. _huff_lengthlist_line_128x11_2sub2,
  121692. 0, 0, 0, 0, 0,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. NULL,
  121697. 0
  121698. };
  121699. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121704. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121705. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121706. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121707. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121708. };
  121709. static static_codebook _huff_book_line_128x11_2sub3 = {
  121710. 1, 128,
  121711. _huff_lengthlist_line_128x11_2sub3,
  121712. 0, 0, 0, 0, 0,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. NULL,
  121717. 0
  121718. };
  121719. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121720. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121721. 5, 4,
  121722. };
  121723. static static_codebook _huff_book_line_128x11_3sub1 = {
  121724. 1, 18,
  121725. _huff_lengthlist_line_128x11_3sub1,
  121726. 0, 0, 0, 0, 0,
  121727. NULL,
  121728. NULL,
  121729. NULL,
  121730. NULL,
  121731. 0
  121732. };
  121733. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121736. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121737. 12, 6,
  121738. };
  121739. static static_codebook _huff_book_line_128x11_3sub2 = {
  121740. 1, 50,
  121741. _huff_lengthlist_line_128x11_3sub2,
  121742. 0, 0, 0, 0, 0,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. NULL,
  121747. 0
  121748. };
  121749. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121754. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121756. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121757. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121758. };
  121759. static static_codebook _huff_book_line_128x11_3sub3 = {
  121760. 1, 128,
  121761. _huff_lengthlist_line_128x11_3sub3,
  121762. 0, 0, 0, 0, 0,
  121763. NULL,
  121764. NULL,
  121765. NULL,
  121766. NULL,
  121767. 0
  121768. };
  121769. static long _huff_lengthlist_line_128x17_class1[] = {
  121770. 1, 3, 4, 7, 2, 5, 6, 7,
  121771. };
  121772. static static_codebook _huff_book_line_128x17_class1 = {
  121773. 1, 8,
  121774. _huff_lengthlist_line_128x17_class1,
  121775. 0, 0, 0, 0, 0,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. NULL,
  121780. 0
  121781. };
  121782. static long _huff_lengthlist_line_128x17_class2[] = {
  121783. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121784. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121785. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121786. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121787. };
  121788. static static_codebook _huff_book_line_128x17_class2 = {
  121789. 1, 64,
  121790. _huff_lengthlist_line_128x17_class2,
  121791. 0, 0, 0, 0, 0,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. NULL,
  121796. 0
  121797. };
  121798. static long _huff_lengthlist_line_128x17_class3[] = {
  121799. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121800. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121801. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121802. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121803. };
  121804. static static_codebook _huff_book_line_128x17_class3 = {
  121805. 1, 64,
  121806. _huff_lengthlist_line_128x17_class3,
  121807. 0, 0, 0, 0, 0,
  121808. NULL,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. 0
  121813. };
  121814. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121815. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121816. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121817. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121818. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121819. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121820. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121821. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121822. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121823. };
  121824. static static_codebook _huff_book_line_128x17_0sub0 = {
  121825. 1, 128,
  121826. _huff_lengthlist_line_128x17_0sub0,
  121827. 0, 0, 0, 0, 0,
  121828. NULL,
  121829. NULL,
  121830. NULL,
  121831. NULL,
  121832. 0
  121833. };
  121834. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121835. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121836. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121837. };
  121838. static static_codebook _huff_book_line_128x17_1sub0 = {
  121839. 1, 32,
  121840. _huff_lengthlist_line_128x17_1sub0,
  121841. 0, 0, 0, 0, 0,
  121842. NULL,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. 0
  121847. };
  121848. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121851. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121852. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121853. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121854. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121855. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121856. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121857. };
  121858. static static_codebook _huff_book_line_128x17_1sub1 = {
  121859. 1, 128,
  121860. _huff_lengthlist_line_128x17_1sub1,
  121861. 0, 0, 0, 0, 0,
  121862. NULL,
  121863. NULL,
  121864. NULL,
  121865. NULL,
  121866. 0
  121867. };
  121868. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121869. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121870. 9, 4,
  121871. };
  121872. static static_codebook _huff_book_line_128x17_2sub1 = {
  121873. 1, 18,
  121874. _huff_lengthlist_line_128x17_2sub1,
  121875. 0, 0, 0, 0, 0,
  121876. NULL,
  121877. NULL,
  121878. NULL,
  121879. NULL,
  121880. 0
  121881. };
  121882. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121885. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121886. 13,13,
  121887. };
  121888. static static_codebook _huff_book_line_128x17_2sub2 = {
  121889. 1, 50,
  121890. _huff_lengthlist_line_128x17_2sub2,
  121891. 0, 0, 0, 0, 0,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. 0
  121897. };
  121898. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121903. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121904. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121905. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121906. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121907. };
  121908. static static_codebook _huff_book_line_128x17_2sub3 = {
  121909. 1, 128,
  121910. _huff_lengthlist_line_128x17_2sub3,
  121911. 0, 0, 0, 0, 0,
  121912. NULL,
  121913. NULL,
  121914. NULL,
  121915. NULL,
  121916. 0
  121917. };
  121918. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121919. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121920. 6, 4,
  121921. };
  121922. static static_codebook _huff_book_line_128x17_3sub1 = {
  121923. 1, 18,
  121924. _huff_lengthlist_line_128x17_3sub1,
  121925. 0, 0, 0, 0, 0,
  121926. NULL,
  121927. NULL,
  121928. NULL,
  121929. NULL,
  121930. 0
  121931. };
  121932. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121935. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121936. 10, 8,
  121937. };
  121938. static static_codebook _huff_book_line_128x17_3sub2 = {
  121939. 1, 50,
  121940. _huff_lengthlist_line_128x17_3sub2,
  121941. 0, 0, 0, 0, 0,
  121942. NULL,
  121943. NULL,
  121944. NULL,
  121945. NULL,
  121946. 0
  121947. };
  121948. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121953. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121954. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121957. };
  121958. static static_codebook _huff_book_line_128x17_3sub3 = {
  121959. 1, 128,
  121960. _huff_lengthlist_line_128x17_3sub3,
  121961. 0, 0, 0, 0, 0,
  121962. NULL,
  121963. NULL,
  121964. NULL,
  121965. NULL,
  121966. 0
  121967. };
  121968. static long _huff_lengthlist_line_1024x27_class1[] = {
  121969. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121970. };
  121971. static static_codebook _huff_book_line_1024x27_class1 = {
  121972. 1, 16,
  121973. _huff_lengthlist_line_1024x27_class1,
  121974. 0, 0, 0, 0, 0,
  121975. NULL,
  121976. NULL,
  121977. NULL,
  121978. NULL,
  121979. 0
  121980. };
  121981. static long _huff_lengthlist_line_1024x27_class2[] = {
  121982. 1, 4, 2, 6, 3, 7, 5, 7,
  121983. };
  121984. static static_codebook _huff_book_line_1024x27_class2 = {
  121985. 1, 8,
  121986. _huff_lengthlist_line_1024x27_class2,
  121987. 0, 0, 0, 0, 0,
  121988. NULL,
  121989. NULL,
  121990. NULL,
  121991. NULL,
  121992. 0
  121993. };
  121994. static long _huff_lengthlist_line_1024x27_class3[] = {
  121995. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121996. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121997. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121998. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121999. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122000. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122001. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122002. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122003. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122004. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122005. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122006. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122007. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122008. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122009. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122010. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122011. };
  122012. static static_codebook _huff_book_line_1024x27_class3 = {
  122013. 1, 256,
  122014. _huff_lengthlist_line_1024x27_class3,
  122015. 0, 0, 0, 0, 0,
  122016. NULL,
  122017. NULL,
  122018. NULL,
  122019. NULL,
  122020. 0
  122021. };
  122022. static long _huff_lengthlist_line_1024x27_class4[] = {
  122023. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122024. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122025. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122026. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122027. };
  122028. static static_codebook _huff_book_line_1024x27_class4 = {
  122029. 1, 64,
  122030. _huff_lengthlist_line_1024x27_class4,
  122031. 0, 0, 0, 0, 0,
  122032. NULL,
  122033. NULL,
  122034. NULL,
  122035. NULL,
  122036. 0
  122037. };
  122038. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122039. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122040. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122041. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122042. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122043. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122044. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122045. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122046. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122047. };
  122048. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122049. 1, 128,
  122050. _huff_lengthlist_line_1024x27_0sub0,
  122051. 0, 0, 0, 0, 0,
  122052. NULL,
  122053. NULL,
  122054. NULL,
  122055. NULL,
  122056. 0
  122057. };
  122058. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122059. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122060. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122061. };
  122062. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122063. 1, 32,
  122064. _huff_lengthlist_line_1024x27_1sub0,
  122065. 0, 0, 0, 0, 0,
  122066. NULL,
  122067. NULL,
  122068. NULL,
  122069. NULL,
  122070. 0
  122071. };
  122072. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122076. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122077. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122078. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122079. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122080. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122081. };
  122082. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122083. 1, 128,
  122084. _huff_lengthlist_line_1024x27_1sub1,
  122085. 0, 0, 0, 0, 0,
  122086. NULL,
  122087. NULL,
  122088. NULL,
  122089. NULL,
  122090. 0
  122091. };
  122092. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122093. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122094. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122095. };
  122096. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122097. 1, 32,
  122098. _huff_lengthlist_line_1024x27_2sub0,
  122099. 0, 0, 0, 0, 0,
  122100. NULL,
  122101. NULL,
  122102. NULL,
  122103. NULL,
  122104. 0
  122105. };
  122106. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122110. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122111. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122112. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122113. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122114. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122115. };
  122116. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122117. 1, 128,
  122118. _huff_lengthlist_line_1024x27_2sub1,
  122119. 0, 0, 0, 0, 0,
  122120. NULL,
  122121. NULL,
  122122. NULL,
  122123. NULL,
  122124. 0
  122125. };
  122126. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122127. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122128. 5, 5,
  122129. };
  122130. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122131. 1, 18,
  122132. _huff_lengthlist_line_1024x27_3sub1,
  122133. 0, 0, 0, 0, 0,
  122134. NULL,
  122135. NULL,
  122136. NULL,
  122137. NULL,
  122138. 0
  122139. };
  122140. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122143. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122144. 9,11,
  122145. };
  122146. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122147. 1, 50,
  122148. _huff_lengthlist_line_1024x27_3sub2,
  122149. 0, 0, 0, 0, 0,
  122150. NULL,
  122151. NULL,
  122152. NULL,
  122153. NULL,
  122154. 0
  122155. };
  122156. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122161. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122162. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122163. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122164. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122165. };
  122166. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122167. 1, 128,
  122168. _huff_lengthlist_line_1024x27_3sub3,
  122169. 0, 0, 0, 0, 0,
  122170. NULL,
  122171. NULL,
  122172. NULL,
  122173. NULL,
  122174. 0
  122175. };
  122176. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122177. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122178. 5, 4,
  122179. };
  122180. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122181. 1, 18,
  122182. _huff_lengthlist_line_1024x27_4sub1,
  122183. 0, 0, 0, 0, 0,
  122184. NULL,
  122185. NULL,
  122186. NULL,
  122187. NULL,
  122188. 0
  122189. };
  122190. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122193. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122194. 9,12,
  122195. };
  122196. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122197. 1, 50,
  122198. _huff_lengthlist_line_1024x27_4sub2,
  122199. 0, 0, 0, 0, 0,
  122200. NULL,
  122201. NULL,
  122202. NULL,
  122203. NULL,
  122204. 0
  122205. };
  122206. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122211. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122212. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122213. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122214. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122215. };
  122216. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122217. 1, 128,
  122218. _huff_lengthlist_line_1024x27_4sub3,
  122219. 0, 0, 0, 0, 0,
  122220. NULL,
  122221. NULL,
  122222. NULL,
  122223. NULL,
  122224. 0
  122225. };
  122226. static long _huff_lengthlist_line_2048x27_class1[] = {
  122227. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122228. };
  122229. static static_codebook _huff_book_line_2048x27_class1 = {
  122230. 1, 16,
  122231. _huff_lengthlist_line_2048x27_class1,
  122232. 0, 0, 0, 0, 0,
  122233. NULL,
  122234. NULL,
  122235. NULL,
  122236. NULL,
  122237. 0
  122238. };
  122239. static long _huff_lengthlist_line_2048x27_class2[] = {
  122240. 1, 2, 3, 6, 4, 7, 5, 7,
  122241. };
  122242. static static_codebook _huff_book_line_2048x27_class2 = {
  122243. 1, 8,
  122244. _huff_lengthlist_line_2048x27_class2,
  122245. 0, 0, 0, 0, 0,
  122246. NULL,
  122247. NULL,
  122248. NULL,
  122249. NULL,
  122250. 0
  122251. };
  122252. static long _huff_lengthlist_line_2048x27_class3[] = {
  122253. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122254. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122255. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122256. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122257. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122258. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122259. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122260. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122261. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122262. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122263. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122264. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122265. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122266. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122267. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122268. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122269. };
  122270. static static_codebook _huff_book_line_2048x27_class3 = {
  122271. 1, 256,
  122272. _huff_lengthlist_line_2048x27_class3,
  122273. 0, 0, 0, 0, 0,
  122274. NULL,
  122275. NULL,
  122276. NULL,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist_line_2048x27_class4[] = {
  122281. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122282. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122283. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122284. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122285. };
  122286. static static_codebook _huff_book_line_2048x27_class4 = {
  122287. 1, 64,
  122288. _huff_lengthlist_line_2048x27_class4,
  122289. 0, 0, 0, 0, 0,
  122290. NULL,
  122291. NULL,
  122292. NULL,
  122293. NULL,
  122294. 0
  122295. };
  122296. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122297. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122298. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122299. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122300. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122301. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122302. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122303. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122304. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122305. };
  122306. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122307. 1, 128,
  122308. _huff_lengthlist_line_2048x27_0sub0,
  122309. 0, 0, 0, 0, 0,
  122310. NULL,
  122311. NULL,
  122312. NULL,
  122313. NULL,
  122314. 0
  122315. };
  122316. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122317. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122318. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122319. };
  122320. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122321. 1, 32,
  122322. _huff_lengthlist_line_2048x27_1sub0,
  122323. 0, 0, 0, 0, 0,
  122324. NULL,
  122325. NULL,
  122326. NULL,
  122327. NULL,
  122328. 0
  122329. };
  122330. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122334. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122335. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122336. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122337. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122338. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122339. };
  122340. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122341. 1, 128,
  122342. _huff_lengthlist_line_2048x27_1sub1,
  122343. 0, 0, 0, 0, 0,
  122344. NULL,
  122345. NULL,
  122346. NULL,
  122347. NULL,
  122348. 0
  122349. };
  122350. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122351. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122352. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122353. };
  122354. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122355. 1, 32,
  122356. _huff_lengthlist_line_2048x27_2sub0,
  122357. 0, 0, 0, 0, 0,
  122358. NULL,
  122359. NULL,
  122360. NULL,
  122361. NULL,
  122362. 0
  122363. };
  122364. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  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. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122368. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122369. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122370. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122371. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122372. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122373. };
  122374. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122375. 1, 128,
  122376. _huff_lengthlist_line_2048x27_2sub1,
  122377. 0, 0, 0, 0, 0,
  122378. NULL,
  122379. NULL,
  122380. NULL,
  122381. NULL,
  122382. 0
  122383. };
  122384. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122385. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122386. 5, 5,
  122387. };
  122388. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122389. 1, 18,
  122390. _huff_lengthlist_line_2048x27_3sub1,
  122391. 0, 0, 0, 0, 0,
  122392. NULL,
  122393. NULL,
  122394. NULL,
  122395. NULL,
  122396. 0
  122397. };
  122398. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122401. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122402. 10,12,
  122403. };
  122404. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122405. 1, 50,
  122406. _huff_lengthlist_line_2048x27_3sub2,
  122407. 0, 0, 0, 0, 0,
  122408. NULL,
  122409. NULL,
  122410. NULL,
  122411. NULL,
  122412. 0
  122413. };
  122414. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122419. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122420. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122421. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122422. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122423. };
  122424. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122425. 1, 128,
  122426. _huff_lengthlist_line_2048x27_3sub3,
  122427. 0, 0, 0, 0, 0,
  122428. NULL,
  122429. NULL,
  122430. NULL,
  122431. NULL,
  122432. 0
  122433. };
  122434. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122435. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122436. 4, 5,
  122437. };
  122438. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122439. 1, 18,
  122440. _huff_lengthlist_line_2048x27_4sub1,
  122441. 0, 0, 0, 0, 0,
  122442. NULL,
  122443. NULL,
  122444. NULL,
  122445. NULL,
  122446. 0
  122447. };
  122448. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122451. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122452. 10,10,
  122453. };
  122454. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122455. 1, 50,
  122456. _huff_lengthlist_line_2048x27_4sub2,
  122457. 0, 0, 0, 0, 0,
  122458. NULL,
  122459. NULL,
  122460. NULL,
  122461. NULL,
  122462. 0
  122463. };
  122464. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  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, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122469. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122470. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122471. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122472. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122473. };
  122474. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122475. 1, 128,
  122476. _huff_lengthlist_line_2048x27_4sub3,
  122477. 0, 0, 0, 0, 0,
  122478. NULL,
  122479. NULL,
  122480. NULL,
  122481. NULL,
  122482. 0
  122483. };
  122484. static long _huff_lengthlist_line_256x4low_class0[] = {
  122485. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122486. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122487. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122488. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122489. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122490. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122491. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122492. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122493. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122494. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122495. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122496. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122497. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122498. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122499. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122500. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122501. };
  122502. static static_codebook _huff_book_line_256x4low_class0 = {
  122503. 1, 256,
  122504. _huff_lengthlist_line_256x4low_class0,
  122505. 0, 0, 0, 0, 0,
  122506. NULL,
  122507. NULL,
  122508. NULL,
  122509. NULL,
  122510. 0
  122511. };
  122512. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122513. 1, 3, 2, 3,
  122514. };
  122515. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122516. 1, 4,
  122517. _huff_lengthlist_line_256x4low_0sub0,
  122518. 0, 0, 0, 0, 0,
  122519. NULL,
  122520. NULL,
  122521. NULL,
  122522. NULL,
  122523. 0
  122524. };
  122525. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122526. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122527. };
  122528. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122529. 1, 10,
  122530. _huff_lengthlist_line_256x4low_0sub1,
  122531. 0, 0, 0, 0, 0,
  122532. NULL,
  122533. NULL,
  122534. NULL,
  122535. NULL,
  122536. 0
  122537. };
  122538. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122540. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122541. };
  122542. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122543. 1, 25,
  122544. _huff_lengthlist_line_256x4low_0sub2,
  122545. 0, 0, 0, 0, 0,
  122546. NULL,
  122547. NULL,
  122548. NULL,
  122549. NULL,
  122550. 0
  122551. };
  122552. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  122555. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122556. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122557. };
  122558. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122559. 1, 64,
  122560. _huff_lengthlist_line_256x4low_0sub3,
  122561. 0, 0, 0, 0, 0,
  122562. NULL,
  122563. NULL,
  122564. NULL,
  122565. NULL,
  122566. 0
  122567. };
  122568. /*** End of inlined file: floor_books.h ***/
  122569. static static_codebook *_floor_128x4_books[]={
  122570. &_huff_book_line_128x4_class0,
  122571. &_huff_book_line_128x4_0sub0,
  122572. &_huff_book_line_128x4_0sub1,
  122573. &_huff_book_line_128x4_0sub2,
  122574. &_huff_book_line_128x4_0sub3,
  122575. };
  122576. static static_codebook *_floor_256x4_books[]={
  122577. &_huff_book_line_256x4_class0,
  122578. &_huff_book_line_256x4_0sub0,
  122579. &_huff_book_line_256x4_0sub1,
  122580. &_huff_book_line_256x4_0sub2,
  122581. &_huff_book_line_256x4_0sub3,
  122582. };
  122583. static static_codebook *_floor_128x7_books[]={
  122584. &_huff_book_line_128x7_class0,
  122585. &_huff_book_line_128x7_class1,
  122586. &_huff_book_line_128x7_0sub1,
  122587. &_huff_book_line_128x7_0sub2,
  122588. &_huff_book_line_128x7_0sub3,
  122589. &_huff_book_line_128x7_1sub1,
  122590. &_huff_book_line_128x7_1sub2,
  122591. &_huff_book_line_128x7_1sub3,
  122592. };
  122593. static static_codebook *_floor_256x7_books[]={
  122594. &_huff_book_line_256x7_class0,
  122595. &_huff_book_line_256x7_class1,
  122596. &_huff_book_line_256x7_0sub1,
  122597. &_huff_book_line_256x7_0sub2,
  122598. &_huff_book_line_256x7_0sub3,
  122599. &_huff_book_line_256x7_1sub1,
  122600. &_huff_book_line_256x7_1sub2,
  122601. &_huff_book_line_256x7_1sub3,
  122602. };
  122603. static static_codebook *_floor_128x11_books[]={
  122604. &_huff_book_line_128x11_class1,
  122605. &_huff_book_line_128x11_class2,
  122606. &_huff_book_line_128x11_class3,
  122607. &_huff_book_line_128x11_0sub0,
  122608. &_huff_book_line_128x11_1sub0,
  122609. &_huff_book_line_128x11_1sub1,
  122610. &_huff_book_line_128x11_2sub1,
  122611. &_huff_book_line_128x11_2sub2,
  122612. &_huff_book_line_128x11_2sub3,
  122613. &_huff_book_line_128x11_3sub1,
  122614. &_huff_book_line_128x11_3sub2,
  122615. &_huff_book_line_128x11_3sub3,
  122616. };
  122617. static static_codebook *_floor_128x17_books[]={
  122618. &_huff_book_line_128x17_class1,
  122619. &_huff_book_line_128x17_class2,
  122620. &_huff_book_line_128x17_class3,
  122621. &_huff_book_line_128x17_0sub0,
  122622. &_huff_book_line_128x17_1sub0,
  122623. &_huff_book_line_128x17_1sub1,
  122624. &_huff_book_line_128x17_2sub1,
  122625. &_huff_book_line_128x17_2sub2,
  122626. &_huff_book_line_128x17_2sub3,
  122627. &_huff_book_line_128x17_3sub1,
  122628. &_huff_book_line_128x17_3sub2,
  122629. &_huff_book_line_128x17_3sub3,
  122630. };
  122631. static static_codebook *_floor_256x4low_books[]={
  122632. &_huff_book_line_256x4low_class0,
  122633. &_huff_book_line_256x4low_0sub0,
  122634. &_huff_book_line_256x4low_0sub1,
  122635. &_huff_book_line_256x4low_0sub2,
  122636. &_huff_book_line_256x4low_0sub3,
  122637. };
  122638. static static_codebook *_floor_1024x27_books[]={
  122639. &_huff_book_line_1024x27_class1,
  122640. &_huff_book_line_1024x27_class2,
  122641. &_huff_book_line_1024x27_class3,
  122642. &_huff_book_line_1024x27_class4,
  122643. &_huff_book_line_1024x27_0sub0,
  122644. &_huff_book_line_1024x27_1sub0,
  122645. &_huff_book_line_1024x27_1sub1,
  122646. &_huff_book_line_1024x27_2sub0,
  122647. &_huff_book_line_1024x27_2sub1,
  122648. &_huff_book_line_1024x27_3sub1,
  122649. &_huff_book_line_1024x27_3sub2,
  122650. &_huff_book_line_1024x27_3sub3,
  122651. &_huff_book_line_1024x27_4sub1,
  122652. &_huff_book_line_1024x27_4sub2,
  122653. &_huff_book_line_1024x27_4sub3,
  122654. };
  122655. static static_codebook *_floor_2048x27_books[]={
  122656. &_huff_book_line_2048x27_class1,
  122657. &_huff_book_line_2048x27_class2,
  122658. &_huff_book_line_2048x27_class3,
  122659. &_huff_book_line_2048x27_class4,
  122660. &_huff_book_line_2048x27_0sub0,
  122661. &_huff_book_line_2048x27_1sub0,
  122662. &_huff_book_line_2048x27_1sub1,
  122663. &_huff_book_line_2048x27_2sub0,
  122664. &_huff_book_line_2048x27_2sub1,
  122665. &_huff_book_line_2048x27_3sub1,
  122666. &_huff_book_line_2048x27_3sub2,
  122667. &_huff_book_line_2048x27_3sub3,
  122668. &_huff_book_line_2048x27_4sub1,
  122669. &_huff_book_line_2048x27_4sub2,
  122670. &_huff_book_line_2048x27_4sub3,
  122671. };
  122672. static static_codebook *_floor_512x17_books[]={
  122673. &_huff_book_line_512x17_class1,
  122674. &_huff_book_line_512x17_class2,
  122675. &_huff_book_line_512x17_class3,
  122676. &_huff_book_line_512x17_0sub0,
  122677. &_huff_book_line_512x17_1sub0,
  122678. &_huff_book_line_512x17_1sub1,
  122679. &_huff_book_line_512x17_2sub1,
  122680. &_huff_book_line_512x17_2sub2,
  122681. &_huff_book_line_512x17_2sub3,
  122682. &_huff_book_line_512x17_3sub1,
  122683. &_huff_book_line_512x17_3sub2,
  122684. &_huff_book_line_512x17_3sub3,
  122685. };
  122686. static static_codebook **_floor_books[10]={
  122687. _floor_128x4_books,
  122688. _floor_256x4_books,
  122689. _floor_128x7_books,
  122690. _floor_256x7_books,
  122691. _floor_128x11_books,
  122692. _floor_128x17_books,
  122693. _floor_256x4low_books,
  122694. _floor_1024x27_books,
  122695. _floor_2048x27_books,
  122696. _floor_512x17_books,
  122697. };
  122698. static vorbis_info_floor1 _floor[10]={
  122699. /* 128 x 4 */
  122700. {
  122701. 1,{0},{4},{2},{0},
  122702. {{1,2,3,4}},
  122703. 4,{0,128, 33,8,16,70},
  122704. 60,30,500, 1.,18., -1
  122705. },
  122706. /* 256 x 4 */
  122707. {
  122708. 1,{0},{4},{2},{0},
  122709. {{1,2,3,4}},
  122710. 4,{0,256, 66,16,32,140},
  122711. 60,30,500, 1.,18., -1
  122712. },
  122713. /* 128 x 7 */
  122714. {
  122715. 2,{0,1},{3,4},{2,2},{0,1},
  122716. {{-1,2,3,4},{-1,5,6,7}},
  122717. 4,{0,128, 14,4,58, 2,8,28,90},
  122718. 60,30,500, 1.,18., -1
  122719. },
  122720. /* 256 x 7 */
  122721. {
  122722. 2,{0,1},{3,4},{2,2},{0,1},
  122723. {{-1,2,3,4},{-1,5,6,7}},
  122724. 4,{0,256, 28,8,116, 4,16,56,180},
  122725. 60,30,500, 1.,18., -1
  122726. },
  122727. /* 128 x 11 */
  122728. {
  122729. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122730. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122731. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122732. 60,30,500, 1,18., -1
  122733. },
  122734. /* 128 x 17 */
  122735. {
  122736. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122737. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122738. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122739. 60,30,500, 1,18., -1
  122740. },
  122741. /* 256 x 4 (low bitrate version) */
  122742. {
  122743. 1,{0},{4},{2},{0},
  122744. {{1,2,3,4}},
  122745. 4,{0,256, 66,16,32,140},
  122746. 60,30,500, 1.,18., -1
  122747. },
  122748. /* 1024 x 27 */
  122749. {
  122750. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122751. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122752. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122753. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122754. 60,30,500, 3,18., -1 /* lowpass */
  122755. },
  122756. /* 2048 x 27 */
  122757. {
  122758. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122759. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122760. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122761. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122762. 60,30,500, 3,18., -1 /* lowpass */
  122763. },
  122764. /* 512 x 17 */
  122765. {
  122766. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122767. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122768. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122769. 7,23,39, 55,79,110, 156,232,360},
  122770. 60,30,500, 1,18., -1 /* lowpass! */
  122771. },
  122772. };
  122773. /*** End of inlined file: floor_all.h ***/
  122774. /*** Start of inlined file: residue_44.h ***/
  122775. /*** Start of inlined file: res_books_stereo.h ***/
  122776. static long _vq_quantlist__16c0_s_p1_0[] = {
  122777. 1,
  122778. 0,
  122779. 2,
  122780. };
  122781. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122782. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122783. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122788. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122793. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122828. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122833. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122838. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122874. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122879. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122884. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0,
  123193. };
  123194. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123195. -0.5, 0.5,
  123196. };
  123197. static long _vq_quantmap__16c0_s_p1_0[] = {
  123198. 1, 0, 2,
  123199. };
  123200. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123201. _vq_quantthresh__16c0_s_p1_0,
  123202. _vq_quantmap__16c0_s_p1_0,
  123203. 3,
  123204. 3
  123205. };
  123206. static static_codebook _16c0_s_p1_0 = {
  123207. 8, 6561,
  123208. _vq_lengthlist__16c0_s_p1_0,
  123209. 1, -535822336, 1611661312, 2, 0,
  123210. _vq_quantlist__16c0_s_p1_0,
  123211. NULL,
  123212. &_vq_auxt__16c0_s_p1_0,
  123213. NULL,
  123214. 0
  123215. };
  123216. static long _vq_quantlist__16c0_s_p2_0[] = {
  123217. 2,
  123218. 1,
  123219. 3,
  123220. 0,
  123221. 4,
  123222. };
  123223. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0,
  123264. };
  123265. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123266. -1.5, -0.5, 0.5, 1.5,
  123267. };
  123268. static long _vq_quantmap__16c0_s_p2_0[] = {
  123269. 3, 1, 0, 2, 4,
  123270. };
  123271. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123272. _vq_quantthresh__16c0_s_p2_0,
  123273. _vq_quantmap__16c0_s_p2_0,
  123274. 5,
  123275. 5
  123276. };
  123277. static static_codebook _16c0_s_p2_0 = {
  123278. 4, 625,
  123279. _vq_lengthlist__16c0_s_p2_0,
  123280. 1, -533725184, 1611661312, 3, 0,
  123281. _vq_quantlist__16c0_s_p2_0,
  123282. NULL,
  123283. &_vq_auxt__16c0_s_p2_0,
  123284. NULL,
  123285. 0
  123286. };
  123287. static long _vq_quantlist__16c0_s_p3_0[] = {
  123288. 2,
  123289. 1,
  123290. 3,
  123291. 0,
  123292. 4,
  123293. };
  123294. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123295. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0,
  123335. };
  123336. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123337. -1.5, -0.5, 0.5, 1.5,
  123338. };
  123339. static long _vq_quantmap__16c0_s_p3_0[] = {
  123340. 3, 1, 0, 2, 4,
  123341. };
  123342. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123343. _vq_quantthresh__16c0_s_p3_0,
  123344. _vq_quantmap__16c0_s_p3_0,
  123345. 5,
  123346. 5
  123347. };
  123348. static static_codebook _16c0_s_p3_0 = {
  123349. 4, 625,
  123350. _vq_lengthlist__16c0_s_p3_0,
  123351. 1, -533725184, 1611661312, 3, 0,
  123352. _vq_quantlist__16c0_s_p3_0,
  123353. NULL,
  123354. &_vq_auxt__16c0_s_p3_0,
  123355. NULL,
  123356. 0
  123357. };
  123358. static long _vq_quantlist__16c0_s_p4_0[] = {
  123359. 4,
  123360. 3,
  123361. 5,
  123362. 2,
  123363. 6,
  123364. 1,
  123365. 7,
  123366. 0,
  123367. 8,
  123368. };
  123369. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123370. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123371. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123372. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123373. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123374. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0,
  123376. };
  123377. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123378. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123379. };
  123380. static long _vq_quantmap__16c0_s_p4_0[] = {
  123381. 7, 5, 3, 1, 0, 2, 4, 6,
  123382. 8,
  123383. };
  123384. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123385. _vq_quantthresh__16c0_s_p4_0,
  123386. _vq_quantmap__16c0_s_p4_0,
  123387. 9,
  123388. 9
  123389. };
  123390. static static_codebook _16c0_s_p4_0 = {
  123391. 2, 81,
  123392. _vq_lengthlist__16c0_s_p4_0,
  123393. 1, -531628032, 1611661312, 4, 0,
  123394. _vq_quantlist__16c0_s_p4_0,
  123395. NULL,
  123396. &_vq_auxt__16c0_s_p4_0,
  123397. NULL,
  123398. 0
  123399. };
  123400. static long _vq_quantlist__16c0_s_p5_0[] = {
  123401. 4,
  123402. 3,
  123403. 5,
  123404. 2,
  123405. 6,
  123406. 1,
  123407. 7,
  123408. 0,
  123409. 8,
  123410. };
  123411. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123412. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123413. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123414. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123415. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123416. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123417. 10,
  123418. };
  123419. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123420. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123421. };
  123422. static long _vq_quantmap__16c0_s_p5_0[] = {
  123423. 7, 5, 3, 1, 0, 2, 4, 6,
  123424. 8,
  123425. };
  123426. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123427. _vq_quantthresh__16c0_s_p5_0,
  123428. _vq_quantmap__16c0_s_p5_0,
  123429. 9,
  123430. 9
  123431. };
  123432. static static_codebook _16c0_s_p5_0 = {
  123433. 2, 81,
  123434. _vq_lengthlist__16c0_s_p5_0,
  123435. 1, -531628032, 1611661312, 4, 0,
  123436. _vq_quantlist__16c0_s_p5_0,
  123437. NULL,
  123438. &_vq_auxt__16c0_s_p5_0,
  123439. NULL,
  123440. 0
  123441. };
  123442. static long _vq_quantlist__16c0_s_p6_0[] = {
  123443. 8,
  123444. 7,
  123445. 9,
  123446. 6,
  123447. 10,
  123448. 5,
  123449. 11,
  123450. 4,
  123451. 12,
  123452. 3,
  123453. 13,
  123454. 2,
  123455. 14,
  123456. 1,
  123457. 15,
  123458. 0,
  123459. 16,
  123460. };
  123461. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123462. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123463. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123464. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123465. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123466. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123467. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123468. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123469. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123470. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123471. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123472. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123473. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123474. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123475. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123476. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123477. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123478. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123480. 14,
  123481. };
  123482. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123483. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123484. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123485. };
  123486. static long _vq_quantmap__16c0_s_p6_0[] = {
  123487. 15, 13, 11, 9, 7, 5, 3, 1,
  123488. 0, 2, 4, 6, 8, 10, 12, 14,
  123489. 16,
  123490. };
  123491. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123492. _vq_quantthresh__16c0_s_p6_0,
  123493. _vq_quantmap__16c0_s_p6_0,
  123494. 17,
  123495. 17
  123496. };
  123497. static static_codebook _16c0_s_p6_0 = {
  123498. 2, 289,
  123499. _vq_lengthlist__16c0_s_p6_0,
  123500. 1, -529530880, 1611661312, 5, 0,
  123501. _vq_quantlist__16c0_s_p6_0,
  123502. NULL,
  123503. &_vq_auxt__16c0_s_p6_0,
  123504. NULL,
  123505. 0
  123506. };
  123507. static long _vq_quantlist__16c0_s_p7_0[] = {
  123508. 1,
  123509. 0,
  123510. 2,
  123511. };
  123512. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123513. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123514. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123515. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123516. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123517. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123518. 13,
  123519. };
  123520. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123521. -5.5, 5.5,
  123522. };
  123523. static long _vq_quantmap__16c0_s_p7_0[] = {
  123524. 1, 0, 2,
  123525. };
  123526. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123527. _vq_quantthresh__16c0_s_p7_0,
  123528. _vq_quantmap__16c0_s_p7_0,
  123529. 3,
  123530. 3
  123531. };
  123532. static static_codebook _16c0_s_p7_0 = {
  123533. 4, 81,
  123534. _vq_lengthlist__16c0_s_p7_0,
  123535. 1, -529137664, 1618345984, 2, 0,
  123536. _vq_quantlist__16c0_s_p7_0,
  123537. NULL,
  123538. &_vq_auxt__16c0_s_p7_0,
  123539. NULL,
  123540. 0
  123541. };
  123542. static long _vq_quantlist__16c0_s_p7_1[] = {
  123543. 5,
  123544. 4,
  123545. 6,
  123546. 3,
  123547. 7,
  123548. 2,
  123549. 8,
  123550. 1,
  123551. 9,
  123552. 0,
  123553. 10,
  123554. };
  123555. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123556. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123557. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123558. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123559. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123560. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123561. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123562. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123563. 11,11,11, 9, 9, 9, 9,10,10,
  123564. };
  123565. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123566. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123567. 3.5, 4.5,
  123568. };
  123569. static long _vq_quantmap__16c0_s_p7_1[] = {
  123570. 9, 7, 5, 3, 1, 0, 2, 4,
  123571. 6, 8, 10,
  123572. };
  123573. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123574. _vq_quantthresh__16c0_s_p7_1,
  123575. _vq_quantmap__16c0_s_p7_1,
  123576. 11,
  123577. 11
  123578. };
  123579. static static_codebook _16c0_s_p7_1 = {
  123580. 2, 121,
  123581. _vq_lengthlist__16c0_s_p7_1,
  123582. 1, -531365888, 1611661312, 4, 0,
  123583. _vq_quantlist__16c0_s_p7_1,
  123584. NULL,
  123585. &_vq_auxt__16c0_s_p7_1,
  123586. NULL,
  123587. 0
  123588. };
  123589. static long _vq_quantlist__16c0_s_p8_0[] = {
  123590. 6,
  123591. 5,
  123592. 7,
  123593. 4,
  123594. 8,
  123595. 3,
  123596. 9,
  123597. 2,
  123598. 10,
  123599. 1,
  123600. 11,
  123601. 0,
  123602. 12,
  123603. };
  123604. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123605. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123606. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123607. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123608. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123609. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123610. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123611. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123612. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123613. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123614. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123615. 0,12,13,13,12,13,14,14,14,
  123616. };
  123617. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123618. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123619. 12.5, 17.5, 22.5, 27.5,
  123620. };
  123621. static long _vq_quantmap__16c0_s_p8_0[] = {
  123622. 11, 9, 7, 5, 3, 1, 0, 2,
  123623. 4, 6, 8, 10, 12,
  123624. };
  123625. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123626. _vq_quantthresh__16c0_s_p8_0,
  123627. _vq_quantmap__16c0_s_p8_0,
  123628. 13,
  123629. 13
  123630. };
  123631. static static_codebook _16c0_s_p8_0 = {
  123632. 2, 169,
  123633. _vq_lengthlist__16c0_s_p8_0,
  123634. 1, -526516224, 1616117760, 4, 0,
  123635. _vq_quantlist__16c0_s_p8_0,
  123636. NULL,
  123637. &_vq_auxt__16c0_s_p8_0,
  123638. NULL,
  123639. 0
  123640. };
  123641. static long _vq_quantlist__16c0_s_p8_1[] = {
  123642. 2,
  123643. 1,
  123644. 3,
  123645. 0,
  123646. 4,
  123647. };
  123648. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123649. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123650. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123651. };
  123652. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123653. -1.5, -0.5, 0.5, 1.5,
  123654. };
  123655. static long _vq_quantmap__16c0_s_p8_1[] = {
  123656. 3, 1, 0, 2, 4,
  123657. };
  123658. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123659. _vq_quantthresh__16c0_s_p8_1,
  123660. _vq_quantmap__16c0_s_p8_1,
  123661. 5,
  123662. 5
  123663. };
  123664. static static_codebook _16c0_s_p8_1 = {
  123665. 2, 25,
  123666. _vq_lengthlist__16c0_s_p8_1,
  123667. 1, -533725184, 1611661312, 3, 0,
  123668. _vq_quantlist__16c0_s_p8_1,
  123669. NULL,
  123670. &_vq_auxt__16c0_s_p8_1,
  123671. NULL,
  123672. 0
  123673. };
  123674. static long _vq_quantlist__16c0_s_p9_0[] = {
  123675. 1,
  123676. 0,
  123677. 2,
  123678. };
  123679. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123680. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123681. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123682. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123683. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123684. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123685. 7,
  123686. };
  123687. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123688. -157.5, 157.5,
  123689. };
  123690. static long _vq_quantmap__16c0_s_p9_0[] = {
  123691. 1, 0, 2,
  123692. };
  123693. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123694. _vq_quantthresh__16c0_s_p9_0,
  123695. _vq_quantmap__16c0_s_p9_0,
  123696. 3,
  123697. 3
  123698. };
  123699. static static_codebook _16c0_s_p9_0 = {
  123700. 4, 81,
  123701. _vq_lengthlist__16c0_s_p9_0,
  123702. 1, -518803456, 1628680192, 2, 0,
  123703. _vq_quantlist__16c0_s_p9_0,
  123704. NULL,
  123705. &_vq_auxt__16c0_s_p9_0,
  123706. NULL,
  123707. 0
  123708. };
  123709. static long _vq_quantlist__16c0_s_p9_1[] = {
  123710. 7,
  123711. 6,
  123712. 8,
  123713. 5,
  123714. 9,
  123715. 4,
  123716. 10,
  123717. 3,
  123718. 11,
  123719. 2,
  123720. 12,
  123721. 1,
  123722. 13,
  123723. 0,
  123724. 14,
  123725. };
  123726. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123727. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123728. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123729. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123730. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123731. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123732. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123733. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123736. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123737. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123738. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123740. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123741. 10,
  123742. };
  123743. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123744. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123745. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123746. };
  123747. static long _vq_quantmap__16c0_s_p9_1[] = {
  123748. 13, 11, 9, 7, 5, 3, 1, 0,
  123749. 2, 4, 6, 8, 10, 12, 14,
  123750. };
  123751. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123752. _vq_quantthresh__16c0_s_p9_1,
  123753. _vq_quantmap__16c0_s_p9_1,
  123754. 15,
  123755. 15
  123756. };
  123757. static static_codebook _16c0_s_p9_1 = {
  123758. 2, 225,
  123759. _vq_lengthlist__16c0_s_p9_1,
  123760. 1, -520986624, 1620377600, 4, 0,
  123761. _vq_quantlist__16c0_s_p9_1,
  123762. NULL,
  123763. &_vq_auxt__16c0_s_p9_1,
  123764. NULL,
  123765. 0
  123766. };
  123767. static long _vq_quantlist__16c0_s_p9_2[] = {
  123768. 10,
  123769. 9,
  123770. 11,
  123771. 8,
  123772. 12,
  123773. 7,
  123774. 13,
  123775. 6,
  123776. 14,
  123777. 5,
  123778. 15,
  123779. 4,
  123780. 16,
  123781. 3,
  123782. 17,
  123783. 2,
  123784. 18,
  123785. 1,
  123786. 19,
  123787. 0,
  123788. 20,
  123789. };
  123790. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123791. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123792. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123793. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123794. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123795. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123796. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123797. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123798. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123799. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123800. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123801. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123802. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123803. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123804. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123805. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123806. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123807. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123808. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123809. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123810. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123811. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123812. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123813. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123814. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123815. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123816. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123817. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123818. 10,11,10,10,11, 9,10,10,10,
  123819. };
  123820. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123821. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123822. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123823. 6.5, 7.5, 8.5, 9.5,
  123824. };
  123825. static long _vq_quantmap__16c0_s_p9_2[] = {
  123826. 19, 17, 15, 13, 11, 9, 7, 5,
  123827. 3, 1, 0, 2, 4, 6, 8, 10,
  123828. 12, 14, 16, 18, 20,
  123829. };
  123830. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123831. _vq_quantthresh__16c0_s_p9_2,
  123832. _vq_quantmap__16c0_s_p9_2,
  123833. 21,
  123834. 21
  123835. };
  123836. static static_codebook _16c0_s_p9_2 = {
  123837. 2, 441,
  123838. _vq_lengthlist__16c0_s_p9_2,
  123839. 1, -529268736, 1611661312, 5, 0,
  123840. _vq_quantlist__16c0_s_p9_2,
  123841. NULL,
  123842. &_vq_auxt__16c0_s_p9_2,
  123843. NULL,
  123844. 0
  123845. };
  123846. static long _huff_lengthlist__16c0_s_single[] = {
  123847. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123848. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123849. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123850. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123851. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123852. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123853. 16,16,18,18,
  123854. };
  123855. static static_codebook _huff_book__16c0_s_single = {
  123856. 2, 100,
  123857. _huff_lengthlist__16c0_s_single,
  123858. 0, 0, 0, 0, 0,
  123859. NULL,
  123860. NULL,
  123861. NULL,
  123862. NULL,
  123863. 0
  123864. };
  123865. static long _huff_lengthlist__16c1_s_long[] = {
  123866. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123867. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123868. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123869. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123870. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123871. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123872. 12,11,11,13,
  123873. };
  123874. static static_codebook _huff_book__16c1_s_long = {
  123875. 2, 100,
  123876. _huff_lengthlist__16c1_s_long,
  123877. 0, 0, 0, 0, 0,
  123878. NULL,
  123879. NULL,
  123880. NULL,
  123881. NULL,
  123882. 0
  123883. };
  123884. static long _vq_quantlist__16c1_s_p1_0[] = {
  123885. 1,
  123886. 0,
  123887. 2,
  123888. };
  123889. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123890. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123891. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123896. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123901. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123936. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123941. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123946. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123982. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123987. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123992. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0,
  124301. };
  124302. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124303. -0.5, 0.5,
  124304. };
  124305. static long _vq_quantmap__16c1_s_p1_0[] = {
  124306. 1, 0, 2,
  124307. };
  124308. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124309. _vq_quantthresh__16c1_s_p1_0,
  124310. _vq_quantmap__16c1_s_p1_0,
  124311. 3,
  124312. 3
  124313. };
  124314. static static_codebook _16c1_s_p1_0 = {
  124315. 8, 6561,
  124316. _vq_lengthlist__16c1_s_p1_0,
  124317. 1, -535822336, 1611661312, 2, 0,
  124318. _vq_quantlist__16c1_s_p1_0,
  124319. NULL,
  124320. &_vq_auxt__16c1_s_p1_0,
  124321. NULL,
  124322. 0
  124323. };
  124324. static long _vq_quantlist__16c1_s_p2_0[] = {
  124325. 2,
  124326. 1,
  124327. 3,
  124328. 0,
  124329. 4,
  124330. };
  124331. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0,
  124372. };
  124373. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124374. -1.5, -0.5, 0.5, 1.5,
  124375. };
  124376. static long _vq_quantmap__16c1_s_p2_0[] = {
  124377. 3, 1, 0, 2, 4,
  124378. };
  124379. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124380. _vq_quantthresh__16c1_s_p2_0,
  124381. _vq_quantmap__16c1_s_p2_0,
  124382. 5,
  124383. 5
  124384. };
  124385. static static_codebook _16c1_s_p2_0 = {
  124386. 4, 625,
  124387. _vq_lengthlist__16c1_s_p2_0,
  124388. 1, -533725184, 1611661312, 3, 0,
  124389. _vq_quantlist__16c1_s_p2_0,
  124390. NULL,
  124391. &_vq_auxt__16c1_s_p2_0,
  124392. NULL,
  124393. 0
  124394. };
  124395. static long _vq_quantlist__16c1_s_p3_0[] = {
  124396. 2,
  124397. 1,
  124398. 3,
  124399. 0,
  124400. 4,
  124401. };
  124402. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124403. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0,
  124443. };
  124444. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124445. -1.5, -0.5, 0.5, 1.5,
  124446. };
  124447. static long _vq_quantmap__16c1_s_p3_0[] = {
  124448. 3, 1, 0, 2, 4,
  124449. };
  124450. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124451. _vq_quantthresh__16c1_s_p3_0,
  124452. _vq_quantmap__16c1_s_p3_0,
  124453. 5,
  124454. 5
  124455. };
  124456. static static_codebook _16c1_s_p3_0 = {
  124457. 4, 625,
  124458. _vq_lengthlist__16c1_s_p3_0,
  124459. 1, -533725184, 1611661312, 3, 0,
  124460. _vq_quantlist__16c1_s_p3_0,
  124461. NULL,
  124462. &_vq_auxt__16c1_s_p3_0,
  124463. NULL,
  124464. 0
  124465. };
  124466. static long _vq_quantlist__16c1_s_p4_0[] = {
  124467. 4,
  124468. 3,
  124469. 5,
  124470. 2,
  124471. 6,
  124472. 1,
  124473. 7,
  124474. 0,
  124475. 8,
  124476. };
  124477. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124478. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124479. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124480. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124481. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124482. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0,
  124484. };
  124485. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124486. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124487. };
  124488. static long _vq_quantmap__16c1_s_p4_0[] = {
  124489. 7, 5, 3, 1, 0, 2, 4, 6,
  124490. 8,
  124491. };
  124492. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124493. _vq_quantthresh__16c1_s_p4_0,
  124494. _vq_quantmap__16c1_s_p4_0,
  124495. 9,
  124496. 9
  124497. };
  124498. static static_codebook _16c1_s_p4_0 = {
  124499. 2, 81,
  124500. _vq_lengthlist__16c1_s_p4_0,
  124501. 1, -531628032, 1611661312, 4, 0,
  124502. _vq_quantlist__16c1_s_p4_0,
  124503. NULL,
  124504. &_vq_auxt__16c1_s_p4_0,
  124505. NULL,
  124506. 0
  124507. };
  124508. static long _vq_quantlist__16c1_s_p5_0[] = {
  124509. 4,
  124510. 3,
  124511. 5,
  124512. 2,
  124513. 6,
  124514. 1,
  124515. 7,
  124516. 0,
  124517. 8,
  124518. };
  124519. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124520. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124521. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124522. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124523. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124524. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124525. 10,
  124526. };
  124527. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124528. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124529. };
  124530. static long _vq_quantmap__16c1_s_p5_0[] = {
  124531. 7, 5, 3, 1, 0, 2, 4, 6,
  124532. 8,
  124533. };
  124534. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124535. _vq_quantthresh__16c1_s_p5_0,
  124536. _vq_quantmap__16c1_s_p5_0,
  124537. 9,
  124538. 9
  124539. };
  124540. static static_codebook _16c1_s_p5_0 = {
  124541. 2, 81,
  124542. _vq_lengthlist__16c1_s_p5_0,
  124543. 1, -531628032, 1611661312, 4, 0,
  124544. _vq_quantlist__16c1_s_p5_0,
  124545. NULL,
  124546. &_vq_auxt__16c1_s_p5_0,
  124547. NULL,
  124548. 0
  124549. };
  124550. static long _vq_quantlist__16c1_s_p6_0[] = {
  124551. 8,
  124552. 7,
  124553. 9,
  124554. 6,
  124555. 10,
  124556. 5,
  124557. 11,
  124558. 4,
  124559. 12,
  124560. 3,
  124561. 13,
  124562. 2,
  124563. 14,
  124564. 1,
  124565. 15,
  124566. 0,
  124567. 16,
  124568. };
  124569. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124570. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124571. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124572. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124573. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124574. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124575. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124576. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124577. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124578. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124579. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124580. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124581. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124582. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124583. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124584. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124585. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124586. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124588. 14,
  124589. };
  124590. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124591. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124592. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124593. };
  124594. static long _vq_quantmap__16c1_s_p6_0[] = {
  124595. 15, 13, 11, 9, 7, 5, 3, 1,
  124596. 0, 2, 4, 6, 8, 10, 12, 14,
  124597. 16,
  124598. };
  124599. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124600. _vq_quantthresh__16c1_s_p6_0,
  124601. _vq_quantmap__16c1_s_p6_0,
  124602. 17,
  124603. 17
  124604. };
  124605. static static_codebook _16c1_s_p6_0 = {
  124606. 2, 289,
  124607. _vq_lengthlist__16c1_s_p6_0,
  124608. 1, -529530880, 1611661312, 5, 0,
  124609. _vq_quantlist__16c1_s_p6_0,
  124610. NULL,
  124611. &_vq_auxt__16c1_s_p6_0,
  124612. NULL,
  124613. 0
  124614. };
  124615. static long _vq_quantlist__16c1_s_p7_0[] = {
  124616. 1,
  124617. 0,
  124618. 2,
  124619. };
  124620. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124621. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124622. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124623. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124624. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124625. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124626. 11,
  124627. };
  124628. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124629. -5.5, 5.5,
  124630. };
  124631. static long _vq_quantmap__16c1_s_p7_0[] = {
  124632. 1, 0, 2,
  124633. };
  124634. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124635. _vq_quantthresh__16c1_s_p7_0,
  124636. _vq_quantmap__16c1_s_p7_0,
  124637. 3,
  124638. 3
  124639. };
  124640. static static_codebook _16c1_s_p7_0 = {
  124641. 4, 81,
  124642. _vq_lengthlist__16c1_s_p7_0,
  124643. 1, -529137664, 1618345984, 2, 0,
  124644. _vq_quantlist__16c1_s_p7_0,
  124645. NULL,
  124646. &_vq_auxt__16c1_s_p7_0,
  124647. NULL,
  124648. 0
  124649. };
  124650. static long _vq_quantlist__16c1_s_p7_1[] = {
  124651. 5,
  124652. 4,
  124653. 6,
  124654. 3,
  124655. 7,
  124656. 2,
  124657. 8,
  124658. 1,
  124659. 9,
  124660. 0,
  124661. 10,
  124662. };
  124663. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124664. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124665. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124666. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124667. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124668. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124669. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124670. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124671. 10,10,10, 8, 8, 8, 8, 9, 9,
  124672. };
  124673. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124674. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124675. 3.5, 4.5,
  124676. };
  124677. static long _vq_quantmap__16c1_s_p7_1[] = {
  124678. 9, 7, 5, 3, 1, 0, 2, 4,
  124679. 6, 8, 10,
  124680. };
  124681. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124682. _vq_quantthresh__16c1_s_p7_1,
  124683. _vq_quantmap__16c1_s_p7_1,
  124684. 11,
  124685. 11
  124686. };
  124687. static static_codebook _16c1_s_p7_1 = {
  124688. 2, 121,
  124689. _vq_lengthlist__16c1_s_p7_1,
  124690. 1, -531365888, 1611661312, 4, 0,
  124691. _vq_quantlist__16c1_s_p7_1,
  124692. NULL,
  124693. &_vq_auxt__16c1_s_p7_1,
  124694. NULL,
  124695. 0
  124696. };
  124697. static long _vq_quantlist__16c1_s_p8_0[] = {
  124698. 6,
  124699. 5,
  124700. 7,
  124701. 4,
  124702. 8,
  124703. 3,
  124704. 9,
  124705. 2,
  124706. 10,
  124707. 1,
  124708. 11,
  124709. 0,
  124710. 12,
  124711. };
  124712. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124713. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124714. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124715. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124716. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124717. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124718. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124719. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124720. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124721. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124722. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124723. 0,12,12,12,12,13,13,14,15,
  124724. };
  124725. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124726. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124727. 12.5, 17.5, 22.5, 27.5,
  124728. };
  124729. static long _vq_quantmap__16c1_s_p8_0[] = {
  124730. 11, 9, 7, 5, 3, 1, 0, 2,
  124731. 4, 6, 8, 10, 12,
  124732. };
  124733. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124734. _vq_quantthresh__16c1_s_p8_0,
  124735. _vq_quantmap__16c1_s_p8_0,
  124736. 13,
  124737. 13
  124738. };
  124739. static static_codebook _16c1_s_p8_0 = {
  124740. 2, 169,
  124741. _vq_lengthlist__16c1_s_p8_0,
  124742. 1, -526516224, 1616117760, 4, 0,
  124743. _vq_quantlist__16c1_s_p8_0,
  124744. NULL,
  124745. &_vq_auxt__16c1_s_p8_0,
  124746. NULL,
  124747. 0
  124748. };
  124749. static long _vq_quantlist__16c1_s_p8_1[] = {
  124750. 2,
  124751. 1,
  124752. 3,
  124753. 0,
  124754. 4,
  124755. };
  124756. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124757. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124758. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124759. };
  124760. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124761. -1.5, -0.5, 0.5, 1.5,
  124762. };
  124763. static long _vq_quantmap__16c1_s_p8_1[] = {
  124764. 3, 1, 0, 2, 4,
  124765. };
  124766. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124767. _vq_quantthresh__16c1_s_p8_1,
  124768. _vq_quantmap__16c1_s_p8_1,
  124769. 5,
  124770. 5
  124771. };
  124772. static static_codebook _16c1_s_p8_1 = {
  124773. 2, 25,
  124774. _vq_lengthlist__16c1_s_p8_1,
  124775. 1, -533725184, 1611661312, 3, 0,
  124776. _vq_quantlist__16c1_s_p8_1,
  124777. NULL,
  124778. &_vq_auxt__16c1_s_p8_1,
  124779. NULL,
  124780. 0
  124781. };
  124782. static long _vq_quantlist__16c1_s_p9_0[] = {
  124783. 6,
  124784. 5,
  124785. 7,
  124786. 4,
  124787. 8,
  124788. 3,
  124789. 9,
  124790. 2,
  124791. 10,
  124792. 1,
  124793. 11,
  124794. 0,
  124795. 12,
  124796. };
  124797. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124798. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124799. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124800. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124801. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124802. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124803. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124804. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124805. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124806. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124807. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124808. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124809. };
  124810. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124811. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124812. 787.5, 1102.5, 1417.5, 1732.5,
  124813. };
  124814. static long _vq_quantmap__16c1_s_p9_0[] = {
  124815. 11, 9, 7, 5, 3, 1, 0, 2,
  124816. 4, 6, 8, 10, 12,
  124817. };
  124818. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124819. _vq_quantthresh__16c1_s_p9_0,
  124820. _vq_quantmap__16c1_s_p9_0,
  124821. 13,
  124822. 13
  124823. };
  124824. static static_codebook _16c1_s_p9_0 = {
  124825. 2, 169,
  124826. _vq_lengthlist__16c1_s_p9_0,
  124827. 1, -513964032, 1628680192, 4, 0,
  124828. _vq_quantlist__16c1_s_p9_0,
  124829. NULL,
  124830. &_vq_auxt__16c1_s_p9_0,
  124831. NULL,
  124832. 0
  124833. };
  124834. static long _vq_quantlist__16c1_s_p9_1[] = {
  124835. 7,
  124836. 6,
  124837. 8,
  124838. 5,
  124839. 9,
  124840. 4,
  124841. 10,
  124842. 3,
  124843. 11,
  124844. 2,
  124845. 12,
  124846. 1,
  124847. 13,
  124848. 0,
  124849. 14,
  124850. };
  124851. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124852. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124853. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124854. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124855. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124856. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124857. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124858. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124859. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124860. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124861. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124862. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124863. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124864. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124865. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124866. 13,
  124867. };
  124868. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124869. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124870. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124871. };
  124872. static long _vq_quantmap__16c1_s_p9_1[] = {
  124873. 13, 11, 9, 7, 5, 3, 1, 0,
  124874. 2, 4, 6, 8, 10, 12, 14,
  124875. };
  124876. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124877. _vq_quantthresh__16c1_s_p9_1,
  124878. _vq_quantmap__16c1_s_p9_1,
  124879. 15,
  124880. 15
  124881. };
  124882. static static_codebook _16c1_s_p9_1 = {
  124883. 2, 225,
  124884. _vq_lengthlist__16c1_s_p9_1,
  124885. 1, -520986624, 1620377600, 4, 0,
  124886. _vq_quantlist__16c1_s_p9_1,
  124887. NULL,
  124888. &_vq_auxt__16c1_s_p9_1,
  124889. NULL,
  124890. 0
  124891. };
  124892. static long _vq_quantlist__16c1_s_p9_2[] = {
  124893. 10,
  124894. 9,
  124895. 11,
  124896. 8,
  124897. 12,
  124898. 7,
  124899. 13,
  124900. 6,
  124901. 14,
  124902. 5,
  124903. 15,
  124904. 4,
  124905. 16,
  124906. 3,
  124907. 17,
  124908. 2,
  124909. 18,
  124910. 1,
  124911. 19,
  124912. 0,
  124913. 20,
  124914. };
  124915. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124916. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124917. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124918. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124919. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124920. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124921. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124922. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124923. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124924. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124925. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124926. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124927. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124928. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124929. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124930. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124931. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124932. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124933. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124934. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124935. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124936. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124937. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124938. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124939. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124940. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124941. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124942. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124943. 11,11,11,11,12,11,11,12,11,
  124944. };
  124945. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124946. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124947. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124948. 6.5, 7.5, 8.5, 9.5,
  124949. };
  124950. static long _vq_quantmap__16c1_s_p9_2[] = {
  124951. 19, 17, 15, 13, 11, 9, 7, 5,
  124952. 3, 1, 0, 2, 4, 6, 8, 10,
  124953. 12, 14, 16, 18, 20,
  124954. };
  124955. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124956. _vq_quantthresh__16c1_s_p9_2,
  124957. _vq_quantmap__16c1_s_p9_2,
  124958. 21,
  124959. 21
  124960. };
  124961. static static_codebook _16c1_s_p9_2 = {
  124962. 2, 441,
  124963. _vq_lengthlist__16c1_s_p9_2,
  124964. 1, -529268736, 1611661312, 5, 0,
  124965. _vq_quantlist__16c1_s_p9_2,
  124966. NULL,
  124967. &_vq_auxt__16c1_s_p9_2,
  124968. NULL,
  124969. 0
  124970. };
  124971. static long _huff_lengthlist__16c1_s_short[] = {
  124972. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124973. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124974. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124975. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124976. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124977. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124978. 9, 9,10,13,
  124979. };
  124980. static static_codebook _huff_book__16c1_s_short = {
  124981. 2, 100,
  124982. _huff_lengthlist__16c1_s_short,
  124983. 0, 0, 0, 0, 0,
  124984. NULL,
  124985. NULL,
  124986. NULL,
  124987. NULL,
  124988. 0
  124989. };
  124990. static long _huff_lengthlist__16c2_s_long[] = {
  124991. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124992. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124993. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124994. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124995. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124996. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124997. 14,14,16,18,
  124998. };
  124999. static static_codebook _huff_book__16c2_s_long = {
  125000. 2, 100,
  125001. _huff_lengthlist__16c2_s_long,
  125002. 0, 0, 0, 0, 0,
  125003. NULL,
  125004. NULL,
  125005. NULL,
  125006. NULL,
  125007. 0
  125008. };
  125009. static long _vq_quantlist__16c2_s_p1_0[] = {
  125010. 1,
  125011. 0,
  125012. 2,
  125013. };
  125014. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125015. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125016. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0,
  125021. };
  125022. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125023. -0.5, 0.5,
  125024. };
  125025. static long _vq_quantmap__16c2_s_p1_0[] = {
  125026. 1, 0, 2,
  125027. };
  125028. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125029. _vq_quantthresh__16c2_s_p1_0,
  125030. _vq_quantmap__16c2_s_p1_0,
  125031. 3,
  125032. 3
  125033. };
  125034. static static_codebook _16c2_s_p1_0 = {
  125035. 4, 81,
  125036. _vq_lengthlist__16c2_s_p1_0,
  125037. 1, -535822336, 1611661312, 2, 0,
  125038. _vq_quantlist__16c2_s_p1_0,
  125039. NULL,
  125040. &_vq_auxt__16c2_s_p1_0,
  125041. NULL,
  125042. 0
  125043. };
  125044. static long _vq_quantlist__16c2_s_p2_0[] = {
  125045. 2,
  125046. 1,
  125047. 3,
  125048. 0,
  125049. 4,
  125050. };
  125051. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125052. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125053. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125054. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125055. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125056. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125057. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125058. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125059. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125065. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125066. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125067. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125073. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125074. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125075. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125081. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125082. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125083. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125088. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125089. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125090. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125091. 13,
  125092. };
  125093. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125094. -1.5, -0.5, 0.5, 1.5,
  125095. };
  125096. static long _vq_quantmap__16c2_s_p2_0[] = {
  125097. 3, 1, 0, 2, 4,
  125098. };
  125099. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125100. _vq_quantthresh__16c2_s_p2_0,
  125101. _vq_quantmap__16c2_s_p2_0,
  125102. 5,
  125103. 5
  125104. };
  125105. static static_codebook _16c2_s_p2_0 = {
  125106. 4, 625,
  125107. _vq_lengthlist__16c2_s_p2_0,
  125108. 1, -533725184, 1611661312, 3, 0,
  125109. _vq_quantlist__16c2_s_p2_0,
  125110. NULL,
  125111. &_vq_auxt__16c2_s_p2_0,
  125112. NULL,
  125113. 0
  125114. };
  125115. static long _vq_quantlist__16c2_s_p3_0[] = {
  125116. 4,
  125117. 3,
  125118. 5,
  125119. 2,
  125120. 6,
  125121. 1,
  125122. 7,
  125123. 0,
  125124. 8,
  125125. };
  125126. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125127. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125128. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125129. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125130. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0,
  125133. };
  125134. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125135. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125136. };
  125137. static long _vq_quantmap__16c2_s_p3_0[] = {
  125138. 7, 5, 3, 1, 0, 2, 4, 6,
  125139. 8,
  125140. };
  125141. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125142. _vq_quantthresh__16c2_s_p3_0,
  125143. _vq_quantmap__16c2_s_p3_0,
  125144. 9,
  125145. 9
  125146. };
  125147. static static_codebook _16c2_s_p3_0 = {
  125148. 2, 81,
  125149. _vq_lengthlist__16c2_s_p3_0,
  125150. 1, -531628032, 1611661312, 4, 0,
  125151. _vq_quantlist__16c2_s_p3_0,
  125152. NULL,
  125153. &_vq_auxt__16c2_s_p3_0,
  125154. NULL,
  125155. 0
  125156. };
  125157. static long _vq_quantlist__16c2_s_p4_0[] = {
  125158. 8,
  125159. 7,
  125160. 9,
  125161. 6,
  125162. 10,
  125163. 5,
  125164. 11,
  125165. 4,
  125166. 12,
  125167. 3,
  125168. 13,
  125169. 2,
  125170. 14,
  125171. 1,
  125172. 15,
  125173. 0,
  125174. 16,
  125175. };
  125176. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125177. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125178. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125179. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125180. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125181. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125182. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125183. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125184. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125185. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125186. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0,
  125196. };
  125197. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125198. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125199. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125200. };
  125201. static long _vq_quantmap__16c2_s_p4_0[] = {
  125202. 15, 13, 11, 9, 7, 5, 3, 1,
  125203. 0, 2, 4, 6, 8, 10, 12, 14,
  125204. 16,
  125205. };
  125206. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125207. _vq_quantthresh__16c2_s_p4_0,
  125208. _vq_quantmap__16c2_s_p4_0,
  125209. 17,
  125210. 17
  125211. };
  125212. static static_codebook _16c2_s_p4_0 = {
  125213. 2, 289,
  125214. _vq_lengthlist__16c2_s_p4_0,
  125215. 1, -529530880, 1611661312, 5, 0,
  125216. _vq_quantlist__16c2_s_p4_0,
  125217. NULL,
  125218. &_vq_auxt__16c2_s_p4_0,
  125219. NULL,
  125220. 0
  125221. };
  125222. static long _vq_quantlist__16c2_s_p5_0[] = {
  125223. 1,
  125224. 0,
  125225. 2,
  125226. };
  125227. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125228. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125229. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125230. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125231. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125232. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125233. 12,
  125234. };
  125235. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125236. -5.5, 5.5,
  125237. };
  125238. static long _vq_quantmap__16c2_s_p5_0[] = {
  125239. 1, 0, 2,
  125240. };
  125241. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125242. _vq_quantthresh__16c2_s_p5_0,
  125243. _vq_quantmap__16c2_s_p5_0,
  125244. 3,
  125245. 3
  125246. };
  125247. static static_codebook _16c2_s_p5_0 = {
  125248. 4, 81,
  125249. _vq_lengthlist__16c2_s_p5_0,
  125250. 1, -529137664, 1618345984, 2, 0,
  125251. _vq_quantlist__16c2_s_p5_0,
  125252. NULL,
  125253. &_vq_auxt__16c2_s_p5_0,
  125254. NULL,
  125255. 0
  125256. };
  125257. static long _vq_quantlist__16c2_s_p5_1[] = {
  125258. 5,
  125259. 4,
  125260. 6,
  125261. 3,
  125262. 7,
  125263. 2,
  125264. 8,
  125265. 1,
  125266. 9,
  125267. 0,
  125268. 10,
  125269. };
  125270. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125271. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125272. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125273. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125274. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125275. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125276. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125277. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125278. 11,11,11, 7, 7, 8, 8, 8, 8,
  125279. };
  125280. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125282. 3.5, 4.5,
  125283. };
  125284. static long _vq_quantmap__16c2_s_p5_1[] = {
  125285. 9, 7, 5, 3, 1, 0, 2, 4,
  125286. 6, 8, 10,
  125287. };
  125288. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125289. _vq_quantthresh__16c2_s_p5_1,
  125290. _vq_quantmap__16c2_s_p5_1,
  125291. 11,
  125292. 11
  125293. };
  125294. static static_codebook _16c2_s_p5_1 = {
  125295. 2, 121,
  125296. _vq_lengthlist__16c2_s_p5_1,
  125297. 1, -531365888, 1611661312, 4, 0,
  125298. _vq_quantlist__16c2_s_p5_1,
  125299. NULL,
  125300. &_vq_auxt__16c2_s_p5_1,
  125301. NULL,
  125302. 0
  125303. };
  125304. static long _vq_quantlist__16c2_s_p6_0[] = {
  125305. 6,
  125306. 5,
  125307. 7,
  125308. 4,
  125309. 8,
  125310. 3,
  125311. 9,
  125312. 2,
  125313. 10,
  125314. 1,
  125315. 11,
  125316. 0,
  125317. 12,
  125318. };
  125319. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125320. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125321. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125322. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125323. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125324. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125325. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. };
  125332. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125333. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125334. 12.5, 17.5, 22.5, 27.5,
  125335. };
  125336. static long _vq_quantmap__16c2_s_p6_0[] = {
  125337. 11, 9, 7, 5, 3, 1, 0, 2,
  125338. 4, 6, 8, 10, 12,
  125339. };
  125340. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125341. _vq_quantthresh__16c2_s_p6_0,
  125342. _vq_quantmap__16c2_s_p6_0,
  125343. 13,
  125344. 13
  125345. };
  125346. static static_codebook _16c2_s_p6_0 = {
  125347. 2, 169,
  125348. _vq_lengthlist__16c2_s_p6_0,
  125349. 1, -526516224, 1616117760, 4, 0,
  125350. _vq_quantlist__16c2_s_p6_0,
  125351. NULL,
  125352. &_vq_auxt__16c2_s_p6_0,
  125353. NULL,
  125354. 0
  125355. };
  125356. static long _vq_quantlist__16c2_s_p6_1[] = {
  125357. 2,
  125358. 1,
  125359. 3,
  125360. 0,
  125361. 4,
  125362. };
  125363. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125364. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125365. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125366. };
  125367. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125368. -1.5, -0.5, 0.5, 1.5,
  125369. };
  125370. static long _vq_quantmap__16c2_s_p6_1[] = {
  125371. 3, 1, 0, 2, 4,
  125372. };
  125373. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125374. _vq_quantthresh__16c2_s_p6_1,
  125375. _vq_quantmap__16c2_s_p6_1,
  125376. 5,
  125377. 5
  125378. };
  125379. static static_codebook _16c2_s_p6_1 = {
  125380. 2, 25,
  125381. _vq_lengthlist__16c2_s_p6_1,
  125382. 1, -533725184, 1611661312, 3, 0,
  125383. _vq_quantlist__16c2_s_p6_1,
  125384. NULL,
  125385. &_vq_auxt__16c2_s_p6_1,
  125386. NULL,
  125387. 0
  125388. };
  125389. static long _vq_quantlist__16c2_s_p7_0[] = {
  125390. 6,
  125391. 5,
  125392. 7,
  125393. 4,
  125394. 8,
  125395. 3,
  125396. 9,
  125397. 2,
  125398. 10,
  125399. 1,
  125400. 11,
  125401. 0,
  125402. 12,
  125403. };
  125404. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125405. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125406. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125407. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125408. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125409. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125410. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125411. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125412. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125413. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125414. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125415. 18,13,14,13,13,14,13,15,14,
  125416. };
  125417. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125418. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125419. 27.5, 38.5, 49.5, 60.5,
  125420. };
  125421. static long _vq_quantmap__16c2_s_p7_0[] = {
  125422. 11, 9, 7, 5, 3, 1, 0, 2,
  125423. 4, 6, 8, 10, 12,
  125424. };
  125425. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125426. _vq_quantthresh__16c2_s_p7_0,
  125427. _vq_quantmap__16c2_s_p7_0,
  125428. 13,
  125429. 13
  125430. };
  125431. static static_codebook _16c2_s_p7_0 = {
  125432. 2, 169,
  125433. _vq_lengthlist__16c2_s_p7_0,
  125434. 1, -523206656, 1618345984, 4, 0,
  125435. _vq_quantlist__16c2_s_p7_0,
  125436. NULL,
  125437. &_vq_auxt__16c2_s_p7_0,
  125438. NULL,
  125439. 0
  125440. };
  125441. static long _vq_quantlist__16c2_s_p7_1[] = {
  125442. 5,
  125443. 4,
  125444. 6,
  125445. 3,
  125446. 7,
  125447. 2,
  125448. 8,
  125449. 1,
  125450. 9,
  125451. 0,
  125452. 10,
  125453. };
  125454. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125455. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125456. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125457. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125458. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125459. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125460. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125461. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125462. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125463. };
  125464. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125465. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125466. 3.5, 4.5,
  125467. };
  125468. static long _vq_quantmap__16c2_s_p7_1[] = {
  125469. 9, 7, 5, 3, 1, 0, 2, 4,
  125470. 6, 8, 10,
  125471. };
  125472. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125473. _vq_quantthresh__16c2_s_p7_1,
  125474. _vq_quantmap__16c2_s_p7_1,
  125475. 11,
  125476. 11
  125477. };
  125478. static static_codebook _16c2_s_p7_1 = {
  125479. 2, 121,
  125480. _vq_lengthlist__16c2_s_p7_1,
  125481. 1, -531365888, 1611661312, 4, 0,
  125482. _vq_quantlist__16c2_s_p7_1,
  125483. NULL,
  125484. &_vq_auxt__16c2_s_p7_1,
  125485. NULL,
  125486. 0
  125487. };
  125488. static long _vq_quantlist__16c2_s_p8_0[] = {
  125489. 7,
  125490. 6,
  125491. 8,
  125492. 5,
  125493. 9,
  125494. 4,
  125495. 10,
  125496. 3,
  125497. 11,
  125498. 2,
  125499. 12,
  125500. 1,
  125501. 13,
  125502. 0,
  125503. 14,
  125504. };
  125505. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125506. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125507. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125508. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125509. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125510. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125511. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125512. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125513. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125514. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125515. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125516. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125517. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125518. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125519. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125520. 13,
  125521. };
  125522. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125523. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125524. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125525. };
  125526. static long _vq_quantmap__16c2_s_p8_0[] = {
  125527. 13, 11, 9, 7, 5, 3, 1, 0,
  125528. 2, 4, 6, 8, 10, 12, 14,
  125529. };
  125530. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125531. _vq_quantthresh__16c2_s_p8_0,
  125532. _vq_quantmap__16c2_s_p8_0,
  125533. 15,
  125534. 15
  125535. };
  125536. static static_codebook _16c2_s_p8_0 = {
  125537. 2, 225,
  125538. _vq_lengthlist__16c2_s_p8_0,
  125539. 1, -520986624, 1620377600, 4, 0,
  125540. _vq_quantlist__16c2_s_p8_0,
  125541. NULL,
  125542. &_vq_auxt__16c2_s_p8_0,
  125543. NULL,
  125544. 0
  125545. };
  125546. static long _vq_quantlist__16c2_s_p8_1[] = {
  125547. 10,
  125548. 9,
  125549. 11,
  125550. 8,
  125551. 12,
  125552. 7,
  125553. 13,
  125554. 6,
  125555. 14,
  125556. 5,
  125557. 15,
  125558. 4,
  125559. 16,
  125560. 3,
  125561. 17,
  125562. 2,
  125563. 18,
  125564. 1,
  125565. 19,
  125566. 0,
  125567. 20,
  125568. };
  125569. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125570. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125571. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125572. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125573. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125574. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125575. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125576. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125577. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125578. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125579. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125580. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125581. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125582. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125583. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125584. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125585. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125586. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125587. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125588. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125589. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125590. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125591. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125592. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125593. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125594. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125595. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125596. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125597. 10,11,10,10,10,10,10,10,10,
  125598. };
  125599. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125600. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125601. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125602. 6.5, 7.5, 8.5, 9.5,
  125603. };
  125604. static long _vq_quantmap__16c2_s_p8_1[] = {
  125605. 19, 17, 15, 13, 11, 9, 7, 5,
  125606. 3, 1, 0, 2, 4, 6, 8, 10,
  125607. 12, 14, 16, 18, 20,
  125608. };
  125609. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125610. _vq_quantthresh__16c2_s_p8_1,
  125611. _vq_quantmap__16c2_s_p8_1,
  125612. 21,
  125613. 21
  125614. };
  125615. static static_codebook _16c2_s_p8_1 = {
  125616. 2, 441,
  125617. _vq_lengthlist__16c2_s_p8_1,
  125618. 1, -529268736, 1611661312, 5, 0,
  125619. _vq_quantlist__16c2_s_p8_1,
  125620. NULL,
  125621. &_vq_auxt__16c2_s_p8_1,
  125622. NULL,
  125623. 0
  125624. };
  125625. static long _vq_quantlist__16c2_s_p9_0[] = {
  125626. 6,
  125627. 5,
  125628. 7,
  125629. 4,
  125630. 8,
  125631. 3,
  125632. 9,
  125633. 2,
  125634. 10,
  125635. 1,
  125636. 11,
  125637. 0,
  125638. 12,
  125639. };
  125640. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125641. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125643. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125644. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125645. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125646. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125647. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125648. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125649. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125650. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125651. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125652. };
  125653. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125654. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125655. 2327.5, 3258.5, 4189.5, 5120.5,
  125656. };
  125657. static long _vq_quantmap__16c2_s_p9_0[] = {
  125658. 11, 9, 7, 5, 3, 1, 0, 2,
  125659. 4, 6, 8, 10, 12,
  125660. };
  125661. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125662. _vq_quantthresh__16c2_s_p9_0,
  125663. _vq_quantmap__16c2_s_p9_0,
  125664. 13,
  125665. 13
  125666. };
  125667. static static_codebook _16c2_s_p9_0 = {
  125668. 2, 169,
  125669. _vq_lengthlist__16c2_s_p9_0,
  125670. 1, -510275072, 1631393792, 4, 0,
  125671. _vq_quantlist__16c2_s_p9_0,
  125672. NULL,
  125673. &_vq_auxt__16c2_s_p9_0,
  125674. NULL,
  125675. 0
  125676. };
  125677. static long _vq_quantlist__16c2_s_p9_1[] = {
  125678. 8,
  125679. 7,
  125680. 9,
  125681. 6,
  125682. 10,
  125683. 5,
  125684. 11,
  125685. 4,
  125686. 12,
  125687. 3,
  125688. 13,
  125689. 2,
  125690. 14,
  125691. 1,
  125692. 15,
  125693. 0,
  125694. 16,
  125695. };
  125696. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125697. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125698. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125699. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125700. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125701. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125702. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125703. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125704. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125705. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125708. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125712. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125713. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125715. 10,
  125716. };
  125717. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125718. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125719. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125720. };
  125721. static long _vq_quantmap__16c2_s_p9_1[] = {
  125722. 15, 13, 11, 9, 7, 5, 3, 1,
  125723. 0, 2, 4, 6, 8, 10, 12, 14,
  125724. 16,
  125725. };
  125726. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125727. _vq_quantthresh__16c2_s_p9_1,
  125728. _vq_quantmap__16c2_s_p9_1,
  125729. 17,
  125730. 17
  125731. };
  125732. static static_codebook _16c2_s_p9_1 = {
  125733. 2, 289,
  125734. _vq_lengthlist__16c2_s_p9_1,
  125735. 1, -518488064, 1622704128, 5, 0,
  125736. _vq_quantlist__16c2_s_p9_1,
  125737. NULL,
  125738. &_vq_auxt__16c2_s_p9_1,
  125739. NULL,
  125740. 0
  125741. };
  125742. static long _vq_quantlist__16c2_s_p9_2[] = {
  125743. 13,
  125744. 12,
  125745. 14,
  125746. 11,
  125747. 15,
  125748. 10,
  125749. 16,
  125750. 9,
  125751. 17,
  125752. 8,
  125753. 18,
  125754. 7,
  125755. 19,
  125756. 6,
  125757. 20,
  125758. 5,
  125759. 21,
  125760. 4,
  125761. 22,
  125762. 3,
  125763. 23,
  125764. 2,
  125765. 24,
  125766. 1,
  125767. 25,
  125768. 0,
  125769. 26,
  125770. };
  125771. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125772. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125773. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125774. };
  125775. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125776. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125777. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125778. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125779. 11.5, 12.5,
  125780. };
  125781. static long _vq_quantmap__16c2_s_p9_2[] = {
  125782. 25, 23, 21, 19, 17, 15, 13, 11,
  125783. 9, 7, 5, 3, 1, 0, 2, 4,
  125784. 6, 8, 10, 12, 14, 16, 18, 20,
  125785. 22, 24, 26,
  125786. };
  125787. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125788. _vq_quantthresh__16c2_s_p9_2,
  125789. _vq_quantmap__16c2_s_p9_2,
  125790. 27,
  125791. 27
  125792. };
  125793. static static_codebook _16c2_s_p9_2 = {
  125794. 1, 27,
  125795. _vq_lengthlist__16c2_s_p9_2,
  125796. 1, -528875520, 1611661312, 5, 0,
  125797. _vq_quantlist__16c2_s_p9_2,
  125798. NULL,
  125799. &_vq_auxt__16c2_s_p9_2,
  125800. NULL,
  125801. 0
  125802. };
  125803. static long _huff_lengthlist__16c2_s_short[] = {
  125804. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125805. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125806. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125807. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125808. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125809. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125810. 15,12,14,14,
  125811. };
  125812. static static_codebook _huff_book__16c2_s_short = {
  125813. 2, 100,
  125814. _huff_lengthlist__16c2_s_short,
  125815. 0, 0, 0, 0, 0,
  125816. NULL,
  125817. NULL,
  125818. NULL,
  125819. NULL,
  125820. 0
  125821. };
  125822. static long _vq_quantlist__8c0_s_p1_0[] = {
  125823. 1,
  125824. 0,
  125825. 2,
  125826. };
  125827. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125828. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125829. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125834. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125839. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125874. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125879. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125884. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125920. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125925. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125930. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0,
  126239. };
  126240. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126241. -0.5, 0.5,
  126242. };
  126243. static long _vq_quantmap__8c0_s_p1_0[] = {
  126244. 1, 0, 2,
  126245. };
  126246. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126247. _vq_quantthresh__8c0_s_p1_0,
  126248. _vq_quantmap__8c0_s_p1_0,
  126249. 3,
  126250. 3
  126251. };
  126252. static static_codebook _8c0_s_p1_0 = {
  126253. 8, 6561,
  126254. _vq_lengthlist__8c0_s_p1_0,
  126255. 1, -535822336, 1611661312, 2, 0,
  126256. _vq_quantlist__8c0_s_p1_0,
  126257. NULL,
  126258. &_vq_auxt__8c0_s_p1_0,
  126259. NULL,
  126260. 0
  126261. };
  126262. static long _vq_quantlist__8c0_s_p2_0[] = {
  126263. 2,
  126264. 1,
  126265. 3,
  126266. 0,
  126267. 4,
  126268. };
  126269. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0,
  126310. };
  126311. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126312. -1.5, -0.5, 0.5, 1.5,
  126313. };
  126314. static long _vq_quantmap__8c0_s_p2_0[] = {
  126315. 3, 1, 0, 2, 4,
  126316. };
  126317. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126318. _vq_quantthresh__8c0_s_p2_0,
  126319. _vq_quantmap__8c0_s_p2_0,
  126320. 5,
  126321. 5
  126322. };
  126323. static static_codebook _8c0_s_p2_0 = {
  126324. 4, 625,
  126325. _vq_lengthlist__8c0_s_p2_0,
  126326. 1, -533725184, 1611661312, 3, 0,
  126327. _vq_quantlist__8c0_s_p2_0,
  126328. NULL,
  126329. &_vq_auxt__8c0_s_p2_0,
  126330. NULL,
  126331. 0
  126332. };
  126333. static long _vq_quantlist__8c0_s_p3_0[] = {
  126334. 2,
  126335. 1,
  126336. 3,
  126337. 0,
  126338. 4,
  126339. };
  126340. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126341. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0,
  126381. };
  126382. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126383. -1.5, -0.5, 0.5, 1.5,
  126384. };
  126385. static long _vq_quantmap__8c0_s_p3_0[] = {
  126386. 3, 1, 0, 2, 4,
  126387. };
  126388. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126389. _vq_quantthresh__8c0_s_p3_0,
  126390. _vq_quantmap__8c0_s_p3_0,
  126391. 5,
  126392. 5
  126393. };
  126394. static static_codebook _8c0_s_p3_0 = {
  126395. 4, 625,
  126396. _vq_lengthlist__8c0_s_p3_0,
  126397. 1, -533725184, 1611661312, 3, 0,
  126398. _vq_quantlist__8c0_s_p3_0,
  126399. NULL,
  126400. &_vq_auxt__8c0_s_p3_0,
  126401. NULL,
  126402. 0
  126403. };
  126404. static long _vq_quantlist__8c0_s_p4_0[] = {
  126405. 4,
  126406. 3,
  126407. 5,
  126408. 2,
  126409. 6,
  126410. 1,
  126411. 7,
  126412. 0,
  126413. 8,
  126414. };
  126415. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126416. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126417. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126418. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126419. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126420. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0,
  126422. };
  126423. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126424. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126425. };
  126426. static long _vq_quantmap__8c0_s_p4_0[] = {
  126427. 7, 5, 3, 1, 0, 2, 4, 6,
  126428. 8,
  126429. };
  126430. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126431. _vq_quantthresh__8c0_s_p4_0,
  126432. _vq_quantmap__8c0_s_p4_0,
  126433. 9,
  126434. 9
  126435. };
  126436. static static_codebook _8c0_s_p4_0 = {
  126437. 2, 81,
  126438. _vq_lengthlist__8c0_s_p4_0,
  126439. 1, -531628032, 1611661312, 4, 0,
  126440. _vq_quantlist__8c0_s_p4_0,
  126441. NULL,
  126442. &_vq_auxt__8c0_s_p4_0,
  126443. NULL,
  126444. 0
  126445. };
  126446. static long _vq_quantlist__8c0_s_p5_0[] = {
  126447. 4,
  126448. 3,
  126449. 5,
  126450. 2,
  126451. 6,
  126452. 1,
  126453. 7,
  126454. 0,
  126455. 8,
  126456. };
  126457. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126458. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126459. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126460. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126461. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126462. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126463. 10,
  126464. };
  126465. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126466. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126467. };
  126468. static long _vq_quantmap__8c0_s_p5_0[] = {
  126469. 7, 5, 3, 1, 0, 2, 4, 6,
  126470. 8,
  126471. };
  126472. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126473. _vq_quantthresh__8c0_s_p5_0,
  126474. _vq_quantmap__8c0_s_p5_0,
  126475. 9,
  126476. 9
  126477. };
  126478. static static_codebook _8c0_s_p5_0 = {
  126479. 2, 81,
  126480. _vq_lengthlist__8c0_s_p5_0,
  126481. 1, -531628032, 1611661312, 4, 0,
  126482. _vq_quantlist__8c0_s_p5_0,
  126483. NULL,
  126484. &_vq_auxt__8c0_s_p5_0,
  126485. NULL,
  126486. 0
  126487. };
  126488. static long _vq_quantlist__8c0_s_p6_0[] = {
  126489. 8,
  126490. 7,
  126491. 9,
  126492. 6,
  126493. 10,
  126494. 5,
  126495. 11,
  126496. 4,
  126497. 12,
  126498. 3,
  126499. 13,
  126500. 2,
  126501. 14,
  126502. 1,
  126503. 15,
  126504. 0,
  126505. 16,
  126506. };
  126507. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126508. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126509. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126510. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126511. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126512. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126513. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126514. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126515. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126516. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126517. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126518. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126519. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126520. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126521. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126522. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126523. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126524. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126526. 14,
  126527. };
  126528. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126529. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126530. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126531. };
  126532. static long _vq_quantmap__8c0_s_p6_0[] = {
  126533. 15, 13, 11, 9, 7, 5, 3, 1,
  126534. 0, 2, 4, 6, 8, 10, 12, 14,
  126535. 16,
  126536. };
  126537. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126538. _vq_quantthresh__8c0_s_p6_0,
  126539. _vq_quantmap__8c0_s_p6_0,
  126540. 17,
  126541. 17
  126542. };
  126543. static static_codebook _8c0_s_p6_0 = {
  126544. 2, 289,
  126545. _vq_lengthlist__8c0_s_p6_0,
  126546. 1, -529530880, 1611661312, 5, 0,
  126547. _vq_quantlist__8c0_s_p6_0,
  126548. NULL,
  126549. &_vq_auxt__8c0_s_p6_0,
  126550. NULL,
  126551. 0
  126552. };
  126553. static long _vq_quantlist__8c0_s_p7_0[] = {
  126554. 1,
  126555. 0,
  126556. 2,
  126557. };
  126558. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126559. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126560. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126561. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126562. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126563. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126564. 10,
  126565. };
  126566. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126567. -5.5, 5.5,
  126568. };
  126569. static long _vq_quantmap__8c0_s_p7_0[] = {
  126570. 1, 0, 2,
  126571. };
  126572. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126573. _vq_quantthresh__8c0_s_p7_0,
  126574. _vq_quantmap__8c0_s_p7_0,
  126575. 3,
  126576. 3
  126577. };
  126578. static static_codebook _8c0_s_p7_0 = {
  126579. 4, 81,
  126580. _vq_lengthlist__8c0_s_p7_0,
  126581. 1, -529137664, 1618345984, 2, 0,
  126582. _vq_quantlist__8c0_s_p7_0,
  126583. NULL,
  126584. &_vq_auxt__8c0_s_p7_0,
  126585. NULL,
  126586. 0
  126587. };
  126588. static long _vq_quantlist__8c0_s_p7_1[] = {
  126589. 5,
  126590. 4,
  126591. 6,
  126592. 3,
  126593. 7,
  126594. 2,
  126595. 8,
  126596. 1,
  126597. 9,
  126598. 0,
  126599. 10,
  126600. };
  126601. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126602. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126603. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126604. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126605. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126606. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126607. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126608. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126609. 10,10,10, 9, 9, 9,10,10,10,
  126610. };
  126611. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126612. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126613. 3.5, 4.5,
  126614. };
  126615. static long _vq_quantmap__8c0_s_p7_1[] = {
  126616. 9, 7, 5, 3, 1, 0, 2, 4,
  126617. 6, 8, 10,
  126618. };
  126619. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126620. _vq_quantthresh__8c0_s_p7_1,
  126621. _vq_quantmap__8c0_s_p7_1,
  126622. 11,
  126623. 11
  126624. };
  126625. static static_codebook _8c0_s_p7_1 = {
  126626. 2, 121,
  126627. _vq_lengthlist__8c0_s_p7_1,
  126628. 1, -531365888, 1611661312, 4, 0,
  126629. _vq_quantlist__8c0_s_p7_1,
  126630. NULL,
  126631. &_vq_auxt__8c0_s_p7_1,
  126632. NULL,
  126633. 0
  126634. };
  126635. static long _vq_quantlist__8c0_s_p8_0[] = {
  126636. 6,
  126637. 5,
  126638. 7,
  126639. 4,
  126640. 8,
  126641. 3,
  126642. 9,
  126643. 2,
  126644. 10,
  126645. 1,
  126646. 11,
  126647. 0,
  126648. 12,
  126649. };
  126650. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126651. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126652. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126653. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126654. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126655. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126656. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126657. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126658. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126659. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126660. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126661. 0, 0,13,13,11,13,13,11,12,
  126662. };
  126663. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126664. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126665. 12.5, 17.5, 22.5, 27.5,
  126666. };
  126667. static long _vq_quantmap__8c0_s_p8_0[] = {
  126668. 11, 9, 7, 5, 3, 1, 0, 2,
  126669. 4, 6, 8, 10, 12,
  126670. };
  126671. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126672. _vq_quantthresh__8c0_s_p8_0,
  126673. _vq_quantmap__8c0_s_p8_0,
  126674. 13,
  126675. 13
  126676. };
  126677. static static_codebook _8c0_s_p8_0 = {
  126678. 2, 169,
  126679. _vq_lengthlist__8c0_s_p8_0,
  126680. 1, -526516224, 1616117760, 4, 0,
  126681. _vq_quantlist__8c0_s_p8_0,
  126682. NULL,
  126683. &_vq_auxt__8c0_s_p8_0,
  126684. NULL,
  126685. 0
  126686. };
  126687. static long _vq_quantlist__8c0_s_p8_1[] = {
  126688. 2,
  126689. 1,
  126690. 3,
  126691. 0,
  126692. 4,
  126693. };
  126694. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126695. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126696. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126697. };
  126698. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126699. -1.5, -0.5, 0.5, 1.5,
  126700. };
  126701. static long _vq_quantmap__8c0_s_p8_1[] = {
  126702. 3, 1, 0, 2, 4,
  126703. };
  126704. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126705. _vq_quantthresh__8c0_s_p8_1,
  126706. _vq_quantmap__8c0_s_p8_1,
  126707. 5,
  126708. 5
  126709. };
  126710. static static_codebook _8c0_s_p8_1 = {
  126711. 2, 25,
  126712. _vq_lengthlist__8c0_s_p8_1,
  126713. 1, -533725184, 1611661312, 3, 0,
  126714. _vq_quantlist__8c0_s_p8_1,
  126715. NULL,
  126716. &_vq_auxt__8c0_s_p8_1,
  126717. NULL,
  126718. 0
  126719. };
  126720. static long _vq_quantlist__8c0_s_p9_0[] = {
  126721. 1,
  126722. 0,
  126723. 2,
  126724. };
  126725. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126726. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126727. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126728. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126729. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126730. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126731. 7,
  126732. };
  126733. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126734. -157.5, 157.5,
  126735. };
  126736. static long _vq_quantmap__8c0_s_p9_0[] = {
  126737. 1, 0, 2,
  126738. };
  126739. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126740. _vq_quantthresh__8c0_s_p9_0,
  126741. _vq_quantmap__8c0_s_p9_0,
  126742. 3,
  126743. 3
  126744. };
  126745. static static_codebook _8c0_s_p9_0 = {
  126746. 4, 81,
  126747. _vq_lengthlist__8c0_s_p9_0,
  126748. 1, -518803456, 1628680192, 2, 0,
  126749. _vq_quantlist__8c0_s_p9_0,
  126750. NULL,
  126751. &_vq_auxt__8c0_s_p9_0,
  126752. NULL,
  126753. 0
  126754. };
  126755. static long _vq_quantlist__8c0_s_p9_1[] = {
  126756. 7,
  126757. 6,
  126758. 8,
  126759. 5,
  126760. 9,
  126761. 4,
  126762. 10,
  126763. 3,
  126764. 11,
  126765. 2,
  126766. 12,
  126767. 1,
  126768. 13,
  126769. 0,
  126770. 14,
  126771. };
  126772. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126773. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126774. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126775. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126776. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126777. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126778. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126787. 11,
  126788. };
  126789. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126790. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126791. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126792. };
  126793. static long _vq_quantmap__8c0_s_p9_1[] = {
  126794. 13, 11, 9, 7, 5, 3, 1, 0,
  126795. 2, 4, 6, 8, 10, 12, 14,
  126796. };
  126797. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126798. _vq_quantthresh__8c0_s_p9_1,
  126799. _vq_quantmap__8c0_s_p9_1,
  126800. 15,
  126801. 15
  126802. };
  126803. static static_codebook _8c0_s_p9_1 = {
  126804. 2, 225,
  126805. _vq_lengthlist__8c0_s_p9_1,
  126806. 1, -520986624, 1620377600, 4, 0,
  126807. _vq_quantlist__8c0_s_p9_1,
  126808. NULL,
  126809. &_vq_auxt__8c0_s_p9_1,
  126810. NULL,
  126811. 0
  126812. };
  126813. static long _vq_quantlist__8c0_s_p9_2[] = {
  126814. 10,
  126815. 9,
  126816. 11,
  126817. 8,
  126818. 12,
  126819. 7,
  126820. 13,
  126821. 6,
  126822. 14,
  126823. 5,
  126824. 15,
  126825. 4,
  126826. 16,
  126827. 3,
  126828. 17,
  126829. 2,
  126830. 18,
  126831. 1,
  126832. 19,
  126833. 0,
  126834. 20,
  126835. };
  126836. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126837. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126838. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126839. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126840. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126841. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126842. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126843. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126844. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126845. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126846. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126847. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126848. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126849. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126850. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126851. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126852. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126853. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126854. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126855. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126856. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126857. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126858. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126859. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126860. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126861. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126862. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126863. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126864. 10,11, 9,11,10, 9,10, 9,10,
  126865. };
  126866. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126867. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126868. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126869. 6.5, 7.5, 8.5, 9.5,
  126870. };
  126871. static long _vq_quantmap__8c0_s_p9_2[] = {
  126872. 19, 17, 15, 13, 11, 9, 7, 5,
  126873. 3, 1, 0, 2, 4, 6, 8, 10,
  126874. 12, 14, 16, 18, 20,
  126875. };
  126876. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126877. _vq_quantthresh__8c0_s_p9_2,
  126878. _vq_quantmap__8c0_s_p9_2,
  126879. 21,
  126880. 21
  126881. };
  126882. static static_codebook _8c0_s_p9_2 = {
  126883. 2, 441,
  126884. _vq_lengthlist__8c0_s_p9_2,
  126885. 1, -529268736, 1611661312, 5, 0,
  126886. _vq_quantlist__8c0_s_p9_2,
  126887. NULL,
  126888. &_vq_auxt__8c0_s_p9_2,
  126889. NULL,
  126890. 0
  126891. };
  126892. static long _huff_lengthlist__8c0_s_single[] = {
  126893. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126894. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126895. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126896. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126897. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126898. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126899. 17,16,17,17,
  126900. };
  126901. static static_codebook _huff_book__8c0_s_single = {
  126902. 2, 100,
  126903. _huff_lengthlist__8c0_s_single,
  126904. 0, 0, 0, 0, 0,
  126905. NULL,
  126906. NULL,
  126907. NULL,
  126908. NULL,
  126909. 0
  126910. };
  126911. static long _vq_quantlist__8c1_s_p1_0[] = {
  126912. 1,
  126913. 0,
  126914. 2,
  126915. };
  126916. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126917. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126918. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126923. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126928. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126963. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126968. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126973. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127009. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127014. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127019. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0,
  127328. };
  127329. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127330. -0.5, 0.5,
  127331. };
  127332. static long _vq_quantmap__8c1_s_p1_0[] = {
  127333. 1, 0, 2,
  127334. };
  127335. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127336. _vq_quantthresh__8c1_s_p1_0,
  127337. _vq_quantmap__8c1_s_p1_0,
  127338. 3,
  127339. 3
  127340. };
  127341. static static_codebook _8c1_s_p1_0 = {
  127342. 8, 6561,
  127343. _vq_lengthlist__8c1_s_p1_0,
  127344. 1, -535822336, 1611661312, 2, 0,
  127345. _vq_quantlist__8c1_s_p1_0,
  127346. NULL,
  127347. &_vq_auxt__8c1_s_p1_0,
  127348. NULL,
  127349. 0
  127350. };
  127351. static long _vq_quantlist__8c1_s_p2_0[] = {
  127352. 2,
  127353. 1,
  127354. 3,
  127355. 0,
  127356. 4,
  127357. };
  127358. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0,
  127399. };
  127400. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127401. -1.5, -0.5, 0.5, 1.5,
  127402. };
  127403. static long _vq_quantmap__8c1_s_p2_0[] = {
  127404. 3, 1, 0, 2, 4,
  127405. };
  127406. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127407. _vq_quantthresh__8c1_s_p2_0,
  127408. _vq_quantmap__8c1_s_p2_0,
  127409. 5,
  127410. 5
  127411. };
  127412. static static_codebook _8c1_s_p2_0 = {
  127413. 4, 625,
  127414. _vq_lengthlist__8c1_s_p2_0,
  127415. 1, -533725184, 1611661312, 3, 0,
  127416. _vq_quantlist__8c1_s_p2_0,
  127417. NULL,
  127418. &_vq_auxt__8c1_s_p2_0,
  127419. NULL,
  127420. 0
  127421. };
  127422. static long _vq_quantlist__8c1_s_p3_0[] = {
  127423. 2,
  127424. 1,
  127425. 3,
  127426. 0,
  127427. 4,
  127428. };
  127429. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127430. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0,
  127470. };
  127471. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127472. -1.5, -0.5, 0.5, 1.5,
  127473. };
  127474. static long _vq_quantmap__8c1_s_p3_0[] = {
  127475. 3, 1, 0, 2, 4,
  127476. };
  127477. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127478. _vq_quantthresh__8c1_s_p3_0,
  127479. _vq_quantmap__8c1_s_p3_0,
  127480. 5,
  127481. 5
  127482. };
  127483. static static_codebook _8c1_s_p3_0 = {
  127484. 4, 625,
  127485. _vq_lengthlist__8c1_s_p3_0,
  127486. 1, -533725184, 1611661312, 3, 0,
  127487. _vq_quantlist__8c1_s_p3_0,
  127488. NULL,
  127489. &_vq_auxt__8c1_s_p3_0,
  127490. NULL,
  127491. 0
  127492. };
  127493. static long _vq_quantlist__8c1_s_p4_0[] = {
  127494. 4,
  127495. 3,
  127496. 5,
  127497. 2,
  127498. 6,
  127499. 1,
  127500. 7,
  127501. 0,
  127502. 8,
  127503. };
  127504. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127505. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127506. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127507. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127508. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127509. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0,
  127511. };
  127512. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127514. };
  127515. static long _vq_quantmap__8c1_s_p4_0[] = {
  127516. 7, 5, 3, 1, 0, 2, 4, 6,
  127517. 8,
  127518. };
  127519. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127520. _vq_quantthresh__8c1_s_p4_0,
  127521. _vq_quantmap__8c1_s_p4_0,
  127522. 9,
  127523. 9
  127524. };
  127525. static static_codebook _8c1_s_p4_0 = {
  127526. 2, 81,
  127527. _vq_lengthlist__8c1_s_p4_0,
  127528. 1, -531628032, 1611661312, 4, 0,
  127529. _vq_quantlist__8c1_s_p4_0,
  127530. NULL,
  127531. &_vq_auxt__8c1_s_p4_0,
  127532. NULL,
  127533. 0
  127534. };
  127535. static long _vq_quantlist__8c1_s_p5_0[] = {
  127536. 4,
  127537. 3,
  127538. 5,
  127539. 2,
  127540. 6,
  127541. 1,
  127542. 7,
  127543. 0,
  127544. 8,
  127545. };
  127546. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127547. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127548. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127549. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127550. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127551. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127552. 10,
  127553. };
  127554. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127555. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127556. };
  127557. static long _vq_quantmap__8c1_s_p5_0[] = {
  127558. 7, 5, 3, 1, 0, 2, 4, 6,
  127559. 8,
  127560. };
  127561. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127562. _vq_quantthresh__8c1_s_p5_0,
  127563. _vq_quantmap__8c1_s_p5_0,
  127564. 9,
  127565. 9
  127566. };
  127567. static static_codebook _8c1_s_p5_0 = {
  127568. 2, 81,
  127569. _vq_lengthlist__8c1_s_p5_0,
  127570. 1, -531628032, 1611661312, 4, 0,
  127571. _vq_quantlist__8c1_s_p5_0,
  127572. NULL,
  127573. &_vq_auxt__8c1_s_p5_0,
  127574. NULL,
  127575. 0
  127576. };
  127577. static long _vq_quantlist__8c1_s_p6_0[] = {
  127578. 8,
  127579. 7,
  127580. 9,
  127581. 6,
  127582. 10,
  127583. 5,
  127584. 11,
  127585. 4,
  127586. 12,
  127587. 3,
  127588. 13,
  127589. 2,
  127590. 14,
  127591. 1,
  127592. 15,
  127593. 0,
  127594. 16,
  127595. };
  127596. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127597. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127598. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127599. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127600. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127601. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127602. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127603. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127604. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127605. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127606. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127607. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127608. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127609. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127610. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127611. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127612. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127613. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127615. 14,
  127616. };
  127617. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127618. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127619. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127620. };
  127621. static long _vq_quantmap__8c1_s_p6_0[] = {
  127622. 15, 13, 11, 9, 7, 5, 3, 1,
  127623. 0, 2, 4, 6, 8, 10, 12, 14,
  127624. 16,
  127625. };
  127626. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127627. _vq_quantthresh__8c1_s_p6_0,
  127628. _vq_quantmap__8c1_s_p6_0,
  127629. 17,
  127630. 17
  127631. };
  127632. static static_codebook _8c1_s_p6_0 = {
  127633. 2, 289,
  127634. _vq_lengthlist__8c1_s_p6_0,
  127635. 1, -529530880, 1611661312, 5, 0,
  127636. _vq_quantlist__8c1_s_p6_0,
  127637. NULL,
  127638. &_vq_auxt__8c1_s_p6_0,
  127639. NULL,
  127640. 0
  127641. };
  127642. static long _vq_quantlist__8c1_s_p7_0[] = {
  127643. 1,
  127644. 0,
  127645. 2,
  127646. };
  127647. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127648. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127649. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127650. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127651. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127652. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127653. 9,
  127654. };
  127655. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127656. -5.5, 5.5,
  127657. };
  127658. static long _vq_quantmap__8c1_s_p7_0[] = {
  127659. 1, 0, 2,
  127660. };
  127661. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127662. _vq_quantthresh__8c1_s_p7_0,
  127663. _vq_quantmap__8c1_s_p7_0,
  127664. 3,
  127665. 3
  127666. };
  127667. static static_codebook _8c1_s_p7_0 = {
  127668. 4, 81,
  127669. _vq_lengthlist__8c1_s_p7_0,
  127670. 1, -529137664, 1618345984, 2, 0,
  127671. _vq_quantlist__8c1_s_p7_0,
  127672. NULL,
  127673. &_vq_auxt__8c1_s_p7_0,
  127674. NULL,
  127675. 0
  127676. };
  127677. static long _vq_quantlist__8c1_s_p7_1[] = {
  127678. 5,
  127679. 4,
  127680. 6,
  127681. 3,
  127682. 7,
  127683. 2,
  127684. 8,
  127685. 1,
  127686. 9,
  127687. 0,
  127688. 10,
  127689. };
  127690. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127691. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127692. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127693. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127694. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127695. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127696. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127697. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127698. 10,10,10, 8, 8, 8, 8, 8, 8,
  127699. };
  127700. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127701. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127702. 3.5, 4.5,
  127703. };
  127704. static long _vq_quantmap__8c1_s_p7_1[] = {
  127705. 9, 7, 5, 3, 1, 0, 2, 4,
  127706. 6, 8, 10,
  127707. };
  127708. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127709. _vq_quantthresh__8c1_s_p7_1,
  127710. _vq_quantmap__8c1_s_p7_1,
  127711. 11,
  127712. 11
  127713. };
  127714. static static_codebook _8c1_s_p7_1 = {
  127715. 2, 121,
  127716. _vq_lengthlist__8c1_s_p7_1,
  127717. 1, -531365888, 1611661312, 4, 0,
  127718. _vq_quantlist__8c1_s_p7_1,
  127719. NULL,
  127720. &_vq_auxt__8c1_s_p7_1,
  127721. NULL,
  127722. 0
  127723. };
  127724. static long _vq_quantlist__8c1_s_p8_0[] = {
  127725. 6,
  127726. 5,
  127727. 7,
  127728. 4,
  127729. 8,
  127730. 3,
  127731. 9,
  127732. 2,
  127733. 10,
  127734. 1,
  127735. 11,
  127736. 0,
  127737. 12,
  127738. };
  127739. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127740. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127741. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127742. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127743. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127744. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127745. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127746. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127747. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127748. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127749. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127750. 0,12,12,11,10,12,11,13,12,
  127751. };
  127752. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127753. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127754. 12.5, 17.5, 22.5, 27.5,
  127755. };
  127756. static long _vq_quantmap__8c1_s_p8_0[] = {
  127757. 11, 9, 7, 5, 3, 1, 0, 2,
  127758. 4, 6, 8, 10, 12,
  127759. };
  127760. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127761. _vq_quantthresh__8c1_s_p8_0,
  127762. _vq_quantmap__8c1_s_p8_0,
  127763. 13,
  127764. 13
  127765. };
  127766. static static_codebook _8c1_s_p8_0 = {
  127767. 2, 169,
  127768. _vq_lengthlist__8c1_s_p8_0,
  127769. 1, -526516224, 1616117760, 4, 0,
  127770. _vq_quantlist__8c1_s_p8_0,
  127771. NULL,
  127772. &_vq_auxt__8c1_s_p8_0,
  127773. NULL,
  127774. 0
  127775. };
  127776. static long _vq_quantlist__8c1_s_p8_1[] = {
  127777. 2,
  127778. 1,
  127779. 3,
  127780. 0,
  127781. 4,
  127782. };
  127783. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127784. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127785. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127786. };
  127787. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127788. -1.5, -0.5, 0.5, 1.5,
  127789. };
  127790. static long _vq_quantmap__8c1_s_p8_1[] = {
  127791. 3, 1, 0, 2, 4,
  127792. };
  127793. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127794. _vq_quantthresh__8c1_s_p8_1,
  127795. _vq_quantmap__8c1_s_p8_1,
  127796. 5,
  127797. 5
  127798. };
  127799. static static_codebook _8c1_s_p8_1 = {
  127800. 2, 25,
  127801. _vq_lengthlist__8c1_s_p8_1,
  127802. 1, -533725184, 1611661312, 3, 0,
  127803. _vq_quantlist__8c1_s_p8_1,
  127804. NULL,
  127805. &_vq_auxt__8c1_s_p8_1,
  127806. NULL,
  127807. 0
  127808. };
  127809. static long _vq_quantlist__8c1_s_p9_0[] = {
  127810. 6,
  127811. 5,
  127812. 7,
  127813. 4,
  127814. 8,
  127815. 3,
  127816. 9,
  127817. 2,
  127818. 10,
  127819. 1,
  127820. 11,
  127821. 0,
  127822. 12,
  127823. };
  127824. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127825. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127826. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127827. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127829. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127830. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127831. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127832. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127835. 10,10,10,10,10, 9, 9, 9, 9,
  127836. };
  127837. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127838. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127839. 787.5, 1102.5, 1417.5, 1732.5,
  127840. };
  127841. static long _vq_quantmap__8c1_s_p9_0[] = {
  127842. 11, 9, 7, 5, 3, 1, 0, 2,
  127843. 4, 6, 8, 10, 12,
  127844. };
  127845. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127846. _vq_quantthresh__8c1_s_p9_0,
  127847. _vq_quantmap__8c1_s_p9_0,
  127848. 13,
  127849. 13
  127850. };
  127851. static static_codebook _8c1_s_p9_0 = {
  127852. 2, 169,
  127853. _vq_lengthlist__8c1_s_p9_0,
  127854. 1, -513964032, 1628680192, 4, 0,
  127855. _vq_quantlist__8c1_s_p9_0,
  127856. NULL,
  127857. &_vq_auxt__8c1_s_p9_0,
  127858. NULL,
  127859. 0
  127860. };
  127861. static long _vq_quantlist__8c1_s_p9_1[] = {
  127862. 7,
  127863. 6,
  127864. 8,
  127865. 5,
  127866. 9,
  127867. 4,
  127868. 10,
  127869. 3,
  127870. 11,
  127871. 2,
  127872. 12,
  127873. 1,
  127874. 13,
  127875. 0,
  127876. 14,
  127877. };
  127878. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127879. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127880. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127881. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127882. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127883. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127884. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127885. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127886. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127887. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127888. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127889. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127890. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127891. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127892. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127893. 15,
  127894. };
  127895. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127896. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127897. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127898. };
  127899. static long _vq_quantmap__8c1_s_p9_1[] = {
  127900. 13, 11, 9, 7, 5, 3, 1, 0,
  127901. 2, 4, 6, 8, 10, 12, 14,
  127902. };
  127903. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127904. _vq_quantthresh__8c1_s_p9_1,
  127905. _vq_quantmap__8c1_s_p9_1,
  127906. 15,
  127907. 15
  127908. };
  127909. static static_codebook _8c1_s_p9_1 = {
  127910. 2, 225,
  127911. _vq_lengthlist__8c1_s_p9_1,
  127912. 1, -520986624, 1620377600, 4, 0,
  127913. _vq_quantlist__8c1_s_p9_1,
  127914. NULL,
  127915. &_vq_auxt__8c1_s_p9_1,
  127916. NULL,
  127917. 0
  127918. };
  127919. static long _vq_quantlist__8c1_s_p9_2[] = {
  127920. 10,
  127921. 9,
  127922. 11,
  127923. 8,
  127924. 12,
  127925. 7,
  127926. 13,
  127927. 6,
  127928. 14,
  127929. 5,
  127930. 15,
  127931. 4,
  127932. 16,
  127933. 3,
  127934. 17,
  127935. 2,
  127936. 18,
  127937. 1,
  127938. 19,
  127939. 0,
  127940. 20,
  127941. };
  127942. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127943. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127944. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127945. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127946. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127947. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127948. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127949. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127950. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127951. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127952. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127953. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127954. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127955. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127956. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127957. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127958. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127959. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127960. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127961. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127962. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127963. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127964. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127965. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127966. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127967. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127968. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127969. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127970. 10,10,10,10,10,10,10,10,10,
  127971. };
  127972. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127973. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127974. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127975. 6.5, 7.5, 8.5, 9.5,
  127976. };
  127977. static long _vq_quantmap__8c1_s_p9_2[] = {
  127978. 19, 17, 15, 13, 11, 9, 7, 5,
  127979. 3, 1, 0, 2, 4, 6, 8, 10,
  127980. 12, 14, 16, 18, 20,
  127981. };
  127982. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127983. _vq_quantthresh__8c1_s_p9_2,
  127984. _vq_quantmap__8c1_s_p9_2,
  127985. 21,
  127986. 21
  127987. };
  127988. static static_codebook _8c1_s_p9_2 = {
  127989. 2, 441,
  127990. _vq_lengthlist__8c1_s_p9_2,
  127991. 1, -529268736, 1611661312, 5, 0,
  127992. _vq_quantlist__8c1_s_p9_2,
  127993. NULL,
  127994. &_vq_auxt__8c1_s_p9_2,
  127995. NULL,
  127996. 0
  127997. };
  127998. static long _huff_lengthlist__8c1_s_single[] = {
  127999. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128000. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128001. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128002. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128003. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128004. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128005. 9, 7, 7, 8,
  128006. };
  128007. static static_codebook _huff_book__8c1_s_single = {
  128008. 2, 100,
  128009. _huff_lengthlist__8c1_s_single,
  128010. 0, 0, 0, 0, 0,
  128011. NULL,
  128012. NULL,
  128013. NULL,
  128014. NULL,
  128015. 0
  128016. };
  128017. static long _huff_lengthlist__44c2_s_long[] = {
  128018. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128019. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128020. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128021. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128022. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128023. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128024. 10, 8, 8, 9,
  128025. };
  128026. static static_codebook _huff_book__44c2_s_long = {
  128027. 2, 100,
  128028. _huff_lengthlist__44c2_s_long,
  128029. 0, 0, 0, 0, 0,
  128030. NULL,
  128031. NULL,
  128032. NULL,
  128033. NULL,
  128034. 0
  128035. };
  128036. static long _vq_quantlist__44c2_s_p1_0[] = {
  128037. 1,
  128038. 0,
  128039. 2,
  128040. };
  128041. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128042. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128043. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128048. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128053. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128088. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128093. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128098. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128134. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128139. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128144. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0,
  128453. };
  128454. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128455. -0.5, 0.5,
  128456. };
  128457. static long _vq_quantmap__44c2_s_p1_0[] = {
  128458. 1, 0, 2,
  128459. };
  128460. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128461. _vq_quantthresh__44c2_s_p1_0,
  128462. _vq_quantmap__44c2_s_p1_0,
  128463. 3,
  128464. 3
  128465. };
  128466. static static_codebook _44c2_s_p1_0 = {
  128467. 8, 6561,
  128468. _vq_lengthlist__44c2_s_p1_0,
  128469. 1, -535822336, 1611661312, 2, 0,
  128470. _vq_quantlist__44c2_s_p1_0,
  128471. NULL,
  128472. &_vq_auxt__44c2_s_p1_0,
  128473. NULL,
  128474. 0
  128475. };
  128476. static long _vq_quantlist__44c2_s_p2_0[] = {
  128477. 2,
  128478. 1,
  128479. 3,
  128480. 0,
  128481. 4,
  128482. };
  128483. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128484. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128485. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128486. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128487. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128488. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128494. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128495. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128496. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128502. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128503. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128510. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128511. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0,
  128524. };
  128525. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128526. -1.5, -0.5, 0.5, 1.5,
  128527. };
  128528. static long _vq_quantmap__44c2_s_p2_0[] = {
  128529. 3, 1, 0, 2, 4,
  128530. };
  128531. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128532. _vq_quantthresh__44c2_s_p2_0,
  128533. _vq_quantmap__44c2_s_p2_0,
  128534. 5,
  128535. 5
  128536. };
  128537. static static_codebook _44c2_s_p2_0 = {
  128538. 4, 625,
  128539. _vq_lengthlist__44c2_s_p2_0,
  128540. 1, -533725184, 1611661312, 3, 0,
  128541. _vq_quantlist__44c2_s_p2_0,
  128542. NULL,
  128543. &_vq_auxt__44c2_s_p2_0,
  128544. NULL,
  128545. 0
  128546. };
  128547. static long _vq_quantlist__44c2_s_p3_0[] = {
  128548. 2,
  128549. 1,
  128550. 3,
  128551. 0,
  128552. 4,
  128553. };
  128554. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128555. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0,
  128595. };
  128596. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128597. -1.5, -0.5, 0.5, 1.5,
  128598. };
  128599. static long _vq_quantmap__44c2_s_p3_0[] = {
  128600. 3, 1, 0, 2, 4,
  128601. };
  128602. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128603. _vq_quantthresh__44c2_s_p3_0,
  128604. _vq_quantmap__44c2_s_p3_0,
  128605. 5,
  128606. 5
  128607. };
  128608. static static_codebook _44c2_s_p3_0 = {
  128609. 4, 625,
  128610. _vq_lengthlist__44c2_s_p3_0,
  128611. 1, -533725184, 1611661312, 3, 0,
  128612. _vq_quantlist__44c2_s_p3_0,
  128613. NULL,
  128614. &_vq_auxt__44c2_s_p3_0,
  128615. NULL,
  128616. 0
  128617. };
  128618. static long _vq_quantlist__44c2_s_p4_0[] = {
  128619. 4,
  128620. 3,
  128621. 5,
  128622. 2,
  128623. 6,
  128624. 1,
  128625. 7,
  128626. 0,
  128627. 8,
  128628. };
  128629. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128630. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128631. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128632. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128633. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128634. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0,
  128636. };
  128637. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128638. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128639. };
  128640. static long _vq_quantmap__44c2_s_p4_0[] = {
  128641. 7, 5, 3, 1, 0, 2, 4, 6,
  128642. 8,
  128643. };
  128644. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128645. _vq_quantthresh__44c2_s_p4_0,
  128646. _vq_quantmap__44c2_s_p4_0,
  128647. 9,
  128648. 9
  128649. };
  128650. static static_codebook _44c2_s_p4_0 = {
  128651. 2, 81,
  128652. _vq_lengthlist__44c2_s_p4_0,
  128653. 1, -531628032, 1611661312, 4, 0,
  128654. _vq_quantlist__44c2_s_p4_0,
  128655. NULL,
  128656. &_vq_auxt__44c2_s_p4_0,
  128657. NULL,
  128658. 0
  128659. };
  128660. static long _vq_quantlist__44c2_s_p5_0[] = {
  128661. 4,
  128662. 3,
  128663. 5,
  128664. 2,
  128665. 6,
  128666. 1,
  128667. 7,
  128668. 0,
  128669. 8,
  128670. };
  128671. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128672. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128673. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128674. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128675. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128676. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128677. 11,
  128678. };
  128679. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128680. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128681. };
  128682. static long _vq_quantmap__44c2_s_p5_0[] = {
  128683. 7, 5, 3, 1, 0, 2, 4, 6,
  128684. 8,
  128685. };
  128686. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128687. _vq_quantthresh__44c2_s_p5_0,
  128688. _vq_quantmap__44c2_s_p5_0,
  128689. 9,
  128690. 9
  128691. };
  128692. static static_codebook _44c2_s_p5_0 = {
  128693. 2, 81,
  128694. _vq_lengthlist__44c2_s_p5_0,
  128695. 1, -531628032, 1611661312, 4, 0,
  128696. _vq_quantlist__44c2_s_p5_0,
  128697. NULL,
  128698. &_vq_auxt__44c2_s_p5_0,
  128699. NULL,
  128700. 0
  128701. };
  128702. static long _vq_quantlist__44c2_s_p6_0[] = {
  128703. 8,
  128704. 7,
  128705. 9,
  128706. 6,
  128707. 10,
  128708. 5,
  128709. 11,
  128710. 4,
  128711. 12,
  128712. 3,
  128713. 13,
  128714. 2,
  128715. 14,
  128716. 1,
  128717. 15,
  128718. 0,
  128719. 16,
  128720. };
  128721. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128722. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128723. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128724. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128725. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128726. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128727. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128728. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128729. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128730. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128731. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128732. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128733. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128734. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128735. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128736. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128737. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128738. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128740. 14,
  128741. };
  128742. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128743. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128744. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128745. };
  128746. static long _vq_quantmap__44c2_s_p6_0[] = {
  128747. 15, 13, 11, 9, 7, 5, 3, 1,
  128748. 0, 2, 4, 6, 8, 10, 12, 14,
  128749. 16,
  128750. };
  128751. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128752. _vq_quantthresh__44c2_s_p6_0,
  128753. _vq_quantmap__44c2_s_p6_0,
  128754. 17,
  128755. 17
  128756. };
  128757. static static_codebook _44c2_s_p6_0 = {
  128758. 2, 289,
  128759. _vq_lengthlist__44c2_s_p6_0,
  128760. 1, -529530880, 1611661312, 5, 0,
  128761. _vq_quantlist__44c2_s_p6_0,
  128762. NULL,
  128763. &_vq_auxt__44c2_s_p6_0,
  128764. NULL,
  128765. 0
  128766. };
  128767. static long _vq_quantlist__44c2_s_p7_0[] = {
  128768. 1,
  128769. 0,
  128770. 2,
  128771. };
  128772. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128773. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128774. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128775. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128776. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128777. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128778. 11,
  128779. };
  128780. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128781. -5.5, 5.5,
  128782. };
  128783. static long _vq_quantmap__44c2_s_p7_0[] = {
  128784. 1, 0, 2,
  128785. };
  128786. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128787. _vq_quantthresh__44c2_s_p7_0,
  128788. _vq_quantmap__44c2_s_p7_0,
  128789. 3,
  128790. 3
  128791. };
  128792. static static_codebook _44c2_s_p7_0 = {
  128793. 4, 81,
  128794. _vq_lengthlist__44c2_s_p7_0,
  128795. 1, -529137664, 1618345984, 2, 0,
  128796. _vq_quantlist__44c2_s_p7_0,
  128797. NULL,
  128798. &_vq_auxt__44c2_s_p7_0,
  128799. NULL,
  128800. 0
  128801. };
  128802. static long _vq_quantlist__44c2_s_p7_1[] = {
  128803. 5,
  128804. 4,
  128805. 6,
  128806. 3,
  128807. 7,
  128808. 2,
  128809. 8,
  128810. 1,
  128811. 9,
  128812. 0,
  128813. 10,
  128814. };
  128815. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128816. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128817. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128818. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128819. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128820. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128821. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128822. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128823. 10,10,10, 8, 8, 8, 8, 8, 8,
  128824. };
  128825. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128826. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128827. 3.5, 4.5,
  128828. };
  128829. static long _vq_quantmap__44c2_s_p7_1[] = {
  128830. 9, 7, 5, 3, 1, 0, 2, 4,
  128831. 6, 8, 10,
  128832. };
  128833. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128834. _vq_quantthresh__44c2_s_p7_1,
  128835. _vq_quantmap__44c2_s_p7_1,
  128836. 11,
  128837. 11
  128838. };
  128839. static static_codebook _44c2_s_p7_1 = {
  128840. 2, 121,
  128841. _vq_lengthlist__44c2_s_p7_1,
  128842. 1, -531365888, 1611661312, 4, 0,
  128843. _vq_quantlist__44c2_s_p7_1,
  128844. NULL,
  128845. &_vq_auxt__44c2_s_p7_1,
  128846. NULL,
  128847. 0
  128848. };
  128849. static long _vq_quantlist__44c2_s_p8_0[] = {
  128850. 6,
  128851. 5,
  128852. 7,
  128853. 4,
  128854. 8,
  128855. 3,
  128856. 9,
  128857. 2,
  128858. 10,
  128859. 1,
  128860. 11,
  128861. 0,
  128862. 12,
  128863. };
  128864. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128865. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128866. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128867. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128868. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128869. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128870. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128871. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128872. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128873. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128874. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128875. 0,12,12,12,12,13,12,14,14,
  128876. };
  128877. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128878. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128879. 12.5, 17.5, 22.5, 27.5,
  128880. };
  128881. static long _vq_quantmap__44c2_s_p8_0[] = {
  128882. 11, 9, 7, 5, 3, 1, 0, 2,
  128883. 4, 6, 8, 10, 12,
  128884. };
  128885. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128886. _vq_quantthresh__44c2_s_p8_0,
  128887. _vq_quantmap__44c2_s_p8_0,
  128888. 13,
  128889. 13
  128890. };
  128891. static static_codebook _44c2_s_p8_0 = {
  128892. 2, 169,
  128893. _vq_lengthlist__44c2_s_p8_0,
  128894. 1, -526516224, 1616117760, 4, 0,
  128895. _vq_quantlist__44c2_s_p8_0,
  128896. NULL,
  128897. &_vq_auxt__44c2_s_p8_0,
  128898. NULL,
  128899. 0
  128900. };
  128901. static long _vq_quantlist__44c2_s_p8_1[] = {
  128902. 2,
  128903. 1,
  128904. 3,
  128905. 0,
  128906. 4,
  128907. };
  128908. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128909. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128910. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128911. };
  128912. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128913. -1.5, -0.5, 0.5, 1.5,
  128914. };
  128915. static long _vq_quantmap__44c2_s_p8_1[] = {
  128916. 3, 1, 0, 2, 4,
  128917. };
  128918. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128919. _vq_quantthresh__44c2_s_p8_1,
  128920. _vq_quantmap__44c2_s_p8_1,
  128921. 5,
  128922. 5
  128923. };
  128924. static static_codebook _44c2_s_p8_1 = {
  128925. 2, 25,
  128926. _vq_lengthlist__44c2_s_p8_1,
  128927. 1, -533725184, 1611661312, 3, 0,
  128928. _vq_quantlist__44c2_s_p8_1,
  128929. NULL,
  128930. &_vq_auxt__44c2_s_p8_1,
  128931. NULL,
  128932. 0
  128933. };
  128934. static long _vq_quantlist__44c2_s_p9_0[] = {
  128935. 6,
  128936. 5,
  128937. 7,
  128938. 4,
  128939. 8,
  128940. 3,
  128941. 9,
  128942. 2,
  128943. 10,
  128944. 1,
  128945. 11,
  128946. 0,
  128947. 12,
  128948. };
  128949. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128950. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128951. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128953. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128960. 11,11,11,11,11,11,11,11,11,
  128961. };
  128962. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128963. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128964. 552.5, 773.5, 994.5, 1215.5,
  128965. };
  128966. static long _vq_quantmap__44c2_s_p9_0[] = {
  128967. 11, 9, 7, 5, 3, 1, 0, 2,
  128968. 4, 6, 8, 10, 12,
  128969. };
  128970. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128971. _vq_quantthresh__44c2_s_p9_0,
  128972. _vq_quantmap__44c2_s_p9_0,
  128973. 13,
  128974. 13
  128975. };
  128976. static static_codebook _44c2_s_p9_0 = {
  128977. 2, 169,
  128978. _vq_lengthlist__44c2_s_p9_0,
  128979. 1, -514541568, 1627103232, 4, 0,
  128980. _vq_quantlist__44c2_s_p9_0,
  128981. NULL,
  128982. &_vq_auxt__44c2_s_p9_0,
  128983. NULL,
  128984. 0
  128985. };
  128986. static long _vq_quantlist__44c2_s_p9_1[] = {
  128987. 6,
  128988. 5,
  128989. 7,
  128990. 4,
  128991. 8,
  128992. 3,
  128993. 9,
  128994. 2,
  128995. 10,
  128996. 1,
  128997. 11,
  128998. 0,
  128999. 12,
  129000. };
  129001. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129002. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129003. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129004. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129005. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129006. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129007. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129008. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129009. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129010. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129011. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129012. 17,13,12,12,10,13,11,14,14,
  129013. };
  129014. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129015. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129016. 42.5, 59.5, 76.5, 93.5,
  129017. };
  129018. static long _vq_quantmap__44c2_s_p9_1[] = {
  129019. 11, 9, 7, 5, 3, 1, 0, 2,
  129020. 4, 6, 8, 10, 12,
  129021. };
  129022. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129023. _vq_quantthresh__44c2_s_p9_1,
  129024. _vq_quantmap__44c2_s_p9_1,
  129025. 13,
  129026. 13
  129027. };
  129028. static static_codebook _44c2_s_p9_1 = {
  129029. 2, 169,
  129030. _vq_lengthlist__44c2_s_p9_1,
  129031. 1, -522616832, 1620115456, 4, 0,
  129032. _vq_quantlist__44c2_s_p9_1,
  129033. NULL,
  129034. &_vq_auxt__44c2_s_p9_1,
  129035. NULL,
  129036. 0
  129037. };
  129038. static long _vq_quantlist__44c2_s_p9_2[] = {
  129039. 8,
  129040. 7,
  129041. 9,
  129042. 6,
  129043. 10,
  129044. 5,
  129045. 11,
  129046. 4,
  129047. 12,
  129048. 3,
  129049. 13,
  129050. 2,
  129051. 14,
  129052. 1,
  129053. 15,
  129054. 0,
  129055. 16,
  129056. };
  129057. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129058. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129059. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129060. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129061. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129062. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129063. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129064. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129065. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129066. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129067. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129068. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129069. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129070. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129071. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129072. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129073. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129074. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129075. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129076. 10,
  129077. };
  129078. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129079. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129080. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129081. };
  129082. static long _vq_quantmap__44c2_s_p9_2[] = {
  129083. 15, 13, 11, 9, 7, 5, 3, 1,
  129084. 0, 2, 4, 6, 8, 10, 12, 14,
  129085. 16,
  129086. };
  129087. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129088. _vq_quantthresh__44c2_s_p9_2,
  129089. _vq_quantmap__44c2_s_p9_2,
  129090. 17,
  129091. 17
  129092. };
  129093. static static_codebook _44c2_s_p9_2 = {
  129094. 2, 289,
  129095. _vq_lengthlist__44c2_s_p9_2,
  129096. 1, -529530880, 1611661312, 5, 0,
  129097. _vq_quantlist__44c2_s_p9_2,
  129098. NULL,
  129099. &_vq_auxt__44c2_s_p9_2,
  129100. NULL,
  129101. 0
  129102. };
  129103. static long _huff_lengthlist__44c2_s_short[] = {
  129104. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129105. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129106. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129107. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129108. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129109. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129110. 6, 8, 9,12,
  129111. };
  129112. static static_codebook _huff_book__44c2_s_short = {
  129113. 2, 100,
  129114. _huff_lengthlist__44c2_s_short,
  129115. 0, 0, 0, 0, 0,
  129116. NULL,
  129117. NULL,
  129118. NULL,
  129119. NULL,
  129120. 0
  129121. };
  129122. static long _huff_lengthlist__44c3_s_long[] = {
  129123. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129124. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129125. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129126. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129127. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129128. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129129. 9, 8, 8, 8,
  129130. };
  129131. static static_codebook _huff_book__44c3_s_long = {
  129132. 2, 100,
  129133. _huff_lengthlist__44c3_s_long,
  129134. 0, 0, 0, 0, 0,
  129135. NULL,
  129136. NULL,
  129137. NULL,
  129138. NULL,
  129139. 0
  129140. };
  129141. static long _vq_quantlist__44c3_s_p1_0[] = {
  129142. 1,
  129143. 0,
  129144. 2,
  129145. };
  129146. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129147. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129148. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129153. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129158. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129193. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129198. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129203. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129239. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129244. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129249. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0,
  129558. };
  129559. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129560. -0.5, 0.5,
  129561. };
  129562. static long _vq_quantmap__44c3_s_p1_0[] = {
  129563. 1, 0, 2,
  129564. };
  129565. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129566. _vq_quantthresh__44c3_s_p1_0,
  129567. _vq_quantmap__44c3_s_p1_0,
  129568. 3,
  129569. 3
  129570. };
  129571. static static_codebook _44c3_s_p1_0 = {
  129572. 8, 6561,
  129573. _vq_lengthlist__44c3_s_p1_0,
  129574. 1, -535822336, 1611661312, 2, 0,
  129575. _vq_quantlist__44c3_s_p1_0,
  129576. NULL,
  129577. &_vq_auxt__44c3_s_p1_0,
  129578. NULL,
  129579. 0
  129580. };
  129581. static long _vq_quantlist__44c3_s_p2_0[] = {
  129582. 2,
  129583. 1,
  129584. 3,
  129585. 0,
  129586. 4,
  129587. };
  129588. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129589. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129590. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129591. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129592. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129593. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129599. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129600. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129601. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129607. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129608. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129615. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129616. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0,
  129629. };
  129630. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129631. -1.5, -0.5, 0.5, 1.5,
  129632. };
  129633. static long _vq_quantmap__44c3_s_p2_0[] = {
  129634. 3, 1, 0, 2, 4,
  129635. };
  129636. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129637. _vq_quantthresh__44c3_s_p2_0,
  129638. _vq_quantmap__44c3_s_p2_0,
  129639. 5,
  129640. 5
  129641. };
  129642. static static_codebook _44c3_s_p2_0 = {
  129643. 4, 625,
  129644. _vq_lengthlist__44c3_s_p2_0,
  129645. 1, -533725184, 1611661312, 3, 0,
  129646. _vq_quantlist__44c3_s_p2_0,
  129647. NULL,
  129648. &_vq_auxt__44c3_s_p2_0,
  129649. NULL,
  129650. 0
  129651. };
  129652. static long _vq_quantlist__44c3_s_p3_0[] = {
  129653. 2,
  129654. 1,
  129655. 3,
  129656. 0,
  129657. 4,
  129658. };
  129659. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129660. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0,
  129700. };
  129701. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129702. -1.5, -0.5, 0.5, 1.5,
  129703. };
  129704. static long _vq_quantmap__44c3_s_p3_0[] = {
  129705. 3, 1, 0, 2, 4,
  129706. };
  129707. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129708. _vq_quantthresh__44c3_s_p3_0,
  129709. _vq_quantmap__44c3_s_p3_0,
  129710. 5,
  129711. 5
  129712. };
  129713. static static_codebook _44c3_s_p3_0 = {
  129714. 4, 625,
  129715. _vq_lengthlist__44c3_s_p3_0,
  129716. 1, -533725184, 1611661312, 3, 0,
  129717. _vq_quantlist__44c3_s_p3_0,
  129718. NULL,
  129719. &_vq_auxt__44c3_s_p3_0,
  129720. NULL,
  129721. 0
  129722. };
  129723. static long _vq_quantlist__44c3_s_p4_0[] = {
  129724. 4,
  129725. 3,
  129726. 5,
  129727. 2,
  129728. 6,
  129729. 1,
  129730. 7,
  129731. 0,
  129732. 8,
  129733. };
  129734. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129735. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129736. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129737. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129738. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129739. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0,
  129741. };
  129742. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129743. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129744. };
  129745. static long _vq_quantmap__44c3_s_p4_0[] = {
  129746. 7, 5, 3, 1, 0, 2, 4, 6,
  129747. 8,
  129748. };
  129749. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129750. _vq_quantthresh__44c3_s_p4_0,
  129751. _vq_quantmap__44c3_s_p4_0,
  129752. 9,
  129753. 9
  129754. };
  129755. static static_codebook _44c3_s_p4_0 = {
  129756. 2, 81,
  129757. _vq_lengthlist__44c3_s_p4_0,
  129758. 1, -531628032, 1611661312, 4, 0,
  129759. _vq_quantlist__44c3_s_p4_0,
  129760. NULL,
  129761. &_vq_auxt__44c3_s_p4_0,
  129762. NULL,
  129763. 0
  129764. };
  129765. static long _vq_quantlist__44c3_s_p5_0[] = {
  129766. 4,
  129767. 3,
  129768. 5,
  129769. 2,
  129770. 6,
  129771. 1,
  129772. 7,
  129773. 0,
  129774. 8,
  129775. };
  129776. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129777. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129778. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129779. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129780. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129781. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129782. 11,
  129783. };
  129784. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129785. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129786. };
  129787. static long _vq_quantmap__44c3_s_p5_0[] = {
  129788. 7, 5, 3, 1, 0, 2, 4, 6,
  129789. 8,
  129790. };
  129791. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129792. _vq_quantthresh__44c3_s_p5_0,
  129793. _vq_quantmap__44c3_s_p5_0,
  129794. 9,
  129795. 9
  129796. };
  129797. static static_codebook _44c3_s_p5_0 = {
  129798. 2, 81,
  129799. _vq_lengthlist__44c3_s_p5_0,
  129800. 1, -531628032, 1611661312, 4, 0,
  129801. _vq_quantlist__44c3_s_p5_0,
  129802. NULL,
  129803. &_vq_auxt__44c3_s_p5_0,
  129804. NULL,
  129805. 0
  129806. };
  129807. static long _vq_quantlist__44c3_s_p6_0[] = {
  129808. 8,
  129809. 7,
  129810. 9,
  129811. 6,
  129812. 10,
  129813. 5,
  129814. 11,
  129815. 4,
  129816. 12,
  129817. 3,
  129818. 13,
  129819. 2,
  129820. 14,
  129821. 1,
  129822. 15,
  129823. 0,
  129824. 16,
  129825. };
  129826. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129827. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129828. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129829. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129830. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129831. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129832. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129833. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129834. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129835. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129836. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129837. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129838. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129839. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129840. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129841. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129842. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129843. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129845. 13,
  129846. };
  129847. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129848. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129849. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129850. };
  129851. static long _vq_quantmap__44c3_s_p6_0[] = {
  129852. 15, 13, 11, 9, 7, 5, 3, 1,
  129853. 0, 2, 4, 6, 8, 10, 12, 14,
  129854. 16,
  129855. };
  129856. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129857. _vq_quantthresh__44c3_s_p6_0,
  129858. _vq_quantmap__44c3_s_p6_0,
  129859. 17,
  129860. 17
  129861. };
  129862. static static_codebook _44c3_s_p6_0 = {
  129863. 2, 289,
  129864. _vq_lengthlist__44c3_s_p6_0,
  129865. 1, -529530880, 1611661312, 5, 0,
  129866. _vq_quantlist__44c3_s_p6_0,
  129867. NULL,
  129868. &_vq_auxt__44c3_s_p6_0,
  129869. NULL,
  129870. 0
  129871. };
  129872. static long _vq_quantlist__44c3_s_p7_0[] = {
  129873. 1,
  129874. 0,
  129875. 2,
  129876. };
  129877. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129878. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129879. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129880. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129881. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129882. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129883. 10,
  129884. };
  129885. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129886. -5.5, 5.5,
  129887. };
  129888. static long _vq_quantmap__44c3_s_p7_0[] = {
  129889. 1, 0, 2,
  129890. };
  129891. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129892. _vq_quantthresh__44c3_s_p7_0,
  129893. _vq_quantmap__44c3_s_p7_0,
  129894. 3,
  129895. 3
  129896. };
  129897. static static_codebook _44c3_s_p7_0 = {
  129898. 4, 81,
  129899. _vq_lengthlist__44c3_s_p7_0,
  129900. 1, -529137664, 1618345984, 2, 0,
  129901. _vq_quantlist__44c3_s_p7_0,
  129902. NULL,
  129903. &_vq_auxt__44c3_s_p7_0,
  129904. NULL,
  129905. 0
  129906. };
  129907. static long _vq_quantlist__44c3_s_p7_1[] = {
  129908. 5,
  129909. 4,
  129910. 6,
  129911. 3,
  129912. 7,
  129913. 2,
  129914. 8,
  129915. 1,
  129916. 9,
  129917. 0,
  129918. 10,
  129919. };
  129920. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129921. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129922. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129923. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129924. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129925. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129926. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129927. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129928. 10,10,10, 8, 8, 8, 8, 8, 8,
  129929. };
  129930. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129931. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129932. 3.5, 4.5,
  129933. };
  129934. static long _vq_quantmap__44c3_s_p7_1[] = {
  129935. 9, 7, 5, 3, 1, 0, 2, 4,
  129936. 6, 8, 10,
  129937. };
  129938. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129939. _vq_quantthresh__44c3_s_p7_1,
  129940. _vq_quantmap__44c3_s_p7_1,
  129941. 11,
  129942. 11
  129943. };
  129944. static static_codebook _44c3_s_p7_1 = {
  129945. 2, 121,
  129946. _vq_lengthlist__44c3_s_p7_1,
  129947. 1, -531365888, 1611661312, 4, 0,
  129948. _vq_quantlist__44c3_s_p7_1,
  129949. NULL,
  129950. &_vq_auxt__44c3_s_p7_1,
  129951. NULL,
  129952. 0
  129953. };
  129954. static long _vq_quantlist__44c3_s_p8_0[] = {
  129955. 6,
  129956. 5,
  129957. 7,
  129958. 4,
  129959. 8,
  129960. 3,
  129961. 9,
  129962. 2,
  129963. 10,
  129964. 1,
  129965. 11,
  129966. 0,
  129967. 12,
  129968. };
  129969. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129970. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129971. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129972. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129973. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129974. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129975. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129976. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129977. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129978. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129979. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129980. 0,13,13,12,12,13,12,14,13,
  129981. };
  129982. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129983. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129984. 12.5, 17.5, 22.5, 27.5,
  129985. };
  129986. static long _vq_quantmap__44c3_s_p8_0[] = {
  129987. 11, 9, 7, 5, 3, 1, 0, 2,
  129988. 4, 6, 8, 10, 12,
  129989. };
  129990. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129991. _vq_quantthresh__44c3_s_p8_0,
  129992. _vq_quantmap__44c3_s_p8_0,
  129993. 13,
  129994. 13
  129995. };
  129996. static static_codebook _44c3_s_p8_0 = {
  129997. 2, 169,
  129998. _vq_lengthlist__44c3_s_p8_0,
  129999. 1, -526516224, 1616117760, 4, 0,
  130000. _vq_quantlist__44c3_s_p8_0,
  130001. NULL,
  130002. &_vq_auxt__44c3_s_p8_0,
  130003. NULL,
  130004. 0
  130005. };
  130006. static long _vq_quantlist__44c3_s_p8_1[] = {
  130007. 2,
  130008. 1,
  130009. 3,
  130010. 0,
  130011. 4,
  130012. };
  130013. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130014. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130015. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130016. };
  130017. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130018. -1.5, -0.5, 0.5, 1.5,
  130019. };
  130020. static long _vq_quantmap__44c3_s_p8_1[] = {
  130021. 3, 1, 0, 2, 4,
  130022. };
  130023. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130024. _vq_quantthresh__44c3_s_p8_1,
  130025. _vq_quantmap__44c3_s_p8_1,
  130026. 5,
  130027. 5
  130028. };
  130029. static static_codebook _44c3_s_p8_1 = {
  130030. 2, 25,
  130031. _vq_lengthlist__44c3_s_p8_1,
  130032. 1, -533725184, 1611661312, 3, 0,
  130033. _vq_quantlist__44c3_s_p8_1,
  130034. NULL,
  130035. &_vq_auxt__44c3_s_p8_1,
  130036. NULL,
  130037. 0
  130038. };
  130039. static long _vq_quantlist__44c3_s_p9_0[] = {
  130040. 6,
  130041. 5,
  130042. 7,
  130043. 4,
  130044. 8,
  130045. 3,
  130046. 9,
  130047. 2,
  130048. 10,
  130049. 1,
  130050. 11,
  130051. 0,
  130052. 12,
  130053. };
  130054. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130055. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130056. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130057. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130058. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130059. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130060. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130061. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130062. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130063. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130065. 11,11,11,11,11,11,11,11,11,
  130066. };
  130067. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130068. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130069. 637.5, 892.5, 1147.5, 1402.5,
  130070. };
  130071. static long _vq_quantmap__44c3_s_p9_0[] = {
  130072. 11, 9, 7, 5, 3, 1, 0, 2,
  130073. 4, 6, 8, 10, 12,
  130074. };
  130075. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130076. _vq_quantthresh__44c3_s_p9_0,
  130077. _vq_quantmap__44c3_s_p9_0,
  130078. 13,
  130079. 13
  130080. };
  130081. static static_codebook _44c3_s_p9_0 = {
  130082. 2, 169,
  130083. _vq_lengthlist__44c3_s_p9_0,
  130084. 1, -514332672, 1627381760, 4, 0,
  130085. _vq_quantlist__44c3_s_p9_0,
  130086. NULL,
  130087. &_vq_auxt__44c3_s_p9_0,
  130088. NULL,
  130089. 0
  130090. };
  130091. static long _vq_quantlist__44c3_s_p9_1[] = {
  130092. 7,
  130093. 6,
  130094. 8,
  130095. 5,
  130096. 9,
  130097. 4,
  130098. 10,
  130099. 3,
  130100. 11,
  130101. 2,
  130102. 12,
  130103. 1,
  130104. 13,
  130105. 0,
  130106. 14,
  130107. };
  130108. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130109. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130110. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130111. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130112. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130113. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130114. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130115. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130116. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130117. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130118. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130119. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130120. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130121. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130122. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130123. 15,
  130124. };
  130125. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130126. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130127. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130128. };
  130129. static long _vq_quantmap__44c3_s_p9_1[] = {
  130130. 13, 11, 9, 7, 5, 3, 1, 0,
  130131. 2, 4, 6, 8, 10, 12, 14,
  130132. };
  130133. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130134. _vq_quantthresh__44c3_s_p9_1,
  130135. _vq_quantmap__44c3_s_p9_1,
  130136. 15,
  130137. 15
  130138. };
  130139. static static_codebook _44c3_s_p9_1 = {
  130140. 2, 225,
  130141. _vq_lengthlist__44c3_s_p9_1,
  130142. 1, -522338304, 1620115456, 4, 0,
  130143. _vq_quantlist__44c3_s_p9_1,
  130144. NULL,
  130145. &_vq_auxt__44c3_s_p9_1,
  130146. NULL,
  130147. 0
  130148. };
  130149. static long _vq_quantlist__44c3_s_p9_2[] = {
  130150. 8,
  130151. 7,
  130152. 9,
  130153. 6,
  130154. 10,
  130155. 5,
  130156. 11,
  130157. 4,
  130158. 12,
  130159. 3,
  130160. 13,
  130161. 2,
  130162. 14,
  130163. 1,
  130164. 15,
  130165. 0,
  130166. 16,
  130167. };
  130168. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130169. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130170. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130171. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130172. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130173. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130174. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130175. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130176. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130177. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130178. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130179. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130180. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130181. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130182. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130183. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130184. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130185. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130186. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130187. 10,
  130188. };
  130189. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130190. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130191. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130192. };
  130193. static long _vq_quantmap__44c3_s_p9_2[] = {
  130194. 15, 13, 11, 9, 7, 5, 3, 1,
  130195. 0, 2, 4, 6, 8, 10, 12, 14,
  130196. 16,
  130197. };
  130198. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130199. _vq_quantthresh__44c3_s_p9_2,
  130200. _vq_quantmap__44c3_s_p9_2,
  130201. 17,
  130202. 17
  130203. };
  130204. static static_codebook _44c3_s_p9_2 = {
  130205. 2, 289,
  130206. _vq_lengthlist__44c3_s_p9_2,
  130207. 1, -529530880, 1611661312, 5, 0,
  130208. _vq_quantlist__44c3_s_p9_2,
  130209. NULL,
  130210. &_vq_auxt__44c3_s_p9_2,
  130211. NULL,
  130212. 0
  130213. };
  130214. static long _huff_lengthlist__44c3_s_short[] = {
  130215. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130216. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130217. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130218. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130219. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130220. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130221. 6, 8, 9,11,
  130222. };
  130223. static static_codebook _huff_book__44c3_s_short = {
  130224. 2, 100,
  130225. _huff_lengthlist__44c3_s_short,
  130226. 0, 0, 0, 0, 0,
  130227. NULL,
  130228. NULL,
  130229. NULL,
  130230. NULL,
  130231. 0
  130232. };
  130233. static long _huff_lengthlist__44c4_s_long[] = {
  130234. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130235. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130236. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130237. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130238. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130239. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130240. 9, 8, 7, 7,
  130241. };
  130242. static static_codebook _huff_book__44c4_s_long = {
  130243. 2, 100,
  130244. _huff_lengthlist__44c4_s_long,
  130245. 0, 0, 0, 0, 0,
  130246. NULL,
  130247. NULL,
  130248. NULL,
  130249. NULL,
  130250. 0
  130251. };
  130252. static long _vq_quantlist__44c4_s_p1_0[] = {
  130253. 1,
  130254. 0,
  130255. 2,
  130256. };
  130257. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130258. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130259. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130264. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130269. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130304. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130309. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130314. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130350. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130355. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130360. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0,
  130669. };
  130670. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130671. -0.5, 0.5,
  130672. };
  130673. static long _vq_quantmap__44c4_s_p1_0[] = {
  130674. 1, 0, 2,
  130675. };
  130676. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130677. _vq_quantthresh__44c4_s_p1_0,
  130678. _vq_quantmap__44c4_s_p1_0,
  130679. 3,
  130680. 3
  130681. };
  130682. static static_codebook _44c4_s_p1_0 = {
  130683. 8, 6561,
  130684. _vq_lengthlist__44c4_s_p1_0,
  130685. 1, -535822336, 1611661312, 2, 0,
  130686. _vq_quantlist__44c4_s_p1_0,
  130687. NULL,
  130688. &_vq_auxt__44c4_s_p1_0,
  130689. NULL,
  130690. 0
  130691. };
  130692. static long _vq_quantlist__44c4_s_p2_0[] = {
  130693. 2,
  130694. 1,
  130695. 3,
  130696. 0,
  130697. 4,
  130698. };
  130699. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130700. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130701. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130702. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130703. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130704. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130710. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130711. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130712. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130718. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130719. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130726. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130727. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0,
  130740. };
  130741. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130742. -1.5, -0.5, 0.5, 1.5,
  130743. };
  130744. static long _vq_quantmap__44c4_s_p2_0[] = {
  130745. 3, 1, 0, 2, 4,
  130746. };
  130747. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130748. _vq_quantthresh__44c4_s_p2_0,
  130749. _vq_quantmap__44c4_s_p2_0,
  130750. 5,
  130751. 5
  130752. };
  130753. static static_codebook _44c4_s_p2_0 = {
  130754. 4, 625,
  130755. _vq_lengthlist__44c4_s_p2_0,
  130756. 1, -533725184, 1611661312, 3, 0,
  130757. _vq_quantlist__44c4_s_p2_0,
  130758. NULL,
  130759. &_vq_auxt__44c4_s_p2_0,
  130760. NULL,
  130761. 0
  130762. };
  130763. static long _vq_quantlist__44c4_s_p3_0[] = {
  130764. 2,
  130765. 1,
  130766. 3,
  130767. 0,
  130768. 4,
  130769. };
  130770. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130771. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0,
  130811. };
  130812. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130813. -1.5, -0.5, 0.5, 1.5,
  130814. };
  130815. static long _vq_quantmap__44c4_s_p3_0[] = {
  130816. 3, 1, 0, 2, 4,
  130817. };
  130818. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130819. _vq_quantthresh__44c4_s_p3_0,
  130820. _vq_quantmap__44c4_s_p3_0,
  130821. 5,
  130822. 5
  130823. };
  130824. static static_codebook _44c4_s_p3_0 = {
  130825. 4, 625,
  130826. _vq_lengthlist__44c4_s_p3_0,
  130827. 1, -533725184, 1611661312, 3, 0,
  130828. _vq_quantlist__44c4_s_p3_0,
  130829. NULL,
  130830. &_vq_auxt__44c4_s_p3_0,
  130831. NULL,
  130832. 0
  130833. };
  130834. static long _vq_quantlist__44c4_s_p4_0[] = {
  130835. 4,
  130836. 3,
  130837. 5,
  130838. 2,
  130839. 6,
  130840. 1,
  130841. 7,
  130842. 0,
  130843. 8,
  130844. };
  130845. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130846. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130847. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130848. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130849. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130850. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0,
  130852. };
  130853. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130854. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130855. };
  130856. static long _vq_quantmap__44c4_s_p4_0[] = {
  130857. 7, 5, 3, 1, 0, 2, 4, 6,
  130858. 8,
  130859. };
  130860. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130861. _vq_quantthresh__44c4_s_p4_0,
  130862. _vq_quantmap__44c4_s_p4_0,
  130863. 9,
  130864. 9
  130865. };
  130866. static static_codebook _44c4_s_p4_0 = {
  130867. 2, 81,
  130868. _vq_lengthlist__44c4_s_p4_0,
  130869. 1, -531628032, 1611661312, 4, 0,
  130870. _vq_quantlist__44c4_s_p4_0,
  130871. NULL,
  130872. &_vq_auxt__44c4_s_p4_0,
  130873. NULL,
  130874. 0
  130875. };
  130876. static long _vq_quantlist__44c4_s_p5_0[] = {
  130877. 4,
  130878. 3,
  130879. 5,
  130880. 2,
  130881. 6,
  130882. 1,
  130883. 7,
  130884. 0,
  130885. 8,
  130886. };
  130887. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130888. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130889. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130890. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130891. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130892. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130893. 10,
  130894. };
  130895. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130896. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130897. };
  130898. static long _vq_quantmap__44c4_s_p5_0[] = {
  130899. 7, 5, 3, 1, 0, 2, 4, 6,
  130900. 8,
  130901. };
  130902. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130903. _vq_quantthresh__44c4_s_p5_0,
  130904. _vq_quantmap__44c4_s_p5_0,
  130905. 9,
  130906. 9
  130907. };
  130908. static static_codebook _44c4_s_p5_0 = {
  130909. 2, 81,
  130910. _vq_lengthlist__44c4_s_p5_0,
  130911. 1, -531628032, 1611661312, 4, 0,
  130912. _vq_quantlist__44c4_s_p5_0,
  130913. NULL,
  130914. &_vq_auxt__44c4_s_p5_0,
  130915. NULL,
  130916. 0
  130917. };
  130918. static long _vq_quantlist__44c4_s_p6_0[] = {
  130919. 8,
  130920. 7,
  130921. 9,
  130922. 6,
  130923. 10,
  130924. 5,
  130925. 11,
  130926. 4,
  130927. 12,
  130928. 3,
  130929. 13,
  130930. 2,
  130931. 14,
  130932. 1,
  130933. 15,
  130934. 0,
  130935. 16,
  130936. };
  130937. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130938. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130939. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130940. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130941. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130942. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130943. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130944. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130945. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130946. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130947. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130948. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130949. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130950. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130951. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130952. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130953. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130954. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130956. 13,
  130957. };
  130958. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130959. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130960. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130961. };
  130962. static long _vq_quantmap__44c4_s_p6_0[] = {
  130963. 15, 13, 11, 9, 7, 5, 3, 1,
  130964. 0, 2, 4, 6, 8, 10, 12, 14,
  130965. 16,
  130966. };
  130967. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130968. _vq_quantthresh__44c4_s_p6_0,
  130969. _vq_quantmap__44c4_s_p6_0,
  130970. 17,
  130971. 17
  130972. };
  130973. static static_codebook _44c4_s_p6_0 = {
  130974. 2, 289,
  130975. _vq_lengthlist__44c4_s_p6_0,
  130976. 1, -529530880, 1611661312, 5, 0,
  130977. _vq_quantlist__44c4_s_p6_0,
  130978. NULL,
  130979. &_vq_auxt__44c4_s_p6_0,
  130980. NULL,
  130981. 0
  130982. };
  130983. static long _vq_quantlist__44c4_s_p7_0[] = {
  130984. 1,
  130985. 0,
  130986. 2,
  130987. };
  130988. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130989. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130990. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130991. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130992. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130993. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130994. 10,
  130995. };
  130996. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130997. -5.5, 5.5,
  130998. };
  130999. static long _vq_quantmap__44c4_s_p7_0[] = {
  131000. 1, 0, 2,
  131001. };
  131002. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131003. _vq_quantthresh__44c4_s_p7_0,
  131004. _vq_quantmap__44c4_s_p7_0,
  131005. 3,
  131006. 3
  131007. };
  131008. static static_codebook _44c4_s_p7_0 = {
  131009. 4, 81,
  131010. _vq_lengthlist__44c4_s_p7_0,
  131011. 1, -529137664, 1618345984, 2, 0,
  131012. _vq_quantlist__44c4_s_p7_0,
  131013. NULL,
  131014. &_vq_auxt__44c4_s_p7_0,
  131015. NULL,
  131016. 0
  131017. };
  131018. static long _vq_quantlist__44c4_s_p7_1[] = {
  131019. 5,
  131020. 4,
  131021. 6,
  131022. 3,
  131023. 7,
  131024. 2,
  131025. 8,
  131026. 1,
  131027. 9,
  131028. 0,
  131029. 10,
  131030. };
  131031. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131032. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131033. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131034. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131035. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131036. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131037. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131038. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131039. 10,10,10, 8, 8, 8, 8, 9, 9,
  131040. };
  131041. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131042. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131043. 3.5, 4.5,
  131044. };
  131045. static long _vq_quantmap__44c4_s_p7_1[] = {
  131046. 9, 7, 5, 3, 1, 0, 2, 4,
  131047. 6, 8, 10,
  131048. };
  131049. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131050. _vq_quantthresh__44c4_s_p7_1,
  131051. _vq_quantmap__44c4_s_p7_1,
  131052. 11,
  131053. 11
  131054. };
  131055. static static_codebook _44c4_s_p7_1 = {
  131056. 2, 121,
  131057. _vq_lengthlist__44c4_s_p7_1,
  131058. 1, -531365888, 1611661312, 4, 0,
  131059. _vq_quantlist__44c4_s_p7_1,
  131060. NULL,
  131061. &_vq_auxt__44c4_s_p7_1,
  131062. NULL,
  131063. 0
  131064. };
  131065. static long _vq_quantlist__44c4_s_p8_0[] = {
  131066. 6,
  131067. 5,
  131068. 7,
  131069. 4,
  131070. 8,
  131071. 3,
  131072. 9,
  131073. 2,
  131074. 10,
  131075. 1,
  131076. 11,
  131077. 0,
  131078. 12,
  131079. };
  131080. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131081. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131082. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131083. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131084. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131085. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131086. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131087. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131088. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131089. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131090. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131091. 0,13,12,12,12,12,12,13,13,
  131092. };
  131093. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131094. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131095. 12.5, 17.5, 22.5, 27.5,
  131096. };
  131097. static long _vq_quantmap__44c4_s_p8_0[] = {
  131098. 11, 9, 7, 5, 3, 1, 0, 2,
  131099. 4, 6, 8, 10, 12,
  131100. };
  131101. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131102. _vq_quantthresh__44c4_s_p8_0,
  131103. _vq_quantmap__44c4_s_p8_0,
  131104. 13,
  131105. 13
  131106. };
  131107. static static_codebook _44c4_s_p8_0 = {
  131108. 2, 169,
  131109. _vq_lengthlist__44c4_s_p8_0,
  131110. 1, -526516224, 1616117760, 4, 0,
  131111. _vq_quantlist__44c4_s_p8_0,
  131112. NULL,
  131113. &_vq_auxt__44c4_s_p8_0,
  131114. NULL,
  131115. 0
  131116. };
  131117. static long _vq_quantlist__44c4_s_p8_1[] = {
  131118. 2,
  131119. 1,
  131120. 3,
  131121. 0,
  131122. 4,
  131123. };
  131124. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131125. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131126. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131127. };
  131128. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131129. -1.5, -0.5, 0.5, 1.5,
  131130. };
  131131. static long _vq_quantmap__44c4_s_p8_1[] = {
  131132. 3, 1, 0, 2, 4,
  131133. };
  131134. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131135. _vq_quantthresh__44c4_s_p8_1,
  131136. _vq_quantmap__44c4_s_p8_1,
  131137. 5,
  131138. 5
  131139. };
  131140. static static_codebook _44c4_s_p8_1 = {
  131141. 2, 25,
  131142. _vq_lengthlist__44c4_s_p8_1,
  131143. 1, -533725184, 1611661312, 3, 0,
  131144. _vq_quantlist__44c4_s_p8_1,
  131145. NULL,
  131146. &_vq_auxt__44c4_s_p8_1,
  131147. NULL,
  131148. 0
  131149. };
  131150. static long _vq_quantlist__44c4_s_p9_0[] = {
  131151. 6,
  131152. 5,
  131153. 7,
  131154. 4,
  131155. 8,
  131156. 3,
  131157. 9,
  131158. 2,
  131159. 10,
  131160. 1,
  131161. 11,
  131162. 0,
  131163. 12,
  131164. };
  131165. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131166. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131167. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131168. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131169. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131170. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131171. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131172. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131173. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131174. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131175. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131176. 12,12,12,12,12,12,12,12,12,
  131177. };
  131178. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131179. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131180. 787.5, 1102.5, 1417.5, 1732.5,
  131181. };
  131182. static long _vq_quantmap__44c4_s_p9_0[] = {
  131183. 11, 9, 7, 5, 3, 1, 0, 2,
  131184. 4, 6, 8, 10, 12,
  131185. };
  131186. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131187. _vq_quantthresh__44c4_s_p9_0,
  131188. _vq_quantmap__44c4_s_p9_0,
  131189. 13,
  131190. 13
  131191. };
  131192. static static_codebook _44c4_s_p9_0 = {
  131193. 2, 169,
  131194. _vq_lengthlist__44c4_s_p9_0,
  131195. 1, -513964032, 1628680192, 4, 0,
  131196. _vq_quantlist__44c4_s_p9_0,
  131197. NULL,
  131198. &_vq_auxt__44c4_s_p9_0,
  131199. NULL,
  131200. 0
  131201. };
  131202. static long _vq_quantlist__44c4_s_p9_1[] = {
  131203. 7,
  131204. 6,
  131205. 8,
  131206. 5,
  131207. 9,
  131208. 4,
  131209. 10,
  131210. 3,
  131211. 11,
  131212. 2,
  131213. 12,
  131214. 1,
  131215. 13,
  131216. 0,
  131217. 14,
  131218. };
  131219. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131220. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131221. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131222. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131223. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131224. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131225. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131226. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131227. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131228. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131229. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131230. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131231. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131232. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131233. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131234. 15,
  131235. };
  131236. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131237. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131238. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131239. };
  131240. static long _vq_quantmap__44c4_s_p9_1[] = {
  131241. 13, 11, 9, 7, 5, 3, 1, 0,
  131242. 2, 4, 6, 8, 10, 12, 14,
  131243. };
  131244. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131245. _vq_quantthresh__44c4_s_p9_1,
  131246. _vq_quantmap__44c4_s_p9_1,
  131247. 15,
  131248. 15
  131249. };
  131250. static static_codebook _44c4_s_p9_1 = {
  131251. 2, 225,
  131252. _vq_lengthlist__44c4_s_p9_1,
  131253. 1, -520986624, 1620377600, 4, 0,
  131254. _vq_quantlist__44c4_s_p9_1,
  131255. NULL,
  131256. &_vq_auxt__44c4_s_p9_1,
  131257. NULL,
  131258. 0
  131259. };
  131260. static long _vq_quantlist__44c4_s_p9_2[] = {
  131261. 10,
  131262. 9,
  131263. 11,
  131264. 8,
  131265. 12,
  131266. 7,
  131267. 13,
  131268. 6,
  131269. 14,
  131270. 5,
  131271. 15,
  131272. 4,
  131273. 16,
  131274. 3,
  131275. 17,
  131276. 2,
  131277. 18,
  131278. 1,
  131279. 19,
  131280. 0,
  131281. 20,
  131282. };
  131283. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131284. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131285. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131286. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131287. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131288. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131289. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131290. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131291. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131292. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131293. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131294. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131295. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131296. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131297. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131298. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131299. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131300. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131301. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131302. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131303. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131304. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131305. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131306. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131307. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131308. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131309. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131310. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131311. 10,10,10,10,10,10,10,10,10,
  131312. };
  131313. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131314. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131315. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131316. 6.5, 7.5, 8.5, 9.5,
  131317. };
  131318. static long _vq_quantmap__44c4_s_p9_2[] = {
  131319. 19, 17, 15, 13, 11, 9, 7, 5,
  131320. 3, 1, 0, 2, 4, 6, 8, 10,
  131321. 12, 14, 16, 18, 20,
  131322. };
  131323. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131324. _vq_quantthresh__44c4_s_p9_2,
  131325. _vq_quantmap__44c4_s_p9_2,
  131326. 21,
  131327. 21
  131328. };
  131329. static static_codebook _44c4_s_p9_2 = {
  131330. 2, 441,
  131331. _vq_lengthlist__44c4_s_p9_2,
  131332. 1, -529268736, 1611661312, 5, 0,
  131333. _vq_quantlist__44c4_s_p9_2,
  131334. NULL,
  131335. &_vq_auxt__44c4_s_p9_2,
  131336. NULL,
  131337. 0
  131338. };
  131339. static long _huff_lengthlist__44c4_s_short[] = {
  131340. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131341. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131342. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131343. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131344. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131345. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131346. 7, 9,12,17,
  131347. };
  131348. static static_codebook _huff_book__44c4_s_short = {
  131349. 2, 100,
  131350. _huff_lengthlist__44c4_s_short,
  131351. 0, 0, 0, 0, 0,
  131352. NULL,
  131353. NULL,
  131354. NULL,
  131355. NULL,
  131356. 0
  131357. };
  131358. static long _huff_lengthlist__44c5_s_long[] = {
  131359. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131360. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131361. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131362. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131363. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131364. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131365. 9, 8, 7, 7,
  131366. };
  131367. static static_codebook _huff_book__44c5_s_long = {
  131368. 2, 100,
  131369. _huff_lengthlist__44c5_s_long,
  131370. 0, 0, 0, 0, 0,
  131371. NULL,
  131372. NULL,
  131373. NULL,
  131374. NULL,
  131375. 0
  131376. };
  131377. static long _vq_quantlist__44c5_s_p1_0[] = {
  131378. 1,
  131379. 0,
  131380. 2,
  131381. };
  131382. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131383. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131384. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131389. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131394. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131429. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131434. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131439. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131475. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131480. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131485. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0,
  131794. };
  131795. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131796. -0.5, 0.5,
  131797. };
  131798. static long _vq_quantmap__44c5_s_p1_0[] = {
  131799. 1, 0, 2,
  131800. };
  131801. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131802. _vq_quantthresh__44c5_s_p1_0,
  131803. _vq_quantmap__44c5_s_p1_0,
  131804. 3,
  131805. 3
  131806. };
  131807. static static_codebook _44c5_s_p1_0 = {
  131808. 8, 6561,
  131809. _vq_lengthlist__44c5_s_p1_0,
  131810. 1, -535822336, 1611661312, 2, 0,
  131811. _vq_quantlist__44c5_s_p1_0,
  131812. NULL,
  131813. &_vq_auxt__44c5_s_p1_0,
  131814. NULL,
  131815. 0
  131816. };
  131817. static long _vq_quantlist__44c5_s_p2_0[] = {
  131818. 2,
  131819. 1,
  131820. 3,
  131821. 0,
  131822. 4,
  131823. };
  131824. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131825. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131826. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131827. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131828. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131829. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131835. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131836. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131837. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131843. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131844. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131851. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131852. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0,
  131865. };
  131866. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131867. -1.5, -0.5, 0.5, 1.5,
  131868. };
  131869. static long _vq_quantmap__44c5_s_p2_0[] = {
  131870. 3, 1, 0, 2, 4,
  131871. };
  131872. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131873. _vq_quantthresh__44c5_s_p2_0,
  131874. _vq_quantmap__44c5_s_p2_0,
  131875. 5,
  131876. 5
  131877. };
  131878. static static_codebook _44c5_s_p2_0 = {
  131879. 4, 625,
  131880. _vq_lengthlist__44c5_s_p2_0,
  131881. 1, -533725184, 1611661312, 3, 0,
  131882. _vq_quantlist__44c5_s_p2_0,
  131883. NULL,
  131884. &_vq_auxt__44c5_s_p2_0,
  131885. NULL,
  131886. 0
  131887. };
  131888. static long _vq_quantlist__44c5_s_p3_0[] = {
  131889. 2,
  131890. 1,
  131891. 3,
  131892. 0,
  131893. 4,
  131894. };
  131895. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131896. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0,
  131936. };
  131937. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131938. -1.5, -0.5, 0.5, 1.5,
  131939. };
  131940. static long _vq_quantmap__44c5_s_p3_0[] = {
  131941. 3, 1, 0, 2, 4,
  131942. };
  131943. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131944. _vq_quantthresh__44c5_s_p3_0,
  131945. _vq_quantmap__44c5_s_p3_0,
  131946. 5,
  131947. 5
  131948. };
  131949. static static_codebook _44c5_s_p3_0 = {
  131950. 4, 625,
  131951. _vq_lengthlist__44c5_s_p3_0,
  131952. 1, -533725184, 1611661312, 3, 0,
  131953. _vq_quantlist__44c5_s_p3_0,
  131954. NULL,
  131955. &_vq_auxt__44c5_s_p3_0,
  131956. NULL,
  131957. 0
  131958. };
  131959. static long _vq_quantlist__44c5_s_p4_0[] = {
  131960. 4,
  131961. 3,
  131962. 5,
  131963. 2,
  131964. 6,
  131965. 1,
  131966. 7,
  131967. 0,
  131968. 8,
  131969. };
  131970. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131971. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131972. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131973. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131974. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131975. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0,
  131977. };
  131978. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131979. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131980. };
  131981. static long _vq_quantmap__44c5_s_p4_0[] = {
  131982. 7, 5, 3, 1, 0, 2, 4, 6,
  131983. 8,
  131984. };
  131985. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131986. _vq_quantthresh__44c5_s_p4_0,
  131987. _vq_quantmap__44c5_s_p4_0,
  131988. 9,
  131989. 9
  131990. };
  131991. static static_codebook _44c5_s_p4_0 = {
  131992. 2, 81,
  131993. _vq_lengthlist__44c5_s_p4_0,
  131994. 1, -531628032, 1611661312, 4, 0,
  131995. _vq_quantlist__44c5_s_p4_0,
  131996. NULL,
  131997. &_vq_auxt__44c5_s_p4_0,
  131998. NULL,
  131999. 0
  132000. };
  132001. static long _vq_quantlist__44c5_s_p5_0[] = {
  132002. 4,
  132003. 3,
  132004. 5,
  132005. 2,
  132006. 6,
  132007. 1,
  132008. 7,
  132009. 0,
  132010. 8,
  132011. };
  132012. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132013. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132014. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132015. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132016. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132017. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132018. 10,
  132019. };
  132020. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132021. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132022. };
  132023. static long _vq_quantmap__44c5_s_p5_0[] = {
  132024. 7, 5, 3, 1, 0, 2, 4, 6,
  132025. 8,
  132026. };
  132027. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132028. _vq_quantthresh__44c5_s_p5_0,
  132029. _vq_quantmap__44c5_s_p5_0,
  132030. 9,
  132031. 9
  132032. };
  132033. static static_codebook _44c5_s_p5_0 = {
  132034. 2, 81,
  132035. _vq_lengthlist__44c5_s_p5_0,
  132036. 1, -531628032, 1611661312, 4, 0,
  132037. _vq_quantlist__44c5_s_p5_0,
  132038. NULL,
  132039. &_vq_auxt__44c5_s_p5_0,
  132040. NULL,
  132041. 0
  132042. };
  132043. static long _vq_quantlist__44c5_s_p6_0[] = {
  132044. 8,
  132045. 7,
  132046. 9,
  132047. 6,
  132048. 10,
  132049. 5,
  132050. 11,
  132051. 4,
  132052. 12,
  132053. 3,
  132054. 13,
  132055. 2,
  132056. 14,
  132057. 1,
  132058. 15,
  132059. 0,
  132060. 16,
  132061. };
  132062. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132063. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132064. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132065. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132066. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132067. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132068. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132069. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132070. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132071. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132072. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132073. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132074. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132075. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132076. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132077. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132078. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132079. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132081. 13,
  132082. };
  132083. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132084. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132085. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132086. };
  132087. static long _vq_quantmap__44c5_s_p6_0[] = {
  132088. 15, 13, 11, 9, 7, 5, 3, 1,
  132089. 0, 2, 4, 6, 8, 10, 12, 14,
  132090. 16,
  132091. };
  132092. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132093. _vq_quantthresh__44c5_s_p6_0,
  132094. _vq_quantmap__44c5_s_p6_0,
  132095. 17,
  132096. 17
  132097. };
  132098. static static_codebook _44c5_s_p6_0 = {
  132099. 2, 289,
  132100. _vq_lengthlist__44c5_s_p6_0,
  132101. 1, -529530880, 1611661312, 5, 0,
  132102. _vq_quantlist__44c5_s_p6_0,
  132103. NULL,
  132104. &_vq_auxt__44c5_s_p6_0,
  132105. NULL,
  132106. 0
  132107. };
  132108. static long _vq_quantlist__44c5_s_p7_0[] = {
  132109. 1,
  132110. 0,
  132111. 2,
  132112. };
  132113. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132114. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132115. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132116. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132117. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132118. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132119. 10,
  132120. };
  132121. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132122. -5.5, 5.5,
  132123. };
  132124. static long _vq_quantmap__44c5_s_p7_0[] = {
  132125. 1, 0, 2,
  132126. };
  132127. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132128. _vq_quantthresh__44c5_s_p7_0,
  132129. _vq_quantmap__44c5_s_p7_0,
  132130. 3,
  132131. 3
  132132. };
  132133. static static_codebook _44c5_s_p7_0 = {
  132134. 4, 81,
  132135. _vq_lengthlist__44c5_s_p7_0,
  132136. 1, -529137664, 1618345984, 2, 0,
  132137. _vq_quantlist__44c5_s_p7_0,
  132138. NULL,
  132139. &_vq_auxt__44c5_s_p7_0,
  132140. NULL,
  132141. 0
  132142. };
  132143. static long _vq_quantlist__44c5_s_p7_1[] = {
  132144. 5,
  132145. 4,
  132146. 6,
  132147. 3,
  132148. 7,
  132149. 2,
  132150. 8,
  132151. 1,
  132152. 9,
  132153. 0,
  132154. 10,
  132155. };
  132156. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132157. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132158. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132159. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132160. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132161. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132162. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132163. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132164. 10,10,10, 8, 8, 8, 8, 8, 8,
  132165. };
  132166. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132167. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132168. 3.5, 4.5,
  132169. };
  132170. static long _vq_quantmap__44c5_s_p7_1[] = {
  132171. 9, 7, 5, 3, 1, 0, 2, 4,
  132172. 6, 8, 10,
  132173. };
  132174. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132175. _vq_quantthresh__44c5_s_p7_1,
  132176. _vq_quantmap__44c5_s_p7_1,
  132177. 11,
  132178. 11
  132179. };
  132180. static static_codebook _44c5_s_p7_1 = {
  132181. 2, 121,
  132182. _vq_lengthlist__44c5_s_p7_1,
  132183. 1, -531365888, 1611661312, 4, 0,
  132184. _vq_quantlist__44c5_s_p7_1,
  132185. NULL,
  132186. &_vq_auxt__44c5_s_p7_1,
  132187. NULL,
  132188. 0
  132189. };
  132190. static long _vq_quantlist__44c5_s_p8_0[] = {
  132191. 6,
  132192. 5,
  132193. 7,
  132194. 4,
  132195. 8,
  132196. 3,
  132197. 9,
  132198. 2,
  132199. 10,
  132200. 1,
  132201. 11,
  132202. 0,
  132203. 12,
  132204. };
  132205. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132206. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132207. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132208. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132209. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132210. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132211. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132212. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132213. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132214. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132215. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132216. 0,12,12,12,12,12,12,13,13,
  132217. };
  132218. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132219. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132220. 12.5, 17.5, 22.5, 27.5,
  132221. };
  132222. static long _vq_quantmap__44c5_s_p8_0[] = {
  132223. 11, 9, 7, 5, 3, 1, 0, 2,
  132224. 4, 6, 8, 10, 12,
  132225. };
  132226. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132227. _vq_quantthresh__44c5_s_p8_0,
  132228. _vq_quantmap__44c5_s_p8_0,
  132229. 13,
  132230. 13
  132231. };
  132232. static static_codebook _44c5_s_p8_0 = {
  132233. 2, 169,
  132234. _vq_lengthlist__44c5_s_p8_0,
  132235. 1, -526516224, 1616117760, 4, 0,
  132236. _vq_quantlist__44c5_s_p8_0,
  132237. NULL,
  132238. &_vq_auxt__44c5_s_p8_0,
  132239. NULL,
  132240. 0
  132241. };
  132242. static long _vq_quantlist__44c5_s_p8_1[] = {
  132243. 2,
  132244. 1,
  132245. 3,
  132246. 0,
  132247. 4,
  132248. };
  132249. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132250. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132251. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132252. };
  132253. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132254. -1.5, -0.5, 0.5, 1.5,
  132255. };
  132256. static long _vq_quantmap__44c5_s_p8_1[] = {
  132257. 3, 1, 0, 2, 4,
  132258. };
  132259. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132260. _vq_quantthresh__44c5_s_p8_1,
  132261. _vq_quantmap__44c5_s_p8_1,
  132262. 5,
  132263. 5
  132264. };
  132265. static static_codebook _44c5_s_p8_1 = {
  132266. 2, 25,
  132267. _vq_lengthlist__44c5_s_p8_1,
  132268. 1, -533725184, 1611661312, 3, 0,
  132269. _vq_quantlist__44c5_s_p8_1,
  132270. NULL,
  132271. &_vq_auxt__44c5_s_p8_1,
  132272. NULL,
  132273. 0
  132274. };
  132275. static long _vq_quantlist__44c5_s_p9_0[] = {
  132276. 7,
  132277. 6,
  132278. 8,
  132279. 5,
  132280. 9,
  132281. 4,
  132282. 10,
  132283. 3,
  132284. 11,
  132285. 2,
  132286. 12,
  132287. 1,
  132288. 13,
  132289. 0,
  132290. 14,
  132291. };
  132292. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132293. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132294. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132295. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132296. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132297. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132298. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132299. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132300. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132301. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132302. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132303. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132304. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132305. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132306. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132307. 12,
  132308. };
  132309. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132310. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132311. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132312. };
  132313. static long _vq_quantmap__44c5_s_p9_0[] = {
  132314. 13, 11, 9, 7, 5, 3, 1, 0,
  132315. 2, 4, 6, 8, 10, 12, 14,
  132316. };
  132317. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132318. _vq_quantthresh__44c5_s_p9_0,
  132319. _vq_quantmap__44c5_s_p9_0,
  132320. 15,
  132321. 15
  132322. };
  132323. static static_codebook _44c5_s_p9_0 = {
  132324. 2, 225,
  132325. _vq_lengthlist__44c5_s_p9_0,
  132326. 1, -512522752, 1628852224, 4, 0,
  132327. _vq_quantlist__44c5_s_p9_0,
  132328. NULL,
  132329. &_vq_auxt__44c5_s_p9_0,
  132330. NULL,
  132331. 0
  132332. };
  132333. static long _vq_quantlist__44c5_s_p9_1[] = {
  132334. 8,
  132335. 7,
  132336. 9,
  132337. 6,
  132338. 10,
  132339. 5,
  132340. 11,
  132341. 4,
  132342. 12,
  132343. 3,
  132344. 13,
  132345. 2,
  132346. 14,
  132347. 1,
  132348. 15,
  132349. 0,
  132350. 16,
  132351. };
  132352. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132353. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132354. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132355. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132356. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132357. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132358. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132359. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132360. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132361. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132362. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132363. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132364. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132365. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132366. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132367. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132368. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132369. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132370. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132371. 15,
  132372. };
  132373. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132374. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132375. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132376. };
  132377. static long _vq_quantmap__44c5_s_p9_1[] = {
  132378. 15, 13, 11, 9, 7, 5, 3, 1,
  132379. 0, 2, 4, 6, 8, 10, 12, 14,
  132380. 16,
  132381. };
  132382. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132383. _vq_quantthresh__44c5_s_p9_1,
  132384. _vq_quantmap__44c5_s_p9_1,
  132385. 17,
  132386. 17
  132387. };
  132388. static static_codebook _44c5_s_p9_1 = {
  132389. 2, 289,
  132390. _vq_lengthlist__44c5_s_p9_1,
  132391. 1, -520814592, 1620377600, 5, 0,
  132392. _vq_quantlist__44c5_s_p9_1,
  132393. NULL,
  132394. &_vq_auxt__44c5_s_p9_1,
  132395. NULL,
  132396. 0
  132397. };
  132398. static long _vq_quantlist__44c5_s_p9_2[] = {
  132399. 10,
  132400. 9,
  132401. 11,
  132402. 8,
  132403. 12,
  132404. 7,
  132405. 13,
  132406. 6,
  132407. 14,
  132408. 5,
  132409. 15,
  132410. 4,
  132411. 16,
  132412. 3,
  132413. 17,
  132414. 2,
  132415. 18,
  132416. 1,
  132417. 19,
  132418. 0,
  132419. 20,
  132420. };
  132421. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132422. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132423. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132424. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132425. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132426. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132427. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132428. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132429. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132430. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132431. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132432. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132433. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132434. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132435. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132436. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132437. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132438. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132439. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132440. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132441. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132442. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132443. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132444. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132445. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132446. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132447. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132448. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132449. 10,10,10,10,10,10,10,10,10,
  132450. };
  132451. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132452. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132453. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132454. 6.5, 7.5, 8.5, 9.5,
  132455. };
  132456. static long _vq_quantmap__44c5_s_p9_2[] = {
  132457. 19, 17, 15, 13, 11, 9, 7, 5,
  132458. 3, 1, 0, 2, 4, 6, 8, 10,
  132459. 12, 14, 16, 18, 20,
  132460. };
  132461. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132462. _vq_quantthresh__44c5_s_p9_2,
  132463. _vq_quantmap__44c5_s_p9_2,
  132464. 21,
  132465. 21
  132466. };
  132467. static static_codebook _44c5_s_p9_2 = {
  132468. 2, 441,
  132469. _vq_lengthlist__44c5_s_p9_2,
  132470. 1, -529268736, 1611661312, 5, 0,
  132471. _vq_quantlist__44c5_s_p9_2,
  132472. NULL,
  132473. &_vq_auxt__44c5_s_p9_2,
  132474. NULL,
  132475. 0
  132476. };
  132477. static long _huff_lengthlist__44c5_s_short[] = {
  132478. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132479. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132480. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132481. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132482. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132483. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132484. 6, 8,11,16,
  132485. };
  132486. static static_codebook _huff_book__44c5_s_short = {
  132487. 2, 100,
  132488. _huff_lengthlist__44c5_s_short,
  132489. 0, 0, 0, 0, 0,
  132490. NULL,
  132491. NULL,
  132492. NULL,
  132493. NULL,
  132494. 0
  132495. };
  132496. static long _huff_lengthlist__44c6_s_long[] = {
  132497. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132498. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132499. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132500. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132501. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132502. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132503. 11,10,10,12,
  132504. };
  132505. static static_codebook _huff_book__44c6_s_long = {
  132506. 2, 100,
  132507. _huff_lengthlist__44c6_s_long,
  132508. 0, 0, 0, 0, 0,
  132509. NULL,
  132510. NULL,
  132511. NULL,
  132512. NULL,
  132513. 0
  132514. };
  132515. static long _vq_quantlist__44c6_s_p1_0[] = {
  132516. 1,
  132517. 0,
  132518. 2,
  132519. };
  132520. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132521. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132522. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132524. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132525. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132526. 8,
  132527. };
  132528. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132529. -0.5, 0.5,
  132530. };
  132531. static long _vq_quantmap__44c6_s_p1_0[] = {
  132532. 1, 0, 2,
  132533. };
  132534. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132535. _vq_quantthresh__44c6_s_p1_0,
  132536. _vq_quantmap__44c6_s_p1_0,
  132537. 3,
  132538. 3
  132539. };
  132540. static static_codebook _44c6_s_p1_0 = {
  132541. 4, 81,
  132542. _vq_lengthlist__44c6_s_p1_0,
  132543. 1, -535822336, 1611661312, 2, 0,
  132544. _vq_quantlist__44c6_s_p1_0,
  132545. NULL,
  132546. &_vq_auxt__44c6_s_p1_0,
  132547. NULL,
  132548. 0
  132549. };
  132550. static long _vq_quantlist__44c6_s_p2_0[] = {
  132551. 2,
  132552. 1,
  132553. 3,
  132554. 0,
  132555. 4,
  132556. };
  132557. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132558. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132559. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132560. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132561. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132562. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132563. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132564. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132565. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132567. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132568. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132569. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132570. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132571. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132572. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132573. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132575. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132576. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132577. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132578. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132579. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132580. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132581. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132583. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132584. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132585. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132586. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132587. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132588. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132589. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132594. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132595. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132596. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132597. 13,
  132598. };
  132599. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132600. -1.5, -0.5, 0.5, 1.5,
  132601. };
  132602. static long _vq_quantmap__44c6_s_p2_0[] = {
  132603. 3, 1, 0, 2, 4,
  132604. };
  132605. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132606. _vq_quantthresh__44c6_s_p2_0,
  132607. _vq_quantmap__44c6_s_p2_0,
  132608. 5,
  132609. 5
  132610. };
  132611. static static_codebook _44c6_s_p2_0 = {
  132612. 4, 625,
  132613. _vq_lengthlist__44c6_s_p2_0,
  132614. 1, -533725184, 1611661312, 3, 0,
  132615. _vq_quantlist__44c6_s_p2_0,
  132616. NULL,
  132617. &_vq_auxt__44c6_s_p2_0,
  132618. NULL,
  132619. 0
  132620. };
  132621. static long _vq_quantlist__44c6_s_p3_0[] = {
  132622. 4,
  132623. 3,
  132624. 5,
  132625. 2,
  132626. 6,
  132627. 1,
  132628. 7,
  132629. 0,
  132630. 8,
  132631. };
  132632. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132633. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132634. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132635. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132636. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0,
  132639. };
  132640. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132641. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132642. };
  132643. static long _vq_quantmap__44c6_s_p3_0[] = {
  132644. 7, 5, 3, 1, 0, 2, 4, 6,
  132645. 8,
  132646. };
  132647. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132648. _vq_quantthresh__44c6_s_p3_0,
  132649. _vq_quantmap__44c6_s_p3_0,
  132650. 9,
  132651. 9
  132652. };
  132653. static static_codebook _44c6_s_p3_0 = {
  132654. 2, 81,
  132655. _vq_lengthlist__44c6_s_p3_0,
  132656. 1, -531628032, 1611661312, 4, 0,
  132657. _vq_quantlist__44c6_s_p3_0,
  132658. NULL,
  132659. &_vq_auxt__44c6_s_p3_0,
  132660. NULL,
  132661. 0
  132662. };
  132663. static long _vq_quantlist__44c6_s_p4_0[] = {
  132664. 8,
  132665. 7,
  132666. 9,
  132667. 6,
  132668. 10,
  132669. 5,
  132670. 11,
  132671. 4,
  132672. 12,
  132673. 3,
  132674. 13,
  132675. 2,
  132676. 14,
  132677. 1,
  132678. 15,
  132679. 0,
  132680. 16,
  132681. };
  132682. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132683. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132684. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132685. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132686. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132687. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132688. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132689. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132690. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132691. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132692. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132701. 0,
  132702. };
  132703. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132704. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132705. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132706. };
  132707. static long _vq_quantmap__44c6_s_p4_0[] = {
  132708. 15, 13, 11, 9, 7, 5, 3, 1,
  132709. 0, 2, 4, 6, 8, 10, 12, 14,
  132710. 16,
  132711. };
  132712. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132713. _vq_quantthresh__44c6_s_p4_0,
  132714. _vq_quantmap__44c6_s_p4_0,
  132715. 17,
  132716. 17
  132717. };
  132718. static static_codebook _44c6_s_p4_0 = {
  132719. 2, 289,
  132720. _vq_lengthlist__44c6_s_p4_0,
  132721. 1, -529530880, 1611661312, 5, 0,
  132722. _vq_quantlist__44c6_s_p4_0,
  132723. NULL,
  132724. &_vq_auxt__44c6_s_p4_0,
  132725. NULL,
  132726. 0
  132727. };
  132728. static long _vq_quantlist__44c6_s_p5_0[] = {
  132729. 1,
  132730. 0,
  132731. 2,
  132732. };
  132733. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132734. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132735. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132736. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132737. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132738. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132739. 12,
  132740. };
  132741. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132742. -5.5, 5.5,
  132743. };
  132744. static long _vq_quantmap__44c6_s_p5_0[] = {
  132745. 1, 0, 2,
  132746. };
  132747. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132748. _vq_quantthresh__44c6_s_p5_0,
  132749. _vq_quantmap__44c6_s_p5_0,
  132750. 3,
  132751. 3
  132752. };
  132753. static static_codebook _44c6_s_p5_0 = {
  132754. 4, 81,
  132755. _vq_lengthlist__44c6_s_p5_0,
  132756. 1, -529137664, 1618345984, 2, 0,
  132757. _vq_quantlist__44c6_s_p5_0,
  132758. NULL,
  132759. &_vq_auxt__44c6_s_p5_0,
  132760. NULL,
  132761. 0
  132762. };
  132763. static long _vq_quantlist__44c6_s_p5_1[] = {
  132764. 5,
  132765. 4,
  132766. 6,
  132767. 3,
  132768. 7,
  132769. 2,
  132770. 8,
  132771. 1,
  132772. 9,
  132773. 0,
  132774. 10,
  132775. };
  132776. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132777. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132778. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132779. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132780. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132781. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132782. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132783. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132784. 11,10,10, 7, 7, 8, 8, 8, 8,
  132785. };
  132786. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132787. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132788. 3.5, 4.5,
  132789. };
  132790. static long _vq_quantmap__44c6_s_p5_1[] = {
  132791. 9, 7, 5, 3, 1, 0, 2, 4,
  132792. 6, 8, 10,
  132793. };
  132794. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132795. _vq_quantthresh__44c6_s_p5_1,
  132796. _vq_quantmap__44c6_s_p5_1,
  132797. 11,
  132798. 11
  132799. };
  132800. static static_codebook _44c6_s_p5_1 = {
  132801. 2, 121,
  132802. _vq_lengthlist__44c6_s_p5_1,
  132803. 1, -531365888, 1611661312, 4, 0,
  132804. _vq_quantlist__44c6_s_p5_1,
  132805. NULL,
  132806. &_vq_auxt__44c6_s_p5_1,
  132807. NULL,
  132808. 0
  132809. };
  132810. static long _vq_quantlist__44c6_s_p6_0[] = {
  132811. 6,
  132812. 5,
  132813. 7,
  132814. 4,
  132815. 8,
  132816. 3,
  132817. 9,
  132818. 2,
  132819. 10,
  132820. 1,
  132821. 11,
  132822. 0,
  132823. 12,
  132824. };
  132825. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132826. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132827. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132828. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132829. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132830. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132831. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132836. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132837. };
  132838. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132839. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132840. 12.5, 17.5, 22.5, 27.5,
  132841. };
  132842. static long _vq_quantmap__44c6_s_p6_0[] = {
  132843. 11, 9, 7, 5, 3, 1, 0, 2,
  132844. 4, 6, 8, 10, 12,
  132845. };
  132846. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132847. _vq_quantthresh__44c6_s_p6_0,
  132848. _vq_quantmap__44c6_s_p6_0,
  132849. 13,
  132850. 13
  132851. };
  132852. static static_codebook _44c6_s_p6_0 = {
  132853. 2, 169,
  132854. _vq_lengthlist__44c6_s_p6_0,
  132855. 1, -526516224, 1616117760, 4, 0,
  132856. _vq_quantlist__44c6_s_p6_0,
  132857. NULL,
  132858. &_vq_auxt__44c6_s_p6_0,
  132859. NULL,
  132860. 0
  132861. };
  132862. static long _vq_quantlist__44c6_s_p6_1[] = {
  132863. 2,
  132864. 1,
  132865. 3,
  132866. 0,
  132867. 4,
  132868. };
  132869. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132870. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132871. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132872. };
  132873. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132874. -1.5, -0.5, 0.5, 1.5,
  132875. };
  132876. static long _vq_quantmap__44c6_s_p6_1[] = {
  132877. 3, 1, 0, 2, 4,
  132878. };
  132879. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132880. _vq_quantthresh__44c6_s_p6_1,
  132881. _vq_quantmap__44c6_s_p6_1,
  132882. 5,
  132883. 5
  132884. };
  132885. static static_codebook _44c6_s_p6_1 = {
  132886. 2, 25,
  132887. _vq_lengthlist__44c6_s_p6_1,
  132888. 1, -533725184, 1611661312, 3, 0,
  132889. _vq_quantlist__44c6_s_p6_1,
  132890. NULL,
  132891. &_vq_auxt__44c6_s_p6_1,
  132892. NULL,
  132893. 0
  132894. };
  132895. static long _vq_quantlist__44c6_s_p7_0[] = {
  132896. 6,
  132897. 5,
  132898. 7,
  132899. 4,
  132900. 8,
  132901. 3,
  132902. 9,
  132903. 2,
  132904. 10,
  132905. 1,
  132906. 11,
  132907. 0,
  132908. 12,
  132909. };
  132910. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132911. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132912. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132913. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132914. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132915. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132916. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132917. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132918. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132919. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132920. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132921. 20,13,13,13,13,13,13,14,14,
  132922. };
  132923. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132924. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132925. 27.5, 38.5, 49.5, 60.5,
  132926. };
  132927. static long _vq_quantmap__44c6_s_p7_0[] = {
  132928. 11, 9, 7, 5, 3, 1, 0, 2,
  132929. 4, 6, 8, 10, 12,
  132930. };
  132931. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132932. _vq_quantthresh__44c6_s_p7_0,
  132933. _vq_quantmap__44c6_s_p7_0,
  132934. 13,
  132935. 13
  132936. };
  132937. static static_codebook _44c6_s_p7_0 = {
  132938. 2, 169,
  132939. _vq_lengthlist__44c6_s_p7_0,
  132940. 1, -523206656, 1618345984, 4, 0,
  132941. _vq_quantlist__44c6_s_p7_0,
  132942. NULL,
  132943. &_vq_auxt__44c6_s_p7_0,
  132944. NULL,
  132945. 0
  132946. };
  132947. static long _vq_quantlist__44c6_s_p7_1[] = {
  132948. 5,
  132949. 4,
  132950. 6,
  132951. 3,
  132952. 7,
  132953. 2,
  132954. 8,
  132955. 1,
  132956. 9,
  132957. 0,
  132958. 10,
  132959. };
  132960. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132961. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132962. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132963. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132964. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132965. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132966. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132967. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132968. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132969. };
  132970. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132971. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132972. 3.5, 4.5,
  132973. };
  132974. static long _vq_quantmap__44c6_s_p7_1[] = {
  132975. 9, 7, 5, 3, 1, 0, 2, 4,
  132976. 6, 8, 10,
  132977. };
  132978. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132979. _vq_quantthresh__44c6_s_p7_1,
  132980. _vq_quantmap__44c6_s_p7_1,
  132981. 11,
  132982. 11
  132983. };
  132984. static static_codebook _44c6_s_p7_1 = {
  132985. 2, 121,
  132986. _vq_lengthlist__44c6_s_p7_1,
  132987. 1, -531365888, 1611661312, 4, 0,
  132988. _vq_quantlist__44c6_s_p7_1,
  132989. NULL,
  132990. &_vq_auxt__44c6_s_p7_1,
  132991. NULL,
  132992. 0
  132993. };
  132994. static long _vq_quantlist__44c6_s_p8_0[] = {
  132995. 7,
  132996. 6,
  132997. 8,
  132998. 5,
  132999. 9,
  133000. 4,
  133001. 10,
  133002. 3,
  133003. 11,
  133004. 2,
  133005. 12,
  133006. 1,
  133007. 13,
  133008. 0,
  133009. 14,
  133010. };
  133011. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133012. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133013. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133014. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133015. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133016. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133017. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133018. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133019. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133020. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133021. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133022. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133023. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133024. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133025. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133026. 14,
  133027. };
  133028. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133029. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133030. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133031. };
  133032. static long _vq_quantmap__44c6_s_p8_0[] = {
  133033. 13, 11, 9, 7, 5, 3, 1, 0,
  133034. 2, 4, 6, 8, 10, 12, 14,
  133035. };
  133036. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133037. _vq_quantthresh__44c6_s_p8_0,
  133038. _vq_quantmap__44c6_s_p8_0,
  133039. 15,
  133040. 15
  133041. };
  133042. static static_codebook _44c6_s_p8_0 = {
  133043. 2, 225,
  133044. _vq_lengthlist__44c6_s_p8_0,
  133045. 1, -520986624, 1620377600, 4, 0,
  133046. _vq_quantlist__44c6_s_p8_0,
  133047. NULL,
  133048. &_vq_auxt__44c6_s_p8_0,
  133049. NULL,
  133050. 0
  133051. };
  133052. static long _vq_quantlist__44c6_s_p8_1[] = {
  133053. 10,
  133054. 9,
  133055. 11,
  133056. 8,
  133057. 12,
  133058. 7,
  133059. 13,
  133060. 6,
  133061. 14,
  133062. 5,
  133063. 15,
  133064. 4,
  133065. 16,
  133066. 3,
  133067. 17,
  133068. 2,
  133069. 18,
  133070. 1,
  133071. 19,
  133072. 0,
  133073. 20,
  133074. };
  133075. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133076. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133077. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133079. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133080. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133081. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133082. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133084. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133085. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133086. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133087. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133088. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133089. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133090. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133091. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133092. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133093. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133094. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133095. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133096. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133097. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133098. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133099. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133100. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133101. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133102. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133103. 10,10,10,10,10,10,10,10,10,
  133104. };
  133105. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133106. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133107. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133108. 6.5, 7.5, 8.5, 9.5,
  133109. };
  133110. static long _vq_quantmap__44c6_s_p8_1[] = {
  133111. 19, 17, 15, 13, 11, 9, 7, 5,
  133112. 3, 1, 0, 2, 4, 6, 8, 10,
  133113. 12, 14, 16, 18, 20,
  133114. };
  133115. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133116. _vq_quantthresh__44c6_s_p8_1,
  133117. _vq_quantmap__44c6_s_p8_1,
  133118. 21,
  133119. 21
  133120. };
  133121. static static_codebook _44c6_s_p8_1 = {
  133122. 2, 441,
  133123. _vq_lengthlist__44c6_s_p8_1,
  133124. 1, -529268736, 1611661312, 5, 0,
  133125. _vq_quantlist__44c6_s_p8_1,
  133126. NULL,
  133127. &_vq_auxt__44c6_s_p8_1,
  133128. NULL,
  133129. 0
  133130. };
  133131. static long _vq_quantlist__44c6_s_p9_0[] = {
  133132. 6,
  133133. 5,
  133134. 7,
  133135. 4,
  133136. 8,
  133137. 3,
  133138. 9,
  133139. 2,
  133140. 10,
  133141. 1,
  133142. 11,
  133143. 0,
  133144. 12,
  133145. };
  133146. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133147. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133148. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133150. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133151. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133152. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133153. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133154. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133155. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133156. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133157. 10,10,10,10,10,10,10,10,10,
  133158. };
  133159. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133160. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133161. 1592.5, 2229.5, 2866.5, 3503.5,
  133162. };
  133163. static long _vq_quantmap__44c6_s_p9_0[] = {
  133164. 11, 9, 7, 5, 3, 1, 0, 2,
  133165. 4, 6, 8, 10, 12,
  133166. };
  133167. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133168. _vq_quantthresh__44c6_s_p9_0,
  133169. _vq_quantmap__44c6_s_p9_0,
  133170. 13,
  133171. 13
  133172. };
  133173. static static_codebook _44c6_s_p9_0 = {
  133174. 2, 169,
  133175. _vq_lengthlist__44c6_s_p9_0,
  133176. 1, -511845376, 1630791680, 4, 0,
  133177. _vq_quantlist__44c6_s_p9_0,
  133178. NULL,
  133179. &_vq_auxt__44c6_s_p9_0,
  133180. NULL,
  133181. 0
  133182. };
  133183. static long _vq_quantlist__44c6_s_p9_1[] = {
  133184. 6,
  133185. 5,
  133186. 7,
  133187. 4,
  133188. 8,
  133189. 3,
  133190. 9,
  133191. 2,
  133192. 10,
  133193. 1,
  133194. 11,
  133195. 0,
  133196. 12,
  133197. };
  133198. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133199. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133200. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133201. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133202. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133203. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133204. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133205. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133206. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133207. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133208. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133209. 15,12,10,11,11,13,11,12,13,
  133210. };
  133211. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133212. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133213. 122.5, 171.5, 220.5, 269.5,
  133214. };
  133215. static long _vq_quantmap__44c6_s_p9_1[] = {
  133216. 11, 9, 7, 5, 3, 1, 0, 2,
  133217. 4, 6, 8, 10, 12,
  133218. };
  133219. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133220. _vq_quantthresh__44c6_s_p9_1,
  133221. _vq_quantmap__44c6_s_p9_1,
  133222. 13,
  133223. 13
  133224. };
  133225. static static_codebook _44c6_s_p9_1 = {
  133226. 2, 169,
  133227. _vq_lengthlist__44c6_s_p9_1,
  133228. 1, -518889472, 1622704128, 4, 0,
  133229. _vq_quantlist__44c6_s_p9_1,
  133230. NULL,
  133231. &_vq_auxt__44c6_s_p9_1,
  133232. NULL,
  133233. 0
  133234. };
  133235. static long _vq_quantlist__44c6_s_p9_2[] = {
  133236. 24,
  133237. 23,
  133238. 25,
  133239. 22,
  133240. 26,
  133241. 21,
  133242. 27,
  133243. 20,
  133244. 28,
  133245. 19,
  133246. 29,
  133247. 18,
  133248. 30,
  133249. 17,
  133250. 31,
  133251. 16,
  133252. 32,
  133253. 15,
  133254. 33,
  133255. 14,
  133256. 34,
  133257. 13,
  133258. 35,
  133259. 12,
  133260. 36,
  133261. 11,
  133262. 37,
  133263. 10,
  133264. 38,
  133265. 9,
  133266. 39,
  133267. 8,
  133268. 40,
  133269. 7,
  133270. 41,
  133271. 6,
  133272. 42,
  133273. 5,
  133274. 43,
  133275. 4,
  133276. 44,
  133277. 3,
  133278. 45,
  133279. 2,
  133280. 46,
  133281. 1,
  133282. 47,
  133283. 0,
  133284. 48,
  133285. };
  133286. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133287. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133288. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133289. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133290. 7,
  133291. };
  133292. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133293. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133294. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133295. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133296. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133297. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133298. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133299. };
  133300. static long _vq_quantmap__44c6_s_p9_2[] = {
  133301. 47, 45, 43, 41, 39, 37, 35, 33,
  133302. 31, 29, 27, 25, 23, 21, 19, 17,
  133303. 15, 13, 11, 9, 7, 5, 3, 1,
  133304. 0, 2, 4, 6, 8, 10, 12, 14,
  133305. 16, 18, 20, 22, 24, 26, 28, 30,
  133306. 32, 34, 36, 38, 40, 42, 44, 46,
  133307. 48,
  133308. };
  133309. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133310. _vq_quantthresh__44c6_s_p9_2,
  133311. _vq_quantmap__44c6_s_p9_2,
  133312. 49,
  133313. 49
  133314. };
  133315. static static_codebook _44c6_s_p9_2 = {
  133316. 1, 49,
  133317. _vq_lengthlist__44c6_s_p9_2,
  133318. 1, -526909440, 1611661312, 6, 0,
  133319. _vq_quantlist__44c6_s_p9_2,
  133320. NULL,
  133321. &_vq_auxt__44c6_s_p9_2,
  133322. NULL,
  133323. 0
  133324. };
  133325. static long _huff_lengthlist__44c6_s_short[] = {
  133326. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133327. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133328. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133329. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133330. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133331. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133332. 9,10,17,18,
  133333. };
  133334. static static_codebook _huff_book__44c6_s_short = {
  133335. 2, 100,
  133336. _huff_lengthlist__44c6_s_short,
  133337. 0, 0, 0, 0, 0,
  133338. NULL,
  133339. NULL,
  133340. NULL,
  133341. NULL,
  133342. 0
  133343. };
  133344. static long _huff_lengthlist__44c7_s_long[] = {
  133345. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133346. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133347. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133348. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133349. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133350. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133351. 11,10,10,12,
  133352. };
  133353. static static_codebook _huff_book__44c7_s_long = {
  133354. 2, 100,
  133355. _huff_lengthlist__44c7_s_long,
  133356. 0, 0, 0, 0, 0,
  133357. NULL,
  133358. NULL,
  133359. NULL,
  133360. NULL,
  133361. 0
  133362. };
  133363. static long _vq_quantlist__44c7_s_p1_0[] = {
  133364. 1,
  133365. 0,
  133366. 2,
  133367. };
  133368. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133369. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133370. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133372. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133373. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133374. 8,
  133375. };
  133376. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133377. -0.5, 0.5,
  133378. };
  133379. static long _vq_quantmap__44c7_s_p1_0[] = {
  133380. 1, 0, 2,
  133381. };
  133382. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133383. _vq_quantthresh__44c7_s_p1_0,
  133384. _vq_quantmap__44c7_s_p1_0,
  133385. 3,
  133386. 3
  133387. };
  133388. static static_codebook _44c7_s_p1_0 = {
  133389. 4, 81,
  133390. _vq_lengthlist__44c7_s_p1_0,
  133391. 1, -535822336, 1611661312, 2, 0,
  133392. _vq_quantlist__44c7_s_p1_0,
  133393. NULL,
  133394. &_vq_auxt__44c7_s_p1_0,
  133395. NULL,
  133396. 0
  133397. };
  133398. static long _vq_quantlist__44c7_s_p2_0[] = {
  133399. 2,
  133400. 1,
  133401. 3,
  133402. 0,
  133403. 4,
  133404. };
  133405. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133406. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133407. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133408. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133409. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133410. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133411. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133412. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133413. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133416. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133417. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133418. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133419. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133420. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133421. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133424. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133425. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133426. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133427. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133428. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133429. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133431. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133432. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133433. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133434. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133435. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133436. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133437. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133442. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133443. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133444. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133445. 13,
  133446. };
  133447. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133448. -1.5, -0.5, 0.5, 1.5,
  133449. };
  133450. static long _vq_quantmap__44c7_s_p2_0[] = {
  133451. 3, 1, 0, 2, 4,
  133452. };
  133453. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133454. _vq_quantthresh__44c7_s_p2_0,
  133455. _vq_quantmap__44c7_s_p2_0,
  133456. 5,
  133457. 5
  133458. };
  133459. static static_codebook _44c7_s_p2_0 = {
  133460. 4, 625,
  133461. _vq_lengthlist__44c7_s_p2_0,
  133462. 1, -533725184, 1611661312, 3, 0,
  133463. _vq_quantlist__44c7_s_p2_0,
  133464. NULL,
  133465. &_vq_auxt__44c7_s_p2_0,
  133466. NULL,
  133467. 0
  133468. };
  133469. static long _vq_quantlist__44c7_s_p3_0[] = {
  133470. 4,
  133471. 3,
  133472. 5,
  133473. 2,
  133474. 6,
  133475. 1,
  133476. 7,
  133477. 0,
  133478. 8,
  133479. };
  133480. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133481. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133482. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133483. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133484. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133486. 0,
  133487. };
  133488. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133489. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133490. };
  133491. static long _vq_quantmap__44c7_s_p3_0[] = {
  133492. 7, 5, 3, 1, 0, 2, 4, 6,
  133493. 8,
  133494. };
  133495. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133496. _vq_quantthresh__44c7_s_p3_0,
  133497. _vq_quantmap__44c7_s_p3_0,
  133498. 9,
  133499. 9
  133500. };
  133501. static static_codebook _44c7_s_p3_0 = {
  133502. 2, 81,
  133503. _vq_lengthlist__44c7_s_p3_0,
  133504. 1, -531628032, 1611661312, 4, 0,
  133505. _vq_quantlist__44c7_s_p3_0,
  133506. NULL,
  133507. &_vq_auxt__44c7_s_p3_0,
  133508. NULL,
  133509. 0
  133510. };
  133511. static long _vq_quantlist__44c7_s_p4_0[] = {
  133512. 8,
  133513. 7,
  133514. 9,
  133515. 6,
  133516. 10,
  133517. 5,
  133518. 11,
  133519. 4,
  133520. 12,
  133521. 3,
  133522. 13,
  133523. 2,
  133524. 14,
  133525. 1,
  133526. 15,
  133527. 0,
  133528. 16,
  133529. };
  133530. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133531. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133532. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133533. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133534. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133535. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133536. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133537. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133538. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133539. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133540. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133549. 0,
  133550. };
  133551. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133552. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133553. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133554. };
  133555. static long _vq_quantmap__44c7_s_p4_0[] = {
  133556. 15, 13, 11, 9, 7, 5, 3, 1,
  133557. 0, 2, 4, 6, 8, 10, 12, 14,
  133558. 16,
  133559. };
  133560. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133561. _vq_quantthresh__44c7_s_p4_0,
  133562. _vq_quantmap__44c7_s_p4_0,
  133563. 17,
  133564. 17
  133565. };
  133566. static static_codebook _44c7_s_p4_0 = {
  133567. 2, 289,
  133568. _vq_lengthlist__44c7_s_p4_0,
  133569. 1, -529530880, 1611661312, 5, 0,
  133570. _vq_quantlist__44c7_s_p4_0,
  133571. NULL,
  133572. &_vq_auxt__44c7_s_p4_0,
  133573. NULL,
  133574. 0
  133575. };
  133576. static long _vq_quantlist__44c7_s_p5_0[] = {
  133577. 1,
  133578. 0,
  133579. 2,
  133580. };
  133581. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133582. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133583. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133584. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133585. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133586. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133587. 12,
  133588. };
  133589. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133590. -5.5, 5.5,
  133591. };
  133592. static long _vq_quantmap__44c7_s_p5_0[] = {
  133593. 1, 0, 2,
  133594. };
  133595. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133596. _vq_quantthresh__44c7_s_p5_0,
  133597. _vq_quantmap__44c7_s_p5_0,
  133598. 3,
  133599. 3
  133600. };
  133601. static static_codebook _44c7_s_p5_0 = {
  133602. 4, 81,
  133603. _vq_lengthlist__44c7_s_p5_0,
  133604. 1, -529137664, 1618345984, 2, 0,
  133605. _vq_quantlist__44c7_s_p5_0,
  133606. NULL,
  133607. &_vq_auxt__44c7_s_p5_0,
  133608. NULL,
  133609. 0
  133610. };
  133611. static long _vq_quantlist__44c7_s_p5_1[] = {
  133612. 5,
  133613. 4,
  133614. 6,
  133615. 3,
  133616. 7,
  133617. 2,
  133618. 8,
  133619. 1,
  133620. 9,
  133621. 0,
  133622. 10,
  133623. };
  133624. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133625. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133626. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133627. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133628. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133629. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133630. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133631. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133632. 11,11,11, 7, 7, 8, 8, 8, 8,
  133633. };
  133634. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133635. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133636. 3.5, 4.5,
  133637. };
  133638. static long _vq_quantmap__44c7_s_p5_1[] = {
  133639. 9, 7, 5, 3, 1, 0, 2, 4,
  133640. 6, 8, 10,
  133641. };
  133642. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133643. _vq_quantthresh__44c7_s_p5_1,
  133644. _vq_quantmap__44c7_s_p5_1,
  133645. 11,
  133646. 11
  133647. };
  133648. static static_codebook _44c7_s_p5_1 = {
  133649. 2, 121,
  133650. _vq_lengthlist__44c7_s_p5_1,
  133651. 1, -531365888, 1611661312, 4, 0,
  133652. _vq_quantlist__44c7_s_p5_1,
  133653. NULL,
  133654. &_vq_auxt__44c7_s_p5_1,
  133655. NULL,
  133656. 0
  133657. };
  133658. static long _vq_quantlist__44c7_s_p6_0[] = {
  133659. 6,
  133660. 5,
  133661. 7,
  133662. 4,
  133663. 8,
  133664. 3,
  133665. 9,
  133666. 2,
  133667. 10,
  133668. 1,
  133669. 11,
  133670. 0,
  133671. 12,
  133672. };
  133673. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133674. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133675. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133676. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133677. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133678. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133679. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133684. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133685. };
  133686. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133687. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133688. 12.5, 17.5, 22.5, 27.5,
  133689. };
  133690. static long _vq_quantmap__44c7_s_p6_0[] = {
  133691. 11, 9, 7, 5, 3, 1, 0, 2,
  133692. 4, 6, 8, 10, 12,
  133693. };
  133694. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133695. _vq_quantthresh__44c7_s_p6_0,
  133696. _vq_quantmap__44c7_s_p6_0,
  133697. 13,
  133698. 13
  133699. };
  133700. static static_codebook _44c7_s_p6_0 = {
  133701. 2, 169,
  133702. _vq_lengthlist__44c7_s_p6_0,
  133703. 1, -526516224, 1616117760, 4, 0,
  133704. _vq_quantlist__44c7_s_p6_0,
  133705. NULL,
  133706. &_vq_auxt__44c7_s_p6_0,
  133707. NULL,
  133708. 0
  133709. };
  133710. static long _vq_quantlist__44c7_s_p6_1[] = {
  133711. 2,
  133712. 1,
  133713. 3,
  133714. 0,
  133715. 4,
  133716. };
  133717. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133718. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133719. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133720. };
  133721. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133722. -1.5, -0.5, 0.5, 1.5,
  133723. };
  133724. static long _vq_quantmap__44c7_s_p6_1[] = {
  133725. 3, 1, 0, 2, 4,
  133726. };
  133727. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133728. _vq_quantthresh__44c7_s_p6_1,
  133729. _vq_quantmap__44c7_s_p6_1,
  133730. 5,
  133731. 5
  133732. };
  133733. static static_codebook _44c7_s_p6_1 = {
  133734. 2, 25,
  133735. _vq_lengthlist__44c7_s_p6_1,
  133736. 1, -533725184, 1611661312, 3, 0,
  133737. _vq_quantlist__44c7_s_p6_1,
  133738. NULL,
  133739. &_vq_auxt__44c7_s_p6_1,
  133740. NULL,
  133741. 0
  133742. };
  133743. static long _vq_quantlist__44c7_s_p7_0[] = {
  133744. 6,
  133745. 5,
  133746. 7,
  133747. 4,
  133748. 8,
  133749. 3,
  133750. 9,
  133751. 2,
  133752. 10,
  133753. 1,
  133754. 11,
  133755. 0,
  133756. 12,
  133757. };
  133758. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133759. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133760. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133761. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133762. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133763. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133764. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133765. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133766. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133767. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133768. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133769. 19,13,13,13,13,14,14,15,15,
  133770. };
  133771. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133772. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133773. 27.5, 38.5, 49.5, 60.5,
  133774. };
  133775. static long _vq_quantmap__44c7_s_p7_0[] = {
  133776. 11, 9, 7, 5, 3, 1, 0, 2,
  133777. 4, 6, 8, 10, 12,
  133778. };
  133779. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133780. _vq_quantthresh__44c7_s_p7_0,
  133781. _vq_quantmap__44c7_s_p7_0,
  133782. 13,
  133783. 13
  133784. };
  133785. static static_codebook _44c7_s_p7_0 = {
  133786. 2, 169,
  133787. _vq_lengthlist__44c7_s_p7_0,
  133788. 1, -523206656, 1618345984, 4, 0,
  133789. _vq_quantlist__44c7_s_p7_0,
  133790. NULL,
  133791. &_vq_auxt__44c7_s_p7_0,
  133792. NULL,
  133793. 0
  133794. };
  133795. static long _vq_quantlist__44c7_s_p7_1[] = {
  133796. 5,
  133797. 4,
  133798. 6,
  133799. 3,
  133800. 7,
  133801. 2,
  133802. 8,
  133803. 1,
  133804. 9,
  133805. 0,
  133806. 10,
  133807. };
  133808. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133809. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133810. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133811. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133812. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133813. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133814. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133815. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133816. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133817. };
  133818. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133819. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133820. 3.5, 4.5,
  133821. };
  133822. static long _vq_quantmap__44c7_s_p7_1[] = {
  133823. 9, 7, 5, 3, 1, 0, 2, 4,
  133824. 6, 8, 10,
  133825. };
  133826. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133827. _vq_quantthresh__44c7_s_p7_1,
  133828. _vq_quantmap__44c7_s_p7_1,
  133829. 11,
  133830. 11
  133831. };
  133832. static static_codebook _44c7_s_p7_1 = {
  133833. 2, 121,
  133834. _vq_lengthlist__44c7_s_p7_1,
  133835. 1, -531365888, 1611661312, 4, 0,
  133836. _vq_quantlist__44c7_s_p7_1,
  133837. NULL,
  133838. &_vq_auxt__44c7_s_p7_1,
  133839. NULL,
  133840. 0
  133841. };
  133842. static long _vq_quantlist__44c7_s_p8_0[] = {
  133843. 7,
  133844. 6,
  133845. 8,
  133846. 5,
  133847. 9,
  133848. 4,
  133849. 10,
  133850. 3,
  133851. 11,
  133852. 2,
  133853. 12,
  133854. 1,
  133855. 13,
  133856. 0,
  133857. 14,
  133858. };
  133859. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133860. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133861. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133862. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133863. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133864. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133865. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133866. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133867. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133868. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133869. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133870. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133871. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133872. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133873. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133874. 14,
  133875. };
  133876. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133877. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133878. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133879. };
  133880. static long _vq_quantmap__44c7_s_p8_0[] = {
  133881. 13, 11, 9, 7, 5, 3, 1, 0,
  133882. 2, 4, 6, 8, 10, 12, 14,
  133883. };
  133884. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133885. _vq_quantthresh__44c7_s_p8_0,
  133886. _vq_quantmap__44c7_s_p8_0,
  133887. 15,
  133888. 15
  133889. };
  133890. static static_codebook _44c7_s_p8_0 = {
  133891. 2, 225,
  133892. _vq_lengthlist__44c7_s_p8_0,
  133893. 1, -520986624, 1620377600, 4, 0,
  133894. _vq_quantlist__44c7_s_p8_0,
  133895. NULL,
  133896. &_vq_auxt__44c7_s_p8_0,
  133897. NULL,
  133898. 0
  133899. };
  133900. static long _vq_quantlist__44c7_s_p8_1[] = {
  133901. 10,
  133902. 9,
  133903. 11,
  133904. 8,
  133905. 12,
  133906. 7,
  133907. 13,
  133908. 6,
  133909. 14,
  133910. 5,
  133911. 15,
  133912. 4,
  133913. 16,
  133914. 3,
  133915. 17,
  133916. 2,
  133917. 18,
  133918. 1,
  133919. 19,
  133920. 0,
  133921. 20,
  133922. };
  133923. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133924. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133925. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133926. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133927. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133928. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133929. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133930. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133931. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133932. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133933. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133934. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133935. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133936. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133937. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133938. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133939. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133940. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133941. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133942. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133943. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133944. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133945. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133946. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133947. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133948. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133949. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133950. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133951. 10,10,10,10,10,10,10,10,10,
  133952. };
  133953. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133954. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133955. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133956. 6.5, 7.5, 8.5, 9.5,
  133957. };
  133958. static long _vq_quantmap__44c7_s_p8_1[] = {
  133959. 19, 17, 15, 13, 11, 9, 7, 5,
  133960. 3, 1, 0, 2, 4, 6, 8, 10,
  133961. 12, 14, 16, 18, 20,
  133962. };
  133963. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133964. _vq_quantthresh__44c7_s_p8_1,
  133965. _vq_quantmap__44c7_s_p8_1,
  133966. 21,
  133967. 21
  133968. };
  133969. static static_codebook _44c7_s_p8_1 = {
  133970. 2, 441,
  133971. _vq_lengthlist__44c7_s_p8_1,
  133972. 1, -529268736, 1611661312, 5, 0,
  133973. _vq_quantlist__44c7_s_p8_1,
  133974. NULL,
  133975. &_vq_auxt__44c7_s_p8_1,
  133976. NULL,
  133977. 0
  133978. };
  133979. static long _vq_quantlist__44c7_s_p9_0[] = {
  133980. 6,
  133981. 5,
  133982. 7,
  133983. 4,
  133984. 8,
  133985. 3,
  133986. 9,
  133987. 2,
  133988. 10,
  133989. 1,
  133990. 11,
  133991. 0,
  133992. 12,
  133993. };
  133994. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133995. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133996. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134005. 11,11,11,11,11,11,11,11,11,
  134006. };
  134007. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134008. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134009. 1592.5, 2229.5, 2866.5, 3503.5,
  134010. };
  134011. static long _vq_quantmap__44c7_s_p9_0[] = {
  134012. 11, 9, 7, 5, 3, 1, 0, 2,
  134013. 4, 6, 8, 10, 12,
  134014. };
  134015. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134016. _vq_quantthresh__44c7_s_p9_0,
  134017. _vq_quantmap__44c7_s_p9_0,
  134018. 13,
  134019. 13
  134020. };
  134021. static static_codebook _44c7_s_p9_0 = {
  134022. 2, 169,
  134023. _vq_lengthlist__44c7_s_p9_0,
  134024. 1, -511845376, 1630791680, 4, 0,
  134025. _vq_quantlist__44c7_s_p9_0,
  134026. NULL,
  134027. &_vq_auxt__44c7_s_p9_0,
  134028. NULL,
  134029. 0
  134030. };
  134031. static long _vq_quantlist__44c7_s_p9_1[] = {
  134032. 6,
  134033. 5,
  134034. 7,
  134035. 4,
  134036. 8,
  134037. 3,
  134038. 9,
  134039. 2,
  134040. 10,
  134041. 1,
  134042. 11,
  134043. 0,
  134044. 12,
  134045. };
  134046. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134047. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134048. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134049. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134050. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134051. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134052. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134053. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134054. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134055. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134056. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134057. 15,11,11,10,10,12,12,12,12,
  134058. };
  134059. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134060. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134061. 122.5, 171.5, 220.5, 269.5,
  134062. };
  134063. static long _vq_quantmap__44c7_s_p9_1[] = {
  134064. 11, 9, 7, 5, 3, 1, 0, 2,
  134065. 4, 6, 8, 10, 12,
  134066. };
  134067. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134068. _vq_quantthresh__44c7_s_p9_1,
  134069. _vq_quantmap__44c7_s_p9_1,
  134070. 13,
  134071. 13
  134072. };
  134073. static static_codebook _44c7_s_p9_1 = {
  134074. 2, 169,
  134075. _vq_lengthlist__44c7_s_p9_1,
  134076. 1, -518889472, 1622704128, 4, 0,
  134077. _vq_quantlist__44c7_s_p9_1,
  134078. NULL,
  134079. &_vq_auxt__44c7_s_p9_1,
  134080. NULL,
  134081. 0
  134082. };
  134083. static long _vq_quantlist__44c7_s_p9_2[] = {
  134084. 24,
  134085. 23,
  134086. 25,
  134087. 22,
  134088. 26,
  134089. 21,
  134090. 27,
  134091. 20,
  134092. 28,
  134093. 19,
  134094. 29,
  134095. 18,
  134096. 30,
  134097. 17,
  134098. 31,
  134099. 16,
  134100. 32,
  134101. 15,
  134102. 33,
  134103. 14,
  134104. 34,
  134105. 13,
  134106. 35,
  134107. 12,
  134108. 36,
  134109. 11,
  134110. 37,
  134111. 10,
  134112. 38,
  134113. 9,
  134114. 39,
  134115. 8,
  134116. 40,
  134117. 7,
  134118. 41,
  134119. 6,
  134120. 42,
  134121. 5,
  134122. 43,
  134123. 4,
  134124. 44,
  134125. 3,
  134126. 45,
  134127. 2,
  134128. 46,
  134129. 1,
  134130. 47,
  134131. 0,
  134132. 48,
  134133. };
  134134. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134135. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134136. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134137. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134138. 7,
  134139. };
  134140. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134141. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134142. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134143. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134144. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134145. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134146. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134147. };
  134148. static long _vq_quantmap__44c7_s_p9_2[] = {
  134149. 47, 45, 43, 41, 39, 37, 35, 33,
  134150. 31, 29, 27, 25, 23, 21, 19, 17,
  134151. 15, 13, 11, 9, 7, 5, 3, 1,
  134152. 0, 2, 4, 6, 8, 10, 12, 14,
  134153. 16, 18, 20, 22, 24, 26, 28, 30,
  134154. 32, 34, 36, 38, 40, 42, 44, 46,
  134155. 48,
  134156. };
  134157. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134158. _vq_quantthresh__44c7_s_p9_2,
  134159. _vq_quantmap__44c7_s_p9_2,
  134160. 49,
  134161. 49
  134162. };
  134163. static static_codebook _44c7_s_p9_2 = {
  134164. 1, 49,
  134165. _vq_lengthlist__44c7_s_p9_2,
  134166. 1, -526909440, 1611661312, 6, 0,
  134167. _vq_quantlist__44c7_s_p9_2,
  134168. NULL,
  134169. &_vq_auxt__44c7_s_p9_2,
  134170. NULL,
  134171. 0
  134172. };
  134173. static long _huff_lengthlist__44c7_s_short[] = {
  134174. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134175. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134176. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134177. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134178. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134179. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134180. 10, 9,11,14,
  134181. };
  134182. static static_codebook _huff_book__44c7_s_short = {
  134183. 2, 100,
  134184. _huff_lengthlist__44c7_s_short,
  134185. 0, 0, 0, 0, 0,
  134186. NULL,
  134187. NULL,
  134188. NULL,
  134189. NULL,
  134190. 0
  134191. };
  134192. static long _huff_lengthlist__44c8_s_long[] = {
  134193. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134194. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134195. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134196. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134197. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134198. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134199. 11, 9, 9,10,
  134200. };
  134201. static static_codebook _huff_book__44c8_s_long = {
  134202. 2, 100,
  134203. _huff_lengthlist__44c8_s_long,
  134204. 0, 0, 0, 0, 0,
  134205. NULL,
  134206. NULL,
  134207. NULL,
  134208. NULL,
  134209. 0
  134210. };
  134211. static long _vq_quantlist__44c8_s_p1_0[] = {
  134212. 1,
  134213. 0,
  134214. 2,
  134215. };
  134216. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134217. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134218. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134220. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134221. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134222. 8,
  134223. };
  134224. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134225. -0.5, 0.5,
  134226. };
  134227. static long _vq_quantmap__44c8_s_p1_0[] = {
  134228. 1, 0, 2,
  134229. };
  134230. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134231. _vq_quantthresh__44c8_s_p1_0,
  134232. _vq_quantmap__44c8_s_p1_0,
  134233. 3,
  134234. 3
  134235. };
  134236. static static_codebook _44c8_s_p1_0 = {
  134237. 4, 81,
  134238. _vq_lengthlist__44c8_s_p1_0,
  134239. 1, -535822336, 1611661312, 2, 0,
  134240. _vq_quantlist__44c8_s_p1_0,
  134241. NULL,
  134242. &_vq_auxt__44c8_s_p1_0,
  134243. NULL,
  134244. 0
  134245. };
  134246. static long _vq_quantlist__44c8_s_p2_0[] = {
  134247. 2,
  134248. 1,
  134249. 3,
  134250. 0,
  134251. 4,
  134252. };
  134253. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134254. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134255. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134256. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134257. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134258. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134259. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134260. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134261. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134264. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134265. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134266. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134267. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134268. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134269. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134272. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134273. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134274. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134275. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134276. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134277. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134280. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134281. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134282. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134283. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134284. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134285. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134290. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134291. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134292. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134293. 13,
  134294. };
  134295. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134296. -1.5, -0.5, 0.5, 1.5,
  134297. };
  134298. static long _vq_quantmap__44c8_s_p2_0[] = {
  134299. 3, 1, 0, 2, 4,
  134300. };
  134301. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134302. _vq_quantthresh__44c8_s_p2_0,
  134303. _vq_quantmap__44c8_s_p2_0,
  134304. 5,
  134305. 5
  134306. };
  134307. static static_codebook _44c8_s_p2_0 = {
  134308. 4, 625,
  134309. _vq_lengthlist__44c8_s_p2_0,
  134310. 1, -533725184, 1611661312, 3, 0,
  134311. _vq_quantlist__44c8_s_p2_0,
  134312. NULL,
  134313. &_vq_auxt__44c8_s_p2_0,
  134314. NULL,
  134315. 0
  134316. };
  134317. static long _vq_quantlist__44c8_s_p3_0[] = {
  134318. 4,
  134319. 3,
  134320. 5,
  134321. 2,
  134322. 6,
  134323. 1,
  134324. 7,
  134325. 0,
  134326. 8,
  134327. };
  134328. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134329. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134330. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134331. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134332. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134334. 0,
  134335. };
  134336. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134337. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134338. };
  134339. static long _vq_quantmap__44c8_s_p3_0[] = {
  134340. 7, 5, 3, 1, 0, 2, 4, 6,
  134341. 8,
  134342. };
  134343. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134344. _vq_quantthresh__44c8_s_p3_0,
  134345. _vq_quantmap__44c8_s_p3_0,
  134346. 9,
  134347. 9
  134348. };
  134349. static static_codebook _44c8_s_p3_0 = {
  134350. 2, 81,
  134351. _vq_lengthlist__44c8_s_p3_0,
  134352. 1, -531628032, 1611661312, 4, 0,
  134353. _vq_quantlist__44c8_s_p3_0,
  134354. NULL,
  134355. &_vq_auxt__44c8_s_p3_0,
  134356. NULL,
  134357. 0
  134358. };
  134359. static long _vq_quantlist__44c8_s_p4_0[] = {
  134360. 8,
  134361. 7,
  134362. 9,
  134363. 6,
  134364. 10,
  134365. 5,
  134366. 11,
  134367. 4,
  134368. 12,
  134369. 3,
  134370. 13,
  134371. 2,
  134372. 14,
  134373. 1,
  134374. 15,
  134375. 0,
  134376. 16,
  134377. };
  134378. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134379. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134380. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134381. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134382. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134383. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134384. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134385. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134386. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134387. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134388. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134397. 0,
  134398. };
  134399. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134400. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134401. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134402. };
  134403. static long _vq_quantmap__44c8_s_p4_0[] = {
  134404. 15, 13, 11, 9, 7, 5, 3, 1,
  134405. 0, 2, 4, 6, 8, 10, 12, 14,
  134406. 16,
  134407. };
  134408. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134409. _vq_quantthresh__44c8_s_p4_0,
  134410. _vq_quantmap__44c8_s_p4_0,
  134411. 17,
  134412. 17
  134413. };
  134414. static static_codebook _44c8_s_p4_0 = {
  134415. 2, 289,
  134416. _vq_lengthlist__44c8_s_p4_0,
  134417. 1, -529530880, 1611661312, 5, 0,
  134418. _vq_quantlist__44c8_s_p4_0,
  134419. NULL,
  134420. &_vq_auxt__44c8_s_p4_0,
  134421. NULL,
  134422. 0
  134423. };
  134424. static long _vq_quantlist__44c8_s_p5_0[] = {
  134425. 1,
  134426. 0,
  134427. 2,
  134428. };
  134429. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134430. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134431. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134432. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134433. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134434. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134435. 12,
  134436. };
  134437. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134438. -5.5, 5.5,
  134439. };
  134440. static long _vq_quantmap__44c8_s_p5_0[] = {
  134441. 1, 0, 2,
  134442. };
  134443. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134444. _vq_quantthresh__44c8_s_p5_0,
  134445. _vq_quantmap__44c8_s_p5_0,
  134446. 3,
  134447. 3
  134448. };
  134449. static static_codebook _44c8_s_p5_0 = {
  134450. 4, 81,
  134451. _vq_lengthlist__44c8_s_p5_0,
  134452. 1, -529137664, 1618345984, 2, 0,
  134453. _vq_quantlist__44c8_s_p5_0,
  134454. NULL,
  134455. &_vq_auxt__44c8_s_p5_0,
  134456. NULL,
  134457. 0
  134458. };
  134459. static long _vq_quantlist__44c8_s_p5_1[] = {
  134460. 5,
  134461. 4,
  134462. 6,
  134463. 3,
  134464. 7,
  134465. 2,
  134466. 8,
  134467. 1,
  134468. 9,
  134469. 0,
  134470. 10,
  134471. };
  134472. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134473. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134474. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134475. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134476. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134477. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134478. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134479. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134480. 11,11,11, 7, 7, 7, 7, 8, 8,
  134481. };
  134482. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134483. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134484. 3.5, 4.5,
  134485. };
  134486. static long _vq_quantmap__44c8_s_p5_1[] = {
  134487. 9, 7, 5, 3, 1, 0, 2, 4,
  134488. 6, 8, 10,
  134489. };
  134490. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134491. _vq_quantthresh__44c8_s_p5_1,
  134492. _vq_quantmap__44c8_s_p5_1,
  134493. 11,
  134494. 11
  134495. };
  134496. static static_codebook _44c8_s_p5_1 = {
  134497. 2, 121,
  134498. _vq_lengthlist__44c8_s_p5_1,
  134499. 1, -531365888, 1611661312, 4, 0,
  134500. _vq_quantlist__44c8_s_p5_1,
  134501. NULL,
  134502. &_vq_auxt__44c8_s_p5_1,
  134503. NULL,
  134504. 0
  134505. };
  134506. static long _vq_quantlist__44c8_s_p6_0[] = {
  134507. 6,
  134508. 5,
  134509. 7,
  134510. 4,
  134511. 8,
  134512. 3,
  134513. 9,
  134514. 2,
  134515. 10,
  134516. 1,
  134517. 11,
  134518. 0,
  134519. 12,
  134520. };
  134521. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134522. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134523. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134524. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134525. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134526. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134527. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134532. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134533. };
  134534. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134535. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134536. 12.5, 17.5, 22.5, 27.5,
  134537. };
  134538. static long _vq_quantmap__44c8_s_p6_0[] = {
  134539. 11, 9, 7, 5, 3, 1, 0, 2,
  134540. 4, 6, 8, 10, 12,
  134541. };
  134542. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134543. _vq_quantthresh__44c8_s_p6_0,
  134544. _vq_quantmap__44c8_s_p6_0,
  134545. 13,
  134546. 13
  134547. };
  134548. static static_codebook _44c8_s_p6_0 = {
  134549. 2, 169,
  134550. _vq_lengthlist__44c8_s_p6_0,
  134551. 1, -526516224, 1616117760, 4, 0,
  134552. _vq_quantlist__44c8_s_p6_0,
  134553. NULL,
  134554. &_vq_auxt__44c8_s_p6_0,
  134555. NULL,
  134556. 0
  134557. };
  134558. static long _vq_quantlist__44c8_s_p6_1[] = {
  134559. 2,
  134560. 1,
  134561. 3,
  134562. 0,
  134563. 4,
  134564. };
  134565. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134566. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134567. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134568. };
  134569. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134570. -1.5, -0.5, 0.5, 1.5,
  134571. };
  134572. static long _vq_quantmap__44c8_s_p6_1[] = {
  134573. 3, 1, 0, 2, 4,
  134574. };
  134575. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134576. _vq_quantthresh__44c8_s_p6_1,
  134577. _vq_quantmap__44c8_s_p6_1,
  134578. 5,
  134579. 5
  134580. };
  134581. static static_codebook _44c8_s_p6_1 = {
  134582. 2, 25,
  134583. _vq_lengthlist__44c8_s_p6_1,
  134584. 1, -533725184, 1611661312, 3, 0,
  134585. _vq_quantlist__44c8_s_p6_1,
  134586. NULL,
  134587. &_vq_auxt__44c8_s_p6_1,
  134588. NULL,
  134589. 0
  134590. };
  134591. static long _vq_quantlist__44c8_s_p7_0[] = {
  134592. 6,
  134593. 5,
  134594. 7,
  134595. 4,
  134596. 8,
  134597. 3,
  134598. 9,
  134599. 2,
  134600. 10,
  134601. 1,
  134602. 11,
  134603. 0,
  134604. 12,
  134605. };
  134606. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134607. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134608. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134609. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134610. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134611. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134612. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134613. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134614. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134615. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134616. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134617. 20,13,13,13,13,14,13,15,15,
  134618. };
  134619. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134620. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134621. 27.5, 38.5, 49.5, 60.5,
  134622. };
  134623. static long _vq_quantmap__44c8_s_p7_0[] = {
  134624. 11, 9, 7, 5, 3, 1, 0, 2,
  134625. 4, 6, 8, 10, 12,
  134626. };
  134627. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134628. _vq_quantthresh__44c8_s_p7_0,
  134629. _vq_quantmap__44c8_s_p7_0,
  134630. 13,
  134631. 13
  134632. };
  134633. static static_codebook _44c8_s_p7_0 = {
  134634. 2, 169,
  134635. _vq_lengthlist__44c8_s_p7_0,
  134636. 1, -523206656, 1618345984, 4, 0,
  134637. _vq_quantlist__44c8_s_p7_0,
  134638. NULL,
  134639. &_vq_auxt__44c8_s_p7_0,
  134640. NULL,
  134641. 0
  134642. };
  134643. static long _vq_quantlist__44c8_s_p7_1[] = {
  134644. 5,
  134645. 4,
  134646. 6,
  134647. 3,
  134648. 7,
  134649. 2,
  134650. 8,
  134651. 1,
  134652. 9,
  134653. 0,
  134654. 10,
  134655. };
  134656. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134657. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134658. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134659. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134660. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134661. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134662. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134663. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134664. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134665. };
  134666. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134667. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134668. 3.5, 4.5,
  134669. };
  134670. static long _vq_quantmap__44c8_s_p7_1[] = {
  134671. 9, 7, 5, 3, 1, 0, 2, 4,
  134672. 6, 8, 10,
  134673. };
  134674. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134675. _vq_quantthresh__44c8_s_p7_1,
  134676. _vq_quantmap__44c8_s_p7_1,
  134677. 11,
  134678. 11
  134679. };
  134680. static static_codebook _44c8_s_p7_1 = {
  134681. 2, 121,
  134682. _vq_lengthlist__44c8_s_p7_1,
  134683. 1, -531365888, 1611661312, 4, 0,
  134684. _vq_quantlist__44c8_s_p7_1,
  134685. NULL,
  134686. &_vq_auxt__44c8_s_p7_1,
  134687. NULL,
  134688. 0
  134689. };
  134690. static long _vq_quantlist__44c8_s_p8_0[] = {
  134691. 7,
  134692. 6,
  134693. 8,
  134694. 5,
  134695. 9,
  134696. 4,
  134697. 10,
  134698. 3,
  134699. 11,
  134700. 2,
  134701. 12,
  134702. 1,
  134703. 13,
  134704. 0,
  134705. 14,
  134706. };
  134707. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134708. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134709. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134710. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134711. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134712. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134713. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134714. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134715. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134716. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134717. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134718. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134719. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134720. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134721. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134722. 15,
  134723. };
  134724. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134725. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134726. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134727. };
  134728. static long _vq_quantmap__44c8_s_p8_0[] = {
  134729. 13, 11, 9, 7, 5, 3, 1, 0,
  134730. 2, 4, 6, 8, 10, 12, 14,
  134731. };
  134732. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134733. _vq_quantthresh__44c8_s_p8_0,
  134734. _vq_quantmap__44c8_s_p8_0,
  134735. 15,
  134736. 15
  134737. };
  134738. static static_codebook _44c8_s_p8_0 = {
  134739. 2, 225,
  134740. _vq_lengthlist__44c8_s_p8_0,
  134741. 1, -520986624, 1620377600, 4, 0,
  134742. _vq_quantlist__44c8_s_p8_0,
  134743. NULL,
  134744. &_vq_auxt__44c8_s_p8_0,
  134745. NULL,
  134746. 0
  134747. };
  134748. static long _vq_quantlist__44c8_s_p8_1[] = {
  134749. 10,
  134750. 9,
  134751. 11,
  134752. 8,
  134753. 12,
  134754. 7,
  134755. 13,
  134756. 6,
  134757. 14,
  134758. 5,
  134759. 15,
  134760. 4,
  134761. 16,
  134762. 3,
  134763. 17,
  134764. 2,
  134765. 18,
  134766. 1,
  134767. 19,
  134768. 0,
  134769. 20,
  134770. };
  134771. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134772. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134773. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134774. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134775. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134776. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134777. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134778. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134779. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134780. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134781. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134782. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134783. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134784. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134785. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134786. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134787. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134788. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134789. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134790. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134791. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134792. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134794. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134795. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134796. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134797. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134798. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134799. 10, 9, 9,10,10, 9,10, 9, 9,
  134800. };
  134801. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134802. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134803. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134804. 6.5, 7.5, 8.5, 9.5,
  134805. };
  134806. static long _vq_quantmap__44c8_s_p8_1[] = {
  134807. 19, 17, 15, 13, 11, 9, 7, 5,
  134808. 3, 1, 0, 2, 4, 6, 8, 10,
  134809. 12, 14, 16, 18, 20,
  134810. };
  134811. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134812. _vq_quantthresh__44c8_s_p8_1,
  134813. _vq_quantmap__44c8_s_p8_1,
  134814. 21,
  134815. 21
  134816. };
  134817. static static_codebook _44c8_s_p8_1 = {
  134818. 2, 441,
  134819. _vq_lengthlist__44c8_s_p8_1,
  134820. 1, -529268736, 1611661312, 5, 0,
  134821. _vq_quantlist__44c8_s_p8_1,
  134822. NULL,
  134823. &_vq_auxt__44c8_s_p8_1,
  134824. NULL,
  134825. 0
  134826. };
  134827. static long _vq_quantlist__44c8_s_p9_0[] = {
  134828. 8,
  134829. 7,
  134830. 9,
  134831. 6,
  134832. 10,
  134833. 5,
  134834. 11,
  134835. 4,
  134836. 12,
  134837. 3,
  134838. 13,
  134839. 2,
  134840. 14,
  134841. 1,
  134842. 15,
  134843. 0,
  134844. 16,
  134845. };
  134846. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134847. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134848. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134849. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134861. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134865. 10,
  134866. };
  134867. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134868. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134869. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134870. };
  134871. static long _vq_quantmap__44c8_s_p9_0[] = {
  134872. 15, 13, 11, 9, 7, 5, 3, 1,
  134873. 0, 2, 4, 6, 8, 10, 12, 14,
  134874. 16,
  134875. };
  134876. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134877. _vq_quantthresh__44c8_s_p9_0,
  134878. _vq_quantmap__44c8_s_p9_0,
  134879. 17,
  134880. 17
  134881. };
  134882. static static_codebook _44c8_s_p9_0 = {
  134883. 2, 289,
  134884. _vq_lengthlist__44c8_s_p9_0,
  134885. 1, -509798400, 1631393792, 5, 0,
  134886. _vq_quantlist__44c8_s_p9_0,
  134887. NULL,
  134888. &_vq_auxt__44c8_s_p9_0,
  134889. NULL,
  134890. 0
  134891. };
  134892. static long _vq_quantlist__44c8_s_p9_1[] = {
  134893. 9,
  134894. 8,
  134895. 10,
  134896. 7,
  134897. 11,
  134898. 6,
  134899. 12,
  134900. 5,
  134901. 13,
  134902. 4,
  134903. 14,
  134904. 3,
  134905. 15,
  134906. 2,
  134907. 16,
  134908. 1,
  134909. 17,
  134910. 0,
  134911. 18,
  134912. };
  134913. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134914. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134915. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134916. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134917. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134918. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134919. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134920. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134921. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134922. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134923. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134924. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134925. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134926. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134927. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134928. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134929. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134930. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134931. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134932. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134933. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134934. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134935. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134936. 14,13,13,14,14,15,14,15,14,
  134937. };
  134938. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134939. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134940. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134941. 367.5, 416.5,
  134942. };
  134943. static long _vq_quantmap__44c8_s_p9_1[] = {
  134944. 17, 15, 13, 11, 9, 7, 5, 3,
  134945. 1, 0, 2, 4, 6, 8, 10, 12,
  134946. 14, 16, 18,
  134947. };
  134948. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134949. _vq_quantthresh__44c8_s_p9_1,
  134950. _vq_quantmap__44c8_s_p9_1,
  134951. 19,
  134952. 19
  134953. };
  134954. static static_codebook _44c8_s_p9_1 = {
  134955. 2, 361,
  134956. _vq_lengthlist__44c8_s_p9_1,
  134957. 1, -518287360, 1622704128, 5, 0,
  134958. _vq_quantlist__44c8_s_p9_1,
  134959. NULL,
  134960. &_vq_auxt__44c8_s_p9_1,
  134961. NULL,
  134962. 0
  134963. };
  134964. static long _vq_quantlist__44c8_s_p9_2[] = {
  134965. 24,
  134966. 23,
  134967. 25,
  134968. 22,
  134969. 26,
  134970. 21,
  134971. 27,
  134972. 20,
  134973. 28,
  134974. 19,
  134975. 29,
  134976. 18,
  134977. 30,
  134978. 17,
  134979. 31,
  134980. 16,
  134981. 32,
  134982. 15,
  134983. 33,
  134984. 14,
  134985. 34,
  134986. 13,
  134987. 35,
  134988. 12,
  134989. 36,
  134990. 11,
  134991. 37,
  134992. 10,
  134993. 38,
  134994. 9,
  134995. 39,
  134996. 8,
  134997. 40,
  134998. 7,
  134999. 41,
  135000. 6,
  135001. 42,
  135002. 5,
  135003. 43,
  135004. 4,
  135005. 44,
  135006. 3,
  135007. 45,
  135008. 2,
  135009. 46,
  135010. 1,
  135011. 47,
  135012. 0,
  135013. 48,
  135014. };
  135015. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135016. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135017. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135018. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135019. 7,
  135020. };
  135021. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135022. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135023. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135024. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135025. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135026. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135027. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135028. };
  135029. static long _vq_quantmap__44c8_s_p9_2[] = {
  135030. 47, 45, 43, 41, 39, 37, 35, 33,
  135031. 31, 29, 27, 25, 23, 21, 19, 17,
  135032. 15, 13, 11, 9, 7, 5, 3, 1,
  135033. 0, 2, 4, 6, 8, 10, 12, 14,
  135034. 16, 18, 20, 22, 24, 26, 28, 30,
  135035. 32, 34, 36, 38, 40, 42, 44, 46,
  135036. 48,
  135037. };
  135038. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135039. _vq_quantthresh__44c8_s_p9_2,
  135040. _vq_quantmap__44c8_s_p9_2,
  135041. 49,
  135042. 49
  135043. };
  135044. static static_codebook _44c8_s_p9_2 = {
  135045. 1, 49,
  135046. _vq_lengthlist__44c8_s_p9_2,
  135047. 1, -526909440, 1611661312, 6, 0,
  135048. _vq_quantlist__44c8_s_p9_2,
  135049. NULL,
  135050. &_vq_auxt__44c8_s_p9_2,
  135051. NULL,
  135052. 0
  135053. };
  135054. static long _huff_lengthlist__44c8_s_short[] = {
  135055. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135056. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135057. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135058. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135059. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135060. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135061. 10, 9,11,14,
  135062. };
  135063. static static_codebook _huff_book__44c8_s_short = {
  135064. 2, 100,
  135065. _huff_lengthlist__44c8_s_short,
  135066. 0, 0, 0, 0, 0,
  135067. NULL,
  135068. NULL,
  135069. NULL,
  135070. NULL,
  135071. 0
  135072. };
  135073. static long _huff_lengthlist__44c9_s_long[] = {
  135074. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135075. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135076. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135077. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135078. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135079. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135080. 10, 9, 8, 9,
  135081. };
  135082. static static_codebook _huff_book__44c9_s_long = {
  135083. 2, 100,
  135084. _huff_lengthlist__44c9_s_long,
  135085. 0, 0, 0, 0, 0,
  135086. NULL,
  135087. NULL,
  135088. NULL,
  135089. NULL,
  135090. 0
  135091. };
  135092. static long _vq_quantlist__44c9_s_p1_0[] = {
  135093. 1,
  135094. 0,
  135095. 2,
  135096. };
  135097. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135098. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135099. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135101. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135102. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135103. 7,
  135104. };
  135105. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135106. -0.5, 0.5,
  135107. };
  135108. static long _vq_quantmap__44c9_s_p1_0[] = {
  135109. 1, 0, 2,
  135110. };
  135111. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135112. _vq_quantthresh__44c9_s_p1_0,
  135113. _vq_quantmap__44c9_s_p1_0,
  135114. 3,
  135115. 3
  135116. };
  135117. static static_codebook _44c9_s_p1_0 = {
  135118. 4, 81,
  135119. _vq_lengthlist__44c9_s_p1_0,
  135120. 1, -535822336, 1611661312, 2, 0,
  135121. _vq_quantlist__44c9_s_p1_0,
  135122. NULL,
  135123. &_vq_auxt__44c9_s_p1_0,
  135124. NULL,
  135125. 0
  135126. };
  135127. static long _vq_quantlist__44c9_s_p2_0[] = {
  135128. 2,
  135129. 1,
  135130. 3,
  135131. 0,
  135132. 4,
  135133. };
  135134. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135135. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135136. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135137. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135138. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135139. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135140. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135141. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135142. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135145. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135146. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135147. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135148. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135149. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135150. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135153. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135154. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135155. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135156. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135157. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135158. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135161. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135162. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135163. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135164. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135165. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135166. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135171. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135172. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135173. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135174. 12,
  135175. };
  135176. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135177. -1.5, -0.5, 0.5, 1.5,
  135178. };
  135179. static long _vq_quantmap__44c9_s_p2_0[] = {
  135180. 3, 1, 0, 2, 4,
  135181. };
  135182. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135183. _vq_quantthresh__44c9_s_p2_0,
  135184. _vq_quantmap__44c9_s_p2_0,
  135185. 5,
  135186. 5
  135187. };
  135188. static static_codebook _44c9_s_p2_0 = {
  135189. 4, 625,
  135190. _vq_lengthlist__44c9_s_p2_0,
  135191. 1, -533725184, 1611661312, 3, 0,
  135192. _vq_quantlist__44c9_s_p2_0,
  135193. NULL,
  135194. &_vq_auxt__44c9_s_p2_0,
  135195. NULL,
  135196. 0
  135197. };
  135198. static long _vq_quantlist__44c9_s_p3_0[] = {
  135199. 4,
  135200. 3,
  135201. 5,
  135202. 2,
  135203. 6,
  135204. 1,
  135205. 7,
  135206. 0,
  135207. 8,
  135208. };
  135209. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135210. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135211. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135212. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135213. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0,
  135216. };
  135217. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135218. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135219. };
  135220. static long _vq_quantmap__44c9_s_p3_0[] = {
  135221. 7, 5, 3, 1, 0, 2, 4, 6,
  135222. 8,
  135223. };
  135224. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135225. _vq_quantthresh__44c9_s_p3_0,
  135226. _vq_quantmap__44c9_s_p3_0,
  135227. 9,
  135228. 9
  135229. };
  135230. static static_codebook _44c9_s_p3_0 = {
  135231. 2, 81,
  135232. _vq_lengthlist__44c9_s_p3_0,
  135233. 1, -531628032, 1611661312, 4, 0,
  135234. _vq_quantlist__44c9_s_p3_0,
  135235. NULL,
  135236. &_vq_auxt__44c9_s_p3_0,
  135237. NULL,
  135238. 0
  135239. };
  135240. static long _vq_quantlist__44c9_s_p4_0[] = {
  135241. 8,
  135242. 7,
  135243. 9,
  135244. 6,
  135245. 10,
  135246. 5,
  135247. 11,
  135248. 4,
  135249. 12,
  135250. 3,
  135251. 13,
  135252. 2,
  135253. 14,
  135254. 1,
  135255. 15,
  135256. 0,
  135257. 16,
  135258. };
  135259. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135260. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135261. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135262. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135263. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135264. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135265. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135266. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135267. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135268. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135269. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0,
  135279. };
  135280. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135281. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135282. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135283. };
  135284. static long _vq_quantmap__44c9_s_p4_0[] = {
  135285. 15, 13, 11, 9, 7, 5, 3, 1,
  135286. 0, 2, 4, 6, 8, 10, 12, 14,
  135287. 16,
  135288. };
  135289. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135290. _vq_quantthresh__44c9_s_p4_0,
  135291. _vq_quantmap__44c9_s_p4_0,
  135292. 17,
  135293. 17
  135294. };
  135295. static static_codebook _44c9_s_p4_0 = {
  135296. 2, 289,
  135297. _vq_lengthlist__44c9_s_p4_0,
  135298. 1, -529530880, 1611661312, 5, 0,
  135299. _vq_quantlist__44c9_s_p4_0,
  135300. NULL,
  135301. &_vq_auxt__44c9_s_p4_0,
  135302. NULL,
  135303. 0
  135304. };
  135305. static long _vq_quantlist__44c9_s_p5_0[] = {
  135306. 1,
  135307. 0,
  135308. 2,
  135309. };
  135310. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135311. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135312. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135313. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135314. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135315. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135316. 12,
  135317. };
  135318. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135319. -5.5, 5.5,
  135320. };
  135321. static long _vq_quantmap__44c9_s_p5_0[] = {
  135322. 1, 0, 2,
  135323. };
  135324. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135325. _vq_quantthresh__44c9_s_p5_0,
  135326. _vq_quantmap__44c9_s_p5_0,
  135327. 3,
  135328. 3
  135329. };
  135330. static static_codebook _44c9_s_p5_0 = {
  135331. 4, 81,
  135332. _vq_lengthlist__44c9_s_p5_0,
  135333. 1, -529137664, 1618345984, 2, 0,
  135334. _vq_quantlist__44c9_s_p5_0,
  135335. NULL,
  135336. &_vq_auxt__44c9_s_p5_0,
  135337. NULL,
  135338. 0
  135339. };
  135340. static long _vq_quantlist__44c9_s_p5_1[] = {
  135341. 5,
  135342. 4,
  135343. 6,
  135344. 3,
  135345. 7,
  135346. 2,
  135347. 8,
  135348. 1,
  135349. 9,
  135350. 0,
  135351. 10,
  135352. };
  135353. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135354. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135355. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135356. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135357. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135358. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135359. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135360. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135361. 11,11,11, 7, 7, 7, 7, 7, 7,
  135362. };
  135363. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135364. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135365. 3.5, 4.5,
  135366. };
  135367. static long _vq_quantmap__44c9_s_p5_1[] = {
  135368. 9, 7, 5, 3, 1, 0, 2, 4,
  135369. 6, 8, 10,
  135370. };
  135371. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135372. _vq_quantthresh__44c9_s_p5_1,
  135373. _vq_quantmap__44c9_s_p5_1,
  135374. 11,
  135375. 11
  135376. };
  135377. static static_codebook _44c9_s_p5_1 = {
  135378. 2, 121,
  135379. _vq_lengthlist__44c9_s_p5_1,
  135380. 1, -531365888, 1611661312, 4, 0,
  135381. _vq_quantlist__44c9_s_p5_1,
  135382. NULL,
  135383. &_vq_auxt__44c9_s_p5_1,
  135384. NULL,
  135385. 0
  135386. };
  135387. static long _vq_quantlist__44c9_s_p6_0[] = {
  135388. 6,
  135389. 5,
  135390. 7,
  135391. 4,
  135392. 8,
  135393. 3,
  135394. 9,
  135395. 2,
  135396. 10,
  135397. 1,
  135398. 11,
  135399. 0,
  135400. 12,
  135401. };
  135402. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135403. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135404. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135405. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135406. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135407. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135408. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. };
  135415. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135416. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135417. 12.5, 17.5, 22.5, 27.5,
  135418. };
  135419. static long _vq_quantmap__44c9_s_p6_0[] = {
  135420. 11, 9, 7, 5, 3, 1, 0, 2,
  135421. 4, 6, 8, 10, 12,
  135422. };
  135423. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135424. _vq_quantthresh__44c9_s_p6_0,
  135425. _vq_quantmap__44c9_s_p6_0,
  135426. 13,
  135427. 13
  135428. };
  135429. static static_codebook _44c9_s_p6_0 = {
  135430. 2, 169,
  135431. _vq_lengthlist__44c9_s_p6_0,
  135432. 1, -526516224, 1616117760, 4, 0,
  135433. _vq_quantlist__44c9_s_p6_0,
  135434. NULL,
  135435. &_vq_auxt__44c9_s_p6_0,
  135436. NULL,
  135437. 0
  135438. };
  135439. static long _vq_quantlist__44c9_s_p6_1[] = {
  135440. 2,
  135441. 1,
  135442. 3,
  135443. 0,
  135444. 4,
  135445. };
  135446. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135447. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135448. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135449. };
  135450. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135451. -1.5, -0.5, 0.5, 1.5,
  135452. };
  135453. static long _vq_quantmap__44c9_s_p6_1[] = {
  135454. 3, 1, 0, 2, 4,
  135455. };
  135456. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135457. _vq_quantthresh__44c9_s_p6_1,
  135458. _vq_quantmap__44c9_s_p6_1,
  135459. 5,
  135460. 5
  135461. };
  135462. static static_codebook _44c9_s_p6_1 = {
  135463. 2, 25,
  135464. _vq_lengthlist__44c9_s_p6_1,
  135465. 1, -533725184, 1611661312, 3, 0,
  135466. _vq_quantlist__44c9_s_p6_1,
  135467. NULL,
  135468. &_vq_auxt__44c9_s_p6_1,
  135469. NULL,
  135470. 0
  135471. };
  135472. static long _vq_quantlist__44c9_s_p7_0[] = {
  135473. 6,
  135474. 5,
  135475. 7,
  135476. 4,
  135477. 8,
  135478. 3,
  135479. 9,
  135480. 2,
  135481. 10,
  135482. 1,
  135483. 11,
  135484. 0,
  135485. 12,
  135486. };
  135487. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135488. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135489. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135490. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135491. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135492. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135493. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135494. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135495. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135496. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135497. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135498. 19,12,12,12,12,13,13,14,14,
  135499. };
  135500. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135501. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135502. 27.5, 38.5, 49.5, 60.5,
  135503. };
  135504. static long _vq_quantmap__44c9_s_p7_0[] = {
  135505. 11, 9, 7, 5, 3, 1, 0, 2,
  135506. 4, 6, 8, 10, 12,
  135507. };
  135508. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135509. _vq_quantthresh__44c9_s_p7_0,
  135510. _vq_quantmap__44c9_s_p7_0,
  135511. 13,
  135512. 13
  135513. };
  135514. static static_codebook _44c9_s_p7_0 = {
  135515. 2, 169,
  135516. _vq_lengthlist__44c9_s_p7_0,
  135517. 1, -523206656, 1618345984, 4, 0,
  135518. _vq_quantlist__44c9_s_p7_0,
  135519. NULL,
  135520. &_vq_auxt__44c9_s_p7_0,
  135521. NULL,
  135522. 0
  135523. };
  135524. static long _vq_quantlist__44c9_s_p7_1[] = {
  135525. 5,
  135526. 4,
  135527. 6,
  135528. 3,
  135529. 7,
  135530. 2,
  135531. 8,
  135532. 1,
  135533. 9,
  135534. 0,
  135535. 10,
  135536. };
  135537. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135538. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135539. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135540. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135541. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135542. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135543. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135544. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135545. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135546. };
  135547. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135548. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135549. 3.5, 4.5,
  135550. };
  135551. static long _vq_quantmap__44c9_s_p7_1[] = {
  135552. 9, 7, 5, 3, 1, 0, 2, 4,
  135553. 6, 8, 10,
  135554. };
  135555. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135556. _vq_quantthresh__44c9_s_p7_1,
  135557. _vq_quantmap__44c9_s_p7_1,
  135558. 11,
  135559. 11
  135560. };
  135561. static static_codebook _44c9_s_p7_1 = {
  135562. 2, 121,
  135563. _vq_lengthlist__44c9_s_p7_1,
  135564. 1, -531365888, 1611661312, 4, 0,
  135565. _vq_quantlist__44c9_s_p7_1,
  135566. NULL,
  135567. &_vq_auxt__44c9_s_p7_1,
  135568. NULL,
  135569. 0
  135570. };
  135571. static long _vq_quantlist__44c9_s_p8_0[] = {
  135572. 7,
  135573. 6,
  135574. 8,
  135575. 5,
  135576. 9,
  135577. 4,
  135578. 10,
  135579. 3,
  135580. 11,
  135581. 2,
  135582. 12,
  135583. 1,
  135584. 13,
  135585. 0,
  135586. 14,
  135587. };
  135588. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135589. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135590. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135591. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135592. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135593. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135594. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135595. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135596. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135597. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135598. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135599. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135600. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135601. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135602. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135603. 14,
  135604. };
  135605. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135606. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135607. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135608. };
  135609. static long _vq_quantmap__44c9_s_p8_0[] = {
  135610. 13, 11, 9, 7, 5, 3, 1, 0,
  135611. 2, 4, 6, 8, 10, 12, 14,
  135612. };
  135613. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135614. _vq_quantthresh__44c9_s_p8_0,
  135615. _vq_quantmap__44c9_s_p8_0,
  135616. 15,
  135617. 15
  135618. };
  135619. static static_codebook _44c9_s_p8_0 = {
  135620. 2, 225,
  135621. _vq_lengthlist__44c9_s_p8_0,
  135622. 1, -520986624, 1620377600, 4, 0,
  135623. _vq_quantlist__44c9_s_p8_0,
  135624. NULL,
  135625. &_vq_auxt__44c9_s_p8_0,
  135626. NULL,
  135627. 0
  135628. };
  135629. static long _vq_quantlist__44c9_s_p8_1[] = {
  135630. 10,
  135631. 9,
  135632. 11,
  135633. 8,
  135634. 12,
  135635. 7,
  135636. 13,
  135637. 6,
  135638. 14,
  135639. 5,
  135640. 15,
  135641. 4,
  135642. 16,
  135643. 3,
  135644. 17,
  135645. 2,
  135646. 18,
  135647. 1,
  135648. 19,
  135649. 0,
  135650. 20,
  135651. };
  135652. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135653. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135654. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135655. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135656. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135657. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135658. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135659. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135660. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135661. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135662. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135663. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135664. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135665. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135666. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135667. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135668. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135669. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135670. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135671. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135672. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135673. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135674. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135675. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135676. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135677. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135678. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135679. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135680. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135681. };
  135682. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135683. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135684. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135685. 6.5, 7.5, 8.5, 9.5,
  135686. };
  135687. static long _vq_quantmap__44c9_s_p8_1[] = {
  135688. 19, 17, 15, 13, 11, 9, 7, 5,
  135689. 3, 1, 0, 2, 4, 6, 8, 10,
  135690. 12, 14, 16, 18, 20,
  135691. };
  135692. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135693. _vq_quantthresh__44c9_s_p8_1,
  135694. _vq_quantmap__44c9_s_p8_1,
  135695. 21,
  135696. 21
  135697. };
  135698. static static_codebook _44c9_s_p8_1 = {
  135699. 2, 441,
  135700. _vq_lengthlist__44c9_s_p8_1,
  135701. 1, -529268736, 1611661312, 5, 0,
  135702. _vq_quantlist__44c9_s_p8_1,
  135703. NULL,
  135704. &_vq_auxt__44c9_s_p8_1,
  135705. NULL,
  135706. 0
  135707. };
  135708. static long _vq_quantlist__44c9_s_p9_0[] = {
  135709. 9,
  135710. 8,
  135711. 10,
  135712. 7,
  135713. 11,
  135714. 6,
  135715. 12,
  135716. 5,
  135717. 13,
  135718. 4,
  135719. 14,
  135720. 3,
  135721. 15,
  135722. 2,
  135723. 16,
  135724. 1,
  135725. 17,
  135726. 0,
  135727. 18,
  135728. };
  135729. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135730. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135731. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135732. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135733. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135734. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135735. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135736. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135737. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135738. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135739. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135740. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135741. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135742. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135743. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135744. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135745. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135746. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135752. 11,11,11,11,11,11,11,11,11,
  135753. };
  135754. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135755. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135756. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135757. 6982.5, 7913.5,
  135758. };
  135759. static long _vq_quantmap__44c9_s_p9_0[] = {
  135760. 17, 15, 13, 11, 9, 7, 5, 3,
  135761. 1, 0, 2, 4, 6, 8, 10, 12,
  135762. 14, 16, 18,
  135763. };
  135764. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135765. _vq_quantthresh__44c9_s_p9_0,
  135766. _vq_quantmap__44c9_s_p9_0,
  135767. 19,
  135768. 19
  135769. };
  135770. static static_codebook _44c9_s_p9_0 = {
  135771. 2, 361,
  135772. _vq_lengthlist__44c9_s_p9_0,
  135773. 1, -508535424, 1631393792, 5, 0,
  135774. _vq_quantlist__44c9_s_p9_0,
  135775. NULL,
  135776. &_vq_auxt__44c9_s_p9_0,
  135777. NULL,
  135778. 0
  135779. };
  135780. static long _vq_quantlist__44c9_s_p9_1[] = {
  135781. 9,
  135782. 8,
  135783. 10,
  135784. 7,
  135785. 11,
  135786. 6,
  135787. 12,
  135788. 5,
  135789. 13,
  135790. 4,
  135791. 14,
  135792. 3,
  135793. 15,
  135794. 2,
  135795. 16,
  135796. 1,
  135797. 17,
  135798. 0,
  135799. 18,
  135800. };
  135801. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135802. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135803. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135804. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135805. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135806. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135807. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135808. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135809. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135810. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135811. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135812. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135813. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135814. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135815. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135816. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135817. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135818. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135819. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135820. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135821. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135822. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135823. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135824. 13,13,13,14,13,14,15,15,15,
  135825. };
  135826. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135827. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135828. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135829. 367.5, 416.5,
  135830. };
  135831. static long _vq_quantmap__44c9_s_p9_1[] = {
  135832. 17, 15, 13, 11, 9, 7, 5, 3,
  135833. 1, 0, 2, 4, 6, 8, 10, 12,
  135834. 14, 16, 18,
  135835. };
  135836. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135837. _vq_quantthresh__44c9_s_p9_1,
  135838. _vq_quantmap__44c9_s_p9_1,
  135839. 19,
  135840. 19
  135841. };
  135842. static static_codebook _44c9_s_p9_1 = {
  135843. 2, 361,
  135844. _vq_lengthlist__44c9_s_p9_1,
  135845. 1, -518287360, 1622704128, 5, 0,
  135846. _vq_quantlist__44c9_s_p9_1,
  135847. NULL,
  135848. &_vq_auxt__44c9_s_p9_1,
  135849. NULL,
  135850. 0
  135851. };
  135852. static long _vq_quantlist__44c9_s_p9_2[] = {
  135853. 24,
  135854. 23,
  135855. 25,
  135856. 22,
  135857. 26,
  135858. 21,
  135859. 27,
  135860. 20,
  135861. 28,
  135862. 19,
  135863. 29,
  135864. 18,
  135865. 30,
  135866. 17,
  135867. 31,
  135868. 16,
  135869. 32,
  135870. 15,
  135871. 33,
  135872. 14,
  135873. 34,
  135874. 13,
  135875. 35,
  135876. 12,
  135877. 36,
  135878. 11,
  135879. 37,
  135880. 10,
  135881. 38,
  135882. 9,
  135883. 39,
  135884. 8,
  135885. 40,
  135886. 7,
  135887. 41,
  135888. 6,
  135889. 42,
  135890. 5,
  135891. 43,
  135892. 4,
  135893. 44,
  135894. 3,
  135895. 45,
  135896. 2,
  135897. 46,
  135898. 1,
  135899. 47,
  135900. 0,
  135901. 48,
  135902. };
  135903. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135904. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135905. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135906. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135907. 7,
  135908. };
  135909. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135910. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135911. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135912. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135913. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135914. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135915. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135916. };
  135917. static long _vq_quantmap__44c9_s_p9_2[] = {
  135918. 47, 45, 43, 41, 39, 37, 35, 33,
  135919. 31, 29, 27, 25, 23, 21, 19, 17,
  135920. 15, 13, 11, 9, 7, 5, 3, 1,
  135921. 0, 2, 4, 6, 8, 10, 12, 14,
  135922. 16, 18, 20, 22, 24, 26, 28, 30,
  135923. 32, 34, 36, 38, 40, 42, 44, 46,
  135924. 48,
  135925. };
  135926. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135927. _vq_quantthresh__44c9_s_p9_2,
  135928. _vq_quantmap__44c9_s_p9_2,
  135929. 49,
  135930. 49
  135931. };
  135932. static static_codebook _44c9_s_p9_2 = {
  135933. 1, 49,
  135934. _vq_lengthlist__44c9_s_p9_2,
  135935. 1, -526909440, 1611661312, 6, 0,
  135936. _vq_quantlist__44c9_s_p9_2,
  135937. NULL,
  135938. &_vq_auxt__44c9_s_p9_2,
  135939. NULL,
  135940. 0
  135941. };
  135942. static long _huff_lengthlist__44c9_s_short[] = {
  135943. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135944. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135945. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135946. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135947. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135948. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135949. 9, 8,10,13,
  135950. };
  135951. static static_codebook _huff_book__44c9_s_short = {
  135952. 2, 100,
  135953. _huff_lengthlist__44c9_s_short,
  135954. 0, 0, 0, 0, 0,
  135955. NULL,
  135956. NULL,
  135957. NULL,
  135958. NULL,
  135959. 0
  135960. };
  135961. static long _huff_lengthlist__44c0_s_long[] = {
  135962. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135963. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135964. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135965. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135966. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135967. 12,
  135968. };
  135969. static static_codebook _huff_book__44c0_s_long = {
  135970. 2, 81,
  135971. _huff_lengthlist__44c0_s_long,
  135972. 0, 0, 0, 0, 0,
  135973. NULL,
  135974. NULL,
  135975. NULL,
  135976. NULL,
  135977. 0
  135978. };
  135979. static long _vq_quantlist__44c0_s_p1_0[] = {
  135980. 1,
  135981. 0,
  135982. 2,
  135983. };
  135984. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135985. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135986. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135991. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135996. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136031. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136036. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136041. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136077. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136082. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136087. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0,
  136396. };
  136397. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136398. -0.5, 0.5,
  136399. };
  136400. static long _vq_quantmap__44c0_s_p1_0[] = {
  136401. 1, 0, 2,
  136402. };
  136403. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136404. _vq_quantthresh__44c0_s_p1_0,
  136405. _vq_quantmap__44c0_s_p1_0,
  136406. 3,
  136407. 3
  136408. };
  136409. static static_codebook _44c0_s_p1_0 = {
  136410. 8, 6561,
  136411. _vq_lengthlist__44c0_s_p1_0,
  136412. 1, -535822336, 1611661312, 2, 0,
  136413. _vq_quantlist__44c0_s_p1_0,
  136414. NULL,
  136415. &_vq_auxt__44c0_s_p1_0,
  136416. NULL,
  136417. 0
  136418. };
  136419. static long _vq_quantlist__44c0_s_p2_0[] = {
  136420. 2,
  136421. 1,
  136422. 3,
  136423. 0,
  136424. 4,
  136425. };
  136426. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136427. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0,
  136467. };
  136468. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136469. -1.5, -0.5, 0.5, 1.5,
  136470. };
  136471. static long _vq_quantmap__44c0_s_p2_0[] = {
  136472. 3, 1, 0, 2, 4,
  136473. };
  136474. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136475. _vq_quantthresh__44c0_s_p2_0,
  136476. _vq_quantmap__44c0_s_p2_0,
  136477. 5,
  136478. 5
  136479. };
  136480. static static_codebook _44c0_s_p2_0 = {
  136481. 4, 625,
  136482. _vq_lengthlist__44c0_s_p2_0,
  136483. 1, -533725184, 1611661312, 3, 0,
  136484. _vq_quantlist__44c0_s_p2_0,
  136485. NULL,
  136486. &_vq_auxt__44c0_s_p2_0,
  136487. NULL,
  136488. 0
  136489. };
  136490. static long _vq_quantlist__44c0_s_p3_0[] = {
  136491. 4,
  136492. 3,
  136493. 5,
  136494. 2,
  136495. 6,
  136496. 1,
  136497. 7,
  136498. 0,
  136499. 8,
  136500. };
  136501. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136502. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136503. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136504. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136505. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136506. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0,
  136508. };
  136509. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136510. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136511. };
  136512. static long _vq_quantmap__44c0_s_p3_0[] = {
  136513. 7, 5, 3, 1, 0, 2, 4, 6,
  136514. 8,
  136515. };
  136516. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136517. _vq_quantthresh__44c0_s_p3_0,
  136518. _vq_quantmap__44c0_s_p3_0,
  136519. 9,
  136520. 9
  136521. };
  136522. static static_codebook _44c0_s_p3_0 = {
  136523. 2, 81,
  136524. _vq_lengthlist__44c0_s_p3_0,
  136525. 1, -531628032, 1611661312, 4, 0,
  136526. _vq_quantlist__44c0_s_p3_0,
  136527. NULL,
  136528. &_vq_auxt__44c0_s_p3_0,
  136529. NULL,
  136530. 0
  136531. };
  136532. static long _vq_quantlist__44c0_s_p4_0[] = {
  136533. 4,
  136534. 3,
  136535. 5,
  136536. 2,
  136537. 6,
  136538. 1,
  136539. 7,
  136540. 0,
  136541. 8,
  136542. };
  136543. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136544. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136545. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136546. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136547. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136548. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136549. 10,
  136550. };
  136551. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136552. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136553. };
  136554. static long _vq_quantmap__44c0_s_p4_0[] = {
  136555. 7, 5, 3, 1, 0, 2, 4, 6,
  136556. 8,
  136557. };
  136558. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136559. _vq_quantthresh__44c0_s_p4_0,
  136560. _vq_quantmap__44c0_s_p4_0,
  136561. 9,
  136562. 9
  136563. };
  136564. static static_codebook _44c0_s_p4_0 = {
  136565. 2, 81,
  136566. _vq_lengthlist__44c0_s_p4_0,
  136567. 1, -531628032, 1611661312, 4, 0,
  136568. _vq_quantlist__44c0_s_p4_0,
  136569. NULL,
  136570. &_vq_auxt__44c0_s_p4_0,
  136571. NULL,
  136572. 0
  136573. };
  136574. static long _vq_quantlist__44c0_s_p5_0[] = {
  136575. 8,
  136576. 7,
  136577. 9,
  136578. 6,
  136579. 10,
  136580. 5,
  136581. 11,
  136582. 4,
  136583. 12,
  136584. 3,
  136585. 13,
  136586. 2,
  136587. 14,
  136588. 1,
  136589. 15,
  136590. 0,
  136591. 16,
  136592. };
  136593. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136594. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136595. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136596. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136597. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136598. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136599. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136600. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136601. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136602. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136603. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136604. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136605. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136606. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136607. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136608. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136609. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136610. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136612. 14,
  136613. };
  136614. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136615. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136616. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136617. };
  136618. static long _vq_quantmap__44c0_s_p5_0[] = {
  136619. 15, 13, 11, 9, 7, 5, 3, 1,
  136620. 0, 2, 4, 6, 8, 10, 12, 14,
  136621. 16,
  136622. };
  136623. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136624. _vq_quantthresh__44c0_s_p5_0,
  136625. _vq_quantmap__44c0_s_p5_0,
  136626. 17,
  136627. 17
  136628. };
  136629. static static_codebook _44c0_s_p5_0 = {
  136630. 2, 289,
  136631. _vq_lengthlist__44c0_s_p5_0,
  136632. 1, -529530880, 1611661312, 5, 0,
  136633. _vq_quantlist__44c0_s_p5_0,
  136634. NULL,
  136635. &_vq_auxt__44c0_s_p5_0,
  136636. NULL,
  136637. 0
  136638. };
  136639. static long _vq_quantlist__44c0_s_p6_0[] = {
  136640. 1,
  136641. 0,
  136642. 2,
  136643. };
  136644. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136645. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136646. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136647. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136648. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136649. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136650. 10,
  136651. };
  136652. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136653. -5.5, 5.5,
  136654. };
  136655. static long _vq_quantmap__44c0_s_p6_0[] = {
  136656. 1, 0, 2,
  136657. };
  136658. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136659. _vq_quantthresh__44c0_s_p6_0,
  136660. _vq_quantmap__44c0_s_p6_0,
  136661. 3,
  136662. 3
  136663. };
  136664. static static_codebook _44c0_s_p6_0 = {
  136665. 4, 81,
  136666. _vq_lengthlist__44c0_s_p6_0,
  136667. 1, -529137664, 1618345984, 2, 0,
  136668. _vq_quantlist__44c0_s_p6_0,
  136669. NULL,
  136670. &_vq_auxt__44c0_s_p6_0,
  136671. NULL,
  136672. 0
  136673. };
  136674. static long _vq_quantlist__44c0_s_p6_1[] = {
  136675. 5,
  136676. 4,
  136677. 6,
  136678. 3,
  136679. 7,
  136680. 2,
  136681. 8,
  136682. 1,
  136683. 9,
  136684. 0,
  136685. 10,
  136686. };
  136687. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136688. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136689. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136690. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136691. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136692. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136693. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136694. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136695. 10,10,10, 8, 8, 8, 8, 8, 8,
  136696. };
  136697. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136698. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136699. 3.5, 4.5,
  136700. };
  136701. static long _vq_quantmap__44c0_s_p6_1[] = {
  136702. 9, 7, 5, 3, 1, 0, 2, 4,
  136703. 6, 8, 10,
  136704. };
  136705. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136706. _vq_quantthresh__44c0_s_p6_1,
  136707. _vq_quantmap__44c0_s_p6_1,
  136708. 11,
  136709. 11
  136710. };
  136711. static static_codebook _44c0_s_p6_1 = {
  136712. 2, 121,
  136713. _vq_lengthlist__44c0_s_p6_1,
  136714. 1, -531365888, 1611661312, 4, 0,
  136715. _vq_quantlist__44c0_s_p6_1,
  136716. NULL,
  136717. &_vq_auxt__44c0_s_p6_1,
  136718. NULL,
  136719. 0
  136720. };
  136721. static long _vq_quantlist__44c0_s_p7_0[] = {
  136722. 6,
  136723. 5,
  136724. 7,
  136725. 4,
  136726. 8,
  136727. 3,
  136728. 9,
  136729. 2,
  136730. 10,
  136731. 1,
  136732. 11,
  136733. 0,
  136734. 12,
  136735. };
  136736. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136737. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136738. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136739. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136740. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136741. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136742. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136743. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136744. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136745. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136746. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136747. 0,12,12,11,11,12,12,13,13,
  136748. };
  136749. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136750. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136751. 12.5, 17.5, 22.5, 27.5,
  136752. };
  136753. static long _vq_quantmap__44c0_s_p7_0[] = {
  136754. 11, 9, 7, 5, 3, 1, 0, 2,
  136755. 4, 6, 8, 10, 12,
  136756. };
  136757. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136758. _vq_quantthresh__44c0_s_p7_0,
  136759. _vq_quantmap__44c0_s_p7_0,
  136760. 13,
  136761. 13
  136762. };
  136763. static static_codebook _44c0_s_p7_0 = {
  136764. 2, 169,
  136765. _vq_lengthlist__44c0_s_p7_0,
  136766. 1, -526516224, 1616117760, 4, 0,
  136767. _vq_quantlist__44c0_s_p7_0,
  136768. NULL,
  136769. &_vq_auxt__44c0_s_p7_0,
  136770. NULL,
  136771. 0
  136772. };
  136773. static long _vq_quantlist__44c0_s_p7_1[] = {
  136774. 2,
  136775. 1,
  136776. 3,
  136777. 0,
  136778. 4,
  136779. };
  136780. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136781. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136782. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136783. };
  136784. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136785. -1.5, -0.5, 0.5, 1.5,
  136786. };
  136787. static long _vq_quantmap__44c0_s_p7_1[] = {
  136788. 3, 1, 0, 2, 4,
  136789. };
  136790. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136791. _vq_quantthresh__44c0_s_p7_1,
  136792. _vq_quantmap__44c0_s_p7_1,
  136793. 5,
  136794. 5
  136795. };
  136796. static static_codebook _44c0_s_p7_1 = {
  136797. 2, 25,
  136798. _vq_lengthlist__44c0_s_p7_1,
  136799. 1, -533725184, 1611661312, 3, 0,
  136800. _vq_quantlist__44c0_s_p7_1,
  136801. NULL,
  136802. &_vq_auxt__44c0_s_p7_1,
  136803. NULL,
  136804. 0
  136805. };
  136806. static long _vq_quantlist__44c0_s_p8_0[] = {
  136807. 2,
  136808. 1,
  136809. 3,
  136810. 0,
  136811. 4,
  136812. };
  136813. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136814. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136815. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136816. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136821. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136823. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136824. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136826. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136829. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136853. 11,
  136854. };
  136855. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136856. -331.5, -110.5, 110.5, 331.5,
  136857. };
  136858. static long _vq_quantmap__44c0_s_p8_0[] = {
  136859. 3, 1, 0, 2, 4,
  136860. };
  136861. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136862. _vq_quantthresh__44c0_s_p8_0,
  136863. _vq_quantmap__44c0_s_p8_0,
  136864. 5,
  136865. 5
  136866. };
  136867. static static_codebook _44c0_s_p8_0 = {
  136868. 4, 625,
  136869. _vq_lengthlist__44c0_s_p8_0,
  136870. 1, -518283264, 1627103232, 3, 0,
  136871. _vq_quantlist__44c0_s_p8_0,
  136872. NULL,
  136873. &_vq_auxt__44c0_s_p8_0,
  136874. NULL,
  136875. 0
  136876. };
  136877. static long _vq_quantlist__44c0_s_p8_1[] = {
  136878. 6,
  136879. 5,
  136880. 7,
  136881. 4,
  136882. 8,
  136883. 3,
  136884. 9,
  136885. 2,
  136886. 10,
  136887. 1,
  136888. 11,
  136889. 0,
  136890. 12,
  136891. };
  136892. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136893. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136894. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136895. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136896. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136897. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136898. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136899. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136900. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136901. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136902. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136903. 16,13,13,12,12,14,14,15,13,
  136904. };
  136905. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136906. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136907. 42.5, 59.5, 76.5, 93.5,
  136908. };
  136909. static long _vq_quantmap__44c0_s_p8_1[] = {
  136910. 11, 9, 7, 5, 3, 1, 0, 2,
  136911. 4, 6, 8, 10, 12,
  136912. };
  136913. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136914. _vq_quantthresh__44c0_s_p8_1,
  136915. _vq_quantmap__44c0_s_p8_1,
  136916. 13,
  136917. 13
  136918. };
  136919. static static_codebook _44c0_s_p8_1 = {
  136920. 2, 169,
  136921. _vq_lengthlist__44c0_s_p8_1,
  136922. 1, -522616832, 1620115456, 4, 0,
  136923. _vq_quantlist__44c0_s_p8_1,
  136924. NULL,
  136925. &_vq_auxt__44c0_s_p8_1,
  136926. NULL,
  136927. 0
  136928. };
  136929. static long _vq_quantlist__44c0_s_p8_2[] = {
  136930. 8,
  136931. 7,
  136932. 9,
  136933. 6,
  136934. 10,
  136935. 5,
  136936. 11,
  136937. 4,
  136938. 12,
  136939. 3,
  136940. 13,
  136941. 2,
  136942. 14,
  136943. 1,
  136944. 15,
  136945. 0,
  136946. 16,
  136947. };
  136948. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136949. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136950. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136951. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136952. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136953. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136954. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136955. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136956. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136957. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136958. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136959. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136960. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136961. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136962. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136963. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136964. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136965. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136966. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136967. 10,
  136968. };
  136969. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136970. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136971. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136972. };
  136973. static long _vq_quantmap__44c0_s_p8_2[] = {
  136974. 15, 13, 11, 9, 7, 5, 3, 1,
  136975. 0, 2, 4, 6, 8, 10, 12, 14,
  136976. 16,
  136977. };
  136978. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136979. _vq_quantthresh__44c0_s_p8_2,
  136980. _vq_quantmap__44c0_s_p8_2,
  136981. 17,
  136982. 17
  136983. };
  136984. static static_codebook _44c0_s_p8_2 = {
  136985. 2, 289,
  136986. _vq_lengthlist__44c0_s_p8_2,
  136987. 1, -529530880, 1611661312, 5, 0,
  136988. _vq_quantlist__44c0_s_p8_2,
  136989. NULL,
  136990. &_vq_auxt__44c0_s_p8_2,
  136991. NULL,
  136992. 0
  136993. };
  136994. static long _huff_lengthlist__44c0_s_short[] = {
  136995. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136996. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136997. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136998. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136999. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137000. 12,
  137001. };
  137002. static static_codebook _huff_book__44c0_s_short = {
  137003. 2, 81,
  137004. _huff_lengthlist__44c0_s_short,
  137005. 0, 0, 0, 0, 0,
  137006. NULL,
  137007. NULL,
  137008. NULL,
  137009. NULL,
  137010. 0
  137011. };
  137012. static long _huff_lengthlist__44c0_sm_long[] = {
  137013. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137014. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137015. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137016. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137017. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137018. 13,
  137019. };
  137020. static static_codebook _huff_book__44c0_sm_long = {
  137021. 2, 81,
  137022. _huff_lengthlist__44c0_sm_long,
  137023. 0, 0, 0, 0, 0,
  137024. NULL,
  137025. NULL,
  137026. NULL,
  137027. NULL,
  137028. 0
  137029. };
  137030. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137031. 1,
  137032. 0,
  137033. 2,
  137034. };
  137035. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137036. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137037. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137042. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137047. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137082. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137087. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137092. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137128. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137133. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137138. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0,
  137447. };
  137448. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137449. -0.5, 0.5,
  137450. };
  137451. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137452. 1, 0, 2,
  137453. };
  137454. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137455. _vq_quantthresh__44c0_sm_p1_0,
  137456. _vq_quantmap__44c0_sm_p1_0,
  137457. 3,
  137458. 3
  137459. };
  137460. static static_codebook _44c0_sm_p1_0 = {
  137461. 8, 6561,
  137462. _vq_lengthlist__44c0_sm_p1_0,
  137463. 1, -535822336, 1611661312, 2, 0,
  137464. _vq_quantlist__44c0_sm_p1_0,
  137465. NULL,
  137466. &_vq_auxt__44c0_sm_p1_0,
  137467. NULL,
  137468. 0
  137469. };
  137470. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137471. 2,
  137472. 1,
  137473. 3,
  137474. 0,
  137475. 4,
  137476. };
  137477. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137478. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0,
  137518. };
  137519. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137520. -1.5, -0.5, 0.5, 1.5,
  137521. };
  137522. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137523. 3, 1, 0, 2, 4,
  137524. };
  137525. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137526. _vq_quantthresh__44c0_sm_p2_0,
  137527. _vq_quantmap__44c0_sm_p2_0,
  137528. 5,
  137529. 5
  137530. };
  137531. static static_codebook _44c0_sm_p2_0 = {
  137532. 4, 625,
  137533. _vq_lengthlist__44c0_sm_p2_0,
  137534. 1, -533725184, 1611661312, 3, 0,
  137535. _vq_quantlist__44c0_sm_p2_0,
  137536. NULL,
  137537. &_vq_auxt__44c0_sm_p2_0,
  137538. NULL,
  137539. 0
  137540. };
  137541. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137542. 4,
  137543. 3,
  137544. 5,
  137545. 2,
  137546. 6,
  137547. 1,
  137548. 7,
  137549. 0,
  137550. 8,
  137551. };
  137552. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137553. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137554. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137555. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137556. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137557. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0,
  137559. };
  137560. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137561. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137562. };
  137563. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137564. 7, 5, 3, 1, 0, 2, 4, 6,
  137565. 8,
  137566. };
  137567. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137568. _vq_quantthresh__44c0_sm_p3_0,
  137569. _vq_quantmap__44c0_sm_p3_0,
  137570. 9,
  137571. 9
  137572. };
  137573. static static_codebook _44c0_sm_p3_0 = {
  137574. 2, 81,
  137575. _vq_lengthlist__44c0_sm_p3_0,
  137576. 1, -531628032, 1611661312, 4, 0,
  137577. _vq_quantlist__44c0_sm_p3_0,
  137578. NULL,
  137579. &_vq_auxt__44c0_sm_p3_0,
  137580. NULL,
  137581. 0
  137582. };
  137583. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137584. 4,
  137585. 3,
  137586. 5,
  137587. 2,
  137588. 6,
  137589. 1,
  137590. 7,
  137591. 0,
  137592. 8,
  137593. };
  137594. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137595. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137596. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137597. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137598. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137599. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137600. 11,
  137601. };
  137602. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137603. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137604. };
  137605. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137606. 7, 5, 3, 1, 0, 2, 4, 6,
  137607. 8,
  137608. };
  137609. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137610. _vq_quantthresh__44c0_sm_p4_0,
  137611. _vq_quantmap__44c0_sm_p4_0,
  137612. 9,
  137613. 9
  137614. };
  137615. static static_codebook _44c0_sm_p4_0 = {
  137616. 2, 81,
  137617. _vq_lengthlist__44c0_sm_p4_0,
  137618. 1, -531628032, 1611661312, 4, 0,
  137619. _vq_quantlist__44c0_sm_p4_0,
  137620. NULL,
  137621. &_vq_auxt__44c0_sm_p4_0,
  137622. NULL,
  137623. 0
  137624. };
  137625. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137626. 8,
  137627. 7,
  137628. 9,
  137629. 6,
  137630. 10,
  137631. 5,
  137632. 11,
  137633. 4,
  137634. 12,
  137635. 3,
  137636. 13,
  137637. 2,
  137638. 14,
  137639. 1,
  137640. 15,
  137641. 0,
  137642. 16,
  137643. };
  137644. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137645. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137646. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137647. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137648. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137649. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137650. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137651. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137652. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137653. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137654. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137655. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137656. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137657. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137658. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137659. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137660. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137661. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137663. 14,
  137664. };
  137665. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137666. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137667. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137668. };
  137669. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137670. 15, 13, 11, 9, 7, 5, 3, 1,
  137671. 0, 2, 4, 6, 8, 10, 12, 14,
  137672. 16,
  137673. };
  137674. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137675. _vq_quantthresh__44c0_sm_p5_0,
  137676. _vq_quantmap__44c0_sm_p5_0,
  137677. 17,
  137678. 17
  137679. };
  137680. static static_codebook _44c0_sm_p5_0 = {
  137681. 2, 289,
  137682. _vq_lengthlist__44c0_sm_p5_0,
  137683. 1, -529530880, 1611661312, 5, 0,
  137684. _vq_quantlist__44c0_sm_p5_0,
  137685. NULL,
  137686. &_vq_auxt__44c0_sm_p5_0,
  137687. NULL,
  137688. 0
  137689. };
  137690. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137691. 1,
  137692. 0,
  137693. 2,
  137694. };
  137695. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137696. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137697. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137698. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137699. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137700. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137701. 11,
  137702. };
  137703. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137704. -5.5, 5.5,
  137705. };
  137706. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137707. 1, 0, 2,
  137708. };
  137709. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137710. _vq_quantthresh__44c0_sm_p6_0,
  137711. _vq_quantmap__44c0_sm_p6_0,
  137712. 3,
  137713. 3
  137714. };
  137715. static static_codebook _44c0_sm_p6_0 = {
  137716. 4, 81,
  137717. _vq_lengthlist__44c0_sm_p6_0,
  137718. 1, -529137664, 1618345984, 2, 0,
  137719. _vq_quantlist__44c0_sm_p6_0,
  137720. NULL,
  137721. &_vq_auxt__44c0_sm_p6_0,
  137722. NULL,
  137723. 0
  137724. };
  137725. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137726. 5,
  137727. 4,
  137728. 6,
  137729. 3,
  137730. 7,
  137731. 2,
  137732. 8,
  137733. 1,
  137734. 9,
  137735. 0,
  137736. 10,
  137737. };
  137738. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137739. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137740. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137741. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137742. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137743. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137744. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137745. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137746. 10,10,10, 8, 8, 8, 8, 8, 8,
  137747. };
  137748. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137749. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137750. 3.5, 4.5,
  137751. };
  137752. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137753. 9, 7, 5, 3, 1, 0, 2, 4,
  137754. 6, 8, 10,
  137755. };
  137756. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137757. _vq_quantthresh__44c0_sm_p6_1,
  137758. _vq_quantmap__44c0_sm_p6_1,
  137759. 11,
  137760. 11
  137761. };
  137762. static static_codebook _44c0_sm_p6_1 = {
  137763. 2, 121,
  137764. _vq_lengthlist__44c0_sm_p6_1,
  137765. 1, -531365888, 1611661312, 4, 0,
  137766. _vq_quantlist__44c0_sm_p6_1,
  137767. NULL,
  137768. &_vq_auxt__44c0_sm_p6_1,
  137769. NULL,
  137770. 0
  137771. };
  137772. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137773. 6,
  137774. 5,
  137775. 7,
  137776. 4,
  137777. 8,
  137778. 3,
  137779. 9,
  137780. 2,
  137781. 10,
  137782. 1,
  137783. 11,
  137784. 0,
  137785. 12,
  137786. };
  137787. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137788. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137789. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137790. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137791. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137792. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137793. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137794. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137795. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137796. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137797. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137798. 0,12,12,11,11,13,12,14,14,
  137799. };
  137800. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137801. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137802. 12.5, 17.5, 22.5, 27.5,
  137803. };
  137804. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137805. 11, 9, 7, 5, 3, 1, 0, 2,
  137806. 4, 6, 8, 10, 12,
  137807. };
  137808. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137809. _vq_quantthresh__44c0_sm_p7_0,
  137810. _vq_quantmap__44c0_sm_p7_0,
  137811. 13,
  137812. 13
  137813. };
  137814. static static_codebook _44c0_sm_p7_0 = {
  137815. 2, 169,
  137816. _vq_lengthlist__44c0_sm_p7_0,
  137817. 1, -526516224, 1616117760, 4, 0,
  137818. _vq_quantlist__44c0_sm_p7_0,
  137819. NULL,
  137820. &_vq_auxt__44c0_sm_p7_0,
  137821. NULL,
  137822. 0
  137823. };
  137824. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137825. 2,
  137826. 1,
  137827. 3,
  137828. 0,
  137829. 4,
  137830. };
  137831. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137832. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137833. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137834. };
  137835. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137836. -1.5, -0.5, 0.5, 1.5,
  137837. };
  137838. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137839. 3, 1, 0, 2, 4,
  137840. };
  137841. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137842. _vq_quantthresh__44c0_sm_p7_1,
  137843. _vq_quantmap__44c0_sm_p7_1,
  137844. 5,
  137845. 5
  137846. };
  137847. static static_codebook _44c0_sm_p7_1 = {
  137848. 2, 25,
  137849. _vq_lengthlist__44c0_sm_p7_1,
  137850. 1, -533725184, 1611661312, 3, 0,
  137851. _vq_quantlist__44c0_sm_p7_1,
  137852. NULL,
  137853. &_vq_auxt__44c0_sm_p7_1,
  137854. NULL,
  137855. 0
  137856. };
  137857. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137858. 4,
  137859. 3,
  137860. 5,
  137861. 2,
  137862. 6,
  137863. 1,
  137864. 7,
  137865. 0,
  137866. 8,
  137867. };
  137868. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137869. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137870. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137872. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137873. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137874. 12,
  137875. };
  137876. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137877. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137878. };
  137879. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137880. 7, 5, 3, 1, 0, 2, 4, 6,
  137881. 8,
  137882. };
  137883. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137884. _vq_quantthresh__44c0_sm_p8_0,
  137885. _vq_quantmap__44c0_sm_p8_0,
  137886. 9,
  137887. 9
  137888. };
  137889. static static_codebook _44c0_sm_p8_0 = {
  137890. 2, 81,
  137891. _vq_lengthlist__44c0_sm_p8_0,
  137892. 1, -516186112, 1627103232, 4, 0,
  137893. _vq_quantlist__44c0_sm_p8_0,
  137894. NULL,
  137895. &_vq_auxt__44c0_sm_p8_0,
  137896. NULL,
  137897. 0
  137898. };
  137899. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137900. 6,
  137901. 5,
  137902. 7,
  137903. 4,
  137904. 8,
  137905. 3,
  137906. 9,
  137907. 2,
  137908. 10,
  137909. 1,
  137910. 11,
  137911. 0,
  137912. 12,
  137913. };
  137914. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137915. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137916. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137917. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137918. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137919. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137920. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137921. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137922. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137923. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137924. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137925. 20,13,13,12,12,16,13,15,13,
  137926. };
  137927. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137928. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137929. 42.5, 59.5, 76.5, 93.5,
  137930. };
  137931. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137932. 11, 9, 7, 5, 3, 1, 0, 2,
  137933. 4, 6, 8, 10, 12,
  137934. };
  137935. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137936. _vq_quantthresh__44c0_sm_p8_1,
  137937. _vq_quantmap__44c0_sm_p8_1,
  137938. 13,
  137939. 13
  137940. };
  137941. static static_codebook _44c0_sm_p8_1 = {
  137942. 2, 169,
  137943. _vq_lengthlist__44c0_sm_p8_1,
  137944. 1, -522616832, 1620115456, 4, 0,
  137945. _vq_quantlist__44c0_sm_p8_1,
  137946. NULL,
  137947. &_vq_auxt__44c0_sm_p8_1,
  137948. NULL,
  137949. 0
  137950. };
  137951. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137952. 8,
  137953. 7,
  137954. 9,
  137955. 6,
  137956. 10,
  137957. 5,
  137958. 11,
  137959. 4,
  137960. 12,
  137961. 3,
  137962. 13,
  137963. 2,
  137964. 14,
  137965. 1,
  137966. 15,
  137967. 0,
  137968. 16,
  137969. };
  137970. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137971. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137972. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137973. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137974. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137975. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137976. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137977. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137978. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137979. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137980. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137981. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137982. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137983. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137984. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137985. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137986. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137987. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137988. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137989. 9,
  137990. };
  137991. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137992. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137993. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137994. };
  137995. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137996. 15, 13, 11, 9, 7, 5, 3, 1,
  137997. 0, 2, 4, 6, 8, 10, 12, 14,
  137998. 16,
  137999. };
  138000. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138001. _vq_quantthresh__44c0_sm_p8_2,
  138002. _vq_quantmap__44c0_sm_p8_2,
  138003. 17,
  138004. 17
  138005. };
  138006. static static_codebook _44c0_sm_p8_2 = {
  138007. 2, 289,
  138008. _vq_lengthlist__44c0_sm_p8_2,
  138009. 1, -529530880, 1611661312, 5, 0,
  138010. _vq_quantlist__44c0_sm_p8_2,
  138011. NULL,
  138012. &_vq_auxt__44c0_sm_p8_2,
  138013. NULL,
  138014. 0
  138015. };
  138016. static long _huff_lengthlist__44c0_sm_short[] = {
  138017. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138018. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138019. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138020. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138021. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138022. 12,
  138023. };
  138024. static static_codebook _huff_book__44c0_sm_short = {
  138025. 2, 81,
  138026. _huff_lengthlist__44c0_sm_short,
  138027. 0, 0, 0, 0, 0,
  138028. NULL,
  138029. NULL,
  138030. NULL,
  138031. NULL,
  138032. 0
  138033. };
  138034. static long _huff_lengthlist__44c1_s_long[] = {
  138035. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138036. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138037. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138038. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138039. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138040. 11,
  138041. };
  138042. static static_codebook _huff_book__44c1_s_long = {
  138043. 2, 81,
  138044. _huff_lengthlist__44c1_s_long,
  138045. 0, 0, 0, 0, 0,
  138046. NULL,
  138047. NULL,
  138048. NULL,
  138049. NULL,
  138050. 0
  138051. };
  138052. static long _vq_quantlist__44c1_s_p1_0[] = {
  138053. 1,
  138054. 0,
  138055. 2,
  138056. };
  138057. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138058. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138059. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138064. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138069. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138104. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138109. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  138114. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138150. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138155. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138160. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0,
  138469. };
  138470. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138471. -0.5, 0.5,
  138472. };
  138473. static long _vq_quantmap__44c1_s_p1_0[] = {
  138474. 1, 0, 2,
  138475. };
  138476. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138477. _vq_quantthresh__44c1_s_p1_0,
  138478. _vq_quantmap__44c1_s_p1_0,
  138479. 3,
  138480. 3
  138481. };
  138482. static static_codebook _44c1_s_p1_0 = {
  138483. 8, 6561,
  138484. _vq_lengthlist__44c1_s_p1_0,
  138485. 1, -535822336, 1611661312, 2, 0,
  138486. _vq_quantlist__44c1_s_p1_0,
  138487. NULL,
  138488. &_vq_auxt__44c1_s_p1_0,
  138489. NULL,
  138490. 0
  138491. };
  138492. static long _vq_quantlist__44c1_s_p2_0[] = {
  138493. 2,
  138494. 1,
  138495. 3,
  138496. 0,
  138497. 4,
  138498. };
  138499. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138500. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0,
  138540. };
  138541. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138542. -1.5, -0.5, 0.5, 1.5,
  138543. };
  138544. static long _vq_quantmap__44c1_s_p2_0[] = {
  138545. 3, 1, 0, 2, 4,
  138546. };
  138547. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138548. _vq_quantthresh__44c1_s_p2_0,
  138549. _vq_quantmap__44c1_s_p2_0,
  138550. 5,
  138551. 5
  138552. };
  138553. static static_codebook _44c1_s_p2_0 = {
  138554. 4, 625,
  138555. _vq_lengthlist__44c1_s_p2_0,
  138556. 1, -533725184, 1611661312, 3, 0,
  138557. _vq_quantlist__44c1_s_p2_0,
  138558. NULL,
  138559. &_vq_auxt__44c1_s_p2_0,
  138560. NULL,
  138561. 0
  138562. };
  138563. static long _vq_quantlist__44c1_s_p3_0[] = {
  138564. 4,
  138565. 3,
  138566. 5,
  138567. 2,
  138568. 6,
  138569. 1,
  138570. 7,
  138571. 0,
  138572. 8,
  138573. };
  138574. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138575. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138576. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138577. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138578. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138579. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0,
  138581. };
  138582. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138583. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138584. };
  138585. static long _vq_quantmap__44c1_s_p3_0[] = {
  138586. 7, 5, 3, 1, 0, 2, 4, 6,
  138587. 8,
  138588. };
  138589. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138590. _vq_quantthresh__44c1_s_p3_0,
  138591. _vq_quantmap__44c1_s_p3_0,
  138592. 9,
  138593. 9
  138594. };
  138595. static static_codebook _44c1_s_p3_0 = {
  138596. 2, 81,
  138597. _vq_lengthlist__44c1_s_p3_0,
  138598. 1, -531628032, 1611661312, 4, 0,
  138599. _vq_quantlist__44c1_s_p3_0,
  138600. NULL,
  138601. &_vq_auxt__44c1_s_p3_0,
  138602. NULL,
  138603. 0
  138604. };
  138605. static long _vq_quantlist__44c1_s_p4_0[] = {
  138606. 4,
  138607. 3,
  138608. 5,
  138609. 2,
  138610. 6,
  138611. 1,
  138612. 7,
  138613. 0,
  138614. 8,
  138615. };
  138616. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138617. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138618. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138619. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138620. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138621. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138622. 11,
  138623. };
  138624. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138625. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138626. };
  138627. static long _vq_quantmap__44c1_s_p4_0[] = {
  138628. 7, 5, 3, 1, 0, 2, 4, 6,
  138629. 8,
  138630. };
  138631. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138632. _vq_quantthresh__44c1_s_p4_0,
  138633. _vq_quantmap__44c1_s_p4_0,
  138634. 9,
  138635. 9
  138636. };
  138637. static static_codebook _44c1_s_p4_0 = {
  138638. 2, 81,
  138639. _vq_lengthlist__44c1_s_p4_0,
  138640. 1, -531628032, 1611661312, 4, 0,
  138641. _vq_quantlist__44c1_s_p4_0,
  138642. NULL,
  138643. &_vq_auxt__44c1_s_p4_0,
  138644. NULL,
  138645. 0
  138646. };
  138647. static long _vq_quantlist__44c1_s_p5_0[] = {
  138648. 8,
  138649. 7,
  138650. 9,
  138651. 6,
  138652. 10,
  138653. 5,
  138654. 11,
  138655. 4,
  138656. 12,
  138657. 3,
  138658. 13,
  138659. 2,
  138660. 14,
  138661. 1,
  138662. 15,
  138663. 0,
  138664. 16,
  138665. };
  138666. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138667. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138668. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138669. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138670. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138671. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138672. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138673. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138674. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138675. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138676. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138677. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138678. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138679. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138680. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138681. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138682. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138683. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138685. 14,
  138686. };
  138687. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138688. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138689. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138690. };
  138691. static long _vq_quantmap__44c1_s_p5_0[] = {
  138692. 15, 13, 11, 9, 7, 5, 3, 1,
  138693. 0, 2, 4, 6, 8, 10, 12, 14,
  138694. 16,
  138695. };
  138696. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138697. _vq_quantthresh__44c1_s_p5_0,
  138698. _vq_quantmap__44c1_s_p5_0,
  138699. 17,
  138700. 17
  138701. };
  138702. static static_codebook _44c1_s_p5_0 = {
  138703. 2, 289,
  138704. _vq_lengthlist__44c1_s_p5_0,
  138705. 1, -529530880, 1611661312, 5, 0,
  138706. _vq_quantlist__44c1_s_p5_0,
  138707. NULL,
  138708. &_vq_auxt__44c1_s_p5_0,
  138709. NULL,
  138710. 0
  138711. };
  138712. static long _vq_quantlist__44c1_s_p6_0[] = {
  138713. 1,
  138714. 0,
  138715. 2,
  138716. };
  138717. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138718. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138719. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138720. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138721. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138722. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138723. 11,
  138724. };
  138725. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138726. -5.5, 5.5,
  138727. };
  138728. static long _vq_quantmap__44c1_s_p6_0[] = {
  138729. 1, 0, 2,
  138730. };
  138731. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138732. _vq_quantthresh__44c1_s_p6_0,
  138733. _vq_quantmap__44c1_s_p6_0,
  138734. 3,
  138735. 3
  138736. };
  138737. static static_codebook _44c1_s_p6_0 = {
  138738. 4, 81,
  138739. _vq_lengthlist__44c1_s_p6_0,
  138740. 1, -529137664, 1618345984, 2, 0,
  138741. _vq_quantlist__44c1_s_p6_0,
  138742. NULL,
  138743. &_vq_auxt__44c1_s_p6_0,
  138744. NULL,
  138745. 0
  138746. };
  138747. static long _vq_quantlist__44c1_s_p6_1[] = {
  138748. 5,
  138749. 4,
  138750. 6,
  138751. 3,
  138752. 7,
  138753. 2,
  138754. 8,
  138755. 1,
  138756. 9,
  138757. 0,
  138758. 10,
  138759. };
  138760. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138761. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138762. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138763. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138764. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138765. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138766. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138767. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138768. 10,10,10, 8, 8, 8, 8, 8, 8,
  138769. };
  138770. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138771. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138772. 3.5, 4.5,
  138773. };
  138774. static long _vq_quantmap__44c1_s_p6_1[] = {
  138775. 9, 7, 5, 3, 1, 0, 2, 4,
  138776. 6, 8, 10,
  138777. };
  138778. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138779. _vq_quantthresh__44c1_s_p6_1,
  138780. _vq_quantmap__44c1_s_p6_1,
  138781. 11,
  138782. 11
  138783. };
  138784. static static_codebook _44c1_s_p6_1 = {
  138785. 2, 121,
  138786. _vq_lengthlist__44c1_s_p6_1,
  138787. 1, -531365888, 1611661312, 4, 0,
  138788. _vq_quantlist__44c1_s_p6_1,
  138789. NULL,
  138790. &_vq_auxt__44c1_s_p6_1,
  138791. NULL,
  138792. 0
  138793. };
  138794. static long _vq_quantlist__44c1_s_p7_0[] = {
  138795. 6,
  138796. 5,
  138797. 7,
  138798. 4,
  138799. 8,
  138800. 3,
  138801. 9,
  138802. 2,
  138803. 10,
  138804. 1,
  138805. 11,
  138806. 0,
  138807. 12,
  138808. };
  138809. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138810. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138811. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138812. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138813. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138814. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138815. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138816. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138817. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138818. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138819. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138820. 0,12,11,11,11,13,10,14,13,
  138821. };
  138822. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138823. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138824. 12.5, 17.5, 22.5, 27.5,
  138825. };
  138826. static long _vq_quantmap__44c1_s_p7_0[] = {
  138827. 11, 9, 7, 5, 3, 1, 0, 2,
  138828. 4, 6, 8, 10, 12,
  138829. };
  138830. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138831. _vq_quantthresh__44c1_s_p7_0,
  138832. _vq_quantmap__44c1_s_p7_0,
  138833. 13,
  138834. 13
  138835. };
  138836. static static_codebook _44c1_s_p7_0 = {
  138837. 2, 169,
  138838. _vq_lengthlist__44c1_s_p7_0,
  138839. 1, -526516224, 1616117760, 4, 0,
  138840. _vq_quantlist__44c1_s_p7_0,
  138841. NULL,
  138842. &_vq_auxt__44c1_s_p7_0,
  138843. NULL,
  138844. 0
  138845. };
  138846. static long _vq_quantlist__44c1_s_p7_1[] = {
  138847. 2,
  138848. 1,
  138849. 3,
  138850. 0,
  138851. 4,
  138852. };
  138853. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138854. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138855. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138856. };
  138857. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138858. -1.5, -0.5, 0.5, 1.5,
  138859. };
  138860. static long _vq_quantmap__44c1_s_p7_1[] = {
  138861. 3, 1, 0, 2, 4,
  138862. };
  138863. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138864. _vq_quantthresh__44c1_s_p7_1,
  138865. _vq_quantmap__44c1_s_p7_1,
  138866. 5,
  138867. 5
  138868. };
  138869. static static_codebook _44c1_s_p7_1 = {
  138870. 2, 25,
  138871. _vq_lengthlist__44c1_s_p7_1,
  138872. 1, -533725184, 1611661312, 3, 0,
  138873. _vq_quantlist__44c1_s_p7_1,
  138874. NULL,
  138875. &_vq_auxt__44c1_s_p7_1,
  138876. NULL,
  138877. 0
  138878. };
  138879. static long _vq_quantlist__44c1_s_p8_0[] = {
  138880. 6,
  138881. 5,
  138882. 7,
  138883. 4,
  138884. 8,
  138885. 3,
  138886. 9,
  138887. 2,
  138888. 10,
  138889. 1,
  138890. 11,
  138891. 0,
  138892. 12,
  138893. };
  138894. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138895. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138896. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138897. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138898. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138899. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138900. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138901. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138902. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138903. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138905. 10,10,10,10,10,10,10,10,10,
  138906. };
  138907. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138908. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138909. 552.5, 773.5, 994.5, 1215.5,
  138910. };
  138911. static long _vq_quantmap__44c1_s_p8_0[] = {
  138912. 11, 9, 7, 5, 3, 1, 0, 2,
  138913. 4, 6, 8, 10, 12,
  138914. };
  138915. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138916. _vq_quantthresh__44c1_s_p8_0,
  138917. _vq_quantmap__44c1_s_p8_0,
  138918. 13,
  138919. 13
  138920. };
  138921. static static_codebook _44c1_s_p8_0 = {
  138922. 2, 169,
  138923. _vq_lengthlist__44c1_s_p8_0,
  138924. 1, -514541568, 1627103232, 4, 0,
  138925. _vq_quantlist__44c1_s_p8_0,
  138926. NULL,
  138927. &_vq_auxt__44c1_s_p8_0,
  138928. NULL,
  138929. 0
  138930. };
  138931. static long _vq_quantlist__44c1_s_p8_1[] = {
  138932. 6,
  138933. 5,
  138934. 7,
  138935. 4,
  138936. 8,
  138937. 3,
  138938. 9,
  138939. 2,
  138940. 10,
  138941. 1,
  138942. 11,
  138943. 0,
  138944. 12,
  138945. };
  138946. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138947. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138948. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138949. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138950. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138951. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138952. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138953. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138954. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138955. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138956. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138957. 16,13,12,12,11,14,12,15,13,
  138958. };
  138959. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138960. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138961. 42.5, 59.5, 76.5, 93.5,
  138962. };
  138963. static long _vq_quantmap__44c1_s_p8_1[] = {
  138964. 11, 9, 7, 5, 3, 1, 0, 2,
  138965. 4, 6, 8, 10, 12,
  138966. };
  138967. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138968. _vq_quantthresh__44c1_s_p8_1,
  138969. _vq_quantmap__44c1_s_p8_1,
  138970. 13,
  138971. 13
  138972. };
  138973. static static_codebook _44c1_s_p8_1 = {
  138974. 2, 169,
  138975. _vq_lengthlist__44c1_s_p8_1,
  138976. 1, -522616832, 1620115456, 4, 0,
  138977. _vq_quantlist__44c1_s_p8_1,
  138978. NULL,
  138979. &_vq_auxt__44c1_s_p8_1,
  138980. NULL,
  138981. 0
  138982. };
  138983. static long _vq_quantlist__44c1_s_p8_2[] = {
  138984. 8,
  138985. 7,
  138986. 9,
  138987. 6,
  138988. 10,
  138989. 5,
  138990. 11,
  138991. 4,
  138992. 12,
  138993. 3,
  138994. 13,
  138995. 2,
  138996. 14,
  138997. 1,
  138998. 15,
  138999. 0,
  139000. 16,
  139001. };
  139002. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139003. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139004. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139005. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139006. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139007. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139008. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139009. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139010. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139011. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139012. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139013. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139014. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139015. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139016. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139017. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139018. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139019. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139020. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139021. 9,
  139022. };
  139023. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139024. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139025. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139026. };
  139027. static long _vq_quantmap__44c1_s_p8_2[] = {
  139028. 15, 13, 11, 9, 7, 5, 3, 1,
  139029. 0, 2, 4, 6, 8, 10, 12, 14,
  139030. 16,
  139031. };
  139032. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139033. _vq_quantthresh__44c1_s_p8_2,
  139034. _vq_quantmap__44c1_s_p8_2,
  139035. 17,
  139036. 17
  139037. };
  139038. static static_codebook _44c1_s_p8_2 = {
  139039. 2, 289,
  139040. _vq_lengthlist__44c1_s_p8_2,
  139041. 1, -529530880, 1611661312, 5, 0,
  139042. _vq_quantlist__44c1_s_p8_2,
  139043. NULL,
  139044. &_vq_auxt__44c1_s_p8_2,
  139045. NULL,
  139046. 0
  139047. };
  139048. static long _huff_lengthlist__44c1_s_short[] = {
  139049. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139050. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139051. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139052. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139053. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139054. 11,
  139055. };
  139056. static static_codebook _huff_book__44c1_s_short = {
  139057. 2, 81,
  139058. _huff_lengthlist__44c1_s_short,
  139059. 0, 0, 0, 0, 0,
  139060. NULL,
  139061. NULL,
  139062. NULL,
  139063. NULL,
  139064. 0
  139065. };
  139066. static long _huff_lengthlist__44c1_sm_long[] = {
  139067. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139068. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139069. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139070. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139071. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139072. 11,
  139073. };
  139074. static static_codebook _huff_book__44c1_sm_long = {
  139075. 2, 81,
  139076. _huff_lengthlist__44c1_sm_long,
  139077. 0, 0, 0, 0, 0,
  139078. NULL,
  139079. NULL,
  139080. NULL,
  139081. NULL,
  139082. 0
  139083. };
  139084. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139085. 1,
  139086. 0,
  139087. 2,
  139088. };
  139089. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139090. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139091. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139096. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139101. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139136. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139141. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139146. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139182. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139187. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139192. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0,
  139501. };
  139502. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139503. -0.5, 0.5,
  139504. };
  139505. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139506. 1, 0, 2,
  139507. };
  139508. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139509. _vq_quantthresh__44c1_sm_p1_0,
  139510. _vq_quantmap__44c1_sm_p1_0,
  139511. 3,
  139512. 3
  139513. };
  139514. static static_codebook _44c1_sm_p1_0 = {
  139515. 8, 6561,
  139516. _vq_lengthlist__44c1_sm_p1_0,
  139517. 1, -535822336, 1611661312, 2, 0,
  139518. _vq_quantlist__44c1_sm_p1_0,
  139519. NULL,
  139520. &_vq_auxt__44c1_sm_p1_0,
  139521. NULL,
  139522. 0
  139523. };
  139524. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139525. 2,
  139526. 1,
  139527. 3,
  139528. 0,
  139529. 4,
  139530. };
  139531. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139532. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0,
  139572. };
  139573. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139574. -1.5, -0.5, 0.5, 1.5,
  139575. };
  139576. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139577. 3, 1, 0, 2, 4,
  139578. };
  139579. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139580. _vq_quantthresh__44c1_sm_p2_0,
  139581. _vq_quantmap__44c1_sm_p2_0,
  139582. 5,
  139583. 5
  139584. };
  139585. static static_codebook _44c1_sm_p2_0 = {
  139586. 4, 625,
  139587. _vq_lengthlist__44c1_sm_p2_0,
  139588. 1, -533725184, 1611661312, 3, 0,
  139589. _vq_quantlist__44c1_sm_p2_0,
  139590. NULL,
  139591. &_vq_auxt__44c1_sm_p2_0,
  139592. NULL,
  139593. 0
  139594. };
  139595. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139596. 4,
  139597. 3,
  139598. 5,
  139599. 2,
  139600. 6,
  139601. 1,
  139602. 7,
  139603. 0,
  139604. 8,
  139605. };
  139606. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139607. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139608. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139609. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139610. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139611. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0,
  139613. };
  139614. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139616. };
  139617. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139618. 7, 5, 3, 1, 0, 2, 4, 6,
  139619. 8,
  139620. };
  139621. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139622. _vq_quantthresh__44c1_sm_p3_0,
  139623. _vq_quantmap__44c1_sm_p3_0,
  139624. 9,
  139625. 9
  139626. };
  139627. static static_codebook _44c1_sm_p3_0 = {
  139628. 2, 81,
  139629. _vq_lengthlist__44c1_sm_p3_0,
  139630. 1, -531628032, 1611661312, 4, 0,
  139631. _vq_quantlist__44c1_sm_p3_0,
  139632. NULL,
  139633. &_vq_auxt__44c1_sm_p3_0,
  139634. NULL,
  139635. 0
  139636. };
  139637. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139638. 4,
  139639. 3,
  139640. 5,
  139641. 2,
  139642. 6,
  139643. 1,
  139644. 7,
  139645. 0,
  139646. 8,
  139647. };
  139648. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139649. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139650. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139651. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139652. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139653. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139654. 11,
  139655. };
  139656. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139658. };
  139659. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139660. 7, 5, 3, 1, 0, 2, 4, 6,
  139661. 8,
  139662. };
  139663. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139664. _vq_quantthresh__44c1_sm_p4_0,
  139665. _vq_quantmap__44c1_sm_p4_0,
  139666. 9,
  139667. 9
  139668. };
  139669. static static_codebook _44c1_sm_p4_0 = {
  139670. 2, 81,
  139671. _vq_lengthlist__44c1_sm_p4_0,
  139672. 1, -531628032, 1611661312, 4, 0,
  139673. _vq_quantlist__44c1_sm_p4_0,
  139674. NULL,
  139675. &_vq_auxt__44c1_sm_p4_0,
  139676. NULL,
  139677. 0
  139678. };
  139679. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139680. 8,
  139681. 7,
  139682. 9,
  139683. 6,
  139684. 10,
  139685. 5,
  139686. 11,
  139687. 4,
  139688. 12,
  139689. 3,
  139690. 13,
  139691. 2,
  139692. 14,
  139693. 1,
  139694. 15,
  139695. 0,
  139696. 16,
  139697. };
  139698. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139699. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139700. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139701. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139702. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139703. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139704. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139705. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139706. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139707. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139708. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139709. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139710. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139711. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139712. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139713. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139714. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139715. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139717. 14,
  139718. };
  139719. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139722. };
  139723. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139724. 15, 13, 11, 9, 7, 5, 3, 1,
  139725. 0, 2, 4, 6, 8, 10, 12, 14,
  139726. 16,
  139727. };
  139728. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139729. _vq_quantthresh__44c1_sm_p5_0,
  139730. _vq_quantmap__44c1_sm_p5_0,
  139731. 17,
  139732. 17
  139733. };
  139734. static static_codebook _44c1_sm_p5_0 = {
  139735. 2, 289,
  139736. _vq_lengthlist__44c1_sm_p5_0,
  139737. 1, -529530880, 1611661312, 5, 0,
  139738. _vq_quantlist__44c1_sm_p5_0,
  139739. NULL,
  139740. &_vq_auxt__44c1_sm_p5_0,
  139741. NULL,
  139742. 0
  139743. };
  139744. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139745. 1,
  139746. 0,
  139747. 2,
  139748. };
  139749. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139750. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139751. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139752. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139753. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139754. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139755. 11,
  139756. };
  139757. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139758. -5.5, 5.5,
  139759. };
  139760. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139761. 1, 0, 2,
  139762. };
  139763. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139764. _vq_quantthresh__44c1_sm_p6_0,
  139765. _vq_quantmap__44c1_sm_p6_0,
  139766. 3,
  139767. 3
  139768. };
  139769. static static_codebook _44c1_sm_p6_0 = {
  139770. 4, 81,
  139771. _vq_lengthlist__44c1_sm_p6_0,
  139772. 1, -529137664, 1618345984, 2, 0,
  139773. _vq_quantlist__44c1_sm_p6_0,
  139774. NULL,
  139775. &_vq_auxt__44c1_sm_p6_0,
  139776. NULL,
  139777. 0
  139778. };
  139779. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139780. 5,
  139781. 4,
  139782. 6,
  139783. 3,
  139784. 7,
  139785. 2,
  139786. 8,
  139787. 1,
  139788. 9,
  139789. 0,
  139790. 10,
  139791. };
  139792. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139793. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139794. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139795. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139796. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139797. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139798. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139799. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139800. 10,10,10, 8, 8, 8, 8, 8, 8,
  139801. };
  139802. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139804. 3.5, 4.5,
  139805. };
  139806. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139807. 9, 7, 5, 3, 1, 0, 2, 4,
  139808. 6, 8, 10,
  139809. };
  139810. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139811. _vq_quantthresh__44c1_sm_p6_1,
  139812. _vq_quantmap__44c1_sm_p6_1,
  139813. 11,
  139814. 11
  139815. };
  139816. static static_codebook _44c1_sm_p6_1 = {
  139817. 2, 121,
  139818. _vq_lengthlist__44c1_sm_p6_1,
  139819. 1, -531365888, 1611661312, 4, 0,
  139820. _vq_quantlist__44c1_sm_p6_1,
  139821. NULL,
  139822. &_vq_auxt__44c1_sm_p6_1,
  139823. NULL,
  139824. 0
  139825. };
  139826. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139827. 6,
  139828. 5,
  139829. 7,
  139830. 4,
  139831. 8,
  139832. 3,
  139833. 9,
  139834. 2,
  139835. 10,
  139836. 1,
  139837. 11,
  139838. 0,
  139839. 12,
  139840. };
  139841. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139842. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139843. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139844. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139845. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139846. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139847. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139848. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139849. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139850. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139851. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139852. 0,12,12,11,11,13,12,14,13,
  139853. };
  139854. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139856. 12.5, 17.5, 22.5, 27.5,
  139857. };
  139858. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139859. 11, 9, 7, 5, 3, 1, 0, 2,
  139860. 4, 6, 8, 10, 12,
  139861. };
  139862. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139863. _vq_quantthresh__44c1_sm_p7_0,
  139864. _vq_quantmap__44c1_sm_p7_0,
  139865. 13,
  139866. 13
  139867. };
  139868. static static_codebook _44c1_sm_p7_0 = {
  139869. 2, 169,
  139870. _vq_lengthlist__44c1_sm_p7_0,
  139871. 1, -526516224, 1616117760, 4, 0,
  139872. _vq_quantlist__44c1_sm_p7_0,
  139873. NULL,
  139874. &_vq_auxt__44c1_sm_p7_0,
  139875. NULL,
  139876. 0
  139877. };
  139878. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139879. 2,
  139880. 1,
  139881. 3,
  139882. 0,
  139883. 4,
  139884. };
  139885. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139886. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139887. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139888. };
  139889. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139890. -1.5, -0.5, 0.5, 1.5,
  139891. };
  139892. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139893. 3, 1, 0, 2, 4,
  139894. };
  139895. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139896. _vq_quantthresh__44c1_sm_p7_1,
  139897. _vq_quantmap__44c1_sm_p7_1,
  139898. 5,
  139899. 5
  139900. };
  139901. static static_codebook _44c1_sm_p7_1 = {
  139902. 2, 25,
  139903. _vq_lengthlist__44c1_sm_p7_1,
  139904. 1, -533725184, 1611661312, 3, 0,
  139905. _vq_quantlist__44c1_sm_p7_1,
  139906. NULL,
  139907. &_vq_auxt__44c1_sm_p7_1,
  139908. NULL,
  139909. 0
  139910. };
  139911. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139912. 6,
  139913. 5,
  139914. 7,
  139915. 4,
  139916. 8,
  139917. 3,
  139918. 9,
  139919. 2,
  139920. 10,
  139921. 1,
  139922. 11,
  139923. 0,
  139924. 12,
  139925. };
  139926. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139927. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139928. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139929. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139930. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139931. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139932. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139933. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139934. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139935. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139936. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139937. 13,13,13,13,13,13,13,13,13,
  139938. };
  139939. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139940. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139941. 552.5, 773.5, 994.5, 1215.5,
  139942. };
  139943. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139944. 11, 9, 7, 5, 3, 1, 0, 2,
  139945. 4, 6, 8, 10, 12,
  139946. };
  139947. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139948. _vq_quantthresh__44c1_sm_p8_0,
  139949. _vq_quantmap__44c1_sm_p8_0,
  139950. 13,
  139951. 13
  139952. };
  139953. static static_codebook _44c1_sm_p8_0 = {
  139954. 2, 169,
  139955. _vq_lengthlist__44c1_sm_p8_0,
  139956. 1, -514541568, 1627103232, 4, 0,
  139957. _vq_quantlist__44c1_sm_p8_0,
  139958. NULL,
  139959. &_vq_auxt__44c1_sm_p8_0,
  139960. NULL,
  139961. 0
  139962. };
  139963. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139964. 6,
  139965. 5,
  139966. 7,
  139967. 4,
  139968. 8,
  139969. 3,
  139970. 9,
  139971. 2,
  139972. 10,
  139973. 1,
  139974. 11,
  139975. 0,
  139976. 12,
  139977. };
  139978. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139979. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139980. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139981. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139982. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139983. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139984. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139985. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139986. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139987. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139988. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139989. 20,13,12,12,12,14,12,14,13,
  139990. };
  139991. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139992. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139993. 42.5, 59.5, 76.5, 93.5,
  139994. };
  139995. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139996. 11, 9, 7, 5, 3, 1, 0, 2,
  139997. 4, 6, 8, 10, 12,
  139998. };
  139999. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140000. _vq_quantthresh__44c1_sm_p8_1,
  140001. _vq_quantmap__44c1_sm_p8_1,
  140002. 13,
  140003. 13
  140004. };
  140005. static static_codebook _44c1_sm_p8_1 = {
  140006. 2, 169,
  140007. _vq_lengthlist__44c1_sm_p8_1,
  140008. 1, -522616832, 1620115456, 4, 0,
  140009. _vq_quantlist__44c1_sm_p8_1,
  140010. NULL,
  140011. &_vq_auxt__44c1_sm_p8_1,
  140012. NULL,
  140013. 0
  140014. };
  140015. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140016. 8,
  140017. 7,
  140018. 9,
  140019. 6,
  140020. 10,
  140021. 5,
  140022. 11,
  140023. 4,
  140024. 12,
  140025. 3,
  140026. 13,
  140027. 2,
  140028. 14,
  140029. 1,
  140030. 15,
  140031. 0,
  140032. 16,
  140033. };
  140034. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140035. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140036. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140037. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140038. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140039. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140040. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140041. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140042. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140043. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140044. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140045. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140046. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140047. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140048. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140049. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140050. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140051. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140052. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140053. 9,
  140054. };
  140055. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140056. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140057. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140058. };
  140059. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140060. 15, 13, 11, 9, 7, 5, 3, 1,
  140061. 0, 2, 4, 6, 8, 10, 12, 14,
  140062. 16,
  140063. };
  140064. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140065. _vq_quantthresh__44c1_sm_p8_2,
  140066. _vq_quantmap__44c1_sm_p8_2,
  140067. 17,
  140068. 17
  140069. };
  140070. static static_codebook _44c1_sm_p8_2 = {
  140071. 2, 289,
  140072. _vq_lengthlist__44c1_sm_p8_2,
  140073. 1, -529530880, 1611661312, 5, 0,
  140074. _vq_quantlist__44c1_sm_p8_2,
  140075. NULL,
  140076. &_vq_auxt__44c1_sm_p8_2,
  140077. NULL,
  140078. 0
  140079. };
  140080. static long _huff_lengthlist__44c1_sm_short[] = {
  140081. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140082. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140083. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140084. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140085. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140086. 11,
  140087. };
  140088. static static_codebook _huff_book__44c1_sm_short = {
  140089. 2, 81,
  140090. _huff_lengthlist__44c1_sm_short,
  140091. 0, 0, 0, 0, 0,
  140092. NULL,
  140093. NULL,
  140094. NULL,
  140095. NULL,
  140096. 0
  140097. };
  140098. static long _huff_lengthlist__44cn1_s_long[] = {
  140099. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140100. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140101. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140102. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140103. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140104. 20,
  140105. };
  140106. static static_codebook _huff_book__44cn1_s_long = {
  140107. 2, 81,
  140108. _huff_lengthlist__44cn1_s_long,
  140109. 0, 0, 0, 0, 0,
  140110. NULL,
  140111. NULL,
  140112. NULL,
  140113. NULL,
  140114. 0
  140115. };
  140116. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140117. 1,
  140118. 0,
  140119. 2,
  140120. };
  140121. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140122. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140123. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140128. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140133. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140168. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140173. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140178. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140214. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140219. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140224. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0,
  140533. };
  140534. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140535. -0.5, 0.5,
  140536. };
  140537. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140538. 1, 0, 2,
  140539. };
  140540. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140541. _vq_quantthresh__44cn1_s_p1_0,
  140542. _vq_quantmap__44cn1_s_p1_0,
  140543. 3,
  140544. 3
  140545. };
  140546. static static_codebook _44cn1_s_p1_0 = {
  140547. 8, 6561,
  140548. _vq_lengthlist__44cn1_s_p1_0,
  140549. 1, -535822336, 1611661312, 2, 0,
  140550. _vq_quantlist__44cn1_s_p1_0,
  140551. NULL,
  140552. &_vq_auxt__44cn1_s_p1_0,
  140553. NULL,
  140554. 0
  140555. };
  140556. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140557. 2,
  140558. 1,
  140559. 3,
  140560. 0,
  140561. 4,
  140562. };
  140563. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140564. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0,
  140604. };
  140605. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140606. -1.5, -0.5, 0.5, 1.5,
  140607. };
  140608. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140609. 3, 1, 0, 2, 4,
  140610. };
  140611. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140612. _vq_quantthresh__44cn1_s_p2_0,
  140613. _vq_quantmap__44cn1_s_p2_0,
  140614. 5,
  140615. 5
  140616. };
  140617. static static_codebook _44cn1_s_p2_0 = {
  140618. 4, 625,
  140619. _vq_lengthlist__44cn1_s_p2_0,
  140620. 1, -533725184, 1611661312, 3, 0,
  140621. _vq_quantlist__44cn1_s_p2_0,
  140622. NULL,
  140623. &_vq_auxt__44cn1_s_p2_0,
  140624. NULL,
  140625. 0
  140626. };
  140627. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140628. 4,
  140629. 3,
  140630. 5,
  140631. 2,
  140632. 6,
  140633. 1,
  140634. 7,
  140635. 0,
  140636. 8,
  140637. };
  140638. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140639. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140640. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140641. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140642. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140643. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0,
  140645. };
  140646. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140647. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140648. };
  140649. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140650. 7, 5, 3, 1, 0, 2, 4, 6,
  140651. 8,
  140652. };
  140653. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140654. _vq_quantthresh__44cn1_s_p3_0,
  140655. _vq_quantmap__44cn1_s_p3_0,
  140656. 9,
  140657. 9
  140658. };
  140659. static static_codebook _44cn1_s_p3_0 = {
  140660. 2, 81,
  140661. _vq_lengthlist__44cn1_s_p3_0,
  140662. 1, -531628032, 1611661312, 4, 0,
  140663. _vq_quantlist__44cn1_s_p3_0,
  140664. NULL,
  140665. &_vq_auxt__44cn1_s_p3_0,
  140666. NULL,
  140667. 0
  140668. };
  140669. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140670. 4,
  140671. 3,
  140672. 5,
  140673. 2,
  140674. 6,
  140675. 1,
  140676. 7,
  140677. 0,
  140678. 8,
  140679. };
  140680. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140681. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140682. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140683. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140684. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140685. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140686. 11,
  140687. };
  140688. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140690. };
  140691. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140692. 7, 5, 3, 1, 0, 2, 4, 6,
  140693. 8,
  140694. };
  140695. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140696. _vq_quantthresh__44cn1_s_p4_0,
  140697. _vq_quantmap__44cn1_s_p4_0,
  140698. 9,
  140699. 9
  140700. };
  140701. static static_codebook _44cn1_s_p4_0 = {
  140702. 2, 81,
  140703. _vq_lengthlist__44cn1_s_p4_0,
  140704. 1, -531628032, 1611661312, 4, 0,
  140705. _vq_quantlist__44cn1_s_p4_0,
  140706. NULL,
  140707. &_vq_auxt__44cn1_s_p4_0,
  140708. NULL,
  140709. 0
  140710. };
  140711. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140712. 8,
  140713. 7,
  140714. 9,
  140715. 6,
  140716. 10,
  140717. 5,
  140718. 11,
  140719. 4,
  140720. 12,
  140721. 3,
  140722. 13,
  140723. 2,
  140724. 14,
  140725. 1,
  140726. 15,
  140727. 0,
  140728. 16,
  140729. };
  140730. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140731. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140732. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140733. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140734. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140735. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140736. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140737. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140738. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140739. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140740. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140741. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140742. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140743. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140744. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140745. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140746. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140747. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140749. 14,
  140750. };
  140751. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140752. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140753. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140754. };
  140755. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140756. 15, 13, 11, 9, 7, 5, 3, 1,
  140757. 0, 2, 4, 6, 8, 10, 12, 14,
  140758. 16,
  140759. };
  140760. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140761. _vq_quantthresh__44cn1_s_p5_0,
  140762. _vq_quantmap__44cn1_s_p5_0,
  140763. 17,
  140764. 17
  140765. };
  140766. static static_codebook _44cn1_s_p5_0 = {
  140767. 2, 289,
  140768. _vq_lengthlist__44cn1_s_p5_0,
  140769. 1, -529530880, 1611661312, 5, 0,
  140770. _vq_quantlist__44cn1_s_p5_0,
  140771. NULL,
  140772. &_vq_auxt__44cn1_s_p5_0,
  140773. NULL,
  140774. 0
  140775. };
  140776. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140777. 1,
  140778. 0,
  140779. 2,
  140780. };
  140781. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140782. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140783. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140784. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140785. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140786. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140787. 10,
  140788. };
  140789. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140790. -5.5, 5.5,
  140791. };
  140792. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140793. 1, 0, 2,
  140794. };
  140795. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140796. _vq_quantthresh__44cn1_s_p6_0,
  140797. _vq_quantmap__44cn1_s_p6_0,
  140798. 3,
  140799. 3
  140800. };
  140801. static static_codebook _44cn1_s_p6_0 = {
  140802. 4, 81,
  140803. _vq_lengthlist__44cn1_s_p6_0,
  140804. 1, -529137664, 1618345984, 2, 0,
  140805. _vq_quantlist__44cn1_s_p6_0,
  140806. NULL,
  140807. &_vq_auxt__44cn1_s_p6_0,
  140808. NULL,
  140809. 0
  140810. };
  140811. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140812. 5,
  140813. 4,
  140814. 6,
  140815. 3,
  140816. 7,
  140817. 2,
  140818. 8,
  140819. 1,
  140820. 9,
  140821. 0,
  140822. 10,
  140823. };
  140824. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140825. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140826. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140827. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140828. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140829. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140830. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140831. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140832. 10,10,10, 9, 9, 9, 9, 9, 9,
  140833. };
  140834. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140835. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140836. 3.5, 4.5,
  140837. };
  140838. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140839. 9, 7, 5, 3, 1, 0, 2, 4,
  140840. 6, 8, 10,
  140841. };
  140842. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140843. _vq_quantthresh__44cn1_s_p6_1,
  140844. _vq_quantmap__44cn1_s_p6_1,
  140845. 11,
  140846. 11
  140847. };
  140848. static static_codebook _44cn1_s_p6_1 = {
  140849. 2, 121,
  140850. _vq_lengthlist__44cn1_s_p6_1,
  140851. 1, -531365888, 1611661312, 4, 0,
  140852. _vq_quantlist__44cn1_s_p6_1,
  140853. NULL,
  140854. &_vq_auxt__44cn1_s_p6_1,
  140855. NULL,
  140856. 0
  140857. };
  140858. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140859. 6,
  140860. 5,
  140861. 7,
  140862. 4,
  140863. 8,
  140864. 3,
  140865. 9,
  140866. 2,
  140867. 10,
  140868. 1,
  140869. 11,
  140870. 0,
  140871. 12,
  140872. };
  140873. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140874. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140875. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140876. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140877. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140878. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140879. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140880. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140881. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140882. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140883. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140884. 0,13,13,12,12,13,13,13,14,
  140885. };
  140886. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140887. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140888. 12.5, 17.5, 22.5, 27.5,
  140889. };
  140890. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140891. 11, 9, 7, 5, 3, 1, 0, 2,
  140892. 4, 6, 8, 10, 12,
  140893. };
  140894. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140895. _vq_quantthresh__44cn1_s_p7_0,
  140896. _vq_quantmap__44cn1_s_p7_0,
  140897. 13,
  140898. 13
  140899. };
  140900. static static_codebook _44cn1_s_p7_0 = {
  140901. 2, 169,
  140902. _vq_lengthlist__44cn1_s_p7_0,
  140903. 1, -526516224, 1616117760, 4, 0,
  140904. _vq_quantlist__44cn1_s_p7_0,
  140905. NULL,
  140906. &_vq_auxt__44cn1_s_p7_0,
  140907. NULL,
  140908. 0
  140909. };
  140910. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140911. 2,
  140912. 1,
  140913. 3,
  140914. 0,
  140915. 4,
  140916. };
  140917. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140918. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140919. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140920. };
  140921. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140922. -1.5, -0.5, 0.5, 1.5,
  140923. };
  140924. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140925. 3, 1, 0, 2, 4,
  140926. };
  140927. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140928. _vq_quantthresh__44cn1_s_p7_1,
  140929. _vq_quantmap__44cn1_s_p7_1,
  140930. 5,
  140931. 5
  140932. };
  140933. static static_codebook _44cn1_s_p7_1 = {
  140934. 2, 25,
  140935. _vq_lengthlist__44cn1_s_p7_1,
  140936. 1, -533725184, 1611661312, 3, 0,
  140937. _vq_quantlist__44cn1_s_p7_1,
  140938. NULL,
  140939. &_vq_auxt__44cn1_s_p7_1,
  140940. NULL,
  140941. 0
  140942. };
  140943. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140944. 2,
  140945. 1,
  140946. 3,
  140947. 0,
  140948. 4,
  140949. };
  140950. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140951. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140952. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140954. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140958. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140960. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140966. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140968. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140969. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140971. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140973. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140975. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140979. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140981. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140982. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140984. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140985. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140986. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140987. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140988. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140989. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140990. 12,
  140991. };
  140992. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140993. -331.5, -110.5, 110.5, 331.5,
  140994. };
  140995. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140996. 3, 1, 0, 2, 4,
  140997. };
  140998. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140999. _vq_quantthresh__44cn1_s_p8_0,
  141000. _vq_quantmap__44cn1_s_p8_0,
  141001. 5,
  141002. 5
  141003. };
  141004. static static_codebook _44cn1_s_p8_0 = {
  141005. 4, 625,
  141006. _vq_lengthlist__44cn1_s_p8_0,
  141007. 1, -518283264, 1627103232, 3, 0,
  141008. _vq_quantlist__44cn1_s_p8_0,
  141009. NULL,
  141010. &_vq_auxt__44cn1_s_p8_0,
  141011. NULL,
  141012. 0
  141013. };
  141014. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141015. 6,
  141016. 5,
  141017. 7,
  141018. 4,
  141019. 8,
  141020. 3,
  141021. 9,
  141022. 2,
  141023. 10,
  141024. 1,
  141025. 11,
  141026. 0,
  141027. 12,
  141028. };
  141029. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141030. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141031. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141032. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141033. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141034. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141035. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141036. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141037. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141038. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141039. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141040. 15,12,12,11,11,14,12,13,14,
  141041. };
  141042. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141043. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141044. 42.5, 59.5, 76.5, 93.5,
  141045. };
  141046. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141047. 11, 9, 7, 5, 3, 1, 0, 2,
  141048. 4, 6, 8, 10, 12,
  141049. };
  141050. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141051. _vq_quantthresh__44cn1_s_p8_1,
  141052. _vq_quantmap__44cn1_s_p8_1,
  141053. 13,
  141054. 13
  141055. };
  141056. static static_codebook _44cn1_s_p8_1 = {
  141057. 2, 169,
  141058. _vq_lengthlist__44cn1_s_p8_1,
  141059. 1, -522616832, 1620115456, 4, 0,
  141060. _vq_quantlist__44cn1_s_p8_1,
  141061. NULL,
  141062. &_vq_auxt__44cn1_s_p8_1,
  141063. NULL,
  141064. 0
  141065. };
  141066. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141067. 8,
  141068. 7,
  141069. 9,
  141070. 6,
  141071. 10,
  141072. 5,
  141073. 11,
  141074. 4,
  141075. 12,
  141076. 3,
  141077. 13,
  141078. 2,
  141079. 14,
  141080. 1,
  141081. 15,
  141082. 0,
  141083. 16,
  141084. };
  141085. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141086. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141087. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141088. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141089. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141090. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141091. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141092. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141093. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141094. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141095. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141096. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141097. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141098. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141099. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141100. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141101. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141102. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141103. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141104. 9,
  141105. };
  141106. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141107. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141108. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141109. };
  141110. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141111. 15, 13, 11, 9, 7, 5, 3, 1,
  141112. 0, 2, 4, 6, 8, 10, 12, 14,
  141113. 16,
  141114. };
  141115. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141116. _vq_quantthresh__44cn1_s_p8_2,
  141117. _vq_quantmap__44cn1_s_p8_2,
  141118. 17,
  141119. 17
  141120. };
  141121. static static_codebook _44cn1_s_p8_2 = {
  141122. 2, 289,
  141123. _vq_lengthlist__44cn1_s_p8_2,
  141124. 1, -529530880, 1611661312, 5, 0,
  141125. _vq_quantlist__44cn1_s_p8_2,
  141126. NULL,
  141127. &_vq_auxt__44cn1_s_p8_2,
  141128. NULL,
  141129. 0
  141130. };
  141131. static long _huff_lengthlist__44cn1_s_short[] = {
  141132. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141133. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141134. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141135. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141136. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141137. 10,
  141138. };
  141139. static static_codebook _huff_book__44cn1_s_short = {
  141140. 2, 81,
  141141. _huff_lengthlist__44cn1_s_short,
  141142. 0, 0, 0, 0, 0,
  141143. NULL,
  141144. NULL,
  141145. NULL,
  141146. NULL,
  141147. 0
  141148. };
  141149. static long _huff_lengthlist__44cn1_sm_long[] = {
  141150. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141151. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141152. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141153. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141154. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141155. 17,
  141156. };
  141157. static static_codebook _huff_book__44cn1_sm_long = {
  141158. 2, 81,
  141159. _huff_lengthlist__44cn1_sm_long,
  141160. 0, 0, 0, 0, 0,
  141161. NULL,
  141162. NULL,
  141163. NULL,
  141164. NULL,
  141165. 0
  141166. };
  141167. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141168. 1,
  141169. 0,
  141170. 2,
  141171. };
  141172. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141173. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141174. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141179. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141184. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141219. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141224. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141229. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141265. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141270. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141275. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0,
  141584. };
  141585. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141586. -0.5, 0.5,
  141587. };
  141588. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141589. 1, 0, 2,
  141590. };
  141591. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141592. _vq_quantthresh__44cn1_sm_p1_0,
  141593. _vq_quantmap__44cn1_sm_p1_0,
  141594. 3,
  141595. 3
  141596. };
  141597. static static_codebook _44cn1_sm_p1_0 = {
  141598. 8, 6561,
  141599. _vq_lengthlist__44cn1_sm_p1_0,
  141600. 1, -535822336, 1611661312, 2, 0,
  141601. _vq_quantlist__44cn1_sm_p1_0,
  141602. NULL,
  141603. &_vq_auxt__44cn1_sm_p1_0,
  141604. NULL,
  141605. 0
  141606. };
  141607. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141608. 2,
  141609. 1,
  141610. 3,
  141611. 0,
  141612. 4,
  141613. };
  141614. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141615. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141621. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141654. 0,
  141655. };
  141656. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141657. -1.5, -0.5, 0.5, 1.5,
  141658. };
  141659. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141660. 3, 1, 0, 2, 4,
  141661. };
  141662. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141663. _vq_quantthresh__44cn1_sm_p2_0,
  141664. _vq_quantmap__44cn1_sm_p2_0,
  141665. 5,
  141666. 5
  141667. };
  141668. static static_codebook _44cn1_sm_p2_0 = {
  141669. 4, 625,
  141670. _vq_lengthlist__44cn1_sm_p2_0,
  141671. 1, -533725184, 1611661312, 3, 0,
  141672. _vq_quantlist__44cn1_sm_p2_0,
  141673. NULL,
  141674. &_vq_auxt__44cn1_sm_p2_0,
  141675. NULL,
  141676. 0
  141677. };
  141678. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141679. 4,
  141680. 3,
  141681. 5,
  141682. 2,
  141683. 6,
  141684. 1,
  141685. 7,
  141686. 0,
  141687. 8,
  141688. };
  141689. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141690. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141691. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141692. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141693. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141694. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0,
  141696. };
  141697. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141699. };
  141700. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141701. 7, 5, 3, 1, 0, 2, 4, 6,
  141702. 8,
  141703. };
  141704. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141705. _vq_quantthresh__44cn1_sm_p3_0,
  141706. _vq_quantmap__44cn1_sm_p3_0,
  141707. 9,
  141708. 9
  141709. };
  141710. static static_codebook _44cn1_sm_p3_0 = {
  141711. 2, 81,
  141712. _vq_lengthlist__44cn1_sm_p3_0,
  141713. 1, -531628032, 1611661312, 4, 0,
  141714. _vq_quantlist__44cn1_sm_p3_0,
  141715. NULL,
  141716. &_vq_auxt__44cn1_sm_p3_0,
  141717. NULL,
  141718. 0
  141719. };
  141720. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141721. 4,
  141722. 3,
  141723. 5,
  141724. 2,
  141725. 6,
  141726. 1,
  141727. 7,
  141728. 0,
  141729. 8,
  141730. };
  141731. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141732. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141733. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141734. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141735. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141736. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141737. 11,
  141738. };
  141739. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141741. };
  141742. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141743. 7, 5, 3, 1, 0, 2, 4, 6,
  141744. 8,
  141745. };
  141746. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141747. _vq_quantthresh__44cn1_sm_p4_0,
  141748. _vq_quantmap__44cn1_sm_p4_0,
  141749. 9,
  141750. 9
  141751. };
  141752. static static_codebook _44cn1_sm_p4_0 = {
  141753. 2, 81,
  141754. _vq_lengthlist__44cn1_sm_p4_0,
  141755. 1, -531628032, 1611661312, 4, 0,
  141756. _vq_quantlist__44cn1_sm_p4_0,
  141757. NULL,
  141758. &_vq_auxt__44cn1_sm_p4_0,
  141759. NULL,
  141760. 0
  141761. };
  141762. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141763. 8,
  141764. 7,
  141765. 9,
  141766. 6,
  141767. 10,
  141768. 5,
  141769. 11,
  141770. 4,
  141771. 12,
  141772. 3,
  141773. 13,
  141774. 2,
  141775. 14,
  141776. 1,
  141777. 15,
  141778. 0,
  141779. 16,
  141780. };
  141781. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141782. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141783. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141784. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141785. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141786. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141787. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141788. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141789. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141790. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141791. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141792. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141793. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141794. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141795. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141796. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141797. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141798. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141799. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141800. 14,
  141801. };
  141802. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141805. };
  141806. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141807. 15, 13, 11, 9, 7, 5, 3, 1,
  141808. 0, 2, 4, 6, 8, 10, 12, 14,
  141809. 16,
  141810. };
  141811. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141812. _vq_quantthresh__44cn1_sm_p5_0,
  141813. _vq_quantmap__44cn1_sm_p5_0,
  141814. 17,
  141815. 17
  141816. };
  141817. static static_codebook _44cn1_sm_p5_0 = {
  141818. 2, 289,
  141819. _vq_lengthlist__44cn1_sm_p5_0,
  141820. 1, -529530880, 1611661312, 5, 0,
  141821. _vq_quantlist__44cn1_sm_p5_0,
  141822. NULL,
  141823. &_vq_auxt__44cn1_sm_p5_0,
  141824. NULL,
  141825. 0
  141826. };
  141827. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141828. 1,
  141829. 0,
  141830. 2,
  141831. };
  141832. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141833. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141834. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141835. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141836. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141837. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141838. 10,
  141839. };
  141840. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141841. -5.5, 5.5,
  141842. };
  141843. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141844. 1, 0, 2,
  141845. };
  141846. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141847. _vq_quantthresh__44cn1_sm_p6_0,
  141848. _vq_quantmap__44cn1_sm_p6_0,
  141849. 3,
  141850. 3
  141851. };
  141852. static static_codebook _44cn1_sm_p6_0 = {
  141853. 4, 81,
  141854. _vq_lengthlist__44cn1_sm_p6_0,
  141855. 1, -529137664, 1618345984, 2, 0,
  141856. _vq_quantlist__44cn1_sm_p6_0,
  141857. NULL,
  141858. &_vq_auxt__44cn1_sm_p6_0,
  141859. NULL,
  141860. 0
  141861. };
  141862. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141863. 5,
  141864. 4,
  141865. 6,
  141866. 3,
  141867. 7,
  141868. 2,
  141869. 8,
  141870. 1,
  141871. 9,
  141872. 0,
  141873. 10,
  141874. };
  141875. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141876. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141877. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141878. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141879. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141880. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141881. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141882. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141883. 10,10,10, 8, 9, 8, 8, 9, 8,
  141884. };
  141885. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141887. 3.5, 4.5,
  141888. };
  141889. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141890. 9, 7, 5, 3, 1, 0, 2, 4,
  141891. 6, 8, 10,
  141892. };
  141893. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141894. _vq_quantthresh__44cn1_sm_p6_1,
  141895. _vq_quantmap__44cn1_sm_p6_1,
  141896. 11,
  141897. 11
  141898. };
  141899. static static_codebook _44cn1_sm_p6_1 = {
  141900. 2, 121,
  141901. _vq_lengthlist__44cn1_sm_p6_1,
  141902. 1, -531365888, 1611661312, 4, 0,
  141903. _vq_quantlist__44cn1_sm_p6_1,
  141904. NULL,
  141905. &_vq_auxt__44cn1_sm_p6_1,
  141906. NULL,
  141907. 0
  141908. };
  141909. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141910. 6,
  141911. 5,
  141912. 7,
  141913. 4,
  141914. 8,
  141915. 3,
  141916. 9,
  141917. 2,
  141918. 10,
  141919. 1,
  141920. 11,
  141921. 0,
  141922. 12,
  141923. };
  141924. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141925. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141926. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141927. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141928. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141929. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141930. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141931. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141932. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141933. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141934. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141935. 0,13,12,12,12,13,13,13,14,
  141936. };
  141937. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141939. 12.5, 17.5, 22.5, 27.5,
  141940. };
  141941. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141942. 11, 9, 7, 5, 3, 1, 0, 2,
  141943. 4, 6, 8, 10, 12,
  141944. };
  141945. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141946. _vq_quantthresh__44cn1_sm_p7_0,
  141947. _vq_quantmap__44cn1_sm_p7_0,
  141948. 13,
  141949. 13
  141950. };
  141951. static static_codebook _44cn1_sm_p7_0 = {
  141952. 2, 169,
  141953. _vq_lengthlist__44cn1_sm_p7_0,
  141954. 1, -526516224, 1616117760, 4, 0,
  141955. _vq_quantlist__44cn1_sm_p7_0,
  141956. NULL,
  141957. &_vq_auxt__44cn1_sm_p7_0,
  141958. NULL,
  141959. 0
  141960. };
  141961. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141962. 2,
  141963. 1,
  141964. 3,
  141965. 0,
  141966. 4,
  141967. };
  141968. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141969. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141970. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141971. };
  141972. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141973. -1.5, -0.5, 0.5, 1.5,
  141974. };
  141975. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141976. 3, 1, 0, 2, 4,
  141977. };
  141978. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141979. _vq_quantthresh__44cn1_sm_p7_1,
  141980. _vq_quantmap__44cn1_sm_p7_1,
  141981. 5,
  141982. 5
  141983. };
  141984. static static_codebook _44cn1_sm_p7_1 = {
  141985. 2, 25,
  141986. _vq_lengthlist__44cn1_sm_p7_1,
  141987. 1, -533725184, 1611661312, 3, 0,
  141988. _vq_quantlist__44cn1_sm_p7_1,
  141989. NULL,
  141990. &_vq_auxt__44cn1_sm_p7_1,
  141991. NULL,
  141992. 0
  141993. };
  141994. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141995. 4,
  141996. 3,
  141997. 5,
  141998. 2,
  141999. 6,
  142000. 1,
  142001. 7,
  142002. 0,
  142003. 8,
  142004. };
  142005. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142006. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142007. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142008. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142009. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142010. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142011. 14,
  142012. };
  142013. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142014. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142015. };
  142016. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142017. 7, 5, 3, 1, 0, 2, 4, 6,
  142018. 8,
  142019. };
  142020. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142021. _vq_quantthresh__44cn1_sm_p8_0,
  142022. _vq_quantmap__44cn1_sm_p8_0,
  142023. 9,
  142024. 9
  142025. };
  142026. static static_codebook _44cn1_sm_p8_0 = {
  142027. 2, 81,
  142028. _vq_lengthlist__44cn1_sm_p8_0,
  142029. 1, -516186112, 1627103232, 4, 0,
  142030. _vq_quantlist__44cn1_sm_p8_0,
  142031. NULL,
  142032. &_vq_auxt__44cn1_sm_p8_0,
  142033. NULL,
  142034. 0
  142035. };
  142036. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142037. 6,
  142038. 5,
  142039. 7,
  142040. 4,
  142041. 8,
  142042. 3,
  142043. 9,
  142044. 2,
  142045. 10,
  142046. 1,
  142047. 11,
  142048. 0,
  142049. 12,
  142050. };
  142051. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142052. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142053. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142054. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142055. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142056. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142057. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142058. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142059. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142060. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142061. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142062. 17,12,12,11,10,13,11,13,13,
  142063. };
  142064. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142065. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142066. 42.5, 59.5, 76.5, 93.5,
  142067. };
  142068. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142069. 11, 9, 7, 5, 3, 1, 0, 2,
  142070. 4, 6, 8, 10, 12,
  142071. };
  142072. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142073. _vq_quantthresh__44cn1_sm_p8_1,
  142074. _vq_quantmap__44cn1_sm_p8_1,
  142075. 13,
  142076. 13
  142077. };
  142078. static static_codebook _44cn1_sm_p8_1 = {
  142079. 2, 169,
  142080. _vq_lengthlist__44cn1_sm_p8_1,
  142081. 1, -522616832, 1620115456, 4, 0,
  142082. _vq_quantlist__44cn1_sm_p8_1,
  142083. NULL,
  142084. &_vq_auxt__44cn1_sm_p8_1,
  142085. NULL,
  142086. 0
  142087. };
  142088. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142089. 8,
  142090. 7,
  142091. 9,
  142092. 6,
  142093. 10,
  142094. 5,
  142095. 11,
  142096. 4,
  142097. 12,
  142098. 3,
  142099. 13,
  142100. 2,
  142101. 14,
  142102. 1,
  142103. 15,
  142104. 0,
  142105. 16,
  142106. };
  142107. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142108. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142109. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142110. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142111. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142112. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142113. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142114. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142115. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142116. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142117. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142118. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142119. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142120. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142121. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142122. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142123. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142124. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142125. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142126. 9,
  142127. };
  142128. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142129. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142130. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142131. };
  142132. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142133. 15, 13, 11, 9, 7, 5, 3, 1,
  142134. 0, 2, 4, 6, 8, 10, 12, 14,
  142135. 16,
  142136. };
  142137. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142138. _vq_quantthresh__44cn1_sm_p8_2,
  142139. _vq_quantmap__44cn1_sm_p8_2,
  142140. 17,
  142141. 17
  142142. };
  142143. static static_codebook _44cn1_sm_p8_2 = {
  142144. 2, 289,
  142145. _vq_lengthlist__44cn1_sm_p8_2,
  142146. 1, -529530880, 1611661312, 5, 0,
  142147. _vq_quantlist__44cn1_sm_p8_2,
  142148. NULL,
  142149. &_vq_auxt__44cn1_sm_p8_2,
  142150. NULL,
  142151. 0
  142152. };
  142153. static long _huff_lengthlist__44cn1_sm_short[] = {
  142154. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142155. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142156. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142157. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142158. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142159. 9,
  142160. };
  142161. static static_codebook _huff_book__44cn1_sm_short = {
  142162. 2, 81,
  142163. _huff_lengthlist__44cn1_sm_short,
  142164. 0, 0, 0, 0, 0,
  142165. NULL,
  142166. NULL,
  142167. NULL,
  142168. NULL,
  142169. 0
  142170. };
  142171. /*** End of inlined file: res_books_stereo.h ***/
  142172. /***** residue backends *********************************************/
  142173. static vorbis_info_residue0 _residue_44_low={
  142174. 0,-1, -1, 9,-1,
  142175. /* 0 1 2 3 4 5 6 7 */
  142176. {0},
  142177. {-1},
  142178. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142179. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142180. };
  142181. static vorbis_info_residue0 _residue_44_mid={
  142182. 0,-1, -1, 10,-1,
  142183. /* 0 1 2 3 4 5 6 7 8 */
  142184. {0},
  142185. {-1},
  142186. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142187. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142188. };
  142189. static vorbis_info_residue0 _residue_44_high={
  142190. 0,-1, -1, 10,-1,
  142191. /* 0 1 2 3 4 5 6 7 8 */
  142192. {0},
  142193. {-1},
  142194. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142195. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142196. };
  142197. static static_bookblock _resbook_44s_n1={
  142198. {
  142199. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142200. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142201. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142202. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142203. }
  142204. };
  142205. static static_bookblock _resbook_44sm_n1={
  142206. {
  142207. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142208. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142209. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142210. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142211. }
  142212. };
  142213. static static_bookblock _resbook_44s_0={
  142214. {
  142215. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142216. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142217. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142218. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142219. }
  142220. };
  142221. static static_bookblock _resbook_44sm_0={
  142222. {
  142223. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142224. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142225. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142226. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142227. }
  142228. };
  142229. static static_bookblock _resbook_44s_1={
  142230. {
  142231. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142232. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142233. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142234. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142235. }
  142236. };
  142237. static static_bookblock _resbook_44sm_1={
  142238. {
  142239. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142240. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142241. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142242. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142243. }
  142244. };
  142245. static static_bookblock _resbook_44s_2={
  142246. {
  142247. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142248. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142249. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142250. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142251. }
  142252. };
  142253. static static_bookblock _resbook_44s_3={
  142254. {
  142255. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142256. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142257. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142258. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142259. }
  142260. };
  142261. static static_bookblock _resbook_44s_4={
  142262. {
  142263. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142264. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142265. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142266. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142267. }
  142268. };
  142269. static static_bookblock _resbook_44s_5={
  142270. {
  142271. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142272. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142273. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142274. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142275. }
  142276. };
  142277. static static_bookblock _resbook_44s_6={
  142278. {
  142279. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142280. {0,0,&_44c6_s_p4_0},
  142281. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142282. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142283. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142284. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142285. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142286. }
  142287. };
  142288. static static_bookblock _resbook_44s_7={
  142289. {
  142290. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142291. {0,0,&_44c7_s_p4_0},
  142292. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142293. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142294. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142295. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142296. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142297. }
  142298. };
  142299. static static_bookblock _resbook_44s_8={
  142300. {
  142301. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142302. {0,0,&_44c8_s_p4_0},
  142303. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142304. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142305. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142306. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142307. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142308. }
  142309. };
  142310. static static_bookblock _resbook_44s_9={
  142311. {
  142312. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142313. {0,0,&_44c9_s_p4_0},
  142314. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142315. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142316. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142317. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142318. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142319. }
  142320. };
  142321. static vorbis_residue_template _res_44s_n1[]={
  142322. {2,0, &_residue_44_low,
  142323. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142324. &_resbook_44s_n1,&_resbook_44sm_n1},
  142325. {2,0, &_residue_44_low,
  142326. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142327. &_resbook_44s_n1,&_resbook_44sm_n1}
  142328. };
  142329. static vorbis_residue_template _res_44s_0[]={
  142330. {2,0, &_residue_44_low,
  142331. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142332. &_resbook_44s_0,&_resbook_44sm_0},
  142333. {2,0, &_residue_44_low,
  142334. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142335. &_resbook_44s_0,&_resbook_44sm_0}
  142336. };
  142337. static vorbis_residue_template _res_44s_1[]={
  142338. {2,0, &_residue_44_low,
  142339. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142340. &_resbook_44s_1,&_resbook_44sm_1},
  142341. {2,0, &_residue_44_low,
  142342. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142343. &_resbook_44s_1,&_resbook_44sm_1}
  142344. };
  142345. static vorbis_residue_template _res_44s_2[]={
  142346. {2,0, &_residue_44_mid,
  142347. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142348. &_resbook_44s_2,&_resbook_44s_2},
  142349. {2,0, &_residue_44_mid,
  142350. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142351. &_resbook_44s_2,&_resbook_44s_2}
  142352. };
  142353. static vorbis_residue_template _res_44s_3[]={
  142354. {2,0, &_residue_44_mid,
  142355. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142356. &_resbook_44s_3,&_resbook_44s_3},
  142357. {2,0, &_residue_44_mid,
  142358. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142359. &_resbook_44s_3,&_resbook_44s_3}
  142360. };
  142361. static vorbis_residue_template _res_44s_4[]={
  142362. {2,0, &_residue_44_mid,
  142363. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142364. &_resbook_44s_4,&_resbook_44s_4},
  142365. {2,0, &_residue_44_mid,
  142366. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142367. &_resbook_44s_4,&_resbook_44s_4}
  142368. };
  142369. static vorbis_residue_template _res_44s_5[]={
  142370. {2,0, &_residue_44_mid,
  142371. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142372. &_resbook_44s_5,&_resbook_44s_5},
  142373. {2,0, &_residue_44_mid,
  142374. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142375. &_resbook_44s_5,&_resbook_44s_5}
  142376. };
  142377. static vorbis_residue_template _res_44s_6[]={
  142378. {2,0, &_residue_44_high,
  142379. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142380. &_resbook_44s_6,&_resbook_44s_6},
  142381. {2,0, &_residue_44_high,
  142382. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142383. &_resbook_44s_6,&_resbook_44s_6}
  142384. };
  142385. static vorbis_residue_template _res_44s_7[]={
  142386. {2,0, &_residue_44_high,
  142387. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142388. &_resbook_44s_7,&_resbook_44s_7},
  142389. {2,0, &_residue_44_high,
  142390. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142391. &_resbook_44s_7,&_resbook_44s_7}
  142392. };
  142393. static vorbis_residue_template _res_44s_8[]={
  142394. {2,0, &_residue_44_high,
  142395. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142396. &_resbook_44s_8,&_resbook_44s_8},
  142397. {2,0, &_residue_44_high,
  142398. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142399. &_resbook_44s_8,&_resbook_44s_8}
  142400. };
  142401. static vorbis_residue_template _res_44s_9[]={
  142402. {2,0, &_residue_44_high,
  142403. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142404. &_resbook_44s_9,&_resbook_44s_9},
  142405. {2,0, &_residue_44_high,
  142406. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142407. &_resbook_44s_9,&_resbook_44s_9}
  142408. };
  142409. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142410. { _map_nominal, _res_44s_n1 }, /* -1 */
  142411. { _map_nominal, _res_44s_0 }, /* 0 */
  142412. { _map_nominal, _res_44s_1 }, /* 1 */
  142413. { _map_nominal, _res_44s_2 }, /* 2 */
  142414. { _map_nominal, _res_44s_3 }, /* 3 */
  142415. { _map_nominal, _res_44s_4 }, /* 4 */
  142416. { _map_nominal, _res_44s_5 }, /* 5 */
  142417. { _map_nominal, _res_44s_6 }, /* 6 */
  142418. { _map_nominal, _res_44s_7 }, /* 7 */
  142419. { _map_nominal, _res_44s_8 }, /* 8 */
  142420. { _map_nominal, _res_44s_9 }, /* 9 */
  142421. };
  142422. /*** End of inlined file: residue_44.h ***/
  142423. /*** Start of inlined file: psych_44.h ***/
  142424. /* preecho trigger settings *****************************************/
  142425. static vorbis_info_psy_global _psy_global_44[5]={
  142426. {8, /* lines per eighth octave */
  142427. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142428. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142429. -6.f,
  142430. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142431. },
  142432. {8, /* lines per eighth octave */
  142433. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142434. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142435. -6.f,
  142436. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142437. },
  142438. {8, /* lines per eighth octave */
  142439. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142440. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142441. -6.f,
  142442. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142443. },
  142444. {8, /* lines per eighth octave */
  142445. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142446. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142447. -6.f,
  142448. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142449. },
  142450. {8, /* lines per eighth octave */
  142451. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142452. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142453. -6.f,
  142454. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142455. },
  142456. };
  142457. /* noise compander lookups * low, mid, high quality ****************/
  142458. static compandblock _psy_compand_44[6]={
  142459. /* sub-mode Z short */
  142460. {{
  142461. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142462. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142463. 16,17,18,19,20,21,22, 23, /* 23dB */
  142464. 24,25,26,27,28,29,30, 31, /* 31dB */
  142465. 32,33,34,35,36,37,38, 39, /* 39dB */
  142466. }},
  142467. /* mode_Z nominal short */
  142468. {{
  142469. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142470. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142471. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142472. 15,16,17,17,17,18,18, 19, /* 31dB */
  142473. 19,19,20,21,22,23,24, 25, /* 39dB */
  142474. }},
  142475. /* mode A short */
  142476. {{
  142477. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142478. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142479. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142480. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142481. 11,12,13,14,15,16,17, 18, /* 39dB */
  142482. }},
  142483. /* sub-mode Z long */
  142484. {{
  142485. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142486. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142487. 16,17,18,19,20,21,22, 23, /* 23dB */
  142488. 24,25,26,27,28,29,30, 31, /* 31dB */
  142489. 32,33,34,35,36,37,38, 39, /* 39dB */
  142490. }},
  142491. /* mode_Z nominal long */
  142492. {{
  142493. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142494. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142495. 13,14,14,14,15,15,15, 15, /* 23dB */
  142496. 16,16,17,17,17,18,18, 19, /* 31dB */
  142497. 19,19,20,21,22,23,24, 25, /* 39dB */
  142498. }},
  142499. /* mode A long */
  142500. {{
  142501. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142502. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142503. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142504. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142505. 11,12,13,14,15,16,17, 18, /* 39dB */
  142506. }}
  142507. };
  142508. /* tonal masking curve level adjustments *************************/
  142509. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142510. /* 63 125 250 500 1 2 4 8 16 */
  142511. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142512. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142513. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142514. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142515. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142516. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142517. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142518. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142519. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142520. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142521. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142522. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142523. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142524. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142525. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142526. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142527. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142528. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142529. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142530. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142531. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142532. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142533. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142534. };
  142535. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142536. /* 63 125 250 500 1 2 4 8 16 */
  142537. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142538. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142539. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142540. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142541. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142542. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142543. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142544. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142545. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142546. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142547. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142548. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142549. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142550. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142551. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142552. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142553. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142554. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142555. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142556. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142557. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142558. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142559. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142560. };
  142561. /* noise bias (transition block) */
  142562. static noise3 _psy_noisebias_trans[12]={
  142563. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142564. /* -1 */
  142565. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142566. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142567. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142568. /* 0
  142569. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142570. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142571. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142572. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142573. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142574. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142575. /* 1
  142576. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142577. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142578. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142579. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142580. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142581. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142582. /* 2
  142583. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142584. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142585. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142586. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142587. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142588. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142589. /* 3
  142590. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142591. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142592. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142593. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142594. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142595. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142596. /* 4
  142597. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142598. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142599. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142600. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142601. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142602. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142603. /* 5
  142604. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142605. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142606. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142607. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142608. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142609. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142610. /* 6
  142611. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142612. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142613. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142614. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142615. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142616. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142617. /* 7
  142618. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142619. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142620. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142621. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142622. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142623. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142624. /* 8
  142625. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142626. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142627. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142628. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142629. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142630. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142631. /* 9
  142632. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142633. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142634. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142635. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142636. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142637. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142638. /* 10 */
  142639. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142640. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142641. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142642. };
  142643. /* noise bias (long block) */
  142644. static noise3 _psy_noisebias_long[12]={
  142645. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142646. /* -1 */
  142647. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142648. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142649. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142650. /* 0 */
  142651. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142652. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142653. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142654. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142655. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142656. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142657. /* 1 */
  142658. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142659. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142660. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142661. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142662. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142663. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142664. /* 2 */
  142665. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142666. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142667. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142668. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142669. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142670. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142671. /* 3 */
  142672. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142673. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142674. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142675. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142676. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142677. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142678. /* 4 */
  142679. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142680. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142681. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142682. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142683. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142684. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142685. /* 5 */
  142686. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142687. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142688. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142689. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142690. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142691. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142692. /* 6 */
  142693. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142694. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142695. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142696. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142697. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142698. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142699. /* 7 */
  142700. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142701. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142702. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142703. /* 8 */
  142704. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142705. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142706. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142707. /* 9 */
  142708. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142709. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142710. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142711. /* 10 */
  142712. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142713. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142714. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142715. };
  142716. /* noise bias (impulse block) */
  142717. static noise3 _psy_noisebias_impulse[12]={
  142718. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142719. /* -1 */
  142720. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142721. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142722. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142723. /* 0 */
  142724. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142725. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142726. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142727. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142728. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142729. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142730. /* 1 */
  142731. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142732. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142733. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142734. /* 2 */
  142735. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142736. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142737. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142738. /* 3 */
  142739. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142740. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142741. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142742. /* 4 */
  142743. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142744. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142745. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142746. /* 5 */
  142747. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142748. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142749. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142750. /* 6
  142751. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142752. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142753. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142754. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142755. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142756. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142757. /* 7 */
  142758. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142759. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142760. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142761. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142762. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142763. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142764. /* 8 */
  142765. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142766. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142767. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142768. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142769. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142770. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142771. /* 9 */
  142772. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142773. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142774. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142775. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142776. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142777. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142778. /* 10 */
  142779. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142780. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142781. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142782. };
  142783. /* noise bias (padding block) */
  142784. static noise3 _psy_noisebias_padding[12]={
  142785. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142786. /* -1 */
  142787. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142788. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142789. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142790. /* 0 */
  142791. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142792. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142793. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142794. /* 1 */
  142795. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142796. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142797. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142798. /* 2 */
  142799. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142800. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142801. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142802. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142803. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142804. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142805. /* 3 */
  142806. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142807. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142808. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142809. /* 4 */
  142810. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142811. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142812. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142813. /* 5 */
  142814. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142815. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142816. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142817. /* 6 */
  142818. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142819. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142820. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142821. /* 7 */
  142822. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142823. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142824. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142825. /* 8 */
  142826. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142827. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142828. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142829. /* 9 */
  142830. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142831. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142832. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142833. /* 10 */
  142834. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142835. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142836. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142837. };
  142838. static noiseguard _psy_noiseguards_44[4]={
  142839. {3,3,15},
  142840. {3,3,15},
  142841. {10,10,100},
  142842. {10,10,100},
  142843. };
  142844. static int _psy_tone_suppress[12]={
  142845. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142846. };
  142847. static int _psy_tone_0dB[12]={
  142848. 90,90,95,95,95,95,105,105,105,105,105,105,
  142849. };
  142850. static int _psy_noise_suppress[12]={
  142851. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142852. };
  142853. static vorbis_info_psy _psy_info_template={
  142854. /* blockflag */
  142855. -1,
  142856. /* ath_adjatt, ath_maxatt */
  142857. -140.,-140.,
  142858. /* tonemask att boost/decay,suppr,curves */
  142859. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142860. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142861. 1, -0.f, .5f, .5f, 0,0,0,
  142862. /* noiseoffset*3, noisecompand, max_curve_dB */
  142863. {{-1},{-1},{-1}},{-1},105.f,
  142864. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142865. 0,0,-1,-1,0.,
  142866. };
  142867. /* ath ****************/
  142868. static int _psy_ath_floater[12]={
  142869. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142870. };
  142871. static int _psy_ath_abs[12]={
  142872. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142873. };
  142874. /* stereo setup. These don't map directly to quality level, there's
  142875. an additional indirection as several of the below may be used in a
  142876. single bitmanaged stream
  142877. ****************/
  142878. /* various stereo possibilities */
  142879. /* stereo mode by base quality level */
  142880. static adj_stereo _psy_stereo_modes_44[12]={
  142881. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142882. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142883. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142884. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142885. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142886. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142887. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142888. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142889. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142890. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142891. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142892. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142893. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142894. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142895. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142896. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142897. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142898. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142899. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142900. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142901. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142902. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142903. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142904. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142905. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142906. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142907. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142908. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142909. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142910. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142911. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142912. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142913. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142914. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142915. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142916. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142917. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142918. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142919. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142920. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142921. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142922. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142923. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142924. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142925. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142926. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142927. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142928. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142929. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142930. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142931. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142932. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142933. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142934. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142935. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142936. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142937. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142938. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142939. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142940. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142941. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142942. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142943. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142944. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142945. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142946. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142947. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142948. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142949. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142950. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142951. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142952. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142953. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142954. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142955. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142956. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142957. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142958. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142959. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142960. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142961. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142962. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142963. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142964. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142965. };
  142966. /* tone master attenuation by base quality mode and bitrate tweak */
  142967. static att3 _psy_tone_masteratt_44[12]={
  142968. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142969. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142970. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142971. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142972. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142973. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142974. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142975. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142976. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142977. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142978. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142979. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142980. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142981. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142982. };
  142983. /* lowpass by mode **************/
  142984. static double _psy_lowpass_44[12]={
  142985. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142986. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142987. };
  142988. /* noise normalization **********/
  142989. static int _noise_start_short_44[11]={
  142990. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142991. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142992. };
  142993. static int _noise_start_long_44[11]={
  142994. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142995. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142996. };
  142997. static int _noise_part_short_44[11]={
  142998. 8,8,8,8,8,8,8,8,8,8,8
  142999. };
  143000. static int _noise_part_long_44[11]={
  143001. 32,32,32,32,32,32,32,32,32,32,32
  143002. };
  143003. static double _noise_thresh_44[11]={
  143004. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143005. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143006. };
  143007. static double _noise_thresh_5only[2]={
  143008. .5,.5,
  143009. };
  143010. /*** End of inlined file: psych_44.h ***/
  143011. static double rate_mapping_44_stereo[12]={
  143012. 22500.,32000.,40000.,48000.,56000.,64000.,
  143013. 80000.,96000.,112000.,128000.,160000.,250001.
  143014. };
  143015. static double quality_mapping_44[12]={
  143016. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143017. };
  143018. static int blocksize_short_44[11]={
  143019. 512,256,256,256,256,256,256,256,256,256,256
  143020. };
  143021. static int blocksize_long_44[11]={
  143022. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143023. };
  143024. static double _psy_compand_short_mapping[12]={
  143025. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143026. };
  143027. static double _psy_compand_long_mapping[12]={
  143028. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143029. };
  143030. static double _global_mapping_44[12]={
  143031. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143032. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143033. };
  143034. static int _floor_short_mapping_44[11]={
  143035. 1,0,0,2,2,4,5,5,5,5,5
  143036. };
  143037. static int _floor_long_mapping_44[11]={
  143038. 8,7,7,7,7,7,7,7,7,7,7
  143039. };
  143040. ve_setup_data_template ve_setup_44_stereo={
  143041. 11,
  143042. rate_mapping_44_stereo,
  143043. quality_mapping_44,
  143044. 2,
  143045. 40000,
  143046. 50000,
  143047. blocksize_short_44,
  143048. blocksize_long_44,
  143049. _psy_tone_masteratt_44,
  143050. _psy_tone_0dB,
  143051. _psy_tone_suppress,
  143052. _vp_tonemask_adj_otherblock,
  143053. _vp_tonemask_adj_longblock,
  143054. _vp_tonemask_adj_otherblock,
  143055. _psy_noiseguards_44,
  143056. _psy_noisebias_impulse,
  143057. _psy_noisebias_padding,
  143058. _psy_noisebias_trans,
  143059. _psy_noisebias_long,
  143060. _psy_noise_suppress,
  143061. _psy_compand_44,
  143062. _psy_compand_short_mapping,
  143063. _psy_compand_long_mapping,
  143064. {_noise_start_short_44,_noise_start_long_44},
  143065. {_noise_part_short_44,_noise_part_long_44},
  143066. _noise_thresh_44,
  143067. _psy_ath_floater,
  143068. _psy_ath_abs,
  143069. _psy_lowpass_44,
  143070. _psy_global_44,
  143071. _global_mapping_44,
  143072. _psy_stereo_modes_44,
  143073. _floor_books,
  143074. _floor,
  143075. _floor_short_mapping_44,
  143076. _floor_long_mapping_44,
  143077. _mapres_template_44_stereo
  143078. };
  143079. /*** End of inlined file: setup_44.h ***/
  143080. /*** Start of inlined file: setup_44u.h ***/
  143081. /*** Start of inlined file: residue_44u.h ***/
  143082. /*** Start of inlined file: res_books_uncoupled.h ***/
  143083. static long _vq_quantlist__16u0__p1_0[] = {
  143084. 1,
  143085. 0,
  143086. 2,
  143087. };
  143088. static long _vq_lengthlist__16u0__p1_0[] = {
  143089. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143090. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143091. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143092. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143093. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143094. 12,
  143095. };
  143096. static float _vq_quantthresh__16u0__p1_0[] = {
  143097. -0.5, 0.5,
  143098. };
  143099. static long _vq_quantmap__16u0__p1_0[] = {
  143100. 1, 0, 2,
  143101. };
  143102. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143103. _vq_quantthresh__16u0__p1_0,
  143104. _vq_quantmap__16u0__p1_0,
  143105. 3,
  143106. 3
  143107. };
  143108. static static_codebook _16u0__p1_0 = {
  143109. 4, 81,
  143110. _vq_lengthlist__16u0__p1_0,
  143111. 1, -535822336, 1611661312, 2, 0,
  143112. _vq_quantlist__16u0__p1_0,
  143113. NULL,
  143114. &_vq_auxt__16u0__p1_0,
  143115. NULL,
  143116. 0
  143117. };
  143118. static long _vq_quantlist__16u0__p2_0[] = {
  143119. 1,
  143120. 0,
  143121. 2,
  143122. };
  143123. static long _vq_lengthlist__16u0__p2_0[] = {
  143124. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143125. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143126. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143127. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143128. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143129. 8,
  143130. };
  143131. static float _vq_quantthresh__16u0__p2_0[] = {
  143132. -0.5, 0.5,
  143133. };
  143134. static long _vq_quantmap__16u0__p2_0[] = {
  143135. 1, 0, 2,
  143136. };
  143137. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143138. _vq_quantthresh__16u0__p2_0,
  143139. _vq_quantmap__16u0__p2_0,
  143140. 3,
  143141. 3
  143142. };
  143143. static static_codebook _16u0__p2_0 = {
  143144. 4, 81,
  143145. _vq_lengthlist__16u0__p2_0,
  143146. 1, -535822336, 1611661312, 2, 0,
  143147. _vq_quantlist__16u0__p2_0,
  143148. NULL,
  143149. &_vq_auxt__16u0__p2_0,
  143150. NULL,
  143151. 0
  143152. };
  143153. static long _vq_quantlist__16u0__p3_0[] = {
  143154. 2,
  143155. 1,
  143156. 3,
  143157. 0,
  143158. 4,
  143159. };
  143160. static long _vq_lengthlist__16u0__p3_0[] = {
  143161. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143162. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143163. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143164. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143165. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143166. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143167. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143168. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143169. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143170. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143171. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143172. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143173. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143174. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143175. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143176. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143177. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143178. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143179. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143180. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143181. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143182. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143183. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143184. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143185. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143186. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143187. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143188. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143189. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143190. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143191. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143192. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143193. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143194. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143195. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143196. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143197. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143198. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143199. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143200. 18,
  143201. };
  143202. static float _vq_quantthresh__16u0__p3_0[] = {
  143203. -1.5, -0.5, 0.5, 1.5,
  143204. };
  143205. static long _vq_quantmap__16u0__p3_0[] = {
  143206. 3, 1, 0, 2, 4,
  143207. };
  143208. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143209. _vq_quantthresh__16u0__p3_0,
  143210. _vq_quantmap__16u0__p3_0,
  143211. 5,
  143212. 5
  143213. };
  143214. static static_codebook _16u0__p3_0 = {
  143215. 4, 625,
  143216. _vq_lengthlist__16u0__p3_0,
  143217. 1, -533725184, 1611661312, 3, 0,
  143218. _vq_quantlist__16u0__p3_0,
  143219. NULL,
  143220. &_vq_auxt__16u0__p3_0,
  143221. NULL,
  143222. 0
  143223. };
  143224. static long _vq_quantlist__16u0__p4_0[] = {
  143225. 2,
  143226. 1,
  143227. 3,
  143228. 0,
  143229. 4,
  143230. };
  143231. static long _vq_lengthlist__16u0__p4_0[] = {
  143232. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143233. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143234. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143235. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143236. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143237. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143238. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143239. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143240. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143241. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143242. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143243. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143244. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143245. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143246. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143247. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143248. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143249. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143250. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143251. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143252. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143253. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143254. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143255. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143256. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143257. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143258. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143259. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143260. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143261. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143262. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143263. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143264. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143265. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143266. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143267. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143268. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143269. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143270. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143271. 11,
  143272. };
  143273. static float _vq_quantthresh__16u0__p4_0[] = {
  143274. -1.5, -0.5, 0.5, 1.5,
  143275. };
  143276. static long _vq_quantmap__16u0__p4_0[] = {
  143277. 3, 1, 0, 2, 4,
  143278. };
  143279. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143280. _vq_quantthresh__16u0__p4_0,
  143281. _vq_quantmap__16u0__p4_0,
  143282. 5,
  143283. 5
  143284. };
  143285. static static_codebook _16u0__p4_0 = {
  143286. 4, 625,
  143287. _vq_lengthlist__16u0__p4_0,
  143288. 1, -533725184, 1611661312, 3, 0,
  143289. _vq_quantlist__16u0__p4_0,
  143290. NULL,
  143291. &_vq_auxt__16u0__p4_0,
  143292. NULL,
  143293. 0
  143294. };
  143295. static long _vq_quantlist__16u0__p5_0[] = {
  143296. 4,
  143297. 3,
  143298. 5,
  143299. 2,
  143300. 6,
  143301. 1,
  143302. 7,
  143303. 0,
  143304. 8,
  143305. };
  143306. static long _vq_lengthlist__16u0__p5_0[] = {
  143307. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143308. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143309. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143310. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143311. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143312. 12,
  143313. };
  143314. static float _vq_quantthresh__16u0__p5_0[] = {
  143315. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143316. };
  143317. static long _vq_quantmap__16u0__p5_0[] = {
  143318. 7, 5, 3, 1, 0, 2, 4, 6,
  143319. 8,
  143320. };
  143321. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143322. _vq_quantthresh__16u0__p5_0,
  143323. _vq_quantmap__16u0__p5_0,
  143324. 9,
  143325. 9
  143326. };
  143327. static static_codebook _16u0__p5_0 = {
  143328. 2, 81,
  143329. _vq_lengthlist__16u0__p5_0,
  143330. 1, -531628032, 1611661312, 4, 0,
  143331. _vq_quantlist__16u0__p5_0,
  143332. NULL,
  143333. &_vq_auxt__16u0__p5_0,
  143334. NULL,
  143335. 0
  143336. };
  143337. static long _vq_quantlist__16u0__p6_0[] = {
  143338. 6,
  143339. 5,
  143340. 7,
  143341. 4,
  143342. 8,
  143343. 3,
  143344. 9,
  143345. 2,
  143346. 10,
  143347. 1,
  143348. 11,
  143349. 0,
  143350. 12,
  143351. };
  143352. static long _vq_lengthlist__16u0__p6_0[] = {
  143353. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143354. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143355. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143356. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143357. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143358. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143359. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143360. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143361. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143362. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143363. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143364. };
  143365. static float _vq_quantthresh__16u0__p6_0[] = {
  143366. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143367. 12.5, 17.5, 22.5, 27.5,
  143368. };
  143369. static long _vq_quantmap__16u0__p6_0[] = {
  143370. 11, 9, 7, 5, 3, 1, 0, 2,
  143371. 4, 6, 8, 10, 12,
  143372. };
  143373. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143374. _vq_quantthresh__16u0__p6_0,
  143375. _vq_quantmap__16u0__p6_0,
  143376. 13,
  143377. 13
  143378. };
  143379. static static_codebook _16u0__p6_0 = {
  143380. 2, 169,
  143381. _vq_lengthlist__16u0__p6_0,
  143382. 1, -526516224, 1616117760, 4, 0,
  143383. _vq_quantlist__16u0__p6_0,
  143384. NULL,
  143385. &_vq_auxt__16u0__p6_0,
  143386. NULL,
  143387. 0
  143388. };
  143389. static long _vq_quantlist__16u0__p6_1[] = {
  143390. 2,
  143391. 1,
  143392. 3,
  143393. 0,
  143394. 4,
  143395. };
  143396. static long _vq_lengthlist__16u0__p6_1[] = {
  143397. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143398. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143399. };
  143400. static float _vq_quantthresh__16u0__p6_1[] = {
  143401. -1.5, -0.5, 0.5, 1.5,
  143402. };
  143403. static long _vq_quantmap__16u0__p6_1[] = {
  143404. 3, 1, 0, 2, 4,
  143405. };
  143406. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143407. _vq_quantthresh__16u0__p6_1,
  143408. _vq_quantmap__16u0__p6_1,
  143409. 5,
  143410. 5
  143411. };
  143412. static static_codebook _16u0__p6_1 = {
  143413. 2, 25,
  143414. _vq_lengthlist__16u0__p6_1,
  143415. 1, -533725184, 1611661312, 3, 0,
  143416. _vq_quantlist__16u0__p6_1,
  143417. NULL,
  143418. &_vq_auxt__16u0__p6_1,
  143419. NULL,
  143420. 0
  143421. };
  143422. static long _vq_quantlist__16u0__p7_0[] = {
  143423. 1,
  143424. 0,
  143425. 2,
  143426. };
  143427. static long _vq_lengthlist__16u0__p7_0[] = {
  143428. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143429. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143430. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143431. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143432. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143433. 7,
  143434. };
  143435. static float _vq_quantthresh__16u0__p7_0[] = {
  143436. -157.5, 157.5,
  143437. };
  143438. static long _vq_quantmap__16u0__p7_0[] = {
  143439. 1, 0, 2,
  143440. };
  143441. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143442. _vq_quantthresh__16u0__p7_0,
  143443. _vq_quantmap__16u0__p7_0,
  143444. 3,
  143445. 3
  143446. };
  143447. static static_codebook _16u0__p7_0 = {
  143448. 4, 81,
  143449. _vq_lengthlist__16u0__p7_0,
  143450. 1, -518803456, 1628680192, 2, 0,
  143451. _vq_quantlist__16u0__p7_0,
  143452. NULL,
  143453. &_vq_auxt__16u0__p7_0,
  143454. NULL,
  143455. 0
  143456. };
  143457. static long _vq_quantlist__16u0__p7_1[] = {
  143458. 7,
  143459. 6,
  143460. 8,
  143461. 5,
  143462. 9,
  143463. 4,
  143464. 10,
  143465. 3,
  143466. 11,
  143467. 2,
  143468. 12,
  143469. 1,
  143470. 13,
  143471. 0,
  143472. 14,
  143473. };
  143474. static long _vq_lengthlist__16u0__p7_1[] = {
  143475. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143476. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143477. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143478. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143479. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143480. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143483. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143484. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143486. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143487. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143488. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143489. 10,
  143490. };
  143491. static float _vq_quantthresh__16u0__p7_1[] = {
  143492. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143493. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143494. };
  143495. static long _vq_quantmap__16u0__p7_1[] = {
  143496. 13, 11, 9, 7, 5, 3, 1, 0,
  143497. 2, 4, 6, 8, 10, 12, 14,
  143498. };
  143499. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143500. _vq_quantthresh__16u0__p7_1,
  143501. _vq_quantmap__16u0__p7_1,
  143502. 15,
  143503. 15
  143504. };
  143505. static static_codebook _16u0__p7_1 = {
  143506. 2, 225,
  143507. _vq_lengthlist__16u0__p7_1,
  143508. 1, -520986624, 1620377600, 4, 0,
  143509. _vq_quantlist__16u0__p7_1,
  143510. NULL,
  143511. &_vq_auxt__16u0__p7_1,
  143512. NULL,
  143513. 0
  143514. };
  143515. static long _vq_quantlist__16u0__p7_2[] = {
  143516. 10,
  143517. 9,
  143518. 11,
  143519. 8,
  143520. 12,
  143521. 7,
  143522. 13,
  143523. 6,
  143524. 14,
  143525. 5,
  143526. 15,
  143527. 4,
  143528. 16,
  143529. 3,
  143530. 17,
  143531. 2,
  143532. 18,
  143533. 1,
  143534. 19,
  143535. 0,
  143536. 20,
  143537. };
  143538. static long _vq_lengthlist__16u0__p7_2[] = {
  143539. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143540. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143541. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143542. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143543. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143544. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143545. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143546. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143547. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143548. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143549. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143550. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143551. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143552. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143553. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143554. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143555. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143556. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143557. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143558. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143559. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143560. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143561. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143562. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143563. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143564. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143565. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143566. 10,10,12,11,10,11,11,11,10,
  143567. };
  143568. static float _vq_quantthresh__16u0__p7_2[] = {
  143569. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143570. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143571. 6.5, 7.5, 8.5, 9.5,
  143572. };
  143573. static long _vq_quantmap__16u0__p7_2[] = {
  143574. 19, 17, 15, 13, 11, 9, 7, 5,
  143575. 3, 1, 0, 2, 4, 6, 8, 10,
  143576. 12, 14, 16, 18, 20,
  143577. };
  143578. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143579. _vq_quantthresh__16u0__p7_2,
  143580. _vq_quantmap__16u0__p7_2,
  143581. 21,
  143582. 21
  143583. };
  143584. static static_codebook _16u0__p7_2 = {
  143585. 2, 441,
  143586. _vq_lengthlist__16u0__p7_2,
  143587. 1, -529268736, 1611661312, 5, 0,
  143588. _vq_quantlist__16u0__p7_2,
  143589. NULL,
  143590. &_vq_auxt__16u0__p7_2,
  143591. NULL,
  143592. 0
  143593. };
  143594. static long _huff_lengthlist__16u0__single[] = {
  143595. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143596. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143597. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143598. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143599. };
  143600. static static_codebook _huff_book__16u0__single = {
  143601. 2, 64,
  143602. _huff_lengthlist__16u0__single,
  143603. 0, 0, 0, 0, 0,
  143604. NULL,
  143605. NULL,
  143606. NULL,
  143607. NULL,
  143608. 0
  143609. };
  143610. static long _huff_lengthlist__16u1__long[] = {
  143611. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143612. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143613. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143614. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143615. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143616. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143617. 16,13,16,18,
  143618. };
  143619. static static_codebook _huff_book__16u1__long = {
  143620. 2, 100,
  143621. _huff_lengthlist__16u1__long,
  143622. 0, 0, 0, 0, 0,
  143623. NULL,
  143624. NULL,
  143625. NULL,
  143626. NULL,
  143627. 0
  143628. };
  143629. static long _vq_quantlist__16u1__p1_0[] = {
  143630. 1,
  143631. 0,
  143632. 2,
  143633. };
  143634. static long _vq_lengthlist__16u1__p1_0[] = {
  143635. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143636. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143637. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143638. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143639. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143640. 11,
  143641. };
  143642. static float _vq_quantthresh__16u1__p1_0[] = {
  143643. -0.5, 0.5,
  143644. };
  143645. static long _vq_quantmap__16u1__p1_0[] = {
  143646. 1, 0, 2,
  143647. };
  143648. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143649. _vq_quantthresh__16u1__p1_0,
  143650. _vq_quantmap__16u1__p1_0,
  143651. 3,
  143652. 3
  143653. };
  143654. static static_codebook _16u1__p1_0 = {
  143655. 4, 81,
  143656. _vq_lengthlist__16u1__p1_0,
  143657. 1, -535822336, 1611661312, 2, 0,
  143658. _vq_quantlist__16u1__p1_0,
  143659. NULL,
  143660. &_vq_auxt__16u1__p1_0,
  143661. NULL,
  143662. 0
  143663. };
  143664. static long _vq_quantlist__16u1__p2_0[] = {
  143665. 1,
  143666. 0,
  143667. 2,
  143668. };
  143669. static long _vq_lengthlist__16u1__p2_0[] = {
  143670. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143671. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143672. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143673. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143674. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143675. 8,
  143676. };
  143677. static float _vq_quantthresh__16u1__p2_0[] = {
  143678. -0.5, 0.5,
  143679. };
  143680. static long _vq_quantmap__16u1__p2_0[] = {
  143681. 1, 0, 2,
  143682. };
  143683. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143684. _vq_quantthresh__16u1__p2_0,
  143685. _vq_quantmap__16u1__p2_0,
  143686. 3,
  143687. 3
  143688. };
  143689. static static_codebook _16u1__p2_0 = {
  143690. 4, 81,
  143691. _vq_lengthlist__16u1__p2_0,
  143692. 1, -535822336, 1611661312, 2, 0,
  143693. _vq_quantlist__16u1__p2_0,
  143694. NULL,
  143695. &_vq_auxt__16u1__p2_0,
  143696. NULL,
  143697. 0
  143698. };
  143699. static long _vq_quantlist__16u1__p3_0[] = {
  143700. 2,
  143701. 1,
  143702. 3,
  143703. 0,
  143704. 4,
  143705. };
  143706. static long _vq_lengthlist__16u1__p3_0[] = {
  143707. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143708. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143709. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143710. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143711. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143712. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143713. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143714. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143715. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143716. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143717. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143718. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143719. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143720. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143721. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143722. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143723. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143724. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143725. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143726. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143727. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143728. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143729. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143730. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143731. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143732. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143733. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143734. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143735. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143736. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143737. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143738. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143739. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143740. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143741. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143742. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143743. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143744. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143745. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143746. 16,
  143747. };
  143748. static float _vq_quantthresh__16u1__p3_0[] = {
  143749. -1.5, -0.5, 0.5, 1.5,
  143750. };
  143751. static long _vq_quantmap__16u1__p3_0[] = {
  143752. 3, 1, 0, 2, 4,
  143753. };
  143754. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143755. _vq_quantthresh__16u1__p3_0,
  143756. _vq_quantmap__16u1__p3_0,
  143757. 5,
  143758. 5
  143759. };
  143760. static static_codebook _16u1__p3_0 = {
  143761. 4, 625,
  143762. _vq_lengthlist__16u1__p3_0,
  143763. 1, -533725184, 1611661312, 3, 0,
  143764. _vq_quantlist__16u1__p3_0,
  143765. NULL,
  143766. &_vq_auxt__16u1__p3_0,
  143767. NULL,
  143768. 0
  143769. };
  143770. static long _vq_quantlist__16u1__p4_0[] = {
  143771. 2,
  143772. 1,
  143773. 3,
  143774. 0,
  143775. 4,
  143776. };
  143777. static long _vq_lengthlist__16u1__p4_0[] = {
  143778. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143779. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143780. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143781. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143782. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143783. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143784. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143785. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143786. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143787. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143788. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143789. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143790. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143791. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143792. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143793. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143794. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143795. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143796. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143797. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143798. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143799. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143800. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143801. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143802. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143803. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143804. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143805. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143806. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143807. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143808. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143809. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143810. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143811. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143812. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143813. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143814. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143815. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143816. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143817. 11,
  143818. };
  143819. static float _vq_quantthresh__16u1__p4_0[] = {
  143820. -1.5, -0.5, 0.5, 1.5,
  143821. };
  143822. static long _vq_quantmap__16u1__p4_0[] = {
  143823. 3, 1, 0, 2, 4,
  143824. };
  143825. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143826. _vq_quantthresh__16u1__p4_0,
  143827. _vq_quantmap__16u1__p4_0,
  143828. 5,
  143829. 5
  143830. };
  143831. static static_codebook _16u1__p4_0 = {
  143832. 4, 625,
  143833. _vq_lengthlist__16u1__p4_0,
  143834. 1, -533725184, 1611661312, 3, 0,
  143835. _vq_quantlist__16u1__p4_0,
  143836. NULL,
  143837. &_vq_auxt__16u1__p4_0,
  143838. NULL,
  143839. 0
  143840. };
  143841. static long _vq_quantlist__16u1__p5_0[] = {
  143842. 4,
  143843. 3,
  143844. 5,
  143845. 2,
  143846. 6,
  143847. 1,
  143848. 7,
  143849. 0,
  143850. 8,
  143851. };
  143852. static long _vq_lengthlist__16u1__p5_0[] = {
  143853. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143854. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143855. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143856. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143857. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143858. 13,
  143859. };
  143860. static float _vq_quantthresh__16u1__p5_0[] = {
  143861. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143862. };
  143863. static long _vq_quantmap__16u1__p5_0[] = {
  143864. 7, 5, 3, 1, 0, 2, 4, 6,
  143865. 8,
  143866. };
  143867. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143868. _vq_quantthresh__16u1__p5_0,
  143869. _vq_quantmap__16u1__p5_0,
  143870. 9,
  143871. 9
  143872. };
  143873. static static_codebook _16u1__p5_0 = {
  143874. 2, 81,
  143875. _vq_lengthlist__16u1__p5_0,
  143876. 1, -531628032, 1611661312, 4, 0,
  143877. _vq_quantlist__16u1__p5_0,
  143878. NULL,
  143879. &_vq_auxt__16u1__p5_0,
  143880. NULL,
  143881. 0
  143882. };
  143883. static long _vq_quantlist__16u1__p6_0[] = {
  143884. 4,
  143885. 3,
  143886. 5,
  143887. 2,
  143888. 6,
  143889. 1,
  143890. 7,
  143891. 0,
  143892. 8,
  143893. };
  143894. static long _vq_lengthlist__16u1__p6_0[] = {
  143895. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143896. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143897. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143898. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143899. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143900. 11,
  143901. };
  143902. static float _vq_quantthresh__16u1__p6_0[] = {
  143903. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143904. };
  143905. static long _vq_quantmap__16u1__p6_0[] = {
  143906. 7, 5, 3, 1, 0, 2, 4, 6,
  143907. 8,
  143908. };
  143909. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143910. _vq_quantthresh__16u1__p6_0,
  143911. _vq_quantmap__16u1__p6_0,
  143912. 9,
  143913. 9
  143914. };
  143915. static static_codebook _16u1__p6_0 = {
  143916. 2, 81,
  143917. _vq_lengthlist__16u1__p6_0,
  143918. 1, -531628032, 1611661312, 4, 0,
  143919. _vq_quantlist__16u1__p6_0,
  143920. NULL,
  143921. &_vq_auxt__16u1__p6_0,
  143922. NULL,
  143923. 0
  143924. };
  143925. static long _vq_quantlist__16u1__p7_0[] = {
  143926. 1,
  143927. 0,
  143928. 2,
  143929. };
  143930. static long _vq_lengthlist__16u1__p7_0[] = {
  143931. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143932. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143933. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143934. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143935. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143936. 13,
  143937. };
  143938. static float _vq_quantthresh__16u1__p7_0[] = {
  143939. -5.5, 5.5,
  143940. };
  143941. static long _vq_quantmap__16u1__p7_0[] = {
  143942. 1, 0, 2,
  143943. };
  143944. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143945. _vq_quantthresh__16u1__p7_0,
  143946. _vq_quantmap__16u1__p7_0,
  143947. 3,
  143948. 3
  143949. };
  143950. static static_codebook _16u1__p7_0 = {
  143951. 4, 81,
  143952. _vq_lengthlist__16u1__p7_0,
  143953. 1, -529137664, 1618345984, 2, 0,
  143954. _vq_quantlist__16u1__p7_0,
  143955. NULL,
  143956. &_vq_auxt__16u1__p7_0,
  143957. NULL,
  143958. 0
  143959. };
  143960. static long _vq_quantlist__16u1__p7_1[] = {
  143961. 5,
  143962. 4,
  143963. 6,
  143964. 3,
  143965. 7,
  143966. 2,
  143967. 8,
  143968. 1,
  143969. 9,
  143970. 0,
  143971. 10,
  143972. };
  143973. static long _vq_lengthlist__16u1__p7_1[] = {
  143974. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143975. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143976. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143977. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143978. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143979. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143980. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143981. 8, 9, 9,10,10,10,10,10,10,
  143982. };
  143983. static float _vq_quantthresh__16u1__p7_1[] = {
  143984. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143985. 3.5, 4.5,
  143986. };
  143987. static long _vq_quantmap__16u1__p7_1[] = {
  143988. 9, 7, 5, 3, 1, 0, 2, 4,
  143989. 6, 8, 10,
  143990. };
  143991. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143992. _vq_quantthresh__16u1__p7_1,
  143993. _vq_quantmap__16u1__p7_1,
  143994. 11,
  143995. 11
  143996. };
  143997. static static_codebook _16u1__p7_1 = {
  143998. 2, 121,
  143999. _vq_lengthlist__16u1__p7_1,
  144000. 1, -531365888, 1611661312, 4, 0,
  144001. _vq_quantlist__16u1__p7_1,
  144002. NULL,
  144003. &_vq_auxt__16u1__p7_1,
  144004. NULL,
  144005. 0
  144006. };
  144007. static long _vq_quantlist__16u1__p8_0[] = {
  144008. 5,
  144009. 4,
  144010. 6,
  144011. 3,
  144012. 7,
  144013. 2,
  144014. 8,
  144015. 1,
  144016. 9,
  144017. 0,
  144018. 10,
  144019. };
  144020. static long _vq_lengthlist__16u1__p8_0[] = {
  144021. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144022. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144023. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144024. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144025. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144026. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144027. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144028. 13,14,14,15,15,16,16,15,16,
  144029. };
  144030. static float _vq_quantthresh__16u1__p8_0[] = {
  144031. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144032. 38.5, 49.5,
  144033. };
  144034. static long _vq_quantmap__16u1__p8_0[] = {
  144035. 9, 7, 5, 3, 1, 0, 2, 4,
  144036. 6, 8, 10,
  144037. };
  144038. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144039. _vq_quantthresh__16u1__p8_0,
  144040. _vq_quantmap__16u1__p8_0,
  144041. 11,
  144042. 11
  144043. };
  144044. static static_codebook _16u1__p8_0 = {
  144045. 2, 121,
  144046. _vq_lengthlist__16u1__p8_0,
  144047. 1, -524582912, 1618345984, 4, 0,
  144048. _vq_quantlist__16u1__p8_0,
  144049. NULL,
  144050. &_vq_auxt__16u1__p8_0,
  144051. NULL,
  144052. 0
  144053. };
  144054. static long _vq_quantlist__16u1__p8_1[] = {
  144055. 5,
  144056. 4,
  144057. 6,
  144058. 3,
  144059. 7,
  144060. 2,
  144061. 8,
  144062. 1,
  144063. 9,
  144064. 0,
  144065. 10,
  144066. };
  144067. static long _vq_lengthlist__16u1__p8_1[] = {
  144068. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144069. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144070. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144071. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144072. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144073. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144074. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144075. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144076. };
  144077. static float _vq_quantthresh__16u1__p8_1[] = {
  144078. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144079. 3.5, 4.5,
  144080. };
  144081. static long _vq_quantmap__16u1__p8_1[] = {
  144082. 9, 7, 5, 3, 1, 0, 2, 4,
  144083. 6, 8, 10,
  144084. };
  144085. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144086. _vq_quantthresh__16u1__p8_1,
  144087. _vq_quantmap__16u1__p8_1,
  144088. 11,
  144089. 11
  144090. };
  144091. static static_codebook _16u1__p8_1 = {
  144092. 2, 121,
  144093. _vq_lengthlist__16u1__p8_1,
  144094. 1, -531365888, 1611661312, 4, 0,
  144095. _vq_quantlist__16u1__p8_1,
  144096. NULL,
  144097. &_vq_auxt__16u1__p8_1,
  144098. NULL,
  144099. 0
  144100. };
  144101. static long _vq_quantlist__16u1__p9_0[] = {
  144102. 7,
  144103. 6,
  144104. 8,
  144105. 5,
  144106. 9,
  144107. 4,
  144108. 10,
  144109. 3,
  144110. 11,
  144111. 2,
  144112. 12,
  144113. 1,
  144114. 13,
  144115. 0,
  144116. 14,
  144117. };
  144118. static long _vq_lengthlist__16u1__p9_0[] = {
  144119. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144120. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144121. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144122. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144123. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144124. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144125. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144126. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144127. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144128. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144129. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144130. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144131. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144132. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144133. 8,
  144134. };
  144135. static float _vq_quantthresh__16u1__p9_0[] = {
  144136. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144137. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144138. };
  144139. static long _vq_quantmap__16u1__p9_0[] = {
  144140. 13, 11, 9, 7, 5, 3, 1, 0,
  144141. 2, 4, 6, 8, 10, 12, 14,
  144142. };
  144143. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144144. _vq_quantthresh__16u1__p9_0,
  144145. _vq_quantmap__16u1__p9_0,
  144146. 15,
  144147. 15
  144148. };
  144149. static static_codebook _16u1__p9_0 = {
  144150. 2, 225,
  144151. _vq_lengthlist__16u1__p9_0,
  144152. 1, -514071552, 1627381760, 4, 0,
  144153. _vq_quantlist__16u1__p9_0,
  144154. NULL,
  144155. &_vq_auxt__16u1__p9_0,
  144156. NULL,
  144157. 0
  144158. };
  144159. static long _vq_quantlist__16u1__p9_1[] = {
  144160. 7,
  144161. 6,
  144162. 8,
  144163. 5,
  144164. 9,
  144165. 4,
  144166. 10,
  144167. 3,
  144168. 11,
  144169. 2,
  144170. 12,
  144171. 1,
  144172. 13,
  144173. 0,
  144174. 14,
  144175. };
  144176. static long _vq_lengthlist__16u1__p9_1[] = {
  144177. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144178. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144179. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144180. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144181. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144182. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144183. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144184. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144185. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144186. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144187. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144188. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144190. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144191. 9,
  144192. };
  144193. static float _vq_quantthresh__16u1__p9_1[] = {
  144194. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144195. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144196. };
  144197. static long _vq_quantmap__16u1__p9_1[] = {
  144198. 13, 11, 9, 7, 5, 3, 1, 0,
  144199. 2, 4, 6, 8, 10, 12, 14,
  144200. };
  144201. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144202. _vq_quantthresh__16u1__p9_1,
  144203. _vq_quantmap__16u1__p9_1,
  144204. 15,
  144205. 15
  144206. };
  144207. static static_codebook _16u1__p9_1 = {
  144208. 2, 225,
  144209. _vq_lengthlist__16u1__p9_1,
  144210. 1, -522338304, 1620115456, 4, 0,
  144211. _vq_quantlist__16u1__p9_1,
  144212. NULL,
  144213. &_vq_auxt__16u1__p9_1,
  144214. NULL,
  144215. 0
  144216. };
  144217. static long _vq_quantlist__16u1__p9_2[] = {
  144218. 8,
  144219. 7,
  144220. 9,
  144221. 6,
  144222. 10,
  144223. 5,
  144224. 11,
  144225. 4,
  144226. 12,
  144227. 3,
  144228. 13,
  144229. 2,
  144230. 14,
  144231. 1,
  144232. 15,
  144233. 0,
  144234. 16,
  144235. };
  144236. static long _vq_lengthlist__16u1__p9_2[] = {
  144237. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144238. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144239. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144240. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144241. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144242. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144243. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144244. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144245. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144246. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144247. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144248. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144249. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144250. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144251. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144252. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144253. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144254. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144255. 10,
  144256. };
  144257. static float _vq_quantthresh__16u1__p9_2[] = {
  144258. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144259. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144260. };
  144261. static long _vq_quantmap__16u1__p9_2[] = {
  144262. 15, 13, 11, 9, 7, 5, 3, 1,
  144263. 0, 2, 4, 6, 8, 10, 12, 14,
  144264. 16,
  144265. };
  144266. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144267. _vq_quantthresh__16u1__p9_2,
  144268. _vq_quantmap__16u1__p9_2,
  144269. 17,
  144270. 17
  144271. };
  144272. static static_codebook _16u1__p9_2 = {
  144273. 2, 289,
  144274. _vq_lengthlist__16u1__p9_2,
  144275. 1, -529530880, 1611661312, 5, 0,
  144276. _vq_quantlist__16u1__p9_2,
  144277. NULL,
  144278. &_vq_auxt__16u1__p9_2,
  144279. NULL,
  144280. 0
  144281. };
  144282. static long _huff_lengthlist__16u1__short[] = {
  144283. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144284. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144285. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144286. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144287. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144288. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144289. 16,16,16,16,
  144290. };
  144291. static static_codebook _huff_book__16u1__short = {
  144292. 2, 100,
  144293. _huff_lengthlist__16u1__short,
  144294. 0, 0, 0, 0, 0,
  144295. NULL,
  144296. NULL,
  144297. NULL,
  144298. NULL,
  144299. 0
  144300. };
  144301. static long _huff_lengthlist__16u2__long[] = {
  144302. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144303. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144304. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144305. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144306. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144307. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144308. 13,14,18,18,
  144309. };
  144310. static static_codebook _huff_book__16u2__long = {
  144311. 2, 100,
  144312. _huff_lengthlist__16u2__long,
  144313. 0, 0, 0, 0, 0,
  144314. NULL,
  144315. NULL,
  144316. NULL,
  144317. NULL,
  144318. 0
  144319. };
  144320. static long _huff_lengthlist__16u2__short[] = {
  144321. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144322. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144323. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144324. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144325. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144326. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144327. 16,16,16,16,
  144328. };
  144329. static static_codebook _huff_book__16u2__short = {
  144330. 2, 100,
  144331. _huff_lengthlist__16u2__short,
  144332. 0, 0, 0, 0, 0,
  144333. NULL,
  144334. NULL,
  144335. NULL,
  144336. NULL,
  144337. 0
  144338. };
  144339. static long _vq_quantlist__16u2_p1_0[] = {
  144340. 1,
  144341. 0,
  144342. 2,
  144343. };
  144344. static long _vq_lengthlist__16u2_p1_0[] = {
  144345. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144346. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144347. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144348. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144349. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144350. 10,
  144351. };
  144352. static float _vq_quantthresh__16u2_p1_0[] = {
  144353. -0.5, 0.5,
  144354. };
  144355. static long _vq_quantmap__16u2_p1_0[] = {
  144356. 1, 0, 2,
  144357. };
  144358. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144359. _vq_quantthresh__16u2_p1_0,
  144360. _vq_quantmap__16u2_p1_0,
  144361. 3,
  144362. 3
  144363. };
  144364. static static_codebook _16u2_p1_0 = {
  144365. 4, 81,
  144366. _vq_lengthlist__16u2_p1_0,
  144367. 1, -535822336, 1611661312, 2, 0,
  144368. _vq_quantlist__16u2_p1_0,
  144369. NULL,
  144370. &_vq_auxt__16u2_p1_0,
  144371. NULL,
  144372. 0
  144373. };
  144374. static long _vq_quantlist__16u2_p2_0[] = {
  144375. 2,
  144376. 1,
  144377. 3,
  144378. 0,
  144379. 4,
  144380. };
  144381. static long _vq_lengthlist__16u2_p2_0[] = {
  144382. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144383. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144384. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144385. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144386. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144387. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144388. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144389. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144390. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144391. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144392. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144393. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144394. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144395. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144396. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144397. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144398. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144399. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144400. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144401. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144402. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144403. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144404. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144405. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144406. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144407. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144408. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144409. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144410. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144411. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144412. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144413. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144414. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144415. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144416. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144417. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144418. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144419. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144420. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144421. 13,
  144422. };
  144423. static float _vq_quantthresh__16u2_p2_0[] = {
  144424. -1.5, -0.5, 0.5, 1.5,
  144425. };
  144426. static long _vq_quantmap__16u2_p2_0[] = {
  144427. 3, 1, 0, 2, 4,
  144428. };
  144429. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144430. _vq_quantthresh__16u2_p2_0,
  144431. _vq_quantmap__16u2_p2_0,
  144432. 5,
  144433. 5
  144434. };
  144435. static static_codebook _16u2_p2_0 = {
  144436. 4, 625,
  144437. _vq_lengthlist__16u2_p2_0,
  144438. 1, -533725184, 1611661312, 3, 0,
  144439. _vq_quantlist__16u2_p2_0,
  144440. NULL,
  144441. &_vq_auxt__16u2_p2_0,
  144442. NULL,
  144443. 0
  144444. };
  144445. static long _vq_quantlist__16u2_p3_0[] = {
  144446. 4,
  144447. 3,
  144448. 5,
  144449. 2,
  144450. 6,
  144451. 1,
  144452. 7,
  144453. 0,
  144454. 8,
  144455. };
  144456. static long _vq_lengthlist__16u2_p3_0[] = {
  144457. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144458. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144459. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144460. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144461. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144462. 11,
  144463. };
  144464. static float _vq_quantthresh__16u2_p3_0[] = {
  144465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144466. };
  144467. static long _vq_quantmap__16u2_p3_0[] = {
  144468. 7, 5, 3, 1, 0, 2, 4, 6,
  144469. 8,
  144470. };
  144471. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144472. _vq_quantthresh__16u2_p3_0,
  144473. _vq_quantmap__16u2_p3_0,
  144474. 9,
  144475. 9
  144476. };
  144477. static static_codebook _16u2_p3_0 = {
  144478. 2, 81,
  144479. _vq_lengthlist__16u2_p3_0,
  144480. 1, -531628032, 1611661312, 4, 0,
  144481. _vq_quantlist__16u2_p3_0,
  144482. NULL,
  144483. &_vq_auxt__16u2_p3_0,
  144484. NULL,
  144485. 0
  144486. };
  144487. static long _vq_quantlist__16u2_p4_0[] = {
  144488. 8,
  144489. 7,
  144490. 9,
  144491. 6,
  144492. 10,
  144493. 5,
  144494. 11,
  144495. 4,
  144496. 12,
  144497. 3,
  144498. 13,
  144499. 2,
  144500. 14,
  144501. 1,
  144502. 15,
  144503. 0,
  144504. 16,
  144505. };
  144506. static long _vq_lengthlist__16u2_p4_0[] = {
  144507. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144508. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144509. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144510. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144511. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144512. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144513. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144514. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144515. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144516. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144517. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144518. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144519. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144520. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144521. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144522. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144523. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144524. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144525. 14,
  144526. };
  144527. static float _vq_quantthresh__16u2_p4_0[] = {
  144528. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144529. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144530. };
  144531. static long _vq_quantmap__16u2_p4_0[] = {
  144532. 15, 13, 11, 9, 7, 5, 3, 1,
  144533. 0, 2, 4, 6, 8, 10, 12, 14,
  144534. 16,
  144535. };
  144536. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144537. _vq_quantthresh__16u2_p4_0,
  144538. _vq_quantmap__16u2_p4_0,
  144539. 17,
  144540. 17
  144541. };
  144542. static static_codebook _16u2_p4_0 = {
  144543. 2, 289,
  144544. _vq_lengthlist__16u2_p4_0,
  144545. 1, -529530880, 1611661312, 5, 0,
  144546. _vq_quantlist__16u2_p4_0,
  144547. NULL,
  144548. &_vq_auxt__16u2_p4_0,
  144549. NULL,
  144550. 0
  144551. };
  144552. static long _vq_quantlist__16u2_p5_0[] = {
  144553. 1,
  144554. 0,
  144555. 2,
  144556. };
  144557. static long _vq_lengthlist__16u2_p5_0[] = {
  144558. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144559. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144560. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144561. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144562. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144563. 10,
  144564. };
  144565. static float _vq_quantthresh__16u2_p5_0[] = {
  144566. -5.5, 5.5,
  144567. };
  144568. static long _vq_quantmap__16u2_p5_0[] = {
  144569. 1, 0, 2,
  144570. };
  144571. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144572. _vq_quantthresh__16u2_p5_0,
  144573. _vq_quantmap__16u2_p5_0,
  144574. 3,
  144575. 3
  144576. };
  144577. static static_codebook _16u2_p5_0 = {
  144578. 4, 81,
  144579. _vq_lengthlist__16u2_p5_0,
  144580. 1, -529137664, 1618345984, 2, 0,
  144581. _vq_quantlist__16u2_p5_0,
  144582. NULL,
  144583. &_vq_auxt__16u2_p5_0,
  144584. NULL,
  144585. 0
  144586. };
  144587. static long _vq_quantlist__16u2_p5_1[] = {
  144588. 5,
  144589. 4,
  144590. 6,
  144591. 3,
  144592. 7,
  144593. 2,
  144594. 8,
  144595. 1,
  144596. 9,
  144597. 0,
  144598. 10,
  144599. };
  144600. static long _vq_lengthlist__16u2_p5_1[] = {
  144601. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144602. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144603. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144604. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144605. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144606. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144607. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144608. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144609. };
  144610. static float _vq_quantthresh__16u2_p5_1[] = {
  144611. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144612. 3.5, 4.5,
  144613. };
  144614. static long _vq_quantmap__16u2_p5_1[] = {
  144615. 9, 7, 5, 3, 1, 0, 2, 4,
  144616. 6, 8, 10,
  144617. };
  144618. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144619. _vq_quantthresh__16u2_p5_1,
  144620. _vq_quantmap__16u2_p5_1,
  144621. 11,
  144622. 11
  144623. };
  144624. static static_codebook _16u2_p5_1 = {
  144625. 2, 121,
  144626. _vq_lengthlist__16u2_p5_1,
  144627. 1, -531365888, 1611661312, 4, 0,
  144628. _vq_quantlist__16u2_p5_1,
  144629. NULL,
  144630. &_vq_auxt__16u2_p5_1,
  144631. NULL,
  144632. 0
  144633. };
  144634. static long _vq_quantlist__16u2_p6_0[] = {
  144635. 6,
  144636. 5,
  144637. 7,
  144638. 4,
  144639. 8,
  144640. 3,
  144641. 9,
  144642. 2,
  144643. 10,
  144644. 1,
  144645. 11,
  144646. 0,
  144647. 12,
  144648. };
  144649. static long _vq_lengthlist__16u2_p6_0[] = {
  144650. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144651. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144652. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144653. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144654. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144655. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144656. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144657. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144658. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144659. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144660. 12,13,13,14,14,14,14,15,15,
  144661. };
  144662. static float _vq_quantthresh__16u2_p6_0[] = {
  144663. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144664. 12.5, 17.5, 22.5, 27.5,
  144665. };
  144666. static long _vq_quantmap__16u2_p6_0[] = {
  144667. 11, 9, 7, 5, 3, 1, 0, 2,
  144668. 4, 6, 8, 10, 12,
  144669. };
  144670. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144671. _vq_quantthresh__16u2_p6_0,
  144672. _vq_quantmap__16u2_p6_0,
  144673. 13,
  144674. 13
  144675. };
  144676. static static_codebook _16u2_p6_0 = {
  144677. 2, 169,
  144678. _vq_lengthlist__16u2_p6_0,
  144679. 1, -526516224, 1616117760, 4, 0,
  144680. _vq_quantlist__16u2_p6_0,
  144681. NULL,
  144682. &_vq_auxt__16u2_p6_0,
  144683. NULL,
  144684. 0
  144685. };
  144686. static long _vq_quantlist__16u2_p6_1[] = {
  144687. 2,
  144688. 1,
  144689. 3,
  144690. 0,
  144691. 4,
  144692. };
  144693. static long _vq_lengthlist__16u2_p6_1[] = {
  144694. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144695. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144696. };
  144697. static float _vq_quantthresh__16u2_p6_1[] = {
  144698. -1.5, -0.5, 0.5, 1.5,
  144699. };
  144700. static long _vq_quantmap__16u2_p6_1[] = {
  144701. 3, 1, 0, 2, 4,
  144702. };
  144703. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144704. _vq_quantthresh__16u2_p6_1,
  144705. _vq_quantmap__16u2_p6_1,
  144706. 5,
  144707. 5
  144708. };
  144709. static static_codebook _16u2_p6_1 = {
  144710. 2, 25,
  144711. _vq_lengthlist__16u2_p6_1,
  144712. 1, -533725184, 1611661312, 3, 0,
  144713. _vq_quantlist__16u2_p6_1,
  144714. NULL,
  144715. &_vq_auxt__16u2_p6_1,
  144716. NULL,
  144717. 0
  144718. };
  144719. static long _vq_quantlist__16u2_p7_0[] = {
  144720. 6,
  144721. 5,
  144722. 7,
  144723. 4,
  144724. 8,
  144725. 3,
  144726. 9,
  144727. 2,
  144728. 10,
  144729. 1,
  144730. 11,
  144731. 0,
  144732. 12,
  144733. };
  144734. static long _vq_lengthlist__16u2_p7_0[] = {
  144735. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144736. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144737. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144738. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144739. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144740. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144741. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144742. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144743. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144744. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144745. 12,13,13,13,14,14,14,15,14,
  144746. };
  144747. static float _vq_quantthresh__16u2_p7_0[] = {
  144748. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144749. 27.5, 38.5, 49.5, 60.5,
  144750. };
  144751. static long _vq_quantmap__16u2_p7_0[] = {
  144752. 11, 9, 7, 5, 3, 1, 0, 2,
  144753. 4, 6, 8, 10, 12,
  144754. };
  144755. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144756. _vq_quantthresh__16u2_p7_0,
  144757. _vq_quantmap__16u2_p7_0,
  144758. 13,
  144759. 13
  144760. };
  144761. static static_codebook _16u2_p7_0 = {
  144762. 2, 169,
  144763. _vq_lengthlist__16u2_p7_0,
  144764. 1, -523206656, 1618345984, 4, 0,
  144765. _vq_quantlist__16u2_p7_0,
  144766. NULL,
  144767. &_vq_auxt__16u2_p7_0,
  144768. NULL,
  144769. 0
  144770. };
  144771. static long _vq_quantlist__16u2_p7_1[] = {
  144772. 5,
  144773. 4,
  144774. 6,
  144775. 3,
  144776. 7,
  144777. 2,
  144778. 8,
  144779. 1,
  144780. 9,
  144781. 0,
  144782. 10,
  144783. };
  144784. static long _vq_lengthlist__16u2_p7_1[] = {
  144785. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144786. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144787. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144788. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144789. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144790. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144791. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144792. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144793. };
  144794. static float _vq_quantthresh__16u2_p7_1[] = {
  144795. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144796. 3.5, 4.5,
  144797. };
  144798. static long _vq_quantmap__16u2_p7_1[] = {
  144799. 9, 7, 5, 3, 1, 0, 2, 4,
  144800. 6, 8, 10,
  144801. };
  144802. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144803. _vq_quantthresh__16u2_p7_1,
  144804. _vq_quantmap__16u2_p7_1,
  144805. 11,
  144806. 11
  144807. };
  144808. static static_codebook _16u2_p7_1 = {
  144809. 2, 121,
  144810. _vq_lengthlist__16u2_p7_1,
  144811. 1, -531365888, 1611661312, 4, 0,
  144812. _vq_quantlist__16u2_p7_1,
  144813. NULL,
  144814. &_vq_auxt__16u2_p7_1,
  144815. NULL,
  144816. 0
  144817. };
  144818. static long _vq_quantlist__16u2_p8_0[] = {
  144819. 7,
  144820. 6,
  144821. 8,
  144822. 5,
  144823. 9,
  144824. 4,
  144825. 10,
  144826. 3,
  144827. 11,
  144828. 2,
  144829. 12,
  144830. 1,
  144831. 13,
  144832. 0,
  144833. 14,
  144834. };
  144835. static long _vq_lengthlist__16u2_p8_0[] = {
  144836. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144837. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144838. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144839. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144840. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144841. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144842. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144843. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144844. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144845. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144846. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144847. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144848. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144849. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144850. 14,
  144851. };
  144852. static float _vq_quantthresh__16u2_p8_0[] = {
  144853. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144854. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144855. };
  144856. static long _vq_quantmap__16u2_p8_0[] = {
  144857. 13, 11, 9, 7, 5, 3, 1, 0,
  144858. 2, 4, 6, 8, 10, 12, 14,
  144859. };
  144860. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144861. _vq_quantthresh__16u2_p8_0,
  144862. _vq_quantmap__16u2_p8_0,
  144863. 15,
  144864. 15
  144865. };
  144866. static static_codebook _16u2_p8_0 = {
  144867. 2, 225,
  144868. _vq_lengthlist__16u2_p8_0,
  144869. 1, -520986624, 1620377600, 4, 0,
  144870. _vq_quantlist__16u2_p8_0,
  144871. NULL,
  144872. &_vq_auxt__16u2_p8_0,
  144873. NULL,
  144874. 0
  144875. };
  144876. static long _vq_quantlist__16u2_p8_1[] = {
  144877. 10,
  144878. 9,
  144879. 11,
  144880. 8,
  144881. 12,
  144882. 7,
  144883. 13,
  144884. 6,
  144885. 14,
  144886. 5,
  144887. 15,
  144888. 4,
  144889. 16,
  144890. 3,
  144891. 17,
  144892. 2,
  144893. 18,
  144894. 1,
  144895. 19,
  144896. 0,
  144897. 20,
  144898. };
  144899. static long _vq_lengthlist__16u2_p8_1[] = {
  144900. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144901. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144902. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144903. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144904. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144905. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144906. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144907. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144908. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144909. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144910. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144911. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144912. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144913. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144914. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144915. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144916. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144917. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144918. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144919. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144920. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144921. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144922. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144923. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144925. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144926. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144927. 11,11,10,11,11,11,10,11,11,
  144928. };
  144929. static float _vq_quantthresh__16u2_p8_1[] = {
  144930. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144931. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144932. 6.5, 7.5, 8.5, 9.5,
  144933. };
  144934. static long _vq_quantmap__16u2_p8_1[] = {
  144935. 19, 17, 15, 13, 11, 9, 7, 5,
  144936. 3, 1, 0, 2, 4, 6, 8, 10,
  144937. 12, 14, 16, 18, 20,
  144938. };
  144939. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144940. _vq_quantthresh__16u2_p8_1,
  144941. _vq_quantmap__16u2_p8_1,
  144942. 21,
  144943. 21
  144944. };
  144945. static static_codebook _16u2_p8_1 = {
  144946. 2, 441,
  144947. _vq_lengthlist__16u2_p8_1,
  144948. 1, -529268736, 1611661312, 5, 0,
  144949. _vq_quantlist__16u2_p8_1,
  144950. NULL,
  144951. &_vq_auxt__16u2_p8_1,
  144952. NULL,
  144953. 0
  144954. };
  144955. static long _vq_quantlist__16u2_p9_0[] = {
  144956. 5586,
  144957. 4655,
  144958. 6517,
  144959. 3724,
  144960. 7448,
  144961. 2793,
  144962. 8379,
  144963. 1862,
  144964. 9310,
  144965. 931,
  144966. 10241,
  144967. 0,
  144968. 11172,
  144969. 5521,
  144970. 5651,
  144971. };
  144972. static long _vq_lengthlist__16u2_p9_0[] = {
  144973. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144974. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144975. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144976. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144977. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144980. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144981. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144982. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144983. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144984. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144985. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144986. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144987. 5,
  144988. };
  144989. static float _vq_quantthresh__16u2_p9_0[] = {
  144990. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144991. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144992. };
  144993. static long _vq_quantmap__16u2_p9_0[] = {
  144994. 11, 9, 7, 5, 3, 1, 13, 0,
  144995. 14, 2, 4, 6, 8, 10, 12,
  144996. };
  144997. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144998. _vq_quantthresh__16u2_p9_0,
  144999. _vq_quantmap__16u2_p9_0,
  145000. 15,
  145001. 15
  145002. };
  145003. static static_codebook _16u2_p9_0 = {
  145004. 2, 225,
  145005. _vq_lengthlist__16u2_p9_0,
  145006. 1, -510275072, 1611661312, 14, 0,
  145007. _vq_quantlist__16u2_p9_0,
  145008. NULL,
  145009. &_vq_auxt__16u2_p9_0,
  145010. NULL,
  145011. 0
  145012. };
  145013. static long _vq_quantlist__16u2_p9_1[] = {
  145014. 392,
  145015. 343,
  145016. 441,
  145017. 294,
  145018. 490,
  145019. 245,
  145020. 539,
  145021. 196,
  145022. 588,
  145023. 147,
  145024. 637,
  145025. 98,
  145026. 686,
  145027. 49,
  145028. 735,
  145029. 0,
  145030. 784,
  145031. 388,
  145032. 396,
  145033. };
  145034. static long _vq_lengthlist__16u2_p9_1[] = {
  145035. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145036. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145037. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145038. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145039. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145040. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145041. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145042. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145043. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145044. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145045. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145046. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145047. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145048. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145049. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145055. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145056. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145057. 11,11,11,11,11,11,11, 5, 4,
  145058. };
  145059. static float _vq_quantthresh__16u2_p9_1[] = {
  145060. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145061. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145062. 318.5, 367.5,
  145063. };
  145064. static long _vq_quantmap__16u2_p9_1[] = {
  145065. 15, 13, 11, 9, 7, 5, 3, 1,
  145066. 17, 0, 18, 2, 4, 6, 8, 10,
  145067. 12, 14, 16,
  145068. };
  145069. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145070. _vq_quantthresh__16u2_p9_1,
  145071. _vq_quantmap__16u2_p9_1,
  145072. 19,
  145073. 19
  145074. };
  145075. static static_codebook _16u2_p9_1 = {
  145076. 2, 361,
  145077. _vq_lengthlist__16u2_p9_1,
  145078. 1, -518488064, 1611661312, 10, 0,
  145079. _vq_quantlist__16u2_p9_1,
  145080. NULL,
  145081. &_vq_auxt__16u2_p9_1,
  145082. NULL,
  145083. 0
  145084. };
  145085. static long _vq_quantlist__16u2_p9_2[] = {
  145086. 24,
  145087. 23,
  145088. 25,
  145089. 22,
  145090. 26,
  145091. 21,
  145092. 27,
  145093. 20,
  145094. 28,
  145095. 19,
  145096. 29,
  145097. 18,
  145098. 30,
  145099. 17,
  145100. 31,
  145101. 16,
  145102. 32,
  145103. 15,
  145104. 33,
  145105. 14,
  145106. 34,
  145107. 13,
  145108. 35,
  145109. 12,
  145110. 36,
  145111. 11,
  145112. 37,
  145113. 10,
  145114. 38,
  145115. 9,
  145116. 39,
  145117. 8,
  145118. 40,
  145119. 7,
  145120. 41,
  145121. 6,
  145122. 42,
  145123. 5,
  145124. 43,
  145125. 4,
  145126. 44,
  145127. 3,
  145128. 45,
  145129. 2,
  145130. 46,
  145131. 1,
  145132. 47,
  145133. 0,
  145134. 48,
  145135. };
  145136. static long _vq_lengthlist__16u2_p9_2[] = {
  145137. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145138. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145139. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145140. 11,
  145141. };
  145142. static float _vq_quantthresh__16u2_p9_2[] = {
  145143. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145144. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145145. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145146. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145147. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145148. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145149. };
  145150. static long _vq_quantmap__16u2_p9_2[] = {
  145151. 47, 45, 43, 41, 39, 37, 35, 33,
  145152. 31, 29, 27, 25, 23, 21, 19, 17,
  145153. 15, 13, 11, 9, 7, 5, 3, 1,
  145154. 0, 2, 4, 6, 8, 10, 12, 14,
  145155. 16, 18, 20, 22, 24, 26, 28, 30,
  145156. 32, 34, 36, 38, 40, 42, 44, 46,
  145157. 48,
  145158. };
  145159. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145160. _vq_quantthresh__16u2_p9_2,
  145161. _vq_quantmap__16u2_p9_2,
  145162. 49,
  145163. 49
  145164. };
  145165. static static_codebook _16u2_p9_2 = {
  145166. 1, 49,
  145167. _vq_lengthlist__16u2_p9_2,
  145168. 1, -526909440, 1611661312, 6, 0,
  145169. _vq_quantlist__16u2_p9_2,
  145170. NULL,
  145171. &_vq_auxt__16u2_p9_2,
  145172. NULL,
  145173. 0
  145174. };
  145175. static long _vq_quantlist__8u0__p1_0[] = {
  145176. 1,
  145177. 0,
  145178. 2,
  145179. };
  145180. static long _vq_lengthlist__8u0__p1_0[] = {
  145181. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145182. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145183. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145184. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145185. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145186. 11,
  145187. };
  145188. static float _vq_quantthresh__8u0__p1_0[] = {
  145189. -0.5, 0.5,
  145190. };
  145191. static long _vq_quantmap__8u0__p1_0[] = {
  145192. 1, 0, 2,
  145193. };
  145194. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145195. _vq_quantthresh__8u0__p1_0,
  145196. _vq_quantmap__8u0__p1_0,
  145197. 3,
  145198. 3
  145199. };
  145200. static static_codebook _8u0__p1_0 = {
  145201. 4, 81,
  145202. _vq_lengthlist__8u0__p1_0,
  145203. 1, -535822336, 1611661312, 2, 0,
  145204. _vq_quantlist__8u0__p1_0,
  145205. NULL,
  145206. &_vq_auxt__8u0__p1_0,
  145207. NULL,
  145208. 0
  145209. };
  145210. static long _vq_quantlist__8u0__p2_0[] = {
  145211. 1,
  145212. 0,
  145213. 2,
  145214. };
  145215. static long _vq_lengthlist__8u0__p2_0[] = {
  145216. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145217. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145218. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145219. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145220. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145221. 8,
  145222. };
  145223. static float _vq_quantthresh__8u0__p2_0[] = {
  145224. -0.5, 0.5,
  145225. };
  145226. static long _vq_quantmap__8u0__p2_0[] = {
  145227. 1, 0, 2,
  145228. };
  145229. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145230. _vq_quantthresh__8u0__p2_0,
  145231. _vq_quantmap__8u0__p2_0,
  145232. 3,
  145233. 3
  145234. };
  145235. static static_codebook _8u0__p2_0 = {
  145236. 4, 81,
  145237. _vq_lengthlist__8u0__p2_0,
  145238. 1, -535822336, 1611661312, 2, 0,
  145239. _vq_quantlist__8u0__p2_0,
  145240. NULL,
  145241. &_vq_auxt__8u0__p2_0,
  145242. NULL,
  145243. 0
  145244. };
  145245. static long _vq_quantlist__8u0__p3_0[] = {
  145246. 2,
  145247. 1,
  145248. 3,
  145249. 0,
  145250. 4,
  145251. };
  145252. static long _vq_lengthlist__8u0__p3_0[] = {
  145253. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145254. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145255. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145256. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145257. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145258. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145259. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145260. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145261. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145262. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145263. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145264. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145265. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145266. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145267. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145268. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145269. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145270. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145271. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145272. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145273. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145274. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145275. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145276. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145277. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145278. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145279. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145280. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145281. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145282. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145283. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145284. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145285. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145286. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145287. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145288. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145289. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145290. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145291. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145292. 16,
  145293. };
  145294. static float _vq_quantthresh__8u0__p3_0[] = {
  145295. -1.5, -0.5, 0.5, 1.5,
  145296. };
  145297. static long _vq_quantmap__8u0__p3_0[] = {
  145298. 3, 1, 0, 2, 4,
  145299. };
  145300. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145301. _vq_quantthresh__8u0__p3_0,
  145302. _vq_quantmap__8u0__p3_0,
  145303. 5,
  145304. 5
  145305. };
  145306. static static_codebook _8u0__p3_0 = {
  145307. 4, 625,
  145308. _vq_lengthlist__8u0__p3_0,
  145309. 1, -533725184, 1611661312, 3, 0,
  145310. _vq_quantlist__8u0__p3_0,
  145311. NULL,
  145312. &_vq_auxt__8u0__p3_0,
  145313. NULL,
  145314. 0
  145315. };
  145316. static long _vq_quantlist__8u0__p4_0[] = {
  145317. 2,
  145318. 1,
  145319. 3,
  145320. 0,
  145321. 4,
  145322. };
  145323. static long _vq_lengthlist__8u0__p4_0[] = {
  145324. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145325. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145326. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145327. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145328. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145329. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145330. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145331. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145332. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145333. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145334. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145335. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145336. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145337. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145338. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145339. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145340. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145341. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145342. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145343. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145344. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145345. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145346. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145347. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145348. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145349. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145350. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145351. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145352. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145353. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145354. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145355. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145356. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145357. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145358. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145359. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145360. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145361. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145362. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145363. 12,
  145364. };
  145365. static float _vq_quantthresh__8u0__p4_0[] = {
  145366. -1.5, -0.5, 0.5, 1.5,
  145367. };
  145368. static long _vq_quantmap__8u0__p4_0[] = {
  145369. 3, 1, 0, 2, 4,
  145370. };
  145371. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145372. _vq_quantthresh__8u0__p4_0,
  145373. _vq_quantmap__8u0__p4_0,
  145374. 5,
  145375. 5
  145376. };
  145377. static static_codebook _8u0__p4_0 = {
  145378. 4, 625,
  145379. _vq_lengthlist__8u0__p4_0,
  145380. 1, -533725184, 1611661312, 3, 0,
  145381. _vq_quantlist__8u0__p4_0,
  145382. NULL,
  145383. &_vq_auxt__8u0__p4_0,
  145384. NULL,
  145385. 0
  145386. };
  145387. static long _vq_quantlist__8u0__p5_0[] = {
  145388. 4,
  145389. 3,
  145390. 5,
  145391. 2,
  145392. 6,
  145393. 1,
  145394. 7,
  145395. 0,
  145396. 8,
  145397. };
  145398. static long _vq_lengthlist__8u0__p5_0[] = {
  145399. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145400. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145401. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145402. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145403. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145404. 12,
  145405. };
  145406. static float _vq_quantthresh__8u0__p5_0[] = {
  145407. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145408. };
  145409. static long _vq_quantmap__8u0__p5_0[] = {
  145410. 7, 5, 3, 1, 0, 2, 4, 6,
  145411. 8,
  145412. };
  145413. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145414. _vq_quantthresh__8u0__p5_0,
  145415. _vq_quantmap__8u0__p5_0,
  145416. 9,
  145417. 9
  145418. };
  145419. static static_codebook _8u0__p5_0 = {
  145420. 2, 81,
  145421. _vq_lengthlist__8u0__p5_0,
  145422. 1, -531628032, 1611661312, 4, 0,
  145423. _vq_quantlist__8u0__p5_0,
  145424. NULL,
  145425. &_vq_auxt__8u0__p5_0,
  145426. NULL,
  145427. 0
  145428. };
  145429. static long _vq_quantlist__8u0__p6_0[] = {
  145430. 6,
  145431. 5,
  145432. 7,
  145433. 4,
  145434. 8,
  145435. 3,
  145436. 9,
  145437. 2,
  145438. 10,
  145439. 1,
  145440. 11,
  145441. 0,
  145442. 12,
  145443. };
  145444. static long _vq_lengthlist__8u0__p6_0[] = {
  145445. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145446. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145447. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145448. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145449. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145450. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145451. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145452. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145453. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145454. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145455. 16, 0,15, 0,17, 0, 0, 0, 0,
  145456. };
  145457. static float _vq_quantthresh__8u0__p6_0[] = {
  145458. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145459. 12.5, 17.5, 22.5, 27.5,
  145460. };
  145461. static long _vq_quantmap__8u0__p6_0[] = {
  145462. 11, 9, 7, 5, 3, 1, 0, 2,
  145463. 4, 6, 8, 10, 12,
  145464. };
  145465. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145466. _vq_quantthresh__8u0__p6_0,
  145467. _vq_quantmap__8u0__p6_0,
  145468. 13,
  145469. 13
  145470. };
  145471. static static_codebook _8u0__p6_0 = {
  145472. 2, 169,
  145473. _vq_lengthlist__8u0__p6_0,
  145474. 1, -526516224, 1616117760, 4, 0,
  145475. _vq_quantlist__8u0__p6_0,
  145476. NULL,
  145477. &_vq_auxt__8u0__p6_0,
  145478. NULL,
  145479. 0
  145480. };
  145481. static long _vq_quantlist__8u0__p6_1[] = {
  145482. 2,
  145483. 1,
  145484. 3,
  145485. 0,
  145486. 4,
  145487. };
  145488. static long _vq_lengthlist__8u0__p6_1[] = {
  145489. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145490. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145491. };
  145492. static float _vq_quantthresh__8u0__p6_1[] = {
  145493. -1.5, -0.5, 0.5, 1.5,
  145494. };
  145495. static long _vq_quantmap__8u0__p6_1[] = {
  145496. 3, 1, 0, 2, 4,
  145497. };
  145498. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145499. _vq_quantthresh__8u0__p6_1,
  145500. _vq_quantmap__8u0__p6_1,
  145501. 5,
  145502. 5
  145503. };
  145504. static static_codebook _8u0__p6_1 = {
  145505. 2, 25,
  145506. _vq_lengthlist__8u0__p6_1,
  145507. 1, -533725184, 1611661312, 3, 0,
  145508. _vq_quantlist__8u0__p6_1,
  145509. NULL,
  145510. &_vq_auxt__8u0__p6_1,
  145511. NULL,
  145512. 0
  145513. };
  145514. static long _vq_quantlist__8u0__p7_0[] = {
  145515. 1,
  145516. 0,
  145517. 2,
  145518. };
  145519. static long _vq_lengthlist__8u0__p7_0[] = {
  145520. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145521. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145522. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145523. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145524. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145525. 7,
  145526. };
  145527. static float _vq_quantthresh__8u0__p7_0[] = {
  145528. -157.5, 157.5,
  145529. };
  145530. static long _vq_quantmap__8u0__p7_0[] = {
  145531. 1, 0, 2,
  145532. };
  145533. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145534. _vq_quantthresh__8u0__p7_0,
  145535. _vq_quantmap__8u0__p7_0,
  145536. 3,
  145537. 3
  145538. };
  145539. static static_codebook _8u0__p7_0 = {
  145540. 4, 81,
  145541. _vq_lengthlist__8u0__p7_0,
  145542. 1, -518803456, 1628680192, 2, 0,
  145543. _vq_quantlist__8u0__p7_0,
  145544. NULL,
  145545. &_vq_auxt__8u0__p7_0,
  145546. NULL,
  145547. 0
  145548. };
  145549. static long _vq_quantlist__8u0__p7_1[] = {
  145550. 7,
  145551. 6,
  145552. 8,
  145553. 5,
  145554. 9,
  145555. 4,
  145556. 10,
  145557. 3,
  145558. 11,
  145559. 2,
  145560. 12,
  145561. 1,
  145562. 13,
  145563. 0,
  145564. 14,
  145565. };
  145566. static long _vq_lengthlist__8u0__p7_1[] = {
  145567. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145568. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145569. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145570. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145571. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145572. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145579. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145580. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145581. 10,
  145582. };
  145583. static float _vq_quantthresh__8u0__p7_1[] = {
  145584. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145585. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145586. };
  145587. static long _vq_quantmap__8u0__p7_1[] = {
  145588. 13, 11, 9, 7, 5, 3, 1, 0,
  145589. 2, 4, 6, 8, 10, 12, 14,
  145590. };
  145591. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145592. _vq_quantthresh__8u0__p7_1,
  145593. _vq_quantmap__8u0__p7_1,
  145594. 15,
  145595. 15
  145596. };
  145597. static static_codebook _8u0__p7_1 = {
  145598. 2, 225,
  145599. _vq_lengthlist__8u0__p7_1,
  145600. 1, -520986624, 1620377600, 4, 0,
  145601. _vq_quantlist__8u0__p7_1,
  145602. NULL,
  145603. &_vq_auxt__8u0__p7_1,
  145604. NULL,
  145605. 0
  145606. };
  145607. static long _vq_quantlist__8u0__p7_2[] = {
  145608. 10,
  145609. 9,
  145610. 11,
  145611. 8,
  145612. 12,
  145613. 7,
  145614. 13,
  145615. 6,
  145616. 14,
  145617. 5,
  145618. 15,
  145619. 4,
  145620. 16,
  145621. 3,
  145622. 17,
  145623. 2,
  145624. 18,
  145625. 1,
  145626. 19,
  145627. 0,
  145628. 20,
  145629. };
  145630. static long _vq_lengthlist__8u0__p7_2[] = {
  145631. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145632. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145633. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145634. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145635. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145636. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145637. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145638. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145639. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145640. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145641. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145642. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145643. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145644. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145645. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145646. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145647. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145648. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145649. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145650. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145651. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145652. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145653. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145654. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145655. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145656. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145657. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145658. 11,12,11,11,11,10,10,11,11,
  145659. };
  145660. static float _vq_quantthresh__8u0__p7_2[] = {
  145661. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145662. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145663. 6.5, 7.5, 8.5, 9.5,
  145664. };
  145665. static long _vq_quantmap__8u0__p7_2[] = {
  145666. 19, 17, 15, 13, 11, 9, 7, 5,
  145667. 3, 1, 0, 2, 4, 6, 8, 10,
  145668. 12, 14, 16, 18, 20,
  145669. };
  145670. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145671. _vq_quantthresh__8u0__p7_2,
  145672. _vq_quantmap__8u0__p7_2,
  145673. 21,
  145674. 21
  145675. };
  145676. static static_codebook _8u0__p7_2 = {
  145677. 2, 441,
  145678. _vq_lengthlist__8u0__p7_2,
  145679. 1, -529268736, 1611661312, 5, 0,
  145680. _vq_quantlist__8u0__p7_2,
  145681. NULL,
  145682. &_vq_auxt__8u0__p7_2,
  145683. NULL,
  145684. 0
  145685. };
  145686. static long _huff_lengthlist__8u0__single[] = {
  145687. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145688. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145689. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145690. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145691. };
  145692. static static_codebook _huff_book__8u0__single = {
  145693. 2, 64,
  145694. _huff_lengthlist__8u0__single,
  145695. 0, 0, 0, 0, 0,
  145696. NULL,
  145697. NULL,
  145698. NULL,
  145699. NULL,
  145700. 0
  145701. };
  145702. static long _vq_quantlist__8u1__p1_0[] = {
  145703. 1,
  145704. 0,
  145705. 2,
  145706. };
  145707. static long _vq_lengthlist__8u1__p1_0[] = {
  145708. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145709. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145710. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145711. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145712. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145713. 10,
  145714. };
  145715. static float _vq_quantthresh__8u1__p1_0[] = {
  145716. -0.5, 0.5,
  145717. };
  145718. static long _vq_quantmap__8u1__p1_0[] = {
  145719. 1, 0, 2,
  145720. };
  145721. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145722. _vq_quantthresh__8u1__p1_0,
  145723. _vq_quantmap__8u1__p1_0,
  145724. 3,
  145725. 3
  145726. };
  145727. static static_codebook _8u1__p1_0 = {
  145728. 4, 81,
  145729. _vq_lengthlist__8u1__p1_0,
  145730. 1, -535822336, 1611661312, 2, 0,
  145731. _vq_quantlist__8u1__p1_0,
  145732. NULL,
  145733. &_vq_auxt__8u1__p1_0,
  145734. NULL,
  145735. 0
  145736. };
  145737. static long _vq_quantlist__8u1__p2_0[] = {
  145738. 1,
  145739. 0,
  145740. 2,
  145741. };
  145742. static long _vq_lengthlist__8u1__p2_0[] = {
  145743. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145744. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145745. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145746. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145747. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145748. 7,
  145749. };
  145750. static float _vq_quantthresh__8u1__p2_0[] = {
  145751. -0.5, 0.5,
  145752. };
  145753. static long _vq_quantmap__8u1__p2_0[] = {
  145754. 1, 0, 2,
  145755. };
  145756. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145757. _vq_quantthresh__8u1__p2_0,
  145758. _vq_quantmap__8u1__p2_0,
  145759. 3,
  145760. 3
  145761. };
  145762. static static_codebook _8u1__p2_0 = {
  145763. 4, 81,
  145764. _vq_lengthlist__8u1__p2_0,
  145765. 1, -535822336, 1611661312, 2, 0,
  145766. _vq_quantlist__8u1__p2_0,
  145767. NULL,
  145768. &_vq_auxt__8u1__p2_0,
  145769. NULL,
  145770. 0
  145771. };
  145772. static long _vq_quantlist__8u1__p3_0[] = {
  145773. 2,
  145774. 1,
  145775. 3,
  145776. 0,
  145777. 4,
  145778. };
  145779. static long _vq_lengthlist__8u1__p3_0[] = {
  145780. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145781. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145782. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145783. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145784. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145785. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145786. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145787. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145788. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145789. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145790. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145791. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145792. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145793. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145794. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145795. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145796. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145797. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145798. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145799. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145800. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145801. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145802. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145803. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145804. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145805. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145806. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145807. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145808. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145809. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145810. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145811. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145812. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145813. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145814. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145815. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145816. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145817. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145818. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145819. 16,
  145820. };
  145821. static float _vq_quantthresh__8u1__p3_0[] = {
  145822. -1.5, -0.5, 0.5, 1.5,
  145823. };
  145824. static long _vq_quantmap__8u1__p3_0[] = {
  145825. 3, 1, 0, 2, 4,
  145826. };
  145827. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145828. _vq_quantthresh__8u1__p3_0,
  145829. _vq_quantmap__8u1__p3_0,
  145830. 5,
  145831. 5
  145832. };
  145833. static static_codebook _8u1__p3_0 = {
  145834. 4, 625,
  145835. _vq_lengthlist__8u1__p3_0,
  145836. 1, -533725184, 1611661312, 3, 0,
  145837. _vq_quantlist__8u1__p3_0,
  145838. NULL,
  145839. &_vq_auxt__8u1__p3_0,
  145840. NULL,
  145841. 0
  145842. };
  145843. static long _vq_quantlist__8u1__p4_0[] = {
  145844. 2,
  145845. 1,
  145846. 3,
  145847. 0,
  145848. 4,
  145849. };
  145850. static long _vq_lengthlist__8u1__p4_0[] = {
  145851. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145852. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145853. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145854. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145855. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145856. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145857. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145858. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145859. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145860. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145861. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145862. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145863. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145864. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145865. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145866. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145867. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145868. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145869. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145870. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145871. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145872. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145873. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145874. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145875. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145876. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145877. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145878. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145879. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145880. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145881. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145882. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145883. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145884. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145885. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145886. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145887. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145888. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145889. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145890. 10,
  145891. };
  145892. static float _vq_quantthresh__8u1__p4_0[] = {
  145893. -1.5, -0.5, 0.5, 1.5,
  145894. };
  145895. static long _vq_quantmap__8u1__p4_0[] = {
  145896. 3, 1, 0, 2, 4,
  145897. };
  145898. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145899. _vq_quantthresh__8u1__p4_0,
  145900. _vq_quantmap__8u1__p4_0,
  145901. 5,
  145902. 5
  145903. };
  145904. static static_codebook _8u1__p4_0 = {
  145905. 4, 625,
  145906. _vq_lengthlist__8u1__p4_0,
  145907. 1, -533725184, 1611661312, 3, 0,
  145908. _vq_quantlist__8u1__p4_0,
  145909. NULL,
  145910. &_vq_auxt__8u1__p4_0,
  145911. NULL,
  145912. 0
  145913. };
  145914. static long _vq_quantlist__8u1__p5_0[] = {
  145915. 4,
  145916. 3,
  145917. 5,
  145918. 2,
  145919. 6,
  145920. 1,
  145921. 7,
  145922. 0,
  145923. 8,
  145924. };
  145925. static long _vq_lengthlist__8u1__p5_0[] = {
  145926. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145927. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145928. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145929. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145930. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145931. 13,
  145932. };
  145933. static float _vq_quantthresh__8u1__p5_0[] = {
  145934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145935. };
  145936. static long _vq_quantmap__8u1__p5_0[] = {
  145937. 7, 5, 3, 1, 0, 2, 4, 6,
  145938. 8,
  145939. };
  145940. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145941. _vq_quantthresh__8u1__p5_0,
  145942. _vq_quantmap__8u1__p5_0,
  145943. 9,
  145944. 9
  145945. };
  145946. static static_codebook _8u1__p5_0 = {
  145947. 2, 81,
  145948. _vq_lengthlist__8u1__p5_0,
  145949. 1, -531628032, 1611661312, 4, 0,
  145950. _vq_quantlist__8u1__p5_0,
  145951. NULL,
  145952. &_vq_auxt__8u1__p5_0,
  145953. NULL,
  145954. 0
  145955. };
  145956. static long _vq_quantlist__8u1__p6_0[] = {
  145957. 4,
  145958. 3,
  145959. 5,
  145960. 2,
  145961. 6,
  145962. 1,
  145963. 7,
  145964. 0,
  145965. 8,
  145966. };
  145967. static long _vq_lengthlist__8u1__p6_0[] = {
  145968. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145969. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145970. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145971. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145972. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145973. 10,
  145974. };
  145975. static float _vq_quantthresh__8u1__p6_0[] = {
  145976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145977. };
  145978. static long _vq_quantmap__8u1__p6_0[] = {
  145979. 7, 5, 3, 1, 0, 2, 4, 6,
  145980. 8,
  145981. };
  145982. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145983. _vq_quantthresh__8u1__p6_0,
  145984. _vq_quantmap__8u1__p6_0,
  145985. 9,
  145986. 9
  145987. };
  145988. static static_codebook _8u1__p6_0 = {
  145989. 2, 81,
  145990. _vq_lengthlist__8u1__p6_0,
  145991. 1, -531628032, 1611661312, 4, 0,
  145992. _vq_quantlist__8u1__p6_0,
  145993. NULL,
  145994. &_vq_auxt__8u1__p6_0,
  145995. NULL,
  145996. 0
  145997. };
  145998. static long _vq_quantlist__8u1__p7_0[] = {
  145999. 1,
  146000. 0,
  146001. 2,
  146002. };
  146003. static long _vq_lengthlist__8u1__p7_0[] = {
  146004. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146005. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146006. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146007. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146008. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146009. 11,
  146010. };
  146011. static float _vq_quantthresh__8u1__p7_0[] = {
  146012. -5.5, 5.5,
  146013. };
  146014. static long _vq_quantmap__8u1__p7_0[] = {
  146015. 1, 0, 2,
  146016. };
  146017. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146018. _vq_quantthresh__8u1__p7_0,
  146019. _vq_quantmap__8u1__p7_0,
  146020. 3,
  146021. 3
  146022. };
  146023. static static_codebook _8u1__p7_0 = {
  146024. 4, 81,
  146025. _vq_lengthlist__8u1__p7_0,
  146026. 1, -529137664, 1618345984, 2, 0,
  146027. _vq_quantlist__8u1__p7_0,
  146028. NULL,
  146029. &_vq_auxt__8u1__p7_0,
  146030. NULL,
  146031. 0
  146032. };
  146033. static long _vq_quantlist__8u1__p7_1[] = {
  146034. 5,
  146035. 4,
  146036. 6,
  146037. 3,
  146038. 7,
  146039. 2,
  146040. 8,
  146041. 1,
  146042. 9,
  146043. 0,
  146044. 10,
  146045. };
  146046. static long _vq_lengthlist__8u1__p7_1[] = {
  146047. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146048. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146049. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146050. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146051. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146052. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146053. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146054. 9, 9, 9, 9, 9,10,10,10,10,
  146055. };
  146056. static float _vq_quantthresh__8u1__p7_1[] = {
  146057. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146058. 3.5, 4.5,
  146059. };
  146060. static long _vq_quantmap__8u1__p7_1[] = {
  146061. 9, 7, 5, 3, 1, 0, 2, 4,
  146062. 6, 8, 10,
  146063. };
  146064. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146065. _vq_quantthresh__8u1__p7_1,
  146066. _vq_quantmap__8u1__p7_1,
  146067. 11,
  146068. 11
  146069. };
  146070. static static_codebook _8u1__p7_1 = {
  146071. 2, 121,
  146072. _vq_lengthlist__8u1__p7_1,
  146073. 1, -531365888, 1611661312, 4, 0,
  146074. _vq_quantlist__8u1__p7_1,
  146075. NULL,
  146076. &_vq_auxt__8u1__p7_1,
  146077. NULL,
  146078. 0
  146079. };
  146080. static long _vq_quantlist__8u1__p8_0[] = {
  146081. 5,
  146082. 4,
  146083. 6,
  146084. 3,
  146085. 7,
  146086. 2,
  146087. 8,
  146088. 1,
  146089. 9,
  146090. 0,
  146091. 10,
  146092. };
  146093. static long _vq_lengthlist__8u1__p8_0[] = {
  146094. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146095. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146096. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146097. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146098. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146099. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146100. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146101. 12,13,13,14,14,15,15,15,15,
  146102. };
  146103. static float _vq_quantthresh__8u1__p8_0[] = {
  146104. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146105. 38.5, 49.5,
  146106. };
  146107. static long _vq_quantmap__8u1__p8_0[] = {
  146108. 9, 7, 5, 3, 1, 0, 2, 4,
  146109. 6, 8, 10,
  146110. };
  146111. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146112. _vq_quantthresh__8u1__p8_0,
  146113. _vq_quantmap__8u1__p8_0,
  146114. 11,
  146115. 11
  146116. };
  146117. static static_codebook _8u1__p8_0 = {
  146118. 2, 121,
  146119. _vq_lengthlist__8u1__p8_0,
  146120. 1, -524582912, 1618345984, 4, 0,
  146121. _vq_quantlist__8u1__p8_0,
  146122. NULL,
  146123. &_vq_auxt__8u1__p8_0,
  146124. NULL,
  146125. 0
  146126. };
  146127. static long _vq_quantlist__8u1__p8_1[] = {
  146128. 5,
  146129. 4,
  146130. 6,
  146131. 3,
  146132. 7,
  146133. 2,
  146134. 8,
  146135. 1,
  146136. 9,
  146137. 0,
  146138. 10,
  146139. };
  146140. static long _vq_lengthlist__8u1__p8_1[] = {
  146141. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146142. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146143. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146144. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146145. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146146. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146147. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146148. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146149. };
  146150. static float _vq_quantthresh__8u1__p8_1[] = {
  146151. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146152. 3.5, 4.5,
  146153. };
  146154. static long _vq_quantmap__8u1__p8_1[] = {
  146155. 9, 7, 5, 3, 1, 0, 2, 4,
  146156. 6, 8, 10,
  146157. };
  146158. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146159. _vq_quantthresh__8u1__p8_1,
  146160. _vq_quantmap__8u1__p8_1,
  146161. 11,
  146162. 11
  146163. };
  146164. static static_codebook _8u1__p8_1 = {
  146165. 2, 121,
  146166. _vq_lengthlist__8u1__p8_1,
  146167. 1, -531365888, 1611661312, 4, 0,
  146168. _vq_quantlist__8u1__p8_1,
  146169. NULL,
  146170. &_vq_auxt__8u1__p8_1,
  146171. NULL,
  146172. 0
  146173. };
  146174. static long _vq_quantlist__8u1__p9_0[] = {
  146175. 7,
  146176. 6,
  146177. 8,
  146178. 5,
  146179. 9,
  146180. 4,
  146181. 10,
  146182. 3,
  146183. 11,
  146184. 2,
  146185. 12,
  146186. 1,
  146187. 13,
  146188. 0,
  146189. 14,
  146190. };
  146191. static long _vq_lengthlist__8u1__p9_0[] = {
  146192. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146193. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146194. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146195. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146196. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146197. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146198. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146199. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146200. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146201. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146202. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146203. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146204. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146205. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146206. 10,
  146207. };
  146208. static float _vq_quantthresh__8u1__p9_0[] = {
  146209. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146210. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146211. };
  146212. static long _vq_quantmap__8u1__p9_0[] = {
  146213. 13, 11, 9, 7, 5, 3, 1, 0,
  146214. 2, 4, 6, 8, 10, 12, 14,
  146215. };
  146216. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146217. _vq_quantthresh__8u1__p9_0,
  146218. _vq_quantmap__8u1__p9_0,
  146219. 15,
  146220. 15
  146221. };
  146222. static static_codebook _8u1__p9_0 = {
  146223. 2, 225,
  146224. _vq_lengthlist__8u1__p9_0,
  146225. 1, -514071552, 1627381760, 4, 0,
  146226. _vq_quantlist__8u1__p9_0,
  146227. NULL,
  146228. &_vq_auxt__8u1__p9_0,
  146229. NULL,
  146230. 0
  146231. };
  146232. static long _vq_quantlist__8u1__p9_1[] = {
  146233. 7,
  146234. 6,
  146235. 8,
  146236. 5,
  146237. 9,
  146238. 4,
  146239. 10,
  146240. 3,
  146241. 11,
  146242. 2,
  146243. 12,
  146244. 1,
  146245. 13,
  146246. 0,
  146247. 14,
  146248. };
  146249. static long _vq_lengthlist__8u1__p9_1[] = {
  146250. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146251. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146252. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146253. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146254. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146255. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146256. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146257. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146258. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146259. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146260. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146261. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146262. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146263. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146264. 13,
  146265. };
  146266. static float _vq_quantthresh__8u1__p9_1[] = {
  146267. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146268. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146269. };
  146270. static long _vq_quantmap__8u1__p9_1[] = {
  146271. 13, 11, 9, 7, 5, 3, 1, 0,
  146272. 2, 4, 6, 8, 10, 12, 14,
  146273. };
  146274. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146275. _vq_quantthresh__8u1__p9_1,
  146276. _vq_quantmap__8u1__p9_1,
  146277. 15,
  146278. 15
  146279. };
  146280. static static_codebook _8u1__p9_1 = {
  146281. 2, 225,
  146282. _vq_lengthlist__8u1__p9_1,
  146283. 1, -522338304, 1620115456, 4, 0,
  146284. _vq_quantlist__8u1__p9_1,
  146285. NULL,
  146286. &_vq_auxt__8u1__p9_1,
  146287. NULL,
  146288. 0
  146289. };
  146290. static long _vq_quantlist__8u1__p9_2[] = {
  146291. 8,
  146292. 7,
  146293. 9,
  146294. 6,
  146295. 10,
  146296. 5,
  146297. 11,
  146298. 4,
  146299. 12,
  146300. 3,
  146301. 13,
  146302. 2,
  146303. 14,
  146304. 1,
  146305. 15,
  146306. 0,
  146307. 16,
  146308. };
  146309. static long _vq_lengthlist__8u1__p9_2[] = {
  146310. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146311. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146312. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146313. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146314. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146315. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146316. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146317. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146318. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146319. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146320. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146321. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146322. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146323. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146324. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146325. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146326. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146327. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146328. 10,
  146329. };
  146330. static float _vq_quantthresh__8u1__p9_2[] = {
  146331. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146332. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146333. };
  146334. static long _vq_quantmap__8u1__p9_2[] = {
  146335. 15, 13, 11, 9, 7, 5, 3, 1,
  146336. 0, 2, 4, 6, 8, 10, 12, 14,
  146337. 16,
  146338. };
  146339. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146340. _vq_quantthresh__8u1__p9_2,
  146341. _vq_quantmap__8u1__p9_2,
  146342. 17,
  146343. 17
  146344. };
  146345. static static_codebook _8u1__p9_2 = {
  146346. 2, 289,
  146347. _vq_lengthlist__8u1__p9_2,
  146348. 1, -529530880, 1611661312, 5, 0,
  146349. _vq_quantlist__8u1__p9_2,
  146350. NULL,
  146351. &_vq_auxt__8u1__p9_2,
  146352. NULL,
  146353. 0
  146354. };
  146355. static long _huff_lengthlist__8u1__single[] = {
  146356. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146357. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146358. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146359. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146360. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146361. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146362. 13, 8, 8,15,
  146363. };
  146364. static static_codebook _huff_book__8u1__single = {
  146365. 2, 100,
  146366. _huff_lengthlist__8u1__single,
  146367. 0, 0, 0, 0, 0,
  146368. NULL,
  146369. NULL,
  146370. NULL,
  146371. NULL,
  146372. 0
  146373. };
  146374. static long _huff_lengthlist__44u0__long[] = {
  146375. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146376. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146377. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146378. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146379. };
  146380. static static_codebook _huff_book__44u0__long = {
  146381. 2, 64,
  146382. _huff_lengthlist__44u0__long,
  146383. 0, 0, 0, 0, 0,
  146384. NULL,
  146385. NULL,
  146386. NULL,
  146387. NULL,
  146388. 0
  146389. };
  146390. static long _vq_quantlist__44u0__p1_0[] = {
  146391. 1,
  146392. 0,
  146393. 2,
  146394. };
  146395. static long _vq_lengthlist__44u0__p1_0[] = {
  146396. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146397. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146398. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146399. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146400. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146401. 13,
  146402. };
  146403. static float _vq_quantthresh__44u0__p1_0[] = {
  146404. -0.5, 0.5,
  146405. };
  146406. static long _vq_quantmap__44u0__p1_0[] = {
  146407. 1, 0, 2,
  146408. };
  146409. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146410. _vq_quantthresh__44u0__p1_0,
  146411. _vq_quantmap__44u0__p1_0,
  146412. 3,
  146413. 3
  146414. };
  146415. static static_codebook _44u0__p1_0 = {
  146416. 4, 81,
  146417. _vq_lengthlist__44u0__p1_0,
  146418. 1, -535822336, 1611661312, 2, 0,
  146419. _vq_quantlist__44u0__p1_0,
  146420. NULL,
  146421. &_vq_auxt__44u0__p1_0,
  146422. NULL,
  146423. 0
  146424. };
  146425. static long _vq_quantlist__44u0__p2_0[] = {
  146426. 1,
  146427. 0,
  146428. 2,
  146429. };
  146430. static long _vq_lengthlist__44u0__p2_0[] = {
  146431. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146432. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146433. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146434. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146435. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146436. 9,
  146437. };
  146438. static float _vq_quantthresh__44u0__p2_0[] = {
  146439. -0.5, 0.5,
  146440. };
  146441. static long _vq_quantmap__44u0__p2_0[] = {
  146442. 1, 0, 2,
  146443. };
  146444. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146445. _vq_quantthresh__44u0__p2_0,
  146446. _vq_quantmap__44u0__p2_0,
  146447. 3,
  146448. 3
  146449. };
  146450. static static_codebook _44u0__p2_0 = {
  146451. 4, 81,
  146452. _vq_lengthlist__44u0__p2_0,
  146453. 1, -535822336, 1611661312, 2, 0,
  146454. _vq_quantlist__44u0__p2_0,
  146455. NULL,
  146456. &_vq_auxt__44u0__p2_0,
  146457. NULL,
  146458. 0
  146459. };
  146460. static long _vq_quantlist__44u0__p3_0[] = {
  146461. 2,
  146462. 1,
  146463. 3,
  146464. 0,
  146465. 4,
  146466. };
  146467. static long _vq_lengthlist__44u0__p3_0[] = {
  146468. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146469. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146470. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146471. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146472. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146473. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146474. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146475. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146476. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146477. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146478. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146479. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146480. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146481. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146482. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146483. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146484. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146485. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146486. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146487. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146488. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146489. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146490. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146491. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146492. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146493. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146494. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146495. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146496. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146497. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146498. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146499. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146500. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146501. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146502. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146503. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146504. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146505. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146506. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146507. 19,
  146508. };
  146509. static float _vq_quantthresh__44u0__p3_0[] = {
  146510. -1.5, -0.5, 0.5, 1.5,
  146511. };
  146512. static long _vq_quantmap__44u0__p3_0[] = {
  146513. 3, 1, 0, 2, 4,
  146514. };
  146515. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146516. _vq_quantthresh__44u0__p3_0,
  146517. _vq_quantmap__44u0__p3_0,
  146518. 5,
  146519. 5
  146520. };
  146521. static static_codebook _44u0__p3_0 = {
  146522. 4, 625,
  146523. _vq_lengthlist__44u0__p3_0,
  146524. 1, -533725184, 1611661312, 3, 0,
  146525. _vq_quantlist__44u0__p3_0,
  146526. NULL,
  146527. &_vq_auxt__44u0__p3_0,
  146528. NULL,
  146529. 0
  146530. };
  146531. static long _vq_quantlist__44u0__p4_0[] = {
  146532. 2,
  146533. 1,
  146534. 3,
  146535. 0,
  146536. 4,
  146537. };
  146538. static long _vq_lengthlist__44u0__p4_0[] = {
  146539. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146540. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146541. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146542. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146543. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146544. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146545. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146546. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146547. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146548. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146549. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146550. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146551. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146552. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146553. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146554. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146555. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146556. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146557. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146558. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146559. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146560. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146561. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146562. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146563. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146564. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146565. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146566. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146567. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146568. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146569. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146570. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146571. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146572. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146573. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146574. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146575. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146576. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146577. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146578. 12,
  146579. };
  146580. static float _vq_quantthresh__44u0__p4_0[] = {
  146581. -1.5, -0.5, 0.5, 1.5,
  146582. };
  146583. static long _vq_quantmap__44u0__p4_0[] = {
  146584. 3, 1, 0, 2, 4,
  146585. };
  146586. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146587. _vq_quantthresh__44u0__p4_0,
  146588. _vq_quantmap__44u0__p4_0,
  146589. 5,
  146590. 5
  146591. };
  146592. static static_codebook _44u0__p4_0 = {
  146593. 4, 625,
  146594. _vq_lengthlist__44u0__p4_0,
  146595. 1, -533725184, 1611661312, 3, 0,
  146596. _vq_quantlist__44u0__p4_0,
  146597. NULL,
  146598. &_vq_auxt__44u0__p4_0,
  146599. NULL,
  146600. 0
  146601. };
  146602. static long _vq_quantlist__44u0__p5_0[] = {
  146603. 4,
  146604. 3,
  146605. 5,
  146606. 2,
  146607. 6,
  146608. 1,
  146609. 7,
  146610. 0,
  146611. 8,
  146612. };
  146613. static long _vq_lengthlist__44u0__p5_0[] = {
  146614. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146615. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146616. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146617. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146618. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146619. 12,
  146620. };
  146621. static float _vq_quantthresh__44u0__p5_0[] = {
  146622. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146623. };
  146624. static long _vq_quantmap__44u0__p5_0[] = {
  146625. 7, 5, 3, 1, 0, 2, 4, 6,
  146626. 8,
  146627. };
  146628. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146629. _vq_quantthresh__44u0__p5_0,
  146630. _vq_quantmap__44u0__p5_0,
  146631. 9,
  146632. 9
  146633. };
  146634. static static_codebook _44u0__p5_0 = {
  146635. 2, 81,
  146636. _vq_lengthlist__44u0__p5_0,
  146637. 1, -531628032, 1611661312, 4, 0,
  146638. _vq_quantlist__44u0__p5_0,
  146639. NULL,
  146640. &_vq_auxt__44u0__p5_0,
  146641. NULL,
  146642. 0
  146643. };
  146644. static long _vq_quantlist__44u0__p6_0[] = {
  146645. 6,
  146646. 5,
  146647. 7,
  146648. 4,
  146649. 8,
  146650. 3,
  146651. 9,
  146652. 2,
  146653. 10,
  146654. 1,
  146655. 11,
  146656. 0,
  146657. 12,
  146658. };
  146659. static long _vq_lengthlist__44u0__p6_0[] = {
  146660. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146661. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146662. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146663. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146664. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146665. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146666. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146667. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146668. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146669. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146670. 15,17,16,17,18,17,17,18, 0,
  146671. };
  146672. static float _vq_quantthresh__44u0__p6_0[] = {
  146673. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146674. 12.5, 17.5, 22.5, 27.5,
  146675. };
  146676. static long _vq_quantmap__44u0__p6_0[] = {
  146677. 11, 9, 7, 5, 3, 1, 0, 2,
  146678. 4, 6, 8, 10, 12,
  146679. };
  146680. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146681. _vq_quantthresh__44u0__p6_0,
  146682. _vq_quantmap__44u0__p6_0,
  146683. 13,
  146684. 13
  146685. };
  146686. static static_codebook _44u0__p6_0 = {
  146687. 2, 169,
  146688. _vq_lengthlist__44u0__p6_0,
  146689. 1, -526516224, 1616117760, 4, 0,
  146690. _vq_quantlist__44u0__p6_0,
  146691. NULL,
  146692. &_vq_auxt__44u0__p6_0,
  146693. NULL,
  146694. 0
  146695. };
  146696. static long _vq_quantlist__44u0__p6_1[] = {
  146697. 2,
  146698. 1,
  146699. 3,
  146700. 0,
  146701. 4,
  146702. };
  146703. static long _vq_lengthlist__44u0__p6_1[] = {
  146704. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146705. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146706. };
  146707. static float _vq_quantthresh__44u0__p6_1[] = {
  146708. -1.5, -0.5, 0.5, 1.5,
  146709. };
  146710. static long _vq_quantmap__44u0__p6_1[] = {
  146711. 3, 1, 0, 2, 4,
  146712. };
  146713. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146714. _vq_quantthresh__44u0__p6_1,
  146715. _vq_quantmap__44u0__p6_1,
  146716. 5,
  146717. 5
  146718. };
  146719. static static_codebook _44u0__p6_1 = {
  146720. 2, 25,
  146721. _vq_lengthlist__44u0__p6_1,
  146722. 1, -533725184, 1611661312, 3, 0,
  146723. _vq_quantlist__44u0__p6_1,
  146724. NULL,
  146725. &_vq_auxt__44u0__p6_1,
  146726. NULL,
  146727. 0
  146728. };
  146729. static long _vq_quantlist__44u0__p7_0[] = {
  146730. 2,
  146731. 1,
  146732. 3,
  146733. 0,
  146734. 4,
  146735. };
  146736. static long _vq_lengthlist__44u0__p7_0[] = {
  146737. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146740. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146744. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146767. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146776. 10,
  146777. };
  146778. static float _vq_quantthresh__44u0__p7_0[] = {
  146779. -253.5, -84.5, 84.5, 253.5,
  146780. };
  146781. static long _vq_quantmap__44u0__p7_0[] = {
  146782. 3, 1, 0, 2, 4,
  146783. };
  146784. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146785. _vq_quantthresh__44u0__p7_0,
  146786. _vq_quantmap__44u0__p7_0,
  146787. 5,
  146788. 5
  146789. };
  146790. static static_codebook _44u0__p7_0 = {
  146791. 4, 625,
  146792. _vq_lengthlist__44u0__p7_0,
  146793. 1, -518709248, 1626677248, 3, 0,
  146794. _vq_quantlist__44u0__p7_0,
  146795. NULL,
  146796. &_vq_auxt__44u0__p7_0,
  146797. NULL,
  146798. 0
  146799. };
  146800. static long _vq_quantlist__44u0__p7_1[] = {
  146801. 6,
  146802. 5,
  146803. 7,
  146804. 4,
  146805. 8,
  146806. 3,
  146807. 9,
  146808. 2,
  146809. 10,
  146810. 1,
  146811. 11,
  146812. 0,
  146813. 12,
  146814. };
  146815. static long _vq_lengthlist__44u0__p7_1[] = {
  146816. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146817. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146818. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146819. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146820. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146821. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146822. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146823. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146824. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146825. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146826. 15,15,15,15,15,15,15,15,15,
  146827. };
  146828. static float _vq_quantthresh__44u0__p7_1[] = {
  146829. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146830. 32.5, 45.5, 58.5, 71.5,
  146831. };
  146832. static long _vq_quantmap__44u0__p7_1[] = {
  146833. 11, 9, 7, 5, 3, 1, 0, 2,
  146834. 4, 6, 8, 10, 12,
  146835. };
  146836. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146837. _vq_quantthresh__44u0__p7_1,
  146838. _vq_quantmap__44u0__p7_1,
  146839. 13,
  146840. 13
  146841. };
  146842. static static_codebook _44u0__p7_1 = {
  146843. 2, 169,
  146844. _vq_lengthlist__44u0__p7_1,
  146845. 1, -523010048, 1618608128, 4, 0,
  146846. _vq_quantlist__44u0__p7_1,
  146847. NULL,
  146848. &_vq_auxt__44u0__p7_1,
  146849. NULL,
  146850. 0
  146851. };
  146852. static long _vq_quantlist__44u0__p7_2[] = {
  146853. 6,
  146854. 5,
  146855. 7,
  146856. 4,
  146857. 8,
  146858. 3,
  146859. 9,
  146860. 2,
  146861. 10,
  146862. 1,
  146863. 11,
  146864. 0,
  146865. 12,
  146866. };
  146867. static long _vq_lengthlist__44u0__p7_2[] = {
  146868. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146869. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146870. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146871. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146872. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146873. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146874. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146875. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146876. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146877. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146878. 9, 9, 9,10, 9, 9,10,10, 9,
  146879. };
  146880. static float _vq_quantthresh__44u0__p7_2[] = {
  146881. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146882. 2.5, 3.5, 4.5, 5.5,
  146883. };
  146884. static long _vq_quantmap__44u0__p7_2[] = {
  146885. 11, 9, 7, 5, 3, 1, 0, 2,
  146886. 4, 6, 8, 10, 12,
  146887. };
  146888. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146889. _vq_quantthresh__44u0__p7_2,
  146890. _vq_quantmap__44u0__p7_2,
  146891. 13,
  146892. 13
  146893. };
  146894. static static_codebook _44u0__p7_2 = {
  146895. 2, 169,
  146896. _vq_lengthlist__44u0__p7_2,
  146897. 1, -531103744, 1611661312, 4, 0,
  146898. _vq_quantlist__44u0__p7_2,
  146899. NULL,
  146900. &_vq_auxt__44u0__p7_2,
  146901. NULL,
  146902. 0
  146903. };
  146904. static long _huff_lengthlist__44u0__short[] = {
  146905. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146906. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146907. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146908. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146909. };
  146910. static static_codebook _huff_book__44u0__short = {
  146911. 2, 64,
  146912. _huff_lengthlist__44u0__short,
  146913. 0, 0, 0, 0, 0,
  146914. NULL,
  146915. NULL,
  146916. NULL,
  146917. NULL,
  146918. 0
  146919. };
  146920. static long _huff_lengthlist__44u1__long[] = {
  146921. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146922. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146923. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146924. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146925. };
  146926. static static_codebook _huff_book__44u1__long = {
  146927. 2, 64,
  146928. _huff_lengthlist__44u1__long,
  146929. 0, 0, 0, 0, 0,
  146930. NULL,
  146931. NULL,
  146932. NULL,
  146933. NULL,
  146934. 0
  146935. };
  146936. static long _vq_quantlist__44u1__p1_0[] = {
  146937. 1,
  146938. 0,
  146939. 2,
  146940. };
  146941. static long _vq_lengthlist__44u1__p1_0[] = {
  146942. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146943. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146944. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146945. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146946. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146947. 13,
  146948. };
  146949. static float _vq_quantthresh__44u1__p1_0[] = {
  146950. -0.5, 0.5,
  146951. };
  146952. static long _vq_quantmap__44u1__p1_0[] = {
  146953. 1, 0, 2,
  146954. };
  146955. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146956. _vq_quantthresh__44u1__p1_0,
  146957. _vq_quantmap__44u1__p1_0,
  146958. 3,
  146959. 3
  146960. };
  146961. static static_codebook _44u1__p1_0 = {
  146962. 4, 81,
  146963. _vq_lengthlist__44u1__p1_0,
  146964. 1, -535822336, 1611661312, 2, 0,
  146965. _vq_quantlist__44u1__p1_0,
  146966. NULL,
  146967. &_vq_auxt__44u1__p1_0,
  146968. NULL,
  146969. 0
  146970. };
  146971. static long _vq_quantlist__44u1__p2_0[] = {
  146972. 1,
  146973. 0,
  146974. 2,
  146975. };
  146976. static long _vq_lengthlist__44u1__p2_0[] = {
  146977. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146978. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146979. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146980. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146981. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146982. 9,
  146983. };
  146984. static float _vq_quantthresh__44u1__p2_0[] = {
  146985. -0.5, 0.5,
  146986. };
  146987. static long _vq_quantmap__44u1__p2_0[] = {
  146988. 1, 0, 2,
  146989. };
  146990. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146991. _vq_quantthresh__44u1__p2_0,
  146992. _vq_quantmap__44u1__p2_0,
  146993. 3,
  146994. 3
  146995. };
  146996. static static_codebook _44u1__p2_0 = {
  146997. 4, 81,
  146998. _vq_lengthlist__44u1__p2_0,
  146999. 1, -535822336, 1611661312, 2, 0,
  147000. _vq_quantlist__44u1__p2_0,
  147001. NULL,
  147002. &_vq_auxt__44u1__p2_0,
  147003. NULL,
  147004. 0
  147005. };
  147006. static long _vq_quantlist__44u1__p3_0[] = {
  147007. 2,
  147008. 1,
  147009. 3,
  147010. 0,
  147011. 4,
  147012. };
  147013. static long _vq_lengthlist__44u1__p3_0[] = {
  147014. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147015. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147016. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147017. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147018. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147019. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147020. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147021. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147022. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147023. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147024. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147025. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147026. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147027. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147028. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147029. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147030. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147031. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147032. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147033. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147034. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147035. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147036. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147037. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147038. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147039. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147040. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147041. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147042. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147043. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147044. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147045. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147046. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147047. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147048. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147049. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147050. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147051. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147052. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147053. 19,
  147054. };
  147055. static float _vq_quantthresh__44u1__p3_0[] = {
  147056. -1.5, -0.5, 0.5, 1.5,
  147057. };
  147058. static long _vq_quantmap__44u1__p3_0[] = {
  147059. 3, 1, 0, 2, 4,
  147060. };
  147061. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147062. _vq_quantthresh__44u1__p3_0,
  147063. _vq_quantmap__44u1__p3_0,
  147064. 5,
  147065. 5
  147066. };
  147067. static static_codebook _44u1__p3_0 = {
  147068. 4, 625,
  147069. _vq_lengthlist__44u1__p3_0,
  147070. 1, -533725184, 1611661312, 3, 0,
  147071. _vq_quantlist__44u1__p3_0,
  147072. NULL,
  147073. &_vq_auxt__44u1__p3_0,
  147074. NULL,
  147075. 0
  147076. };
  147077. static long _vq_quantlist__44u1__p4_0[] = {
  147078. 2,
  147079. 1,
  147080. 3,
  147081. 0,
  147082. 4,
  147083. };
  147084. static long _vq_lengthlist__44u1__p4_0[] = {
  147085. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147086. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147087. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147088. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147089. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147090. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147091. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147092. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147093. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147094. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147095. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147096. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147097. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147098. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147099. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147100. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147101. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147102. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147103. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147104. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147105. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147106. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147107. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147108. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147109. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147110. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147111. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147112. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147113. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147114. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147115. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147116. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147117. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147118. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147119. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147120. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147121. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147122. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147123. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147124. 12,
  147125. };
  147126. static float _vq_quantthresh__44u1__p4_0[] = {
  147127. -1.5, -0.5, 0.5, 1.5,
  147128. };
  147129. static long _vq_quantmap__44u1__p4_0[] = {
  147130. 3, 1, 0, 2, 4,
  147131. };
  147132. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147133. _vq_quantthresh__44u1__p4_0,
  147134. _vq_quantmap__44u1__p4_0,
  147135. 5,
  147136. 5
  147137. };
  147138. static static_codebook _44u1__p4_0 = {
  147139. 4, 625,
  147140. _vq_lengthlist__44u1__p4_0,
  147141. 1, -533725184, 1611661312, 3, 0,
  147142. _vq_quantlist__44u1__p4_0,
  147143. NULL,
  147144. &_vq_auxt__44u1__p4_0,
  147145. NULL,
  147146. 0
  147147. };
  147148. static long _vq_quantlist__44u1__p5_0[] = {
  147149. 4,
  147150. 3,
  147151. 5,
  147152. 2,
  147153. 6,
  147154. 1,
  147155. 7,
  147156. 0,
  147157. 8,
  147158. };
  147159. static long _vq_lengthlist__44u1__p5_0[] = {
  147160. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147161. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147162. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147163. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147164. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147165. 12,
  147166. };
  147167. static float _vq_quantthresh__44u1__p5_0[] = {
  147168. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147169. };
  147170. static long _vq_quantmap__44u1__p5_0[] = {
  147171. 7, 5, 3, 1, 0, 2, 4, 6,
  147172. 8,
  147173. };
  147174. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147175. _vq_quantthresh__44u1__p5_0,
  147176. _vq_quantmap__44u1__p5_0,
  147177. 9,
  147178. 9
  147179. };
  147180. static static_codebook _44u1__p5_0 = {
  147181. 2, 81,
  147182. _vq_lengthlist__44u1__p5_0,
  147183. 1, -531628032, 1611661312, 4, 0,
  147184. _vq_quantlist__44u1__p5_0,
  147185. NULL,
  147186. &_vq_auxt__44u1__p5_0,
  147187. NULL,
  147188. 0
  147189. };
  147190. static long _vq_quantlist__44u1__p6_0[] = {
  147191. 6,
  147192. 5,
  147193. 7,
  147194. 4,
  147195. 8,
  147196. 3,
  147197. 9,
  147198. 2,
  147199. 10,
  147200. 1,
  147201. 11,
  147202. 0,
  147203. 12,
  147204. };
  147205. static long _vq_lengthlist__44u1__p6_0[] = {
  147206. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147207. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147208. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147209. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147210. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147211. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147212. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147213. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147214. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147215. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147216. 15,17,16,17,18,17,17,18, 0,
  147217. };
  147218. static float _vq_quantthresh__44u1__p6_0[] = {
  147219. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147220. 12.5, 17.5, 22.5, 27.5,
  147221. };
  147222. static long _vq_quantmap__44u1__p6_0[] = {
  147223. 11, 9, 7, 5, 3, 1, 0, 2,
  147224. 4, 6, 8, 10, 12,
  147225. };
  147226. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147227. _vq_quantthresh__44u1__p6_0,
  147228. _vq_quantmap__44u1__p6_0,
  147229. 13,
  147230. 13
  147231. };
  147232. static static_codebook _44u1__p6_0 = {
  147233. 2, 169,
  147234. _vq_lengthlist__44u1__p6_0,
  147235. 1, -526516224, 1616117760, 4, 0,
  147236. _vq_quantlist__44u1__p6_0,
  147237. NULL,
  147238. &_vq_auxt__44u1__p6_0,
  147239. NULL,
  147240. 0
  147241. };
  147242. static long _vq_quantlist__44u1__p6_1[] = {
  147243. 2,
  147244. 1,
  147245. 3,
  147246. 0,
  147247. 4,
  147248. };
  147249. static long _vq_lengthlist__44u1__p6_1[] = {
  147250. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147251. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147252. };
  147253. static float _vq_quantthresh__44u1__p6_1[] = {
  147254. -1.5, -0.5, 0.5, 1.5,
  147255. };
  147256. static long _vq_quantmap__44u1__p6_1[] = {
  147257. 3, 1, 0, 2, 4,
  147258. };
  147259. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147260. _vq_quantthresh__44u1__p6_1,
  147261. _vq_quantmap__44u1__p6_1,
  147262. 5,
  147263. 5
  147264. };
  147265. static static_codebook _44u1__p6_1 = {
  147266. 2, 25,
  147267. _vq_lengthlist__44u1__p6_1,
  147268. 1, -533725184, 1611661312, 3, 0,
  147269. _vq_quantlist__44u1__p6_1,
  147270. NULL,
  147271. &_vq_auxt__44u1__p6_1,
  147272. NULL,
  147273. 0
  147274. };
  147275. static long _vq_quantlist__44u1__p7_0[] = {
  147276. 3,
  147277. 2,
  147278. 4,
  147279. 1,
  147280. 5,
  147281. 0,
  147282. 6,
  147283. };
  147284. static long _vq_lengthlist__44u1__p7_0[] = {
  147285. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147286. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147287. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147288. 8,
  147289. };
  147290. static float _vq_quantthresh__44u1__p7_0[] = {
  147291. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147292. };
  147293. static long _vq_quantmap__44u1__p7_0[] = {
  147294. 5, 3, 1, 0, 2, 4, 6,
  147295. };
  147296. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147297. _vq_quantthresh__44u1__p7_0,
  147298. _vq_quantmap__44u1__p7_0,
  147299. 7,
  147300. 7
  147301. };
  147302. static static_codebook _44u1__p7_0 = {
  147303. 2, 49,
  147304. _vq_lengthlist__44u1__p7_0,
  147305. 1, -518017024, 1626677248, 3, 0,
  147306. _vq_quantlist__44u1__p7_0,
  147307. NULL,
  147308. &_vq_auxt__44u1__p7_0,
  147309. NULL,
  147310. 0
  147311. };
  147312. static long _vq_quantlist__44u1__p7_1[] = {
  147313. 6,
  147314. 5,
  147315. 7,
  147316. 4,
  147317. 8,
  147318. 3,
  147319. 9,
  147320. 2,
  147321. 10,
  147322. 1,
  147323. 11,
  147324. 0,
  147325. 12,
  147326. };
  147327. static long _vq_lengthlist__44u1__p7_1[] = {
  147328. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147329. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147330. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147331. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147332. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147333. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147334. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147335. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147336. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147337. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147338. 15,15,15,15,15,15,15,15,15,
  147339. };
  147340. static float _vq_quantthresh__44u1__p7_1[] = {
  147341. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147342. 32.5, 45.5, 58.5, 71.5,
  147343. };
  147344. static long _vq_quantmap__44u1__p7_1[] = {
  147345. 11, 9, 7, 5, 3, 1, 0, 2,
  147346. 4, 6, 8, 10, 12,
  147347. };
  147348. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147349. _vq_quantthresh__44u1__p7_1,
  147350. _vq_quantmap__44u1__p7_1,
  147351. 13,
  147352. 13
  147353. };
  147354. static static_codebook _44u1__p7_1 = {
  147355. 2, 169,
  147356. _vq_lengthlist__44u1__p7_1,
  147357. 1, -523010048, 1618608128, 4, 0,
  147358. _vq_quantlist__44u1__p7_1,
  147359. NULL,
  147360. &_vq_auxt__44u1__p7_1,
  147361. NULL,
  147362. 0
  147363. };
  147364. static long _vq_quantlist__44u1__p7_2[] = {
  147365. 6,
  147366. 5,
  147367. 7,
  147368. 4,
  147369. 8,
  147370. 3,
  147371. 9,
  147372. 2,
  147373. 10,
  147374. 1,
  147375. 11,
  147376. 0,
  147377. 12,
  147378. };
  147379. static long _vq_lengthlist__44u1__p7_2[] = {
  147380. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147381. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147382. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147383. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147384. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147385. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147386. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147387. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147388. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147389. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147390. 9, 9, 9,10, 9, 9,10,10, 9,
  147391. };
  147392. static float _vq_quantthresh__44u1__p7_2[] = {
  147393. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147394. 2.5, 3.5, 4.5, 5.5,
  147395. };
  147396. static long _vq_quantmap__44u1__p7_2[] = {
  147397. 11, 9, 7, 5, 3, 1, 0, 2,
  147398. 4, 6, 8, 10, 12,
  147399. };
  147400. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147401. _vq_quantthresh__44u1__p7_2,
  147402. _vq_quantmap__44u1__p7_2,
  147403. 13,
  147404. 13
  147405. };
  147406. static static_codebook _44u1__p7_2 = {
  147407. 2, 169,
  147408. _vq_lengthlist__44u1__p7_2,
  147409. 1, -531103744, 1611661312, 4, 0,
  147410. _vq_quantlist__44u1__p7_2,
  147411. NULL,
  147412. &_vq_auxt__44u1__p7_2,
  147413. NULL,
  147414. 0
  147415. };
  147416. static long _huff_lengthlist__44u1__short[] = {
  147417. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147418. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147419. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147420. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147421. };
  147422. static static_codebook _huff_book__44u1__short = {
  147423. 2, 64,
  147424. _huff_lengthlist__44u1__short,
  147425. 0, 0, 0, 0, 0,
  147426. NULL,
  147427. NULL,
  147428. NULL,
  147429. NULL,
  147430. 0
  147431. };
  147432. static long _huff_lengthlist__44u2__long[] = {
  147433. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147434. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147435. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147436. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147437. };
  147438. static static_codebook _huff_book__44u2__long = {
  147439. 2, 64,
  147440. _huff_lengthlist__44u2__long,
  147441. 0, 0, 0, 0, 0,
  147442. NULL,
  147443. NULL,
  147444. NULL,
  147445. NULL,
  147446. 0
  147447. };
  147448. static long _vq_quantlist__44u2__p1_0[] = {
  147449. 1,
  147450. 0,
  147451. 2,
  147452. };
  147453. static long _vq_lengthlist__44u2__p1_0[] = {
  147454. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147455. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147456. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147457. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147458. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147459. 13,
  147460. };
  147461. static float _vq_quantthresh__44u2__p1_0[] = {
  147462. -0.5, 0.5,
  147463. };
  147464. static long _vq_quantmap__44u2__p1_0[] = {
  147465. 1, 0, 2,
  147466. };
  147467. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147468. _vq_quantthresh__44u2__p1_0,
  147469. _vq_quantmap__44u2__p1_0,
  147470. 3,
  147471. 3
  147472. };
  147473. static static_codebook _44u2__p1_0 = {
  147474. 4, 81,
  147475. _vq_lengthlist__44u2__p1_0,
  147476. 1, -535822336, 1611661312, 2, 0,
  147477. _vq_quantlist__44u2__p1_0,
  147478. NULL,
  147479. &_vq_auxt__44u2__p1_0,
  147480. NULL,
  147481. 0
  147482. };
  147483. static long _vq_quantlist__44u2__p2_0[] = {
  147484. 1,
  147485. 0,
  147486. 2,
  147487. };
  147488. static long _vq_lengthlist__44u2__p2_0[] = {
  147489. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147490. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147491. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147492. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147493. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147494. 9,
  147495. };
  147496. static float _vq_quantthresh__44u2__p2_0[] = {
  147497. -0.5, 0.5,
  147498. };
  147499. static long _vq_quantmap__44u2__p2_0[] = {
  147500. 1, 0, 2,
  147501. };
  147502. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147503. _vq_quantthresh__44u2__p2_0,
  147504. _vq_quantmap__44u2__p2_0,
  147505. 3,
  147506. 3
  147507. };
  147508. static static_codebook _44u2__p2_0 = {
  147509. 4, 81,
  147510. _vq_lengthlist__44u2__p2_0,
  147511. 1, -535822336, 1611661312, 2, 0,
  147512. _vq_quantlist__44u2__p2_0,
  147513. NULL,
  147514. &_vq_auxt__44u2__p2_0,
  147515. NULL,
  147516. 0
  147517. };
  147518. static long _vq_quantlist__44u2__p3_0[] = {
  147519. 2,
  147520. 1,
  147521. 3,
  147522. 0,
  147523. 4,
  147524. };
  147525. static long _vq_lengthlist__44u2__p3_0[] = {
  147526. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147527. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147528. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147529. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147530. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147531. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147532. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147533. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147534. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147535. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147536. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147537. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147538. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147539. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147540. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147541. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147542. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147543. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147544. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147545. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147546. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147547. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147548. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147549. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147550. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147551. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147552. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147553. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147554. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147555. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147556. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147557. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147558. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147559. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147560. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147561. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147562. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147563. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147564. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147565. 0,
  147566. };
  147567. static float _vq_quantthresh__44u2__p3_0[] = {
  147568. -1.5, -0.5, 0.5, 1.5,
  147569. };
  147570. static long _vq_quantmap__44u2__p3_0[] = {
  147571. 3, 1, 0, 2, 4,
  147572. };
  147573. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147574. _vq_quantthresh__44u2__p3_0,
  147575. _vq_quantmap__44u2__p3_0,
  147576. 5,
  147577. 5
  147578. };
  147579. static static_codebook _44u2__p3_0 = {
  147580. 4, 625,
  147581. _vq_lengthlist__44u2__p3_0,
  147582. 1, -533725184, 1611661312, 3, 0,
  147583. _vq_quantlist__44u2__p3_0,
  147584. NULL,
  147585. &_vq_auxt__44u2__p3_0,
  147586. NULL,
  147587. 0
  147588. };
  147589. static long _vq_quantlist__44u2__p4_0[] = {
  147590. 2,
  147591. 1,
  147592. 3,
  147593. 0,
  147594. 4,
  147595. };
  147596. static long _vq_lengthlist__44u2__p4_0[] = {
  147597. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147598. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147599. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147600. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147601. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147602. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147603. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147604. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147605. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147606. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147607. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147608. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147609. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147610. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147611. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147612. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147613. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147614. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147615. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147616. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147617. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147618. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147619. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147620. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147621. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147622. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147623. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147624. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147625. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147626. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147627. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147628. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147629. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147630. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147631. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147632. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147633. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147634. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147635. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147636. 13,
  147637. };
  147638. static float _vq_quantthresh__44u2__p4_0[] = {
  147639. -1.5, -0.5, 0.5, 1.5,
  147640. };
  147641. static long _vq_quantmap__44u2__p4_0[] = {
  147642. 3, 1, 0, 2, 4,
  147643. };
  147644. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147645. _vq_quantthresh__44u2__p4_0,
  147646. _vq_quantmap__44u2__p4_0,
  147647. 5,
  147648. 5
  147649. };
  147650. static static_codebook _44u2__p4_0 = {
  147651. 4, 625,
  147652. _vq_lengthlist__44u2__p4_0,
  147653. 1, -533725184, 1611661312, 3, 0,
  147654. _vq_quantlist__44u2__p4_0,
  147655. NULL,
  147656. &_vq_auxt__44u2__p4_0,
  147657. NULL,
  147658. 0
  147659. };
  147660. static long _vq_quantlist__44u2__p5_0[] = {
  147661. 4,
  147662. 3,
  147663. 5,
  147664. 2,
  147665. 6,
  147666. 1,
  147667. 7,
  147668. 0,
  147669. 8,
  147670. };
  147671. static long _vq_lengthlist__44u2__p5_0[] = {
  147672. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147673. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147674. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147675. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147676. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147677. 13,
  147678. };
  147679. static float _vq_quantthresh__44u2__p5_0[] = {
  147680. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147681. };
  147682. static long _vq_quantmap__44u2__p5_0[] = {
  147683. 7, 5, 3, 1, 0, 2, 4, 6,
  147684. 8,
  147685. };
  147686. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147687. _vq_quantthresh__44u2__p5_0,
  147688. _vq_quantmap__44u2__p5_0,
  147689. 9,
  147690. 9
  147691. };
  147692. static static_codebook _44u2__p5_0 = {
  147693. 2, 81,
  147694. _vq_lengthlist__44u2__p5_0,
  147695. 1, -531628032, 1611661312, 4, 0,
  147696. _vq_quantlist__44u2__p5_0,
  147697. NULL,
  147698. &_vq_auxt__44u2__p5_0,
  147699. NULL,
  147700. 0
  147701. };
  147702. static long _vq_quantlist__44u2__p6_0[] = {
  147703. 6,
  147704. 5,
  147705. 7,
  147706. 4,
  147707. 8,
  147708. 3,
  147709. 9,
  147710. 2,
  147711. 10,
  147712. 1,
  147713. 11,
  147714. 0,
  147715. 12,
  147716. };
  147717. static long _vq_lengthlist__44u2__p6_0[] = {
  147718. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147719. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147720. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147721. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147722. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147723. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147724. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147725. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147726. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147727. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147728. 15,17,17,16,18,17,18, 0, 0,
  147729. };
  147730. static float _vq_quantthresh__44u2__p6_0[] = {
  147731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147732. 12.5, 17.5, 22.5, 27.5,
  147733. };
  147734. static long _vq_quantmap__44u2__p6_0[] = {
  147735. 11, 9, 7, 5, 3, 1, 0, 2,
  147736. 4, 6, 8, 10, 12,
  147737. };
  147738. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147739. _vq_quantthresh__44u2__p6_0,
  147740. _vq_quantmap__44u2__p6_0,
  147741. 13,
  147742. 13
  147743. };
  147744. static static_codebook _44u2__p6_0 = {
  147745. 2, 169,
  147746. _vq_lengthlist__44u2__p6_0,
  147747. 1, -526516224, 1616117760, 4, 0,
  147748. _vq_quantlist__44u2__p6_0,
  147749. NULL,
  147750. &_vq_auxt__44u2__p6_0,
  147751. NULL,
  147752. 0
  147753. };
  147754. static long _vq_quantlist__44u2__p6_1[] = {
  147755. 2,
  147756. 1,
  147757. 3,
  147758. 0,
  147759. 4,
  147760. };
  147761. static long _vq_lengthlist__44u2__p6_1[] = {
  147762. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147763. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147764. };
  147765. static float _vq_quantthresh__44u2__p6_1[] = {
  147766. -1.5, -0.5, 0.5, 1.5,
  147767. };
  147768. static long _vq_quantmap__44u2__p6_1[] = {
  147769. 3, 1, 0, 2, 4,
  147770. };
  147771. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147772. _vq_quantthresh__44u2__p6_1,
  147773. _vq_quantmap__44u2__p6_1,
  147774. 5,
  147775. 5
  147776. };
  147777. static static_codebook _44u2__p6_1 = {
  147778. 2, 25,
  147779. _vq_lengthlist__44u2__p6_1,
  147780. 1, -533725184, 1611661312, 3, 0,
  147781. _vq_quantlist__44u2__p6_1,
  147782. NULL,
  147783. &_vq_auxt__44u2__p6_1,
  147784. NULL,
  147785. 0
  147786. };
  147787. static long _vq_quantlist__44u2__p7_0[] = {
  147788. 4,
  147789. 3,
  147790. 5,
  147791. 2,
  147792. 6,
  147793. 1,
  147794. 7,
  147795. 0,
  147796. 8,
  147797. };
  147798. static long _vq_lengthlist__44u2__p7_0[] = {
  147799. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147800. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147804. 11,
  147805. };
  147806. static float _vq_quantthresh__44u2__p7_0[] = {
  147807. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147808. };
  147809. static long _vq_quantmap__44u2__p7_0[] = {
  147810. 7, 5, 3, 1, 0, 2, 4, 6,
  147811. 8,
  147812. };
  147813. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147814. _vq_quantthresh__44u2__p7_0,
  147815. _vq_quantmap__44u2__p7_0,
  147816. 9,
  147817. 9
  147818. };
  147819. static static_codebook _44u2__p7_0 = {
  147820. 2, 81,
  147821. _vq_lengthlist__44u2__p7_0,
  147822. 1, -516612096, 1626677248, 4, 0,
  147823. _vq_quantlist__44u2__p7_0,
  147824. NULL,
  147825. &_vq_auxt__44u2__p7_0,
  147826. NULL,
  147827. 0
  147828. };
  147829. static long _vq_quantlist__44u2__p7_1[] = {
  147830. 6,
  147831. 5,
  147832. 7,
  147833. 4,
  147834. 8,
  147835. 3,
  147836. 9,
  147837. 2,
  147838. 10,
  147839. 1,
  147840. 11,
  147841. 0,
  147842. 12,
  147843. };
  147844. static long _vq_lengthlist__44u2__p7_1[] = {
  147845. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147846. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147847. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147848. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147849. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147850. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147851. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147852. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147853. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147854. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147855. 14,14,14,17,15,17,17,17,17,
  147856. };
  147857. static float _vq_quantthresh__44u2__p7_1[] = {
  147858. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147859. 32.5, 45.5, 58.5, 71.5,
  147860. };
  147861. static long _vq_quantmap__44u2__p7_1[] = {
  147862. 11, 9, 7, 5, 3, 1, 0, 2,
  147863. 4, 6, 8, 10, 12,
  147864. };
  147865. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147866. _vq_quantthresh__44u2__p7_1,
  147867. _vq_quantmap__44u2__p7_1,
  147868. 13,
  147869. 13
  147870. };
  147871. static static_codebook _44u2__p7_1 = {
  147872. 2, 169,
  147873. _vq_lengthlist__44u2__p7_1,
  147874. 1, -523010048, 1618608128, 4, 0,
  147875. _vq_quantlist__44u2__p7_1,
  147876. NULL,
  147877. &_vq_auxt__44u2__p7_1,
  147878. NULL,
  147879. 0
  147880. };
  147881. static long _vq_quantlist__44u2__p7_2[] = {
  147882. 6,
  147883. 5,
  147884. 7,
  147885. 4,
  147886. 8,
  147887. 3,
  147888. 9,
  147889. 2,
  147890. 10,
  147891. 1,
  147892. 11,
  147893. 0,
  147894. 12,
  147895. };
  147896. static long _vq_lengthlist__44u2__p7_2[] = {
  147897. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147898. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147899. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147900. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147901. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147902. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147903. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147904. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147905. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147906. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147907. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147908. };
  147909. static float _vq_quantthresh__44u2__p7_2[] = {
  147910. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147911. 2.5, 3.5, 4.5, 5.5,
  147912. };
  147913. static long _vq_quantmap__44u2__p7_2[] = {
  147914. 11, 9, 7, 5, 3, 1, 0, 2,
  147915. 4, 6, 8, 10, 12,
  147916. };
  147917. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147918. _vq_quantthresh__44u2__p7_2,
  147919. _vq_quantmap__44u2__p7_2,
  147920. 13,
  147921. 13
  147922. };
  147923. static static_codebook _44u2__p7_2 = {
  147924. 2, 169,
  147925. _vq_lengthlist__44u2__p7_2,
  147926. 1, -531103744, 1611661312, 4, 0,
  147927. _vq_quantlist__44u2__p7_2,
  147928. NULL,
  147929. &_vq_auxt__44u2__p7_2,
  147930. NULL,
  147931. 0
  147932. };
  147933. static long _huff_lengthlist__44u2__short[] = {
  147934. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147935. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147936. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147937. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147938. };
  147939. static static_codebook _huff_book__44u2__short = {
  147940. 2, 64,
  147941. _huff_lengthlist__44u2__short,
  147942. 0, 0, 0, 0, 0,
  147943. NULL,
  147944. NULL,
  147945. NULL,
  147946. NULL,
  147947. 0
  147948. };
  147949. static long _huff_lengthlist__44u3__long[] = {
  147950. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147951. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147952. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147953. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147954. };
  147955. static static_codebook _huff_book__44u3__long = {
  147956. 2, 64,
  147957. _huff_lengthlist__44u3__long,
  147958. 0, 0, 0, 0, 0,
  147959. NULL,
  147960. NULL,
  147961. NULL,
  147962. NULL,
  147963. 0
  147964. };
  147965. static long _vq_quantlist__44u3__p1_0[] = {
  147966. 1,
  147967. 0,
  147968. 2,
  147969. };
  147970. static long _vq_lengthlist__44u3__p1_0[] = {
  147971. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147972. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147973. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147974. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147975. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147976. 13,
  147977. };
  147978. static float _vq_quantthresh__44u3__p1_0[] = {
  147979. -0.5, 0.5,
  147980. };
  147981. static long _vq_quantmap__44u3__p1_0[] = {
  147982. 1, 0, 2,
  147983. };
  147984. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147985. _vq_quantthresh__44u3__p1_0,
  147986. _vq_quantmap__44u3__p1_0,
  147987. 3,
  147988. 3
  147989. };
  147990. static static_codebook _44u3__p1_0 = {
  147991. 4, 81,
  147992. _vq_lengthlist__44u3__p1_0,
  147993. 1, -535822336, 1611661312, 2, 0,
  147994. _vq_quantlist__44u3__p1_0,
  147995. NULL,
  147996. &_vq_auxt__44u3__p1_0,
  147997. NULL,
  147998. 0
  147999. };
  148000. static long _vq_quantlist__44u3__p2_0[] = {
  148001. 1,
  148002. 0,
  148003. 2,
  148004. };
  148005. static long _vq_lengthlist__44u3__p2_0[] = {
  148006. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148007. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148008. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148009. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148010. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148011. 9,
  148012. };
  148013. static float _vq_quantthresh__44u3__p2_0[] = {
  148014. -0.5, 0.5,
  148015. };
  148016. static long _vq_quantmap__44u3__p2_0[] = {
  148017. 1, 0, 2,
  148018. };
  148019. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148020. _vq_quantthresh__44u3__p2_0,
  148021. _vq_quantmap__44u3__p2_0,
  148022. 3,
  148023. 3
  148024. };
  148025. static static_codebook _44u3__p2_0 = {
  148026. 4, 81,
  148027. _vq_lengthlist__44u3__p2_0,
  148028. 1, -535822336, 1611661312, 2, 0,
  148029. _vq_quantlist__44u3__p2_0,
  148030. NULL,
  148031. &_vq_auxt__44u3__p2_0,
  148032. NULL,
  148033. 0
  148034. };
  148035. static long _vq_quantlist__44u3__p3_0[] = {
  148036. 2,
  148037. 1,
  148038. 3,
  148039. 0,
  148040. 4,
  148041. };
  148042. static long _vq_lengthlist__44u3__p3_0[] = {
  148043. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148044. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148045. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148046. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148047. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148048. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148049. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148050. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148051. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148052. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148053. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148054. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148055. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148056. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148057. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148058. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148059. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148060. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148061. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148062. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148063. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148064. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148065. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148066. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148067. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148068. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148069. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148070. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148071. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148072. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148073. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148074. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148075. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148076. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148077. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148078. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148079. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148080. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148081. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148082. 0,
  148083. };
  148084. static float _vq_quantthresh__44u3__p3_0[] = {
  148085. -1.5, -0.5, 0.5, 1.5,
  148086. };
  148087. static long _vq_quantmap__44u3__p3_0[] = {
  148088. 3, 1, 0, 2, 4,
  148089. };
  148090. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148091. _vq_quantthresh__44u3__p3_0,
  148092. _vq_quantmap__44u3__p3_0,
  148093. 5,
  148094. 5
  148095. };
  148096. static static_codebook _44u3__p3_0 = {
  148097. 4, 625,
  148098. _vq_lengthlist__44u3__p3_0,
  148099. 1, -533725184, 1611661312, 3, 0,
  148100. _vq_quantlist__44u3__p3_0,
  148101. NULL,
  148102. &_vq_auxt__44u3__p3_0,
  148103. NULL,
  148104. 0
  148105. };
  148106. static long _vq_quantlist__44u3__p4_0[] = {
  148107. 2,
  148108. 1,
  148109. 3,
  148110. 0,
  148111. 4,
  148112. };
  148113. static long _vq_lengthlist__44u3__p4_0[] = {
  148114. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148115. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148116. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148117. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148118. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148119. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148120. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148121. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148122. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148123. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148124. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148125. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148126. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148127. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148128. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148129. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148130. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148131. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148132. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148133. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148134. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148135. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148136. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148137. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148138. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148139. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148140. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148141. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148142. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148143. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148144. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148145. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148146. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148147. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148148. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148149. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148150. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148151. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148152. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148153. 13,
  148154. };
  148155. static float _vq_quantthresh__44u3__p4_0[] = {
  148156. -1.5, -0.5, 0.5, 1.5,
  148157. };
  148158. static long _vq_quantmap__44u3__p4_0[] = {
  148159. 3, 1, 0, 2, 4,
  148160. };
  148161. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148162. _vq_quantthresh__44u3__p4_0,
  148163. _vq_quantmap__44u3__p4_0,
  148164. 5,
  148165. 5
  148166. };
  148167. static static_codebook _44u3__p4_0 = {
  148168. 4, 625,
  148169. _vq_lengthlist__44u3__p4_0,
  148170. 1, -533725184, 1611661312, 3, 0,
  148171. _vq_quantlist__44u3__p4_0,
  148172. NULL,
  148173. &_vq_auxt__44u3__p4_0,
  148174. NULL,
  148175. 0
  148176. };
  148177. static long _vq_quantlist__44u3__p5_0[] = {
  148178. 4,
  148179. 3,
  148180. 5,
  148181. 2,
  148182. 6,
  148183. 1,
  148184. 7,
  148185. 0,
  148186. 8,
  148187. };
  148188. static long _vq_lengthlist__44u3__p5_0[] = {
  148189. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148190. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148191. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148192. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148193. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148194. 12,
  148195. };
  148196. static float _vq_quantthresh__44u3__p5_0[] = {
  148197. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148198. };
  148199. static long _vq_quantmap__44u3__p5_0[] = {
  148200. 7, 5, 3, 1, 0, 2, 4, 6,
  148201. 8,
  148202. };
  148203. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148204. _vq_quantthresh__44u3__p5_0,
  148205. _vq_quantmap__44u3__p5_0,
  148206. 9,
  148207. 9
  148208. };
  148209. static static_codebook _44u3__p5_0 = {
  148210. 2, 81,
  148211. _vq_lengthlist__44u3__p5_0,
  148212. 1, -531628032, 1611661312, 4, 0,
  148213. _vq_quantlist__44u3__p5_0,
  148214. NULL,
  148215. &_vq_auxt__44u3__p5_0,
  148216. NULL,
  148217. 0
  148218. };
  148219. static long _vq_quantlist__44u3__p6_0[] = {
  148220. 6,
  148221. 5,
  148222. 7,
  148223. 4,
  148224. 8,
  148225. 3,
  148226. 9,
  148227. 2,
  148228. 10,
  148229. 1,
  148230. 11,
  148231. 0,
  148232. 12,
  148233. };
  148234. static long _vq_lengthlist__44u3__p6_0[] = {
  148235. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148236. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148237. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148238. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148239. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148240. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148241. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148242. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148243. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148244. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148245. 15,16,16,16,17,18,16,20,18,
  148246. };
  148247. static float _vq_quantthresh__44u3__p6_0[] = {
  148248. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148249. 12.5, 17.5, 22.5, 27.5,
  148250. };
  148251. static long _vq_quantmap__44u3__p6_0[] = {
  148252. 11, 9, 7, 5, 3, 1, 0, 2,
  148253. 4, 6, 8, 10, 12,
  148254. };
  148255. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148256. _vq_quantthresh__44u3__p6_0,
  148257. _vq_quantmap__44u3__p6_0,
  148258. 13,
  148259. 13
  148260. };
  148261. static static_codebook _44u3__p6_0 = {
  148262. 2, 169,
  148263. _vq_lengthlist__44u3__p6_0,
  148264. 1, -526516224, 1616117760, 4, 0,
  148265. _vq_quantlist__44u3__p6_0,
  148266. NULL,
  148267. &_vq_auxt__44u3__p6_0,
  148268. NULL,
  148269. 0
  148270. };
  148271. static long _vq_quantlist__44u3__p6_1[] = {
  148272. 2,
  148273. 1,
  148274. 3,
  148275. 0,
  148276. 4,
  148277. };
  148278. static long _vq_lengthlist__44u3__p6_1[] = {
  148279. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148280. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148281. };
  148282. static float _vq_quantthresh__44u3__p6_1[] = {
  148283. -1.5, -0.5, 0.5, 1.5,
  148284. };
  148285. static long _vq_quantmap__44u3__p6_1[] = {
  148286. 3, 1, 0, 2, 4,
  148287. };
  148288. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148289. _vq_quantthresh__44u3__p6_1,
  148290. _vq_quantmap__44u3__p6_1,
  148291. 5,
  148292. 5
  148293. };
  148294. static static_codebook _44u3__p6_1 = {
  148295. 2, 25,
  148296. _vq_lengthlist__44u3__p6_1,
  148297. 1, -533725184, 1611661312, 3, 0,
  148298. _vq_quantlist__44u3__p6_1,
  148299. NULL,
  148300. &_vq_auxt__44u3__p6_1,
  148301. NULL,
  148302. 0
  148303. };
  148304. static long _vq_quantlist__44u3__p7_0[] = {
  148305. 4,
  148306. 3,
  148307. 5,
  148308. 2,
  148309. 6,
  148310. 1,
  148311. 7,
  148312. 0,
  148313. 8,
  148314. };
  148315. static long _vq_lengthlist__44u3__p7_0[] = {
  148316. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148317. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148318. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148319. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148320. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148321. 9,
  148322. };
  148323. static float _vq_quantthresh__44u3__p7_0[] = {
  148324. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148325. };
  148326. static long _vq_quantmap__44u3__p7_0[] = {
  148327. 7, 5, 3, 1, 0, 2, 4, 6,
  148328. 8,
  148329. };
  148330. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148331. _vq_quantthresh__44u3__p7_0,
  148332. _vq_quantmap__44u3__p7_0,
  148333. 9,
  148334. 9
  148335. };
  148336. static static_codebook _44u3__p7_0 = {
  148337. 2, 81,
  148338. _vq_lengthlist__44u3__p7_0,
  148339. 1, -515907584, 1627381760, 4, 0,
  148340. _vq_quantlist__44u3__p7_0,
  148341. NULL,
  148342. &_vq_auxt__44u3__p7_0,
  148343. NULL,
  148344. 0
  148345. };
  148346. static long _vq_quantlist__44u3__p7_1[] = {
  148347. 7,
  148348. 6,
  148349. 8,
  148350. 5,
  148351. 9,
  148352. 4,
  148353. 10,
  148354. 3,
  148355. 11,
  148356. 2,
  148357. 12,
  148358. 1,
  148359. 13,
  148360. 0,
  148361. 14,
  148362. };
  148363. static long _vq_lengthlist__44u3__p7_1[] = {
  148364. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148365. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148366. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148367. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148368. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148369. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148370. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148371. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148372. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148373. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148374. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148375. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148376. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148377. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148378. 17,
  148379. };
  148380. static float _vq_quantthresh__44u3__p7_1[] = {
  148381. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148382. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148383. };
  148384. static long _vq_quantmap__44u3__p7_1[] = {
  148385. 13, 11, 9, 7, 5, 3, 1, 0,
  148386. 2, 4, 6, 8, 10, 12, 14,
  148387. };
  148388. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148389. _vq_quantthresh__44u3__p7_1,
  148390. _vq_quantmap__44u3__p7_1,
  148391. 15,
  148392. 15
  148393. };
  148394. static static_codebook _44u3__p7_1 = {
  148395. 2, 225,
  148396. _vq_lengthlist__44u3__p7_1,
  148397. 1, -522338304, 1620115456, 4, 0,
  148398. _vq_quantlist__44u3__p7_1,
  148399. NULL,
  148400. &_vq_auxt__44u3__p7_1,
  148401. NULL,
  148402. 0
  148403. };
  148404. static long _vq_quantlist__44u3__p7_2[] = {
  148405. 8,
  148406. 7,
  148407. 9,
  148408. 6,
  148409. 10,
  148410. 5,
  148411. 11,
  148412. 4,
  148413. 12,
  148414. 3,
  148415. 13,
  148416. 2,
  148417. 14,
  148418. 1,
  148419. 15,
  148420. 0,
  148421. 16,
  148422. };
  148423. static long _vq_lengthlist__44u3__p7_2[] = {
  148424. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148425. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148426. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148427. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148428. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148429. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148430. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148431. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148432. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148433. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148434. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148435. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148436. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148437. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148438. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148441. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148442. 11,
  148443. };
  148444. static float _vq_quantthresh__44u3__p7_2[] = {
  148445. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148446. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148447. };
  148448. static long _vq_quantmap__44u3__p7_2[] = {
  148449. 15, 13, 11, 9, 7, 5, 3, 1,
  148450. 0, 2, 4, 6, 8, 10, 12, 14,
  148451. 16,
  148452. };
  148453. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148454. _vq_quantthresh__44u3__p7_2,
  148455. _vq_quantmap__44u3__p7_2,
  148456. 17,
  148457. 17
  148458. };
  148459. static static_codebook _44u3__p7_2 = {
  148460. 2, 289,
  148461. _vq_lengthlist__44u3__p7_2,
  148462. 1, -529530880, 1611661312, 5, 0,
  148463. _vq_quantlist__44u3__p7_2,
  148464. NULL,
  148465. &_vq_auxt__44u3__p7_2,
  148466. NULL,
  148467. 0
  148468. };
  148469. static long _huff_lengthlist__44u3__short[] = {
  148470. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148471. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148472. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148473. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148474. };
  148475. static static_codebook _huff_book__44u3__short = {
  148476. 2, 64,
  148477. _huff_lengthlist__44u3__short,
  148478. 0, 0, 0, 0, 0,
  148479. NULL,
  148480. NULL,
  148481. NULL,
  148482. NULL,
  148483. 0
  148484. };
  148485. static long _huff_lengthlist__44u4__long[] = {
  148486. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148487. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148488. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148489. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148490. };
  148491. static static_codebook _huff_book__44u4__long = {
  148492. 2, 64,
  148493. _huff_lengthlist__44u4__long,
  148494. 0, 0, 0, 0, 0,
  148495. NULL,
  148496. NULL,
  148497. NULL,
  148498. NULL,
  148499. 0
  148500. };
  148501. static long _vq_quantlist__44u4__p1_0[] = {
  148502. 1,
  148503. 0,
  148504. 2,
  148505. };
  148506. static long _vq_lengthlist__44u4__p1_0[] = {
  148507. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148508. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148509. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148510. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148511. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148512. 13,
  148513. };
  148514. static float _vq_quantthresh__44u4__p1_0[] = {
  148515. -0.5, 0.5,
  148516. };
  148517. static long _vq_quantmap__44u4__p1_0[] = {
  148518. 1, 0, 2,
  148519. };
  148520. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148521. _vq_quantthresh__44u4__p1_0,
  148522. _vq_quantmap__44u4__p1_0,
  148523. 3,
  148524. 3
  148525. };
  148526. static static_codebook _44u4__p1_0 = {
  148527. 4, 81,
  148528. _vq_lengthlist__44u4__p1_0,
  148529. 1, -535822336, 1611661312, 2, 0,
  148530. _vq_quantlist__44u4__p1_0,
  148531. NULL,
  148532. &_vq_auxt__44u4__p1_0,
  148533. NULL,
  148534. 0
  148535. };
  148536. static long _vq_quantlist__44u4__p2_0[] = {
  148537. 1,
  148538. 0,
  148539. 2,
  148540. };
  148541. static long _vq_lengthlist__44u4__p2_0[] = {
  148542. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148543. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148544. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148545. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148546. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148547. 9,
  148548. };
  148549. static float _vq_quantthresh__44u4__p2_0[] = {
  148550. -0.5, 0.5,
  148551. };
  148552. static long _vq_quantmap__44u4__p2_0[] = {
  148553. 1, 0, 2,
  148554. };
  148555. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148556. _vq_quantthresh__44u4__p2_0,
  148557. _vq_quantmap__44u4__p2_0,
  148558. 3,
  148559. 3
  148560. };
  148561. static static_codebook _44u4__p2_0 = {
  148562. 4, 81,
  148563. _vq_lengthlist__44u4__p2_0,
  148564. 1, -535822336, 1611661312, 2, 0,
  148565. _vq_quantlist__44u4__p2_0,
  148566. NULL,
  148567. &_vq_auxt__44u4__p2_0,
  148568. NULL,
  148569. 0
  148570. };
  148571. static long _vq_quantlist__44u4__p3_0[] = {
  148572. 2,
  148573. 1,
  148574. 3,
  148575. 0,
  148576. 4,
  148577. };
  148578. static long _vq_lengthlist__44u4__p3_0[] = {
  148579. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148580. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148581. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148582. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148583. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148584. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148585. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148586. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148587. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148588. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148589. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148590. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148591. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148592. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148593. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148594. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148595. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148596. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148597. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148598. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148599. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148600. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148601. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148602. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148603. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148604. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148605. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148606. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148607. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148608. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148609. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148610. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148611. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148612. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148613. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148614. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148615. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148616. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148617. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148618. 0,
  148619. };
  148620. static float _vq_quantthresh__44u4__p3_0[] = {
  148621. -1.5, -0.5, 0.5, 1.5,
  148622. };
  148623. static long _vq_quantmap__44u4__p3_0[] = {
  148624. 3, 1, 0, 2, 4,
  148625. };
  148626. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148627. _vq_quantthresh__44u4__p3_0,
  148628. _vq_quantmap__44u4__p3_0,
  148629. 5,
  148630. 5
  148631. };
  148632. static static_codebook _44u4__p3_0 = {
  148633. 4, 625,
  148634. _vq_lengthlist__44u4__p3_0,
  148635. 1, -533725184, 1611661312, 3, 0,
  148636. _vq_quantlist__44u4__p3_0,
  148637. NULL,
  148638. &_vq_auxt__44u4__p3_0,
  148639. NULL,
  148640. 0
  148641. };
  148642. static long _vq_quantlist__44u4__p4_0[] = {
  148643. 2,
  148644. 1,
  148645. 3,
  148646. 0,
  148647. 4,
  148648. };
  148649. static long _vq_lengthlist__44u4__p4_0[] = {
  148650. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148651. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148652. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148653. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148654. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148655. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148656. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148657. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148658. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148659. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148660. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148661. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148662. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148663. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148664. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148665. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148666. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148667. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148668. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148669. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148670. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148671. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148672. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148673. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148674. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148675. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148676. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148677. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148678. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148679. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148680. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148681. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148682. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148683. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148684. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148685. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148686. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148687. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148688. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148689. 13,
  148690. };
  148691. static float _vq_quantthresh__44u4__p4_0[] = {
  148692. -1.5, -0.5, 0.5, 1.5,
  148693. };
  148694. static long _vq_quantmap__44u4__p4_0[] = {
  148695. 3, 1, 0, 2, 4,
  148696. };
  148697. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148698. _vq_quantthresh__44u4__p4_0,
  148699. _vq_quantmap__44u4__p4_0,
  148700. 5,
  148701. 5
  148702. };
  148703. static static_codebook _44u4__p4_0 = {
  148704. 4, 625,
  148705. _vq_lengthlist__44u4__p4_0,
  148706. 1, -533725184, 1611661312, 3, 0,
  148707. _vq_quantlist__44u4__p4_0,
  148708. NULL,
  148709. &_vq_auxt__44u4__p4_0,
  148710. NULL,
  148711. 0
  148712. };
  148713. static long _vq_quantlist__44u4__p5_0[] = {
  148714. 4,
  148715. 3,
  148716. 5,
  148717. 2,
  148718. 6,
  148719. 1,
  148720. 7,
  148721. 0,
  148722. 8,
  148723. };
  148724. static long _vq_lengthlist__44u4__p5_0[] = {
  148725. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148726. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148727. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148728. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148729. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148730. 12,
  148731. };
  148732. static float _vq_quantthresh__44u4__p5_0[] = {
  148733. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148734. };
  148735. static long _vq_quantmap__44u4__p5_0[] = {
  148736. 7, 5, 3, 1, 0, 2, 4, 6,
  148737. 8,
  148738. };
  148739. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148740. _vq_quantthresh__44u4__p5_0,
  148741. _vq_quantmap__44u4__p5_0,
  148742. 9,
  148743. 9
  148744. };
  148745. static static_codebook _44u4__p5_0 = {
  148746. 2, 81,
  148747. _vq_lengthlist__44u4__p5_0,
  148748. 1, -531628032, 1611661312, 4, 0,
  148749. _vq_quantlist__44u4__p5_0,
  148750. NULL,
  148751. &_vq_auxt__44u4__p5_0,
  148752. NULL,
  148753. 0
  148754. };
  148755. static long _vq_quantlist__44u4__p6_0[] = {
  148756. 6,
  148757. 5,
  148758. 7,
  148759. 4,
  148760. 8,
  148761. 3,
  148762. 9,
  148763. 2,
  148764. 10,
  148765. 1,
  148766. 11,
  148767. 0,
  148768. 12,
  148769. };
  148770. static long _vq_lengthlist__44u4__p6_0[] = {
  148771. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148772. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148773. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148774. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148775. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148776. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148777. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148778. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148779. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148780. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148781. 16,16,16,17,17,18,17,20,21,
  148782. };
  148783. static float _vq_quantthresh__44u4__p6_0[] = {
  148784. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148785. 12.5, 17.5, 22.5, 27.5,
  148786. };
  148787. static long _vq_quantmap__44u4__p6_0[] = {
  148788. 11, 9, 7, 5, 3, 1, 0, 2,
  148789. 4, 6, 8, 10, 12,
  148790. };
  148791. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148792. _vq_quantthresh__44u4__p6_0,
  148793. _vq_quantmap__44u4__p6_0,
  148794. 13,
  148795. 13
  148796. };
  148797. static static_codebook _44u4__p6_0 = {
  148798. 2, 169,
  148799. _vq_lengthlist__44u4__p6_0,
  148800. 1, -526516224, 1616117760, 4, 0,
  148801. _vq_quantlist__44u4__p6_0,
  148802. NULL,
  148803. &_vq_auxt__44u4__p6_0,
  148804. NULL,
  148805. 0
  148806. };
  148807. static long _vq_quantlist__44u4__p6_1[] = {
  148808. 2,
  148809. 1,
  148810. 3,
  148811. 0,
  148812. 4,
  148813. };
  148814. static long _vq_lengthlist__44u4__p6_1[] = {
  148815. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148816. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148817. };
  148818. static float _vq_quantthresh__44u4__p6_1[] = {
  148819. -1.5, -0.5, 0.5, 1.5,
  148820. };
  148821. static long _vq_quantmap__44u4__p6_1[] = {
  148822. 3, 1, 0, 2, 4,
  148823. };
  148824. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148825. _vq_quantthresh__44u4__p6_1,
  148826. _vq_quantmap__44u4__p6_1,
  148827. 5,
  148828. 5
  148829. };
  148830. static static_codebook _44u4__p6_1 = {
  148831. 2, 25,
  148832. _vq_lengthlist__44u4__p6_1,
  148833. 1, -533725184, 1611661312, 3, 0,
  148834. _vq_quantlist__44u4__p6_1,
  148835. NULL,
  148836. &_vq_auxt__44u4__p6_1,
  148837. NULL,
  148838. 0
  148839. };
  148840. static long _vq_quantlist__44u4__p7_0[] = {
  148841. 6,
  148842. 5,
  148843. 7,
  148844. 4,
  148845. 8,
  148846. 3,
  148847. 9,
  148848. 2,
  148849. 10,
  148850. 1,
  148851. 11,
  148852. 0,
  148853. 12,
  148854. };
  148855. static long _vq_lengthlist__44u4__p7_0[] = {
  148856. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148857. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148858. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148859. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148860. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148861. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148866. 11,11,11,11,11,11,11,11,11,
  148867. };
  148868. static float _vq_quantthresh__44u4__p7_0[] = {
  148869. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148870. 637.5, 892.5, 1147.5, 1402.5,
  148871. };
  148872. static long _vq_quantmap__44u4__p7_0[] = {
  148873. 11, 9, 7, 5, 3, 1, 0, 2,
  148874. 4, 6, 8, 10, 12,
  148875. };
  148876. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148877. _vq_quantthresh__44u4__p7_0,
  148878. _vq_quantmap__44u4__p7_0,
  148879. 13,
  148880. 13
  148881. };
  148882. static static_codebook _44u4__p7_0 = {
  148883. 2, 169,
  148884. _vq_lengthlist__44u4__p7_0,
  148885. 1, -514332672, 1627381760, 4, 0,
  148886. _vq_quantlist__44u4__p7_0,
  148887. NULL,
  148888. &_vq_auxt__44u4__p7_0,
  148889. NULL,
  148890. 0
  148891. };
  148892. static long _vq_quantlist__44u4__p7_1[] = {
  148893. 7,
  148894. 6,
  148895. 8,
  148896. 5,
  148897. 9,
  148898. 4,
  148899. 10,
  148900. 3,
  148901. 11,
  148902. 2,
  148903. 12,
  148904. 1,
  148905. 13,
  148906. 0,
  148907. 14,
  148908. };
  148909. static long _vq_lengthlist__44u4__p7_1[] = {
  148910. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148911. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148912. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148913. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148914. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148915. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148916. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148917. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148918. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148919. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148920. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148921. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148922. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148923. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148924. 16,
  148925. };
  148926. static float _vq_quantthresh__44u4__p7_1[] = {
  148927. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148928. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148929. };
  148930. static long _vq_quantmap__44u4__p7_1[] = {
  148931. 13, 11, 9, 7, 5, 3, 1, 0,
  148932. 2, 4, 6, 8, 10, 12, 14,
  148933. };
  148934. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148935. _vq_quantthresh__44u4__p7_1,
  148936. _vq_quantmap__44u4__p7_1,
  148937. 15,
  148938. 15
  148939. };
  148940. static static_codebook _44u4__p7_1 = {
  148941. 2, 225,
  148942. _vq_lengthlist__44u4__p7_1,
  148943. 1, -522338304, 1620115456, 4, 0,
  148944. _vq_quantlist__44u4__p7_1,
  148945. NULL,
  148946. &_vq_auxt__44u4__p7_1,
  148947. NULL,
  148948. 0
  148949. };
  148950. static long _vq_quantlist__44u4__p7_2[] = {
  148951. 8,
  148952. 7,
  148953. 9,
  148954. 6,
  148955. 10,
  148956. 5,
  148957. 11,
  148958. 4,
  148959. 12,
  148960. 3,
  148961. 13,
  148962. 2,
  148963. 14,
  148964. 1,
  148965. 15,
  148966. 0,
  148967. 16,
  148968. };
  148969. static long _vq_lengthlist__44u4__p7_2[] = {
  148970. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148971. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148972. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148973. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148974. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148975. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148976. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148977. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148978. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148979. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148980. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148981. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148982. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148983. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148984. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148985. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148986. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148987. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148988. 10,
  148989. };
  148990. static float _vq_quantthresh__44u4__p7_2[] = {
  148991. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148992. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148993. };
  148994. static long _vq_quantmap__44u4__p7_2[] = {
  148995. 15, 13, 11, 9, 7, 5, 3, 1,
  148996. 0, 2, 4, 6, 8, 10, 12, 14,
  148997. 16,
  148998. };
  148999. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149000. _vq_quantthresh__44u4__p7_2,
  149001. _vq_quantmap__44u4__p7_2,
  149002. 17,
  149003. 17
  149004. };
  149005. static static_codebook _44u4__p7_2 = {
  149006. 2, 289,
  149007. _vq_lengthlist__44u4__p7_2,
  149008. 1, -529530880, 1611661312, 5, 0,
  149009. _vq_quantlist__44u4__p7_2,
  149010. NULL,
  149011. &_vq_auxt__44u4__p7_2,
  149012. NULL,
  149013. 0
  149014. };
  149015. static long _huff_lengthlist__44u4__short[] = {
  149016. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149017. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149018. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149019. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149020. };
  149021. static static_codebook _huff_book__44u4__short = {
  149022. 2, 64,
  149023. _huff_lengthlist__44u4__short,
  149024. 0, 0, 0, 0, 0,
  149025. NULL,
  149026. NULL,
  149027. NULL,
  149028. NULL,
  149029. 0
  149030. };
  149031. static long _huff_lengthlist__44u5__long[] = {
  149032. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149033. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149034. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149035. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149036. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149037. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149038. 14, 8, 7, 8,
  149039. };
  149040. static static_codebook _huff_book__44u5__long = {
  149041. 2, 100,
  149042. _huff_lengthlist__44u5__long,
  149043. 0, 0, 0, 0, 0,
  149044. NULL,
  149045. NULL,
  149046. NULL,
  149047. NULL,
  149048. 0
  149049. };
  149050. static long _vq_quantlist__44u5__p1_0[] = {
  149051. 1,
  149052. 0,
  149053. 2,
  149054. };
  149055. static long _vq_lengthlist__44u5__p1_0[] = {
  149056. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149057. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149058. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149059. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149060. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149061. 12,
  149062. };
  149063. static float _vq_quantthresh__44u5__p1_0[] = {
  149064. -0.5, 0.5,
  149065. };
  149066. static long _vq_quantmap__44u5__p1_0[] = {
  149067. 1, 0, 2,
  149068. };
  149069. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149070. _vq_quantthresh__44u5__p1_0,
  149071. _vq_quantmap__44u5__p1_0,
  149072. 3,
  149073. 3
  149074. };
  149075. static static_codebook _44u5__p1_0 = {
  149076. 4, 81,
  149077. _vq_lengthlist__44u5__p1_0,
  149078. 1, -535822336, 1611661312, 2, 0,
  149079. _vq_quantlist__44u5__p1_0,
  149080. NULL,
  149081. &_vq_auxt__44u5__p1_0,
  149082. NULL,
  149083. 0
  149084. };
  149085. static long _vq_quantlist__44u5__p2_0[] = {
  149086. 1,
  149087. 0,
  149088. 2,
  149089. };
  149090. static long _vq_lengthlist__44u5__p2_0[] = {
  149091. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149092. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149093. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149094. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149095. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149096. 9,
  149097. };
  149098. static float _vq_quantthresh__44u5__p2_0[] = {
  149099. -0.5, 0.5,
  149100. };
  149101. static long _vq_quantmap__44u5__p2_0[] = {
  149102. 1, 0, 2,
  149103. };
  149104. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149105. _vq_quantthresh__44u5__p2_0,
  149106. _vq_quantmap__44u5__p2_0,
  149107. 3,
  149108. 3
  149109. };
  149110. static static_codebook _44u5__p2_0 = {
  149111. 4, 81,
  149112. _vq_lengthlist__44u5__p2_0,
  149113. 1, -535822336, 1611661312, 2, 0,
  149114. _vq_quantlist__44u5__p2_0,
  149115. NULL,
  149116. &_vq_auxt__44u5__p2_0,
  149117. NULL,
  149118. 0
  149119. };
  149120. static long _vq_quantlist__44u5__p3_0[] = {
  149121. 2,
  149122. 1,
  149123. 3,
  149124. 0,
  149125. 4,
  149126. };
  149127. static long _vq_lengthlist__44u5__p3_0[] = {
  149128. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149129. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149130. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149131. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149132. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149133. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149134. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149135. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149136. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149137. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149138. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149139. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149140. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149141. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149142. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149143. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149144. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149145. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149146. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149147. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149148. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149149. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149150. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149151. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149152. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149153. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149154. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149155. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149156. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149157. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149158. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149159. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149160. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149161. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149162. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149163. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149164. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149165. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149166. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149167. 0,
  149168. };
  149169. static float _vq_quantthresh__44u5__p3_0[] = {
  149170. -1.5, -0.5, 0.5, 1.5,
  149171. };
  149172. static long _vq_quantmap__44u5__p3_0[] = {
  149173. 3, 1, 0, 2, 4,
  149174. };
  149175. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149176. _vq_quantthresh__44u5__p3_0,
  149177. _vq_quantmap__44u5__p3_0,
  149178. 5,
  149179. 5
  149180. };
  149181. static static_codebook _44u5__p3_0 = {
  149182. 4, 625,
  149183. _vq_lengthlist__44u5__p3_0,
  149184. 1, -533725184, 1611661312, 3, 0,
  149185. _vq_quantlist__44u5__p3_0,
  149186. NULL,
  149187. &_vq_auxt__44u5__p3_0,
  149188. NULL,
  149189. 0
  149190. };
  149191. static long _vq_quantlist__44u5__p4_0[] = {
  149192. 2,
  149193. 1,
  149194. 3,
  149195. 0,
  149196. 4,
  149197. };
  149198. static long _vq_lengthlist__44u5__p4_0[] = {
  149199. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149200. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149201. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149202. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149203. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149204. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149205. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149206. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149207. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149208. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149209. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149210. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149211. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149212. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149213. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149214. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149215. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149216. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149217. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149218. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149219. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149220. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149221. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149222. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149223. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149224. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149225. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149226. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149227. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149228. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149229. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149230. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149231. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149232. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149233. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149234. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149235. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149236. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149237. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149238. 12,
  149239. };
  149240. static float _vq_quantthresh__44u5__p4_0[] = {
  149241. -1.5, -0.5, 0.5, 1.5,
  149242. };
  149243. static long _vq_quantmap__44u5__p4_0[] = {
  149244. 3, 1, 0, 2, 4,
  149245. };
  149246. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149247. _vq_quantthresh__44u5__p4_0,
  149248. _vq_quantmap__44u5__p4_0,
  149249. 5,
  149250. 5
  149251. };
  149252. static static_codebook _44u5__p4_0 = {
  149253. 4, 625,
  149254. _vq_lengthlist__44u5__p4_0,
  149255. 1, -533725184, 1611661312, 3, 0,
  149256. _vq_quantlist__44u5__p4_0,
  149257. NULL,
  149258. &_vq_auxt__44u5__p4_0,
  149259. NULL,
  149260. 0
  149261. };
  149262. static long _vq_quantlist__44u5__p5_0[] = {
  149263. 4,
  149264. 3,
  149265. 5,
  149266. 2,
  149267. 6,
  149268. 1,
  149269. 7,
  149270. 0,
  149271. 8,
  149272. };
  149273. static long _vq_lengthlist__44u5__p5_0[] = {
  149274. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149275. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149276. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149277. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149278. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149279. 14,
  149280. };
  149281. static float _vq_quantthresh__44u5__p5_0[] = {
  149282. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149283. };
  149284. static long _vq_quantmap__44u5__p5_0[] = {
  149285. 7, 5, 3, 1, 0, 2, 4, 6,
  149286. 8,
  149287. };
  149288. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149289. _vq_quantthresh__44u5__p5_0,
  149290. _vq_quantmap__44u5__p5_0,
  149291. 9,
  149292. 9
  149293. };
  149294. static static_codebook _44u5__p5_0 = {
  149295. 2, 81,
  149296. _vq_lengthlist__44u5__p5_0,
  149297. 1, -531628032, 1611661312, 4, 0,
  149298. _vq_quantlist__44u5__p5_0,
  149299. NULL,
  149300. &_vq_auxt__44u5__p5_0,
  149301. NULL,
  149302. 0
  149303. };
  149304. static long _vq_quantlist__44u5__p6_0[] = {
  149305. 4,
  149306. 3,
  149307. 5,
  149308. 2,
  149309. 6,
  149310. 1,
  149311. 7,
  149312. 0,
  149313. 8,
  149314. };
  149315. static long _vq_lengthlist__44u5__p6_0[] = {
  149316. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149317. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149318. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149319. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149320. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149321. 11,
  149322. };
  149323. static float _vq_quantthresh__44u5__p6_0[] = {
  149324. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149325. };
  149326. static long _vq_quantmap__44u5__p6_0[] = {
  149327. 7, 5, 3, 1, 0, 2, 4, 6,
  149328. 8,
  149329. };
  149330. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149331. _vq_quantthresh__44u5__p6_0,
  149332. _vq_quantmap__44u5__p6_0,
  149333. 9,
  149334. 9
  149335. };
  149336. static static_codebook _44u5__p6_0 = {
  149337. 2, 81,
  149338. _vq_lengthlist__44u5__p6_0,
  149339. 1, -531628032, 1611661312, 4, 0,
  149340. _vq_quantlist__44u5__p6_0,
  149341. NULL,
  149342. &_vq_auxt__44u5__p6_0,
  149343. NULL,
  149344. 0
  149345. };
  149346. static long _vq_quantlist__44u5__p7_0[] = {
  149347. 1,
  149348. 0,
  149349. 2,
  149350. };
  149351. static long _vq_lengthlist__44u5__p7_0[] = {
  149352. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149353. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149354. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149355. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149356. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149357. 12,
  149358. };
  149359. static float _vq_quantthresh__44u5__p7_0[] = {
  149360. -5.5, 5.5,
  149361. };
  149362. static long _vq_quantmap__44u5__p7_0[] = {
  149363. 1, 0, 2,
  149364. };
  149365. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149366. _vq_quantthresh__44u5__p7_0,
  149367. _vq_quantmap__44u5__p7_0,
  149368. 3,
  149369. 3
  149370. };
  149371. static static_codebook _44u5__p7_0 = {
  149372. 4, 81,
  149373. _vq_lengthlist__44u5__p7_0,
  149374. 1, -529137664, 1618345984, 2, 0,
  149375. _vq_quantlist__44u5__p7_0,
  149376. NULL,
  149377. &_vq_auxt__44u5__p7_0,
  149378. NULL,
  149379. 0
  149380. };
  149381. static long _vq_quantlist__44u5__p7_1[] = {
  149382. 5,
  149383. 4,
  149384. 6,
  149385. 3,
  149386. 7,
  149387. 2,
  149388. 8,
  149389. 1,
  149390. 9,
  149391. 0,
  149392. 10,
  149393. };
  149394. static long _vq_lengthlist__44u5__p7_1[] = {
  149395. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149396. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149397. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149398. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149399. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149400. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149401. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149402. 9, 9, 9, 9, 9,10,10,10,10,
  149403. };
  149404. static float _vq_quantthresh__44u5__p7_1[] = {
  149405. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149406. 3.5, 4.5,
  149407. };
  149408. static long _vq_quantmap__44u5__p7_1[] = {
  149409. 9, 7, 5, 3, 1, 0, 2, 4,
  149410. 6, 8, 10,
  149411. };
  149412. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149413. _vq_quantthresh__44u5__p7_1,
  149414. _vq_quantmap__44u5__p7_1,
  149415. 11,
  149416. 11
  149417. };
  149418. static static_codebook _44u5__p7_1 = {
  149419. 2, 121,
  149420. _vq_lengthlist__44u5__p7_1,
  149421. 1, -531365888, 1611661312, 4, 0,
  149422. _vq_quantlist__44u5__p7_1,
  149423. NULL,
  149424. &_vq_auxt__44u5__p7_1,
  149425. NULL,
  149426. 0
  149427. };
  149428. static long _vq_quantlist__44u5__p8_0[] = {
  149429. 5,
  149430. 4,
  149431. 6,
  149432. 3,
  149433. 7,
  149434. 2,
  149435. 8,
  149436. 1,
  149437. 9,
  149438. 0,
  149439. 10,
  149440. };
  149441. static long _vq_lengthlist__44u5__p8_0[] = {
  149442. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149443. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149444. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149445. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149446. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149447. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149448. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149449. 12,13,13,14,14,14,14,15,15,
  149450. };
  149451. static float _vq_quantthresh__44u5__p8_0[] = {
  149452. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149453. 38.5, 49.5,
  149454. };
  149455. static long _vq_quantmap__44u5__p8_0[] = {
  149456. 9, 7, 5, 3, 1, 0, 2, 4,
  149457. 6, 8, 10,
  149458. };
  149459. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149460. _vq_quantthresh__44u5__p8_0,
  149461. _vq_quantmap__44u5__p8_0,
  149462. 11,
  149463. 11
  149464. };
  149465. static static_codebook _44u5__p8_0 = {
  149466. 2, 121,
  149467. _vq_lengthlist__44u5__p8_0,
  149468. 1, -524582912, 1618345984, 4, 0,
  149469. _vq_quantlist__44u5__p8_0,
  149470. NULL,
  149471. &_vq_auxt__44u5__p8_0,
  149472. NULL,
  149473. 0
  149474. };
  149475. static long _vq_quantlist__44u5__p8_1[] = {
  149476. 5,
  149477. 4,
  149478. 6,
  149479. 3,
  149480. 7,
  149481. 2,
  149482. 8,
  149483. 1,
  149484. 9,
  149485. 0,
  149486. 10,
  149487. };
  149488. static long _vq_lengthlist__44u5__p8_1[] = {
  149489. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149490. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149491. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149492. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149493. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149494. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149495. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149496. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149497. };
  149498. static float _vq_quantthresh__44u5__p8_1[] = {
  149499. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149500. 3.5, 4.5,
  149501. };
  149502. static long _vq_quantmap__44u5__p8_1[] = {
  149503. 9, 7, 5, 3, 1, 0, 2, 4,
  149504. 6, 8, 10,
  149505. };
  149506. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149507. _vq_quantthresh__44u5__p8_1,
  149508. _vq_quantmap__44u5__p8_1,
  149509. 11,
  149510. 11
  149511. };
  149512. static static_codebook _44u5__p8_1 = {
  149513. 2, 121,
  149514. _vq_lengthlist__44u5__p8_1,
  149515. 1, -531365888, 1611661312, 4, 0,
  149516. _vq_quantlist__44u5__p8_1,
  149517. NULL,
  149518. &_vq_auxt__44u5__p8_1,
  149519. NULL,
  149520. 0
  149521. };
  149522. static long _vq_quantlist__44u5__p9_0[] = {
  149523. 6,
  149524. 5,
  149525. 7,
  149526. 4,
  149527. 8,
  149528. 3,
  149529. 9,
  149530. 2,
  149531. 10,
  149532. 1,
  149533. 11,
  149534. 0,
  149535. 12,
  149536. };
  149537. static long _vq_lengthlist__44u5__p9_0[] = {
  149538. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149539. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149540. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149541. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149542. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149543. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149544. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149545. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149546. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149547. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149548. 12,12,12,12,12,12,12,12,12,
  149549. };
  149550. static float _vq_quantthresh__44u5__p9_0[] = {
  149551. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149552. 637.5, 892.5, 1147.5, 1402.5,
  149553. };
  149554. static long _vq_quantmap__44u5__p9_0[] = {
  149555. 11, 9, 7, 5, 3, 1, 0, 2,
  149556. 4, 6, 8, 10, 12,
  149557. };
  149558. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149559. _vq_quantthresh__44u5__p9_0,
  149560. _vq_quantmap__44u5__p9_0,
  149561. 13,
  149562. 13
  149563. };
  149564. static static_codebook _44u5__p9_0 = {
  149565. 2, 169,
  149566. _vq_lengthlist__44u5__p9_0,
  149567. 1, -514332672, 1627381760, 4, 0,
  149568. _vq_quantlist__44u5__p9_0,
  149569. NULL,
  149570. &_vq_auxt__44u5__p9_0,
  149571. NULL,
  149572. 0
  149573. };
  149574. static long _vq_quantlist__44u5__p9_1[] = {
  149575. 7,
  149576. 6,
  149577. 8,
  149578. 5,
  149579. 9,
  149580. 4,
  149581. 10,
  149582. 3,
  149583. 11,
  149584. 2,
  149585. 12,
  149586. 1,
  149587. 13,
  149588. 0,
  149589. 14,
  149590. };
  149591. static long _vq_lengthlist__44u5__p9_1[] = {
  149592. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149593. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149594. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149595. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149596. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149597. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149598. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149599. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149600. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149601. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149602. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149603. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149604. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149605. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149606. 14,
  149607. };
  149608. static float _vq_quantthresh__44u5__p9_1[] = {
  149609. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149610. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149611. };
  149612. static long _vq_quantmap__44u5__p9_1[] = {
  149613. 13, 11, 9, 7, 5, 3, 1, 0,
  149614. 2, 4, 6, 8, 10, 12, 14,
  149615. };
  149616. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149617. _vq_quantthresh__44u5__p9_1,
  149618. _vq_quantmap__44u5__p9_1,
  149619. 15,
  149620. 15
  149621. };
  149622. static static_codebook _44u5__p9_1 = {
  149623. 2, 225,
  149624. _vq_lengthlist__44u5__p9_1,
  149625. 1, -522338304, 1620115456, 4, 0,
  149626. _vq_quantlist__44u5__p9_1,
  149627. NULL,
  149628. &_vq_auxt__44u5__p9_1,
  149629. NULL,
  149630. 0
  149631. };
  149632. static long _vq_quantlist__44u5__p9_2[] = {
  149633. 8,
  149634. 7,
  149635. 9,
  149636. 6,
  149637. 10,
  149638. 5,
  149639. 11,
  149640. 4,
  149641. 12,
  149642. 3,
  149643. 13,
  149644. 2,
  149645. 14,
  149646. 1,
  149647. 15,
  149648. 0,
  149649. 16,
  149650. };
  149651. static long _vq_lengthlist__44u5__p9_2[] = {
  149652. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149653. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149654. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149655. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149656. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149657. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149658. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149659. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149660. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149661. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149662. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149663. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149664. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149665. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149666. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149667. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149668. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149669. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149670. 10,
  149671. };
  149672. static float _vq_quantthresh__44u5__p9_2[] = {
  149673. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149674. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149675. };
  149676. static long _vq_quantmap__44u5__p9_2[] = {
  149677. 15, 13, 11, 9, 7, 5, 3, 1,
  149678. 0, 2, 4, 6, 8, 10, 12, 14,
  149679. 16,
  149680. };
  149681. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149682. _vq_quantthresh__44u5__p9_2,
  149683. _vq_quantmap__44u5__p9_2,
  149684. 17,
  149685. 17
  149686. };
  149687. static static_codebook _44u5__p9_2 = {
  149688. 2, 289,
  149689. _vq_lengthlist__44u5__p9_2,
  149690. 1, -529530880, 1611661312, 5, 0,
  149691. _vq_quantlist__44u5__p9_2,
  149692. NULL,
  149693. &_vq_auxt__44u5__p9_2,
  149694. NULL,
  149695. 0
  149696. };
  149697. static long _huff_lengthlist__44u5__short[] = {
  149698. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149699. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149700. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149701. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149702. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149703. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149704. 6, 8,15,17,
  149705. };
  149706. static static_codebook _huff_book__44u5__short = {
  149707. 2, 100,
  149708. _huff_lengthlist__44u5__short,
  149709. 0, 0, 0, 0, 0,
  149710. NULL,
  149711. NULL,
  149712. NULL,
  149713. NULL,
  149714. 0
  149715. };
  149716. static long _huff_lengthlist__44u6__long[] = {
  149717. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149718. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149719. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149720. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149721. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149722. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149723. 13, 8, 7, 7,
  149724. };
  149725. static static_codebook _huff_book__44u6__long = {
  149726. 2, 100,
  149727. _huff_lengthlist__44u6__long,
  149728. 0, 0, 0, 0, 0,
  149729. NULL,
  149730. NULL,
  149731. NULL,
  149732. NULL,
  149733. 0
  149734. };
  149735. static long _vq_quantlist__44u6__p1_0[] = {
  149736. 1,
  149737. 0,
  149738. 2,
  149739. };
  149740. static long _vq_lengthlist__44u6__p1_0[] = {
  149741. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149742. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149743. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149744. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149745. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149746. 12,
  149747. };
  149748. static float _vq_quantthresh__44u6__p1_0[] = {
  149749. -0.5, 0.5,
  149750. };
  149751. static long _vq_quantmap__44u6__p1_0[] = {
  149752. 1, 0, 2,
  149753. };
  149754. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149755. _vq_quantthresh__44u6__p1_0,
  149756. _vq_quantmap__44u6__p1_0,
  149757. 3,
  149758. 3
  149759. };
  149760. static static_codebook _44u6__p1_0 = {
  149761. 4, 81,
  149762. _vq_lengthlist__44u6__p1_0,
  149763. 1, -535822336, 1611661312, 2, 0,
  149764. _vq_quantlist__44u6__p1_0,
  149765. NULL,
  149766. &_vq_auxt__44u6__p1_0,
  149767. NULL,
  149768. 0
  149769. };
  149770. static long _vq_quantlist__44u6__p2_0[] = {
  149771. 1,
  149772. 0,
  149773. 2,
  149774. };
  149775. static long _vq_lengthlist__44u6__p2_0[] = {
  149776. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149777. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149778. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149779. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149780. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149781. 9,
  149782. };
  149783. static float _vq_quantthresh__44u6__p2_0[] = {
  149784. -0.5, 0.5,
  149785. };
  149786. static long _vq_quantmap__44u6__p2_0[] = {
  149787. 1, 0, 2,
  149788. };
  149789. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149790. _vq_quantthresh__44u6__p2_0,
  149791. _vq_quantmap__44u6__p2_0,
  149792. 3,
  149793. 3
  149794. };
  149795. static static_codebook _44u6__p2_0 = {
  149796. 4, 81,
  149797. _vq_lengthlist__44u6__p2_0,
  149798. 1, -535822336, 1611661312, 2, 0,
  149799. _vq_quantlist__44u6__p2_0,
  149800. NULL,
  149801. &_vq_auxt__44u6__p2_0,
  149802. NULL,
  149803. 0
  149804. };
  149805. static long _vq_quantlist__44u6__p3_0[] = {
  149806. 2,
  149807. 1,
  149808. 3,
  149809. 0,
  149810. 4,
  149811. };
  149812. static long _vq_lengthlist__44u6__p3_0[] = {
  149813. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149814. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149815. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149816. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149817. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149818. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149819. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149820. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149821. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149822. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149823. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149824. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149825. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149826. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149827. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149828. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149829. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149830. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149831. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149832. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149833. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149834. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149835. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149836. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149837. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149838. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149839. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149840. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149841. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149842. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149843. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149844. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149845. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149846. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149847. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149848. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149849. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149850. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149851. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149852. 19,
  149853. };
  149854. static float _vq_quantthresh__44u6__p3_0[] = {
  149855. -1.5, -0.5, 0.5, 1.5,
  149856. };
  149857. static long _vq_quantmap__44u6__p3_0[] = {
  149858. 3, 1, 0, 2, 4,
  149859. };
  149860. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149861. _vq_quantthresh__44u6__p3_0,
  149862. _vq_quantmap__44u6__p3_0,
  149863. 5,
  149864. 5
  149865. };
  149866. static static_codebook _44u6__p3_0 = {
  149867. 4, 625,
  149868. _vq_lengthlist__44u6__p3_0,
  149869. 1, -533725184, 1611661312, 3, 0,
  149870. _vq_quantlist__44u6__p3_0,
  149871. NULL,
  149872. &_vq_auxt__44u6__p3_0,
  149873. NULL,
  149874. 0
  149875. };
  149876. static long _vq_quantlist__44u6__p4_0[] = {
  149877. 2,
  149878. 1,
  149879. 3,
  149880. 0,
  149881. 4,
  149882. };
  149883. static long _vq_lengthlist__44u6__p4_0[] = {
  149884. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149885. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149886. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149887. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149888. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149889. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149890. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149891. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149892. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149893. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149894. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149895. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149896. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149897. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149898. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149899. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149900. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149901. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149902. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149903. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149904. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149905. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149906. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149907. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149908. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149909. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149910. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149911. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149912. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149913. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149914. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149915. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149916. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149917. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149918. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149919. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149920. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149921. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149922. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149923. 13,
  149924. };
  149925. static float _vq_quantthresh__44u6__p4_0[] = {
  149926. -1.5, -0.5, 0.5, 1.5,
  149927. };
  149928. static long _vq_quantmap__44u6__p4_0[] = {
  149929. 3, 1, 0, 2, 4,
  149930. };
  149931. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149932. _vq_quantthresh__44u6__p4_0,
  149933. _vq_quantmap__44u6__p4_0,
  149934. 5,
  149935. 5
  149936. };
  149937. static static_codebook _44u6__p4_0 = {
  149938. 4, 625,
  149939. _vq_lengthlist__44u6__p4_0,
  149940. 1, -533725184, 1611661312, 3, 0,
  149941. _vq_quantlist__44u6__p4_0,
  149942. NULL,
  149943. &_vq_auxt__44u6__p4_0,
  149944. NULL,
  149945. 0
  149946. };
  149947. static long _vq_quantlist__44u6__p5_0[] = {
  149948. 4,
  149949. 3,
  149950. 5,
  149951. 2,
  149952. 6,
  149953. 1,
  149954. 7,
  149955. 0,
  149956. 8,
  149957. };
  149958. static long _vq_lengthlist__44u6__p5_0[] = {
  149959. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149960. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149961. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149962. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149963. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149964. 14,
  149965. };
  149966. static float _vq_quantthresh__44u6__p5_0[] = {
  149967. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149968. };
  149969. static long _vq_quantmap__44u6__p5_0[] = {
  149970. 7, 5, 3, 1, 0, 2, 4, 6,
  149971. 8,
  149972. };
  149973. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149974. _vq_quantthresh__44u6__p5_0,
  149975. _vq_quantmap__44u6__p5_0,
  149976. 9,
  149977. 9
  149978. };
  149979. static static_codebook _44u6__p5_0 = {
  149980. 2, 81,
  149981. _vq_lengthlist__44u6__p5_0,
  149982. 1, -531628032, 1611661312, 4, 0,
  149983. _vq_quantlist__44u6__p5_0,
  149984. NULL,
  149985. &_vq_auxt__44u6__p5_0,
  149986. NULL,
  149987. 0
  149988. };
  149989. static long _vq_quantlist__44u6__p6_0[] = {
  149990. 4,
  149991. 3,
  149992. 5,
  149993. 2,
  149994. 6,
  149995. 1,
  149996. 7,
  149997. 0,
  149998. 8,
  149999. };
  150000. static long _vq_lengthlist__44u6__p6_0[] = {
  150001. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150002. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150003. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150004. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150005. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150006. 12,
  150007. };
  150008. static float _vq_quantthresh__44u6__p6_0[] = {
  150009. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150010. };
  150011. static long _vq_quantmap__44u6__p6_0[] = {
  150012. 7, 5, 3, 1, 0, 2, 4, 6,
  150013. 8,
  150014. };
  150015. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150016. _vq_quantthresh__44u6__p6_0,
  150017. _vq_quantmap__44u6__p6_0,
  150018. 9,
  150019. 9
  150020. };
  150021. static static_codebook _44u6__p6_0 = {
  150022. 2, 81,
  150023. _vq_lengthlist__44u6__p6_0,
  150024. 1, -531628032, 1611661312, 4, 0,
  150025. _vq_quantlist__44u6__p6_0,
  150026. NULL,
  150027. &_vq_auxt__44u6__p6_0,
  150028. NULL,
  150029. 0
  150030. };
  150031. static long _vq_quantlist__44u6__p7_0[] = {
  150032. 1,
  150033. 0,
  150034. 2,
  150035. };
  150036. static long _vq_lengthlist__44u6__p7_0[] = {
  150037. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150038. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150039. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150040. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150041. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150042. 10,
  150043. };
  150044. static float _vq_quantthresh__44u6__p7_0[] = {
  150045. -5.5, 5.5,
  150046. };
  150047. static long _vq_quantmap__44u6__p7_0[] = {
  150048. 1, 0, 2,
  150049. };
  150050. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150051. _vq_quantthresh__44u6__p7_0,
  150052. _vq_quantmap__44u6__p7_0,
  150053. 3,
  150054. 3
  150055. };
  150056. static static_codebook _44u6__p7_0 = {
  150057. 4, 81,
  150058. _vq_lengthlist__44u6__p7_0,
  150059. 1, -529137664, 1618345984, 2, 0,
  150060. _vq_quantlist__44u6__p7_0,
  150061. NULL,
  150062. &_vq_auxt__44u6__p7_0,
  150063. NULL,
  150064. 0
  150065. };
  150066. static long _vq_quantlist__44u6__p7_1[] = {
  150067. 5,
  150068. 4,
  150069. 6,
  150070. 3,
  150071. 7,
  150072. 2,
  150073. 8,
  150074. 1,
  150075. 9,
  150076. 0,
  150077. 10,
  150078. };
  150079. static long _vq_lengthlist__44u6__p7_1[] = {
  150080. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150081. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150082. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150083. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150084. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150085. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150086. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150087. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150088. };
  150089. static float _vq_quantthresh__44u6__p7_1[] = {
  150090. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150091. 3.5, 4.5,
  150092. };
  150093. static long _vq_quantmap__44u6__p7_1[] = {
  150094. 9, 7, 5, 3, 1, 0, 2, 4,
  150095. 6, 8, 10,
  150096. };
  150097. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150098. _vq_quantthresh__44u6__p7_1,
  150099. _vq_quantmap__44u6__p7_1,
  150100. 11,
  150101. 11
  150102. };
  150103. static static_codebook _44u6__p7_1 = {
  150104. 2, 121,
  150105. _vq_lengthlist__44u6__p7_1,
  150106. 1, -531365888, 1611661312, 4, 0,
  150107. _vq_quantlist__44u6__p7_1,
  150108. NULL,
  150109. &_vq_auxt__44u6__p7_1,
  150110. NULL,
  150111. 0
  150112. };
  150113. static long _vq_quantlist__44u6__p8_0[] = {
  150114. 5,
  150115. 4,
  150116. 6,
  150117. 3,
  150118. 7,
  150119. 2,
  150120. 8,
  150121. 1,
  150122. 9,
  150123. 0,
  150124. 10,
  150125. };
  150126. static long _vq_lengthlist__44u6__p8_0[] = {
  150127. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150128. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150129. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150130. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150131. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150132. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150133. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150134. 12,13,13,14,14,14,15,15,15,
  150135. };
  150136. static float _vq_quantthresh__44u6__p8_0[] = {
  150137. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150138. 38.5, 49.5,
  150139. };
  150140. static long _vq_quantmap__44u6__p8_0[] = {
  150141. 9, 7, 5, 3, 1, 0, 2, 4,
  150142. 6, 8, 10,
  150143. };
  150144. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150145. _vq_quantthresh__44u6__p8_0,
  150146. _vq_quantmap__44u6__p8_0,
  150147. 11,
  150148. 11
  150149. };
  150150. static static_codebook _44u6__p8_0 = {
  150151. 2, 121,
  150152. _vq_lengthlist__44u6__p8_0,
  150153. 1, -524582912, 1618345984, 4, 0,
  150154. _vq_quantlist__44u6__p8_0,
  150155. NULL,
  150156. &_vq_auxt__44u6__p8_0,
  150157. NULL,
  150158. 0
  150159. };
  150160. static long _vq_quantlist__44u6__p8_1[] = {
  150161. 5,
  150162. 4,
  150163. 6,
  150164. 3,
  150165. 7,
  150166. 2,
  150167. 8,
  150168. 1,
  150169. 9,
  150170. 0,
  150171. 10,
  150172. };
  150173. static long _vq_lengthlist__44u6__p8_1[] = {
  150174. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150175. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150176. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150177. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150178. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150179. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150180. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150181. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150182. };
  150183. static float _vq_quantthresh__44u6__p8_1[] = {
  150184. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150185. 3.5, 4.5,
  150186. };
  150187. static long _vq_quantmap__44u6__p8_1[] = {
  150188. 9, 7, 5, 3, 1, 0, 2, 4,
  150189. 6, 8, 10,
  150190. };
  150191. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150192. _vq_quantthresh__44u6__p8_1,
  150193. _vq_quantmap__44u6__p8_1,
  150194. 11,
  150195. 11
  150196. };
  150197. static static_codebook _44u6__p8_1 = {
  150198. 2, 121,
  150199. _vq_lengthlist__44u6__p8_1,
  150200. 1, -531365888, 1611661312, 4, 0,
  150201. _vq_quantlist__44u6__p8_1,
  150202. NULL,
  150203. &_vq_auxt__44u6__p8_1,
  150204. NULL,
  150205. 0
  150206. };
  150207. static long _vq_quantlist__44u6__p9_0[] = {
  150208. 7,
  150209. 6,
  150210. 8,
  150211. 5,
  150212. 9,
  150213. 4,
  150214. 10,
  150215. 3,
  150216. 11,
  150217. 2,
  150218. 12,
  150219. 1,
  150220. 13,
  150221. 0,
  150222. 14,
  150223. };
  150224. static long _vq_lengthlist__44u6__p9_0[] = {
  150225. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150226. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150227. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150228. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150229. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150230. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150231. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150232. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150233. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150234. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150235. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150236. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150237. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150238. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150239. 14,
  150240. };
  150241. static float _vq_quantthresh__44u6__p9_0[] = {
  150242. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150243. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150244. };
  150245. static long _vq_quantmap__44u6__p9_0[] = {
  150246. 13, 11, 9, 7, 5, 3, 1, 0,
  150247. 2, 4, 6, 8, 10, 12, 14,
  150248. };
  150249. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150250. _vq_quantthresh__44u6__p9_0,
  150251. _vq_quantmap__44u6__p9_0,
  150252. 15,
  150253. 15
  150254. };
  150255. static static_codebook _44u6__p9_0 = {
  150256. 2, 225,
  150257. _vq_lengthlist__44u6__p9_0,
  150258. 1, -514071552, 1627381760, 4, 0,
  150259. _vq_quantlist__44u6__p9_0,
  150260. NULL,
  150261. &_vq_auxt__44u6__p9_0,
  150262. NULL,
  150263. 0
  150264. };
  150265. static long _vq_quantlist__44u6__p9_1[] = {
  150266. 7,
  150267. 6,
  150268. 8,
  150269. 5,
  150270. 9,
  150271. 4,
  150272. 10,
  150273. 3,
  150274. 11,
  150275. 2,
  150276. 12,
  150277. 1,
  150278. 13,
  150279. 0,
  150280. 14,
  150281. };
  150282. static long _vq_lengthlist__44u6__p9_1[] = {
  150283. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150284. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150285. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150286. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150287. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150288. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150289. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150290. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150291. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150292. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150293. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150294. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150295. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150296. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150297. 13,
  150298. };
  150299. static float _vq_quantthresh__44u6__p9_1[] = {
  150300. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150301. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150302. };
  150303. static long _vq_quantmap__44u6__p9_1[] = {
  150304. 13, 11, 9, 7, 5, 3, 1, 0,
  150305. 2, 4, 6, 8, 10, 12, 14,
  150306. };
  150307. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150308. _vq_quantthresh__44u6__p9_1,
  150309. _vq_quantmap__44u6__p9_1,
  150310. 15,
  150311. 15
  150312. };
  150313. static static_codebook _44u6__p9_1 = {
  150314. 2, 225,
  150315. _vq_lengthlist__44u6__p9_1,
  150316. 1, -522338304, 1620115456, 4, 0,
  150317. _vq_quantlist__44u6__p9_1,
  150318. NULL,
  150319. &_vq_auxt__44u6__p9_1,
  150320. NULL,
  150321. 0
  150322. };
  150323. static long _vq_quantlist__44u6__p9_2[] = {
  150324. 8,
  150325. 7,
  150326. 9,
  150327. 6,
  150328. 10,
  150329. 5,
  150330. 11,
  150331. 4,
  150332. 12,
  150333. 3,
  150334. 13,
  150335. 2,
  150336. 14,
  150337. 1,
  150338. 15,
  150339. 0,
  150340. 16,
  150341. };
  150342. static long _vq_lengthlist__44u6__p9_2[] = {
  150343. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150344. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150345. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150346. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150347. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150348. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150349. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150350. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150351. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150352. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150353. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150354. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150355. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150356. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150357. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150358. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150359. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150360. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150361. 10,
  150362. };
  150363. static float _vq_quantthresh__44u6__p9_2[] = {
  150364. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150365. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150366. };
  150367. static long _vq_quantmap__44u6__p9_2[] = {
  150368. 15, 13, 11, 9, 7, 5, 3, 1,
  150369. 0, 2, 4, 6, 8, 10, 12, 14,
  150370. 16,
  150371. };
  150372. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150373. _vq_quantthresh__44u6__p9_2,
  150374. _vq_quantmap__44u6__p9_2,
  150375. 17,
  150376. 17
  150377. };
  150378. static static_codebook _44u6__p9_2 = {
  150379. 2, 289,
  150380. _vq_lengthlist__44u6__p9_2,
  150381. 1, -529530880, 1611661312, 5, 0,
  150382. _vq_quantlist__44u6__p9_2,
  150383. NULL,
  150384. &_vq_auxt__44u6__p9_2,
  150385. NULL,
  150386. 0
  150387. };
  150388. static long _huff_lengthlist__44u6__short[] = {
  150389. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150390. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150391. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150392. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150393. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150394. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150395. 7, 6, 9,16,
  150396. };
  150397. static static_codebook _huff_book__44u6__short = {
  150398. 2, 100,
  150399. _huff_lengthlist__44u6__short,
  150400. 0, 0, 0, 0, 0,
  150401. NULL,
  150402. NULL,
  150403. NULL,
  150404. NULL,
  150405. 0
  150406. };
  150407. static long _huff_lengthlist__44u7__long[] = {
  150408. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150409. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150410. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150411. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150412. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150413. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150414. 12, 8, 6, 7,
  150415. };
  150416. static static_codebook _huff_book__44u7__long = {
  150417. 2, 100,
  150418. _huff_lengthlist__44u7__long,
  150419. 0, 0, 0, 0, 0,
  150420. NULL,
  150421. NULL,
  150422. NULL,
  150423. NULL,
  150424. 0
  150425. };
  150426. static long _vq_quantlist__44u7__p1_0[] = {
  150427. 1,
  150428. 0,
  150429. 2,
  150430. };
  150431. static long _vq_lengthlist__44u7__p1_0[] = {
  150432. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150433. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150434. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150435. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150436. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150437. 12,
  150438. };
  150439. static float _vq_quantthresh__44u7__p1_0[] = {
  150440. -0.5, 0.5,
  150441. };
  150442. static long _vq_quantmap__44u7__p1_0[] = {
  150443. 1, 0, 2,
  150444. };
  150445. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150446. _vq_quantthresh__44u7__p1_0,
  150447. _vq_quantmap__44u7__p1_0,
  150448. 3,
  150449. 3
  150450. };
  150451. static static_codebook _44u7__p1_0 = {
  150452. 4, 81,
  150453. _vq_lengthlist__44u7__p1_0,
  150454. 1, -535822336, 1611661312, 2, 0,
  150455. _vq_quantlist__44u7__p1_0,
  150456. NULL,
  150457. &_vq_auxt__44u7__p1_0,
  150458. NULL,
  150459. 0
  150460. };
  150461. static long _vq_quantlist__44u7__p2_0[] = {
  150462. 1,
  150463. 0,
  150464. 2,
  150465. };
  150466. static long _vq_lengthlist__44u7__p2_0[] = {
  150467. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150468. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150469. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150470. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150471. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150472. 9,
  150473. };
  150474. static float _vq_quantthresh__44u7__p2_0[] = {
  150475. -0.5, 0.5,
  150476. };
  150477. static long _vq_quantmap__44u7__p2_0[] = {
  150478. 1, 0, 2,
  150479. };
  150480. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150481. _vq_quantthresh__44u7__p2_0,
  150482. _vq_quantmap__44u7__p2_0,
  150483. 3,
  150484. 3
  150485. };
  150486. static static_codebook _44u7__p2_0 = {
  150487. 4, 81,
  150488. _vq_lengthlist__44u7__p2_0,
  150489. 1, -535822336, 1611661312, 2, 0,
  150490. _vq_quantlist__44u7__p2_0,
  150491. NULL,
  150492. &_vq_auxt__44u7__p2_0,
  150493. NULL,
  150494. 0
  150495. };
  150496. static long _vq_quantlist__44u7__p3_0[] = {
  150497. 2,
  150498. 1,
  150499. 3,
  150500. 0,
  150501. 4,
  150502. };
  150503. static long _vq_lengthlist__44u7__p3_0[] = {
  150504. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150505. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150506. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150507. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150508. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150509. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150510. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150511. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150512. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150513. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150514. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150515. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150516. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150517. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150518. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150519. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150520. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150521. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150522. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150523. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150524. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150525. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150526. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150527. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150528. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150529. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150530. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150531. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150532. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150533. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150534. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150535. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150536. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150537. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150538. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150539. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150540. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150541. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150542. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150543. 0,
  150544. };
  150545. static float _vq_quantthresh__44u7__p3_0[] = {
  150546. -1.5, -0.5, 0.5, 1.5,
  150547. };
  150548. static long _vq_quantmap__44u7__p3_0[] = {
  150549. 3, 1, 0, 2, 4,
  150550. };
  150551. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150552. _vq_quantthresh__44u7__p3_0,
  150553. _vq_quantmap__44u7__p3_0,
  150554. 5,
  150555. 5
  150556. };
  150557. static static_codebook _44u7__p3_0 = {
  150558. 4, 625,
  150559. _vq_lengthlist__44u7__p3_0,
  150560. 1, -533725184, 1611661312, 3, 0,
  150561. _vq_quantlist__44u7__p3_0,
  150562. NULL,
  150563. &_vq_auxt__44u7__p3_0,
  150564. NULL,
  150565. 0
  150566. };
  150567. static long _vq_quantlist__44u7__p4_0[] = {
  150568. 2,
  150569. 1,
  150570. 3,
  150571. 0,
  150572. 4,
  150573. };
  150574. static long _vq_lengthlist__44u7__p4_0[] = {
  150575. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150576. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150577. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150578. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150579. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150580. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150581. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150582. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150583. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150584. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150585. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150586. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150587. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150588. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150589. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150590. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150591. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150592. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150593. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150594. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150595. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150596. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150597. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150598. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150599. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150600. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150601. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150602. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150603. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150604. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150605. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150606. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150607. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150608. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150609. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150610. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150611. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150612. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150613. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150614. 14,
  150615. };
  150616. static float _vq_quantthresh__44u7__p4_0[] = {
  150617. -1.5, -0.5, 0.5, 1.5,
  150618. };
  150619. static long _vq_quantmap__44u7__p4_0[] = {
  150620. 3, 1, 0, 2, 4,
  150621. };
  150622. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150623. _vq_quantthresh__44u7__p4_0,
  150624. _vq_quantmap__44u7__p4_0,
  150625. 5,
  150626. 5
  150627. };
  150628. static static_codebook _44u7__p4_0 = {
  150629. 4, 625,
  150630. _vq_lengthlist__44u7__p4_0,
  150631. 1, -533725184, 1611661312, 3, 0,
  150632. _vq_quantlist__44u7__p4_0,
  150633. NULL,
  150634. &_vq_auxt__44u7__p4_0,
  150635. NULL,
  150636. 0
  150637. };
  150638. static long _vq_quantlist__44u7__p5_0[] = {
  150639. 4,
  150640. 3,
  150641. 5,
  150642. 2,
  150643. 6,
  150644. 1,
  150645. 7,
  150646. 0,
  150647. 8,
  150648. };
  150649. static long _vq_lengthlist__44u7__p5_0[] = {
  150650. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150651. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150652. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150653. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150654. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150655. 14,
  150656. };
  150657. static float _vq_quantthresh__44u7__p5_0[] = {
  150658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150659. };
  150660. static long _vq_quantmap__44u7__p5_0[] = {
  150661. 7, 5, 3, 1, 0, 2, 4, 6,
  150662. 8,
  150663. };
  150664. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150665. _vq_quantthresh__44u7__p5_0,
  150666. _vq_quantmap__44u7__p5_0,
  150667. 9,
  150668. 9
  150669. };
  150670. static static_codebook _44u7__p5_0 = {
  150671. 2, 81,
  150672. _vq_lengthlist__44u7__p5_0,
  150673. 1, -531628032, 1611661312, 4, 0,
  150674. _vq_quantlist__44u7__p5_0,
  150675. NULL,
  150676. &_vq_auxt__44u7__p5_0,
  150677. NULL,
  150678. 0
  150679. };
  150680. static long _vq_quantlist__44u7__p6_0[] = {
  150681. 4,
  150682. 3,
  150683. 5,
  150684. 2,
  150685. 6,
  150686. 1,
  150687. 7,
  150688. 0,
  150689. 8,
  150690. };
  150691. static long _vq_lengthlist__44u7__p6_0[] = {
  150692. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150693. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150694. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150695. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150696. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150697. 12,
  150698. };
  150699. static float _vq_quantthresh__44u7__p6_0[] = {
  150700. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150701. };
  150702. static long _vq_quantmap__44u7__p6_0[] = {
  150703. 7, 5, 3, 1, 0, 2, 4, 6,
  150704. 8,
  150705. };
  150706. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150707. _vq_quantthresh__44u7__p6_0,
  150708. _vq_quantmap__44u7__p6_0,
  150709. 9,
  150710. 9
  150711. };
  150712. static static_codebook _44u7__p6_0 = {
  150713. 2, 81,
  150714. _vq_lengthlist__44u7__p6_0,
  150715. 1, -531628032, 1611661312, 4, 0,
  150716. _vq_quantlist__44u7__p6_0,
  150717. NULL,
  150718. &_vq_auxt__44u7__p6_0,
  150719. NULL,
  150720. 0
  150721. };
  150722. static long _vq_quantlist__44u7__p7_0[] = {
  150723. 1,
  150724. 0,
  150725. 2,
  150726. };
  150727. static long _vq_lengthlist__44u7__p7_0[] = {
  150728. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150729. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150730. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150731. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150732. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150733. 10,
  150734. };
  150735. static float _vq_quantthresh__44u7__p7_0[] = {
  150736. -5.5, 5.5,
  150737. };
  150738. static long _vq_quantmap__44u7__p7_0[] = {
  150739. 1, 0, 2,
  150740. };
  150741. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150742. _vq_quantthresh__44u7__p7_0,
  150743. _vq_quantmap__44u7__p7_0,
  150744. 3,
  150745. 3
  150746. };
  150747. static static_codebook _44u7__p7_0 = {
  150748. 4, 81,
  150749. _vq_lengthlist__44u7__p7_0,
  150750. 1, -529137664, 1618345984, 2, 0,
  150751. _vq_quantlist__44u7__p7_0,
  150752. NULL,
  150753. &_vq_auxt__44u7__p7_0,
  150754. NULL,
  150755. 0
  150756. };
  150757. static long _vq_quantlist__44u7__p7_1[] = {
  150758. 5,
  150759. 4,
  150760. 6,
  150761. 3,
  150762. 7,
  150763. 2,
  150764. 8,
  150765. 1,
  150766. 9,
  150767. 0,
  150768. 10,
  150769. };
  150770. static long _vq_lengthlist__44u7__p7_1[] = {
  150771. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150772. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150773. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150774. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150775. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150776. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150777. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150778. 8, 9, 9, 9, 9, 9,10,10,10,
  150779. };
  150780. static float _vq_quantthresh__44u7__p7_1[] = {
  150781. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150782. 3.5, 4.5,
  150783. };
  150784. static long _vq_quantmap__44u7__p7_1[] = {
  150785. 9, 7, 5, 3, 1, 0, 2, 4,
  150786. 6, 8, 10,
  150787. };
  150788. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150789. _vq_quantthresh__44u7__p7_1,
  150790. _vq_quantmap__44u7__p7_1,
  150791. 11,
  150792. 11
  150793. };
  150794. static static_codebook _44u7__p7_1 = {
  150795. 2, 121,
  150796. _vq_lengthlist__44u7__p7_1,
  150797. 1, -531365888, 1611661312, 4, 0,
  150798. _vq_quantlist__44u7__p7_1,
  150799. NULL,
  150800. &_vq_auxt__44u7__p7_1,
  150801. NULL,
  150802. 0
  150803. };
  150804. static long _vq_quantlist__44u7__p8_0[] = {
  150805. 5,
  150806. 4,
  150807. 6,
  150808. 3,
  150809. 7,
  150810. 2,
  150811. 8,
  150812. 1,
  150813. 9,
  150814. 0,
  150815. 10,
  150816. };
  150817. static long _vq_lengthlist__44u7__p8_0[] = {
  150818. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150819. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150820. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150821. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150822. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150823. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150824. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150825. 12,13,13,14,14,15,15,15,16,
  150826. };
  150827. static float _vq_quantthresh__44u7__p8_0[] = {
  150828. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150829. 38.5, 49.5,
  150830. };
  150831. static long _vq_quantmap__44u7__p8_0[] = {
  150832. 9, 7, 5, 3, 1, 0, 2, 4,
  150833. 6, 8, 10,
  150834. };
  150835. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150836. _vq_quantthresh__44u7__p8_0,
  150837. _vq_quantmap__44u7__p8_0,
  150838. 11,
  150839. 11
  150840. };
  150841. static static_codebook _44u7__p8_0 = {
  150842. 2, 121,
  150843. _vq_lengthlist__44u7__p8_0,
  150844. 1, -524582912, 1618345984, 4, 0,
  150845. _vq_quantlist__44u7__p8_0,
  150846. NULL,
  150847. &_vq_auxt__44u7__p8_0,
  150848. NULL,
  150849. 0
  150850. };
  150851. static long _vq_quantlist__44u7__p8_1[] = {
  150852. 5,
  150853. 4,
  150854. 6,
  150855. 3,
  150856. 7,
  150857. 2,
  150858. 8,
  150859. 1,
  150860. 9,
  150861. 0,
  150862. 10,
  150863. };
  150864. static long _vq_lengthlist__44u7__p8_1[] = {
  150865. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150866. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150867. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150868. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150869. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150870. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150871. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150872. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150873. };
  150874. static float _vq_quantthresh__44u7__p8_1[] = {
  150875. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150876. 3.5, 4.5,
  150877. };
  150878. static long _vq_quantmap__44u7__p8_1[] = {
  150879. 9, 7, 5, 3, 1, 0, 2, 4,
  150880. 6, 8, 10,
  150881. };
  150882. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150883. _vq_quantthresh__44u7__p8_1,
  150884. _vq_quantmap__44u7__p8_1,
  150885. 11,
  150886. 11
  150887. };
  150888. static static_codebook _44u7__p8_1 = {
  150889. 2, 121,
  150890. _vq_lengthlist__44u7__p8_1,
  150891. 1, -531365888, 1611661312, 4, 0,
  150892. _vq_quantlist__44u7__p8_1,
  150893. NULL,
  150894. &_vq_auxt__44u7__p8_1,
  150895. NULL,
  150896. 0
  150897. };
  150898. static long _vq_quantlist__44u7__p9_0[] = {
  150899. 5,
  150900. 4,
  150901. 6,
  150902. 3,
  150903. 7,
  150904. 2,
  150905. 8,
  150906. 1,
  150907. 9,
  150908. 0,
  150909. 10,
  150910. };
  150911. static long _vq_lengthlist__44u7__p9_0[] = {
  150912. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150913. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150915. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150916. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150917. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150918. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150919. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150920. };
  150921. static float _vq_quantthresh__44u7__p9_0[] = {
  150922. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150923. 2229.5, 2866.5,
  150924. };
  150925. static long _vq_quantmap__44u7__p9_0[] = {
  150926. 9, 7, 5, 3, 1, 0, 2, 4,
  150927. 6, 8, 10,
  150928. };
  150929. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150930. _vq_quantthresh__44u7__p9_0,
  150931. _vq_quantmap__44u7__p9_0,
  150932. 11,
  150933. 11
  150934. };
  150935. static static_codebook _44u7__p9_0 = {
  150936. 2, 121,
  150937. _vq_lengthlist__44u7__p9_0,
  150938. 1, -512171520, 1630791680, 4, 0,
  150939. _vq_quantlist__44u7__p9_0,
  150940. NULL,
  150941. &_vq_auxt__44u7__p9_0,
  150942. NULL,
  150943. 0
  150944. };
  150945. static long _vq_quantlist__44u7__p9_1[] = {
  150946. 6,
  150947. 5,
  150948. 7,
  150949. 4,
  150950. 8,
  150951. 3,
  150952. 9,
  150953. 2,
  150954. 10,
  150955. 1,
  150956. 11,
  150957. 0,
  150958. 12,
  150959. };
  150960. static long _vq_lengthlist__44u7__p9_1[] = {
  150961. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150962. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150963. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150964. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150965. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150966. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150967. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150968. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150969. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150970. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150971. 15,15,15,15,17,17,16,17,16,
  150972. };
  150973. static float _vq_quantthresh__44u7__p9_1[] = {
  150974. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150975. 122.5, 171.5, 220.5, 269.5,
  150976. };
  150977. static long _vq_quantmap__44u7__p9_1[] = {
  150978. 11, 9, 7, 5, 3, 1, 0, 2,
  150979. 4, 6, 8, 10, 12,
  150980. };
  150981. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150982. _vq_quantthresh__44u7__p9_1,
  150983. _vq_quantmap__44u7__p9_1,
  150984. 13,
  150985. 13
  150986. };
  150987. static static_codebook _44u7__p9_1 = {
  150988. 2, 169,
  150989. _vq_lengthlist__44u7__p9_1,
  150990. 1, -518889472, 1622704128, 4, 0,
  150991. _vq_quantlist__44u7__p9_1,
  150992. NULL,
  150993. &_vq_auxt__44u7__p9_1,
  150994. NULL,
  150995. 0
  150996. };
  150997. static long _vq_quantlist__44u7__p9_2[] = {
  150998. 24,
  150999. 23,
  151000. 25,
  151001. 22,
  151002. 26,
  151003. 21,
  151004. 27,
  151005. 20,
  151006. 28,
  151007. 19,
  151008. 29,
  151009. 18,
  151010. 30,
  151011. 17,
  151012. 31,
  151013. 16,
  151014. 32,
  151015. 15,
  151016. 33,
  151017. 14,
  151018. 34,
  151019. 13,
  151020. 35,
  151021. 12,
  151022. 36,
  151023. 11,
  151024. 37,
  151025. 10,
  151026. 38,
  151027. 9,
  151028. 39,
  151029. 8,
  151030. 40,
  151031. 7,
  151032. 41,
  151033. 6,
  151034. 42,
  151035. 5,
  151036. 43,
  151037. 4,
  151038. 44,
  151039. 3,
  151040. 45,
  151041. 2,
  151042. 46,
  151043. 1,
  151044. 47,
  151045. 0,
  151046. 48,
  151047. };
  151048. static long _vq_lengthlist__44u7__p9_2[] = {
  151049. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151050. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151051. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151052. 8,
  151053. };
  151054. static float _vq_quantthresh__44u7__p9_2[] = {
  151055. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151056. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151057. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151058. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151059. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151060. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151061. };
  151062. static long _vq_quantmap__44u7__p9_2[] = {
  151063. 47, 45, 43, 41, 39, 37, 35, 33,
  151064. 31, 29, 27, 25, 23, 21, 19, 17,
  151065. 15, 13, 11, 9, 7, 5, 3, 1,
  151066. 0, 2, 4, 6, 8, 10, 12, 14,
  151067. 16, 18, 20, 22, 24, 26, 28, 30,
  151068. 32, 34, 36, 38, 40, 42, 44, 46,
  151069. 48,
  151070. };
  151071. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151072. _vq_quantthresh__44u7__p9_2,
  151073. _vq_quantmap__44u7__p9_2,
  151074. 49,
  151075. 49
  151076. };
  151077. static static_codebook _44u7__p9_2 = {
  151078. 1, 49,
  151079. _vq_lengthlist__44u7__p9_2,
  151080. 1, -526909440, 1611661312, 6, 0,
  151081. _vq_quantlist__44u7__p9_2,
  151082. NULL,
  151083. &_vq_auxt__44u7__p9_2,
  151084. NULL,
  151085. 0
  151086. };
  151087. static long _huff_lengthlist__44u7__short[] = {
  151088. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151089. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151090. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151091. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151092. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151093. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151094. 6, 8, 5, 9,
  151095. };
  151096. static static_codebook _huff_book__44u7__short = {
  151097. 2, 100,
  151098. _huff_lengthlist__44u7__short,
  151099. 0, 0, 0, 0, 0,
  151100. NULL,
  151101. NULL,
  151102. NULL,
  151103. NULL,
  151104. 0
  151105. };
  151106. static long _huff_lengthlist__44u8__long[] = {
  151107. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151108. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151109. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151110. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151111. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151112. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151113. 10, 8, 8, 9,
  151114. };
  151115. static static_codebook _huff_book__44u8__long = {
  151116. 2, 100,
  151117. _huff_lengthlist__44u8__long,
  151118. 0, 0, 0, 0, 0,
  151119. NULL,
  151120. NULL,
  151121. NULL,
  151122. NULL,
  151123. 0
  151124. };
  151125. static long _huff_lengthlist__44u8__short[] = {
  151126. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151127. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151128. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151129. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151130. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151131. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151132. 10,10,15,17,
  151133. };
  151134. static static_codebook _huff_book__44u8__short = {
  151135. 2, 100,
  151136. _huff_lengthlist__44u8__short,
  151137. 0, 0, 0, 0, 0,
  151138. NULL,
  151139. NULL,
  151140. NULL,
  151141. NULL,
  151142. 0
  151143. };
  151144. static long _vq_quantlist__44u8_p1_0[] = {
  151145. 1,
  151146. 0,
  151147. 2,
  151148. };
  151149. static long _vq_lengthlist__44u8_p1_0[] = {
  151150. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151151. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151152. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151153. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151154. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151155. 10,
  151156. };
  151157. static float _vq_quantthresh__44u8_p1_0[] = {
  151158. -0.5, 0.5,
  151159. };
  151160. static long _vq_quantmap__44u8_p1_0[] = {
  151161. 1, 0, 2,
  151162. };
  151163. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151164. _vq_quantthresh__44u8_p1_0,
  151165. _vq_quantmap__44u8_p1_0,
  151166. 3,
  151167. 3
  151168. };
  151169. static static_codebook _44u8_p1_0 = {
  151170. 4, 81,
  151171. _vq_lengthlist__44u8_p1_0,
  151172. 1, -535822336, 1611661312, 2, 0,
  151173. _vq_quantlist__44u8_p1_0,
  151174. NULL,
  151175. &_vq_auxt__44u8_p1_0,
  151176. NULL,
  151177. 0
  151178. };
  151179. static long _vq_quantlist__44u8_p2_0[] = {
  151180. 2,
  151181. 1,
  151182. 3,
  151183. 0,
  151184. 4,
  151185. };
  151186. static long _vq_lengthlist__44u8_p2_0[] = {
  151187. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151188. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151189. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151190. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151191. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151192. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151193. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151194. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151195. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151196. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151197. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151198. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151199. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151200. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151201. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151202. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151203. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151204. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151205. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151206. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151207. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151208. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151209. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151210. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151211. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151212. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151213. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151214. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151215. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151216. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151217. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151218. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151219. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151220. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151221. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151222. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151223. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151224. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151225. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151226. 14,
  151227. };
  151228. static float _vq_quantthresh__44u8_p2_0[] = {
  151229. -1.5, -0.5, 0.5, 1.5,
  151230. };
  151231. static long _vq_quantmap__44u8_p2_0[] = {
  151232. 3, 1, 0, 2, 4,
  151233. };
  151234. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151235. _vq_quantthresh__44u8_p2_0,
  151236. _vq_quantmap__44u8_p2_0,
  151237. 5,
  151238. 5
  151239. };
  151240. static static_codebook _44u8_p2_0 = {
  151241. 4, 625,
  151242. _vq_lengthlist__44u8_p2_0,
  151243. 1, -533725184, 1611661312, 3, 0,
  151244. _vq_quantlist__44u8_p2_0,
  151245. NULL,
  151246. &_vq_auxt__44u8_p2_0,
  151247. NULL,
  151248. 0
  151249. };
  151250. static long _vq_quantlist__44u8_p3_0[] = {
  151251. 4,
  151252. 3,
  151253. 5,
  151254. 2,
  151255. 6,
  151256. 1,
  151257. 7,
  151258. 0,
  151259. 8,
  151260. };
  151261. static long _vq_lengthlist__44u8_p3_0[] = {
  151262. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151263. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151264. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151265. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151266. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151267. 12,
  151268. };
  151269. static float _vq_quantthresh__44u8_p3_0[] = {
  151270. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151271. };
  151272. static long _vq_quantmap__44u8_p3_0[] = {
  151273. 7, 5, 3, 1, 0, 2, 4, 6,
  151274. 8,
  151275. };
  151276. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151277. _vq_quantthresh__44u8_p3_0,
  151278. _vq_quantmap__44u8_p3_0,
  151279. 9,
  151280. 9
  151281. };
  151282. static static_codebook _44u8_p3_0 = {
  151283. 2, 81,
  151284. _vq_lengthlist__44u8_p3_0,
  151285. 1, -531628032, 1611661312, 4, 0,
  151286. _vq_quantlist__44u8_p3_0,
  151287. NULL,
  151288. &_vq_auxt__44u8_p3_0,
  151289. NULL,
  151290. 0
  151291. };
  151292. static long _vq_quantlist__44u8_p4_0[] = {
  151293. 8,
  151294. 7,
  151295. 9,
  151296. 6,
  151297. 10,
  151298. 5,
  151299. 11,
  151300. 4,
  151301. 12,
  151302. 3,
  151303. 13,
  151304. 2,
  151305. 14,
  151306. 1,
  151307. 15,
  151308. 0,
  151309. 16,
  151310. };
  151311. static long _vq_lengthlist__44u8_p4_0[] = {
  151312. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151313. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151314. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151315. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151316. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151317. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151318. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151319. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151320. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151321. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151322. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151323. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151324. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151325. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151326. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151327. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151328. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151329. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151330. 14,
  151331. };
  151332. static float _vq_quantthresh__44u8_p4_0[] = {
  151333. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151334. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151335. };
  151336. static long _vq_quantmap__44u8_p4_0[] = {
  151337. 15, 13, 11, 9, 7, 5, 3, 1,
  151338. 0, 2, 4, 6, 8, 10, 12, 14,
  151339. 16,
  151340. };
  151341. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151342. _vq_quantthresh__44u8_p4_0,
  151343. _vq_quantmap__44u8_p4_0,
  151344. 17,
  151345. 17
  151346. };
  151347. static static_codebook _44u8_p4_0 = {
  151348. 2, 289,
  151349. _vq_lengthlist__44u8_p4_0,
  151350. 1, -529530880, 1611661312, 5, 0,
  151351. _vq_quantlist__44u8_p4_0,
  151352. NULL,
  151353. &_vq_auxt__44u8_p4_0,
  151354. NULL,
  151355. 0
  151356. };
  151357. static long _vq_quantlist__44u8_p5_0[] = {
  151358. 1,
  151359. 0,
  151360. 2,
  151361. };
  151362. static long _vq_lengthlist__44u8_p5_0[] = {
  151363. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151364. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151365. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151366. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151367. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151368. 10,
  151369. };
  151370. static float _vq_quantthresh__44u8_p5_0[] = {
  151371. -5.5, 5.5,
  151372. };
  151373. static long _vq_quantmap__44u8_p5_0[] = {
  151374. 1, 0, 2,
  151375. };
  151376. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151377. _vq_quantthresh__44u8_p5_0,
  151378. _vq_quantmap__44u8_p5_0,
  151379. 3,
  151380. 3
  151381. };
  151382. static static_codebook _44u8_p5_0 = {
  151383. 4, 81,
  151384. _vq_lengthlist__44u8_p5_0,
  151385. 1, -529137664, 1618345984, 2, 0,
  151386. _vq_quantlist__44u8_p5_0,
  151387. NULL,
  151388. &_vq_auxt__44u8_p5_0,
  151389. NULL,
  151390. 0
  151391. };
  151392. static long _vq_quantlist__44u8_p5_1[] = {
  151393. 5,
  151394. 4,
  151395. 6,
  151396. 3,
  151397. 7,
  151398. 2,
  151399. 8,
  151400. 1,
  151401. 9,
  151402. 0,
  151403. 10,
  151404. };
  151405. static long _vq_lengthlist__44u8_p5_1[] = {
  151406. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151407. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151408. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151409. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151410. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151411. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151412. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151413. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151414. };
  151415. static float _vq_quantthresh__44u8_p5_1[] = {
  151416. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151417. 3.5, 4.5,
  151418. };
  151419. static long _vq_quantmap__44u8_p5_1[] = {
  151420. 9, 7, 5, 3, 1, 0, 2, 4,
  151421. 6, 8, 10,
  151422. };
  151423. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151424. _vq_quantthresh__44u8_p5_1,
  151425. _vq_quantmap__44u8_p5_1,
  151426. 11,
  151427. 11
  151428. };
  151429. static static_codebook _44u8_p5_1 = {
  151430. 2, 121,
  151431. _vq_lengthlist__44u8_p5_1,
  151432. 1, -531365888, 1611661312, 4, 0,
  151433. _vq_quantlist__44u8_p5_1,
  151434. NULL,
  151435. &_vq_auxt__44u8_p5_1,
  151436. NULL,
  151437. 0
  151438. };
  151439. static long _vq_quantlist__44u8_p6_0[] = {
  151440. 6,
  151441. 5,
  151442. 7,
  151443. 4,
  151444. 8,
  151445. 3,
  151446. 9,
  151447. 2,
  151448. 10,
  151449. 1,
  151450. 11,
  151451. 0,
  151452. 12,
  151453. };
  151454. static long _vq_lengthlist__44u8_p6_0[] = {
  151455. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151456. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151457. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151458. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151459. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151460. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151461. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151462. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151463. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151464. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151465. 11,11,11,11,11,12,11,12,12,
  151466. };
  151467. static float _vq_quantthresh__44u8_p6_0[] = {
  151468. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151469. 12.5, 17.5, 22.5, 27.5,
  151470. };
  151471. static long _vq_quantmap__44u8_p6_0[] = {
  151472. 11, 9, 7, 5, 3, 1, 0, 2,
  151473. 4, 6, 8, 10, 12,
  151474. };
  151475. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151476. _vq_quantthresh__44u8_p6_0,
  151477. _vq_quantmap__44u8_p6_0,
  151478. 13,
  151479. 13
  151480. };
  151481. static static_codebook _44u8_p6_0 = {
  151482. 2, 169,
  151483. _vq_lengthlist__44u8_p6_0,
  151484. 1, -526516224, 1616117760, 4, 0,
  151485. _vq_quantlist__44u8_p6_0,
  151486. NULL,
  151487. &_vq_auxt__44u8_p6_0,
  151488. NULL,
  151489. 0
  151490. };
  151491. static long _vq_quantlist__44u8_p6_1[] = {
  151492. 2,
  151493. 1,
  151494. 3,
  151495. 0,
  151496. 4,
  151497. };
  151498. static long _vq_lengthlist__44u8_p6_1[] = {
  151499. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151500. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151501. };
  151502. static float _vq_quantthresh__44u8_p6_1[] = {
  151503. -1.5, -0.5, 0.5, 1.5,
  151504. };
  151505. static long _vq_quantmap__44u8_p6_1[] = {
  151506. 3, 1, 0, 2, 4,
  151507. };
  151508. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151509. _vq_quantthresh__44u8_p6_1,
  151510. _vq_quantmap__44u8_p6_1,
  151511. 5,
  151512. 5
  151513. };
  151514. static static_codebook _44u8_p6_1 = {
  151515. 2, 25,
  151516. _vq_lengthlist__44u8_p6_1,
  151517. 1, -533725184, 1611661312, 3, 0,
  151518. _vq_quantlist__44u8_p6_1,
  151519. NULL,
  151520. &_vq_auxt__44u8_p6_1,
  151521. NULL,
  151522. 0
  151523. };
  151524. static long _vq_quantlist__44u8_p7_0[] = {
  151525. 6,
  151526. 5,
  151527. 7,
  151528. 4,
  151529. 8,
  151530. 3,
  151531. 9,
  151532. 2,
  151533. 10,
  151534. 1,
  151535. 11,
  151536. 0,
  151537. 12,
  151538. };
  151539. static long _vq_lengthlist__44u8_p7_0[] = {
  151540. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151541. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151542. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151543. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151544. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151545. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151546. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151547. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151548. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151549. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151550. 13,13,14,14,14,15,15,15,16,
  151551. };
  151552. static float _vq_quantthresh__44u8_p7_0[] = {
  151553. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151554. 27.5, 38.5, 49.5, 60.5,
  151555. };
  151556. static long _vq_quantmap__44u8_p7_0[] = {
  151557. 11, 9, 7, 5, 3, 1, 0, 2,
  151558. 4, 6, 8, 10, 12,
  151559. };
  151560. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151561. _vq_quantthresh__44u8_p7_0,
  151562. _vq_quantmap__44u8_p7_0,
  151563. 13,
  151564. 13
  151565. };
  151566. static static_codebook _44u8_p7_0 = {
  151567. 2, 169,
  151568. _vq_lengthlist__44u8_p7_0,
  151569. 1, -523206656, 1618345984, 4, 0,
  151570. _vq_quantlist__44u8_p7_0,
  151571. NULL,
  151572. &_vq_auxt__44u8_p7_0,
  151573. NULL,
  151574. 0
  151575. };
  151576. static long _vq_quantlist__44u8_p7_1[] = {
  151577. 5,
  151578. 4,
  151579. 6,
  151580. 3,
  151581. 7,
  151582. 2,
  151583. 8,
  151584. 1,
  151585. 9,
  151586. 0,
  151587. 10,
  151588. };
  151589. static long _vq_lengthlist__44u8_p7_1[] = {
  151590. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151591. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151592. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151593. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151594. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151595. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151596. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151597. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151598. };
  151599. static float _vq_quantthresh__44u8_p7_1[] = {
  151600. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151601. 3.5, 4.5,
  151602. };
  151603. static long _vq_quantmap__44u8_p7_1[] = {
  151604. 9, 7, 5, 3, 1, 0, 2, 4,
  151605. 6, 8, 10,
  151606. };
  151607. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151608. _vq_quantthresh__44u8_p7_1,
  151609. _vq_quantmap__44u8_p7_1,
  151610. 11,
  151611. 11
  151612. };
  151613. static static_codebook _44u8_p7_1 = {
  151614. 2, 121,
  151615. _vq_lengthlist__44u8_p7_1,
  151616. 1, -531365888, 1611661312, 4, 0,
  151617. _vq_quantlist__44u8_p7_1,
  151618. NULL,
  151619. &_vq_auxt__44u8_p7_1,
  151620. NULL,
  151621. 0
  151622. };
  151623. static long _vq_quantlist__44u8_p8_0[] = {
  151624. 7,
  151625. 6,
  151626. 8,
  151627. 5,
  151628. 9,
  151629. 4,
  151630. 10,
  151631. 3,
  151632. 11,
  151633. 2,
  151634. 12,
  151635. 1,
  151636. 13,
  151637. 0,
  151638. 14,
  151639. };
  151640. static long _vq_lengthlist__44u8_p8_0[] = {
  151641. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151642. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151643. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151644. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151645. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151646. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151647. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151648. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151649. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151650. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151651. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151652. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151653. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151654. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151655. 17,
  151656. };
  151657. static float _vq_quantthresh__44u8_p8_0[] = {
  151658. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151659. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151660. };
  151661. static long _vq_quantmap__44u8_p8_0[] = {
  151662. 13, 11, 9, 7, 5, 3, 1, 0,
  151663. 2, 4, 6, 8, 10, 12, 14,
  151664. };
  151665. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151666. _vq_quantthresh__44u8_p8_0,
  151667. _vq_quantmap__44u8_p8_0,
  151668. 15,
  151669. 15
  151670. };
  151671. static static_codebook _44u8_p8_0 = {
  151672. 2, 225,
  151673. _vq_lengthlist__44u8_p8_0,
  151674. 1, -520986624, 1620377600, 4, 0,
  151675. _vq_quantlist__44u8_p8_0,
  151676. NULL,
  151677. &_vq_auxt__44u8_p8_0,
  151678. NULL,
  151679. 0
  151680. };
  151681. static long _vq_quantlist__44u8_p8_1[] = {
  151682. 10,
  151683. 9,
  151684. 11,
  151685. 8,
  151686. 12,
  151687. 7,
  151688. 13,
  151689. 6,
  151690. 14,
  151691. 5,
  151692. 15,
  151693. 4,
  151694. 16,
  151695. 3,
  151696. 17,
  151697. 2,
  151698. 18,
  151699. 1,
  151700. 19,
  151701. 0,
  151702. 20,
  151703. };
  151704. static long _vq_lengthlist__44u8_p8_1[] = {
  151705. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151706. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151707. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151708. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151709. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151710. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151711. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151712. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151713. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151714. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151715. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151716. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151717. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151718. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151719. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151720. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151721. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151722. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151723. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151724. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151725. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151726. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151727. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151728. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151729. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151730. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151731. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151732. 10,10,10,10,10,10,10,10,10,
  151733. };
  151734. static float _vq_quantthresh__44u8_p8_1[] = {
  151735. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151736. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151737. 6.5, 7.5, 8.5, 9.5,
  151738. };
  151739. static long _vq_quantmap__44u8_p8_1[] = {
  151740. 19, 17, 15, 13, 11, 9, 7, 5,
  151741. 3, 1, 0, 2, 4, 6, 8, 10,
  151742. 12, 14, 16, 18, 20,
  151743. };
  151744. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151745. _vq_quantthresh__44u8_p8_1,
  151746. _vq_quantmap__44u8_p8_1,
  151747. 21,
  151748. 21
  151749. };
  151750. static static_codebook _44u8_p8_1 = {
  151751. 2, 441,
  151752. _vq_lengthlist__44u8_p8_1,
  151753. 1, -529268736, 1611661312, 5, 0,
  151754. _vq_quantlist__44u8_p8_1,
  151755. NULL,
  151756. &_vq_auxt__44u8_p8_1,
  151757. NULL,
  151758. 0
  151759. };
  151760. static long _vq_quantlist__44u8_p9_0[] = {
  151761. 4,
  151762. 3,
  151763. 5,
  151764. 2,
  151765. 6,
  151766. 1,
  151767. 7,
  151768. 0,
  151769. 8,
  151770. };
  151771. static long _vq_lengthlist__44u8_p9_0[] = {
  151772. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151773. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151774. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151775. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151776. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151777. 8,
  151778. };
  151779. static float _vq_quantthresh__44u8_p9_0[] = {
  151780. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151781. };
  151782. static long _vq_quantmap__44u8_p9_0[] = {
  151783. 7, 5, 3, 1, 0, 2, 4, 6,
  151784. 8,
  151785. };
  151786. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151787. _vq_quantthresh__44u8_p9_0,
  151788. _vq_quantmap__44u8_p9_0,
  151789. 9,
  151790. 9
  151791. };
  151792. static static_codebook _44u8_p9_0 = {
  151793. 2, 81,
  151794. _vq_lengthlist__44u8_p9_0,
  151795. 1, -511895552, 1631393792, 4, 0,
  151796. _vq_quantlist__44u8_p9_0,
  151797. NULL,
  151798. &_vq_auxt__44u8_p9_0,
  151799. NULL,
  151800. 0
  151801. };
  151802. static long _vq_quantlist__44u8_p9_1[] = {
  151803. 9,
  151804. 8,
  151805. 10,
  151806. 7,
  151807. 11,
  151808. 6,
  151809. 12,
  151810. 5,
  151811. 13,
  151812. 4,
  151813. 14,
  151814. 3,
  151815. 15,
  151816. 2,
  151817. 16,
  151818. 1,
  151819. 17,
  151820. 0,
  151821. 18,
  151822. };
  151823. static long _vq_lengthlist__44u8_p9_1[] = {
  151824. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151825. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151826. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151827. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151828. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151829. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151830. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151831. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151832. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151833. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151834. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151835. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151836. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151837. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151838. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151839. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151840. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151841. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151842. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151843. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151844. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151845. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151846. 16,15,16,16,16,16,16,16,16,
  151847. };
  151848. static float _vq_quantthresh__44u8_p9_1[] = {
  151849. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151850. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151851. 367.5, 416.5,
  151852. };
  151853. static long _vq_quantmap__44u8_p9_1[] = {
  151854. 17, 15, 13, 11, 9, 7, 5, 3,
  151855. 1, 0, 2, 4, 6, 8, 10, 12,
  151856. 14, 16, 18,
  151857. };
  151858. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151859. _vq_quantthresh__44u8_p9_1,
  151860. _vq_quantmap__44u8_p9_1,
  151861. 19,
  151862. 19
  151863. };
  151864. static static_codebook _44u8_p9_1 = {
  151865. 2, 361,
  151866. _vq_lengthlist__44u8_p9_1,
  151867. 1, -518287360, 1622704128, 5, 0,
  151868. _vq_quantlist__44u8_p9_1,
  151869. NULL,
  151870. &_vq_auxt__44u8_p9_1,
  151871. NULL,
  151872. 0
  151873. };
  151874. static long _vq_quantlist__44u8_p9_2[] = {
  151875. 24,
  151876. 23,
  151877. 25,
  151878. 22,
  151879. 26,
  151880. 21,
  151881. 27,
  151882. 20,
  151883. 28,
  151884. 19,
  151885. 29,
  151886. 18,
  151887. 30,
  151888. 17,
  151889. 31,
  151890. 16,
  151891. 32,
  151892. 15,
  151893. 33,
  151894. 14,
  151895. 34,
  151896. 13,
  151897. 35,
  151898. 12,
  151899. 36,
  151900. 11,
  151901. 37,
  151902. 10,
  151903. 38,
  151904. 9,
  151905. 39,
  151906. 8,
  151907. 40,
  151908. 7,
  151909. 41,
  151910. 6,
  151911. 42,
  151912. 5,
  151913. 43,
  151914. 4,
  151915. 44,
  151916. 3,
  151917. 45,
  151918. 2,
  151919. 46,
  151920. 1,
  151921. 47,
  151922. 0,
  151923. 48,
  151924. };
  151925. static long _vq_lengthlist__44u8_p9_2[] = {
  151926. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151927. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151928. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151929. 7,
  151930. };
  151931. static float _vq_quantthresh__44u8_p9_2[] = {
  151932. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151933. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151934. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151935. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151936. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151937. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151938. };
  151939. static long _vq_quantmap__44u8_p9_2[] = {
  151940. 47, 45, 43, 41, 39, 37, 35, 33,
  151941. 31, 29, 27, 25, 23, 21, 19, 17,
  151942. 15, 13, 11, 9, 7, 5, 3, 1,
  151943. 0, 2, 4, 6, 8, 10, 12, 14,
  151944. 16, 18, 20, 22, 24, 26, 28, 30,
  151945. 32, 34, 36, 38, 40, 42, 44, 46,
  151946. 48,
  151947. };
  151948. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151949. _vq_quantthresh__44u8_p9_2,
  151950. _vq_quantmap__44u8_p9_2,
  151951. 49,
  151952. 49
  151953. };
  151954. static static_codebook _44u8_p9_2 = {
  151955. 1, 49,
  151956. _vq_lengthlist__44u8_p9_2,
  151957. 1, -526909440, 1611661312, 6, 0,
  151958. _vq_quantlist__44u8_p9_2,
  151959. NULL,
  151960. &_vq_auxt__44u8_p9_2,
  151961. NULL,
  151962. 0
  151963. };
  151964. static long _huff_lengthlist__44u9__long[] = {
  151965. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151966. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151967. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151968. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151969. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151970. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151971. 10, 8, 8, 9,
  151972. };
  151973. static static_codebook _huff_book__44u9__long = {
  151974. 2, 100,
  151975. _huff_lengthlist__44u9__long,
  151976. 0, 0, 0, 0, 0,
  151977. NULL,
  151978. NULL,
  151979. NULL,
  151980. NULL,
  151981. 0
  151982. };
  151983. static long _huff_lengthlist__44u9__short[] = {
  151984. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151985. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151986. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151987. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151988. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151989. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151990. 9, 9,12,15,
  151991. };
  151992. static static_codebook _huff_book__44u9__short = {
  151993. 2, 100,
  151994. _huff_lengthlist__44u9__short,
  151995. 0, 0, 0, 0, 0,
  151996. NULL,
  151997. NULL,
  151998. NULL,
  151999. NULL,
  152000. 0
  152001. };
  152002. static long _vq_quantlist__44u9_p1_0[] = {
  152003. 1,
  152004. 0,
  152005. 2,
  152006. };
  152007. static long _vq_lengthlist__44u9_p1_0[] = {
  152008. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152009. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152010. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152011. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152012. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152013. 10,
  152014. };
  152015. static float _vq_quantthresh__44u9_p1_0[] = {
  152016. -0.5, 0.5,
  152017. };
  152018. static long _vq_quantmap__44u9_p1_0[] = {
  152019. 1, 0, 2,
  152020. };
  152021. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152022. _vq_quantthresh__44u9_p1_0,
  152023. _vq_quantmap__44u9_p1_0,
  152024. 3,
  152025. 3
  152026. };
  152027. static static_codebook _44u9_p1_0 = {
  152028. 4, 81,
  152029. _vq_lengthlist__44u9_p1_0,
  152030. 1, -535822336, 1611661312, 2, 0,
  152031. _vq_quantlist__44u9_p1_0,
  152032. NULL,
  152033. &_vq_auxt__44u9_p1_0,
  152034. NULL,
  152035. 0
  152036. };
  152037. static long _vq_quantlist__44u9_p2_0[] = {
  152038. 2,
  152039. 1,
  152040. 3,
  152041. 0,
  152042. 4,
  152043. };
  152044. static long _vq_lengthlist__44u9_p2_0[] = {
  152045. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152046. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152047. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152048. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152049. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152050. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152051. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152052. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152053. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152054. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152055. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152056. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152057. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152058. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152059. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152060. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152061. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152062. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152063. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152064. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152065. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152066. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152067. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152068. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152069. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152070. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152071. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152072. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152073. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152074. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152075. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152076. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152077. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152078. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152079. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152080. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152081. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152082. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152083. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152084. 14,
  152085. };
  152086. static float _vq_quantthresh__44u9_p2_0[] = {
  152087. -1.5, -0.5, 0.5, 1.5,
  152088. };
  152089. static long _vq_quantmap__44u9_p2_0[] = {
  152090. 3, 1, 0, 2, 4,
  152091. };
  152092. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152093. _vq_quantthresh__44u9_p2_0,
  152094. _vq_quantmap__44u9_p2_0,
  152095. 5,
  152096. 5
  152097. };
  152098. static static_codebook _44u9_p2_0 = {
  152099. 4, 625,
  152100. _vq_lengthlist__44u9_p2_0,
  152101. 1, -533725184, 1611661312, 3, 0,
  152102. _vq_quantlist__44u9_p2_0,
  152103. NULL,
  152104. &_vq_auxt__44u9_p2_0,
  152105. NULL,
  152106. 0
  152107. };
  152108. static long _vq_quantlist__44u9_p3_0[] = {
  152109. 4,
  152110. 3,
  152111. 5,
  152112. 2,
  152113. 6,
  152114. 1,
  152115. 7,
  152116. 0,
  152117. 8,
  152118. };
  152119. static long _vq_lengthlist__44u9_p3_0[] = {
  152120. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152121. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152122. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152123. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152124. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152125. 11,
  152126. };
  152127. static float _vq_quantthresh__44u9_p3_0[] = {
  152128. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152129. };
  152130. static long _vq_quantmap__44u9_p3_0[] = {
  152131. 7, 5, 3, 1, 0, 2, 4, 6,
  152132. 8,
  152133. };
  152134. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152135. _vq_quantthresh__44u9_p3_0,
  152136. _vq_quantmap__44u9_p3_0,
  152137. 9,
  152138. 9
  152139. };
  152140. static static_codebook _44u9_p3_0 = {
  152141. 2, 81,
  152142. _vq_lengthlist__44u9_p3_0,
  152143. 1, -531628032, 1611661312, 4, 0,
  152144. _vq_quantlist__44u9_p3_0,
  152145. NULL,
  152146. &_vq_auxt__44u9_p3_0,
  152147. NULL,
  152148. 0
  152149. };
  152150. static long _vq_quantlist__44u9_p4_0[] = {
  152151. 8,
  152152. 7,
  152153. 9,
  152154. 6,
  152155. 10,
  152156. 5,
  152157. 11,
  152158. 4,
  152159. 12,
  152160. 3,
  152161. 13,
  152162. 2,
  152163. 14,
  152164. 1,
  152165. 15,
  152166. 0,
  152167. 16,
  152168. };
  152169. static long _vq_lengthlist__44u9_p4_0[] = {
  152170. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152171. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152172. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152173. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152174. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152175. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152176. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152177. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152178. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152179. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152180. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152181. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152182. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152183. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152184. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152185. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152186. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152187. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152188. 14,
  152189. };
  152190. static float _vq_quantthresh__44u9_p4_0[] = {
  152191. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152192. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152193. };
  152194. static long _vq_quantmap__44u9_p4_0[] = {
  152195. 15, 13, 11, 9, 7, 5, 3, 1,
  152196. 0, 2, 4, 6, 8, 10, 12, 14,
  152197. 16,
  152198. };
  152199. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152200. _vq_quantthresh__44u9_p4_0,
  152201. _vq_quantmap__44u9_p4_0,
  152202. 17,
  152203. 17
  152204. };
  152205. static static_codebook _44u9_p4_0 = {
  152206. 2, 289,
  152207. _vq_lengthlist__44u9_p4_0,
  152208. 1, -529530880, 1611661312, 5, 0,
  152209. _vq_quantlist__44u9_p4_0,
  152210. NULL,
  152211. &_vq_auxt__44u9_p4_0,
  152212. NULL,
  152213. 0
  152214. };
  152215. static long _vq_quantlist__44u9_p5_0[] = {
  152216. 1,
  152217. 0,
  152218. 2,
  152219. };
  152220. static long _vq_lengthlist__44u9_p5_0[] = {
  152221. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152222. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152223. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152224. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152225. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152226. 10,
  152227. };
  152228. static float _vq_quantthresh__44u9_p5_0[] = {
  152229. -5.5, 5.5,
  152230. };
  152231. static long _vq_quantmap__44u9_p5_0[] = {
  152232. 1, 0, 2,
  152233. };
  152234. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152235. _vq_quantthresh__44u9_p5_0,
  152236. _vq_quantmap__44u9_p5_0,
  152237. 3,
  152238. 3
  152239. };
  152240. static static_codebook _44u9_p5_0 = {
  152241. 4, 81,
  152242. _vq_lengthlist__44u9_p5_0,
  152243. 1, -529137664, 1618345984, 2, 0,
  152244. _vq_quantlist__44u9_p5_0,
  152245. NULL,
  152246. &_vq_auxt__44u9_p5_0,
  152247. NULL,
  152248. 0
  152249. };
  152250. static long _vq_quantlist__44u9_p5_1[] = {
  152251. 5,
  152252. 4,
  152253. 6,
  152254. 3,
  152255. 7,
  152256. 2,
  152257. 8,
  152258. 1,
  152259. 9,
  152260. 0,
  152261. 10,
  152262. };
  152263. static long _vq_lengthlist__44u9_p5_1[] = {
  152264. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152265. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152266. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152267. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152268. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152269. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152270. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152271. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152272. };
  152273. static float _vq_quantthresh__44u9_p5_1[] = {
  152274. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152275. 3.5, 4.5,
  152276. };
  152277. static long _vq_quantmap__44u9_p5_1[] = {
  152278. 9, 7, 5, 3, 1, 0, 2, 4,
  152279. 6, 8, 10,
  152280. };
  152281. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152282. _vq_quantthresh__44u9_p5_1,
  152283. _vq_quantmap__44u9_p5_1,
  152284. 11,
  152285. 11
  152286. };
  152287. static static_codebook _44u9_p5_1 = {
  152288. 2, 121,
  152289. _vq_lengthlist__44u9_p5_1,
  152290. 1, -531365888, 1611661312, 4, 0,
  152291. _vq_quantlist__44u9_p5_1,
  152292. NULL,
  152293. &_vq_auxt__44u9_p5_1,
  152294. NULL,
  152295. 0
  152296. };
  152297. static long _vq_quantlist__44u9_p6_0[] = {
  152298. 6,
  152299. 5,
  152300. 7,
  152301. 4,
  152302. 8,
  152303. 3,
  152304. 9,
  152305. 2,
  152306. 10,
  152307. 1,
  152308. 11,
  152309. 0,
  152310. 12,
  152311. };
  152312. static long _vq_lengthlist__44u9_p6_0[] = {
  152313. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152314. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152315. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152316. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152317. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152318. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152319. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152320. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152321. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152322. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152323. 10,11,11,11,11,12,11,12,12,
  152324. };
  152325. static float _vq_quantthresh__44u9_p6_0[] = {
  152326. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152327. 12.5, 17.5, 22.5, 27.5,
  152328. };
  152329. static long _vq_quantmap__44u9_p6_0[] = {
  152330. 11, 9, 7, 5, 3, 1, 0, 2,
  152331. 4, 6, 8, 10, 12,
  152332. };
  152333. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152334. _vq_quantthresh__44u9_p6_0,
  152335. _vq_quantmap__44u9_p6_0,
  152336. 13,
  152337. 13
  152338. };
  152339. static static_codebook _44u9_p6_0 = {
  152340. 2, 169,
  152341. _vq_lengthlist__44u9_p6_0,
  152342. 1, -526516224, 1616117760, 4, 0,
  152343. _vq_quantlist__44u9_p6_0,
  152344. NULL,
  152345. &_vq_auxt__44u9_p6_0,
  152346. NULL,
  152347. 0
  152348. };
  152349. static long _vq_quantlist__44u9_p6_1[] = {
  152350. 2,
  152351. 1,
  152352. 3,
  152353. 0,
  152354. 4,
  152355. };
  152356. static long _vq_lengthlist__44u9_p6_1[] = {
  152357. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152358. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152359. };
  152360. static float _vq_quantthresh__44u9_p6_1[] = {
  152361. -1.5, -0.5, 0.5, 1.5,
  152362. };
  152363. static long _vq_quantmap__44u9_p6_1[] = {
  152364. 3, 1, 0, 2, 4,
  152365. };
  152366. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152367. _vq_quantthresh__44u9_p6_1,
  152368. _vq_quantmap__44u9_p6_1,
  152369. 5,
  152370. 5
  152371. };
  152372. static static_codebook _44u9_p6_1 = {
  152373. 2, 25,
  152374. _vq_lengthlist__44u9_p6_1,
  152375. 1, -533725184, 1611661312, 3, 0,
  152376. _vq_quantlist__44u9_p6_1,
  152377. NULL,
  152378. &_vq_auxt__44u9_p6_1,
  152379. NULL,
  152380. 0
  152381. };
  152382. static long _vq_quantlist__44u9_p7_0[] = {
  152383. 6,
  152384. 5,
  152385. 7,
  152386. 4,
  152387. 8,
  152388. 3,
  152389. 9,
  152390. 2,
  152391. 10,
  152392. 1,
  152393. 11,
  152394. 0,
  152395. 12,
  152396. };
  152397. static long _vq_lengthlist__44u9_p7_0[] = {
  152398. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152399. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152400. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152401. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152402. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152403. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152404. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152405. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152406. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152407. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152408. 12,13,13,14,14,14,15,15,15,
  152409. };
  152410. static float _vq_quantthresh__44u9_p7_0[] = {
  152411. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152412. 27.5, 38.5, 49.5, 60.5,
  152413. };
  152414. static long _vq_quantmap__44u9_p7_0[] = {
  152415. 11, 9, 7, 5, 3, 1, 0, 2,
  152416. 4, 6, 8, 10, 12,
  152417. };
  152418. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152419. _vq_quantthresh__44u9_p7_0,
  152420. _vq_quantmap__44u9_p7_0,
  152421. 13,
  152422. 13
  152423. };
  152424. static static_codebook _44u9_p7_0 = {
  152425. 2, 169,
  152426. _vq_lengthlist__44u9_p7_0,
  152427. 1, -523206656, 1618345984, 4, 0,
  152428. _vq_quantlist__44u9_p7_0,
  152429. NULL,
  152430. &_vq_auxt__44u9_p7_0,
  152431. NULL,
  152432. 0
  152433. };
  152434. static long _vq_quantlist__44u9_p7_1[] = {
  152435. 5,
  152436. 4,
  152437. 6,
  152438. 3,
  152439. 7,
  152440. 2,
  152441. 8,
  152442. 1,
  152443. 9,
  152444. 0,
  152445. 10,
  152446. };
  152447. static long _vq_lengthlist__44u9_p7_1[] = {
  152448. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152449. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152450. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152451. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152452. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152453. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152454. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152455. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152456. };
  152457. static float _vq_quantthresh__44u9_p7_1[] = {
  152458. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152459. 3.5, 4.5,
  152460. };
  152461. static long _vq_quantmap__44u9_p7_1[] = {
  152462. 9, 7, 5, 3, 1, 0, 2, 4,
  152463. 6, 8, 10,
  152464. };
  152465. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152466. _vq_quantthresh__44u9_p7_1,
  152467. _vq_quantmap__44u9_p7_1,
  152468. 11,
  152469. 11
  152470. };
  152471. static static_codebook _44u9_p7_1 = {
  152472. 2, 121,
  152473. _vq_lengthlist__44u9_p7_1,
  152474. 1, -531365888, 1611661312, 4, 0,
  152475. _vq_quantlist__44u9_p7_1,
  152476. NULL,
  152477. &_vq_auxt__44u9_p7_1,
  152478. NULL,
  152479. 0
  152480. };
  152481. static long _vq_quantlist__44u9_p8_0[] = {
  152482. 7,
  152483. 6,
  152484. 8,
  152485. 5,
  152486. 9,
  152487. 4,
  152488. 10,
  152489. 3,
  152490. 11,
  152491. 2,
  152492. 12,
  152493. 1,
  152494. 13,
  152495. 0,
  152496. 14,
  152497. };
  152498. static long _vq_lengthlist__44u9_p8_0[] = {
  152499. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152500. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152501. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152502. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152503. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152504. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152505. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152506. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152507. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152508. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152509. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152510. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152511. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152512. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152513. 15,
  152514. };
  152515. static float _vq_quantthresh__44u9_p8_0[] = {
  152516. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152517. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152518. };
  152519. static long _vq_quantmap__44u9_p8_0[] = {
  152520. 13, 11, 9, 7, 5, 3, 1, 0,
  152521. 2, 4, 6, 8, 10, 12, 14,
  152522. };
  152523. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152524. _vq_quantthresh__44u9_p8_0,
  152525. _vq_quantmap__44u9_p8_0,
  152526. 15,
  152527. 15
  152528. };
  152529. static static_codebook _44u9_p8_0 = {
  152530. 2, 225,
  152531. _vq_lengthlist__44u9_p8_0,
  152532. 1, -520986624, 1620377600, 4, 0,
  152533. _vq_quantlist__44u9_p8_0,
  152534. NULL,
  152535. &_vq_auxt__44u9_p8_0,
  152536. NULL,
  152537. 0
  152538. };
  152539. static long _vq_quantlist__44u9_p8_1[] = {
  152540. 10,
  152541. 9,
  152542. 11,
  152543. 8,
  152544. 12,
  152545. 7,
  152546. 13,
  152547. 6,
  152548. 14,
  152549. 5,
  152550. 15,
  152551. 4,
  152552. 16,
  152553. 3,
  152554. 17,
  152555. 2,
  152556. 18,
  152557. 1,
  152558. 19,
  152559. 0,
  152560. 20,
  152561. };
  152562. static long _vq_lengthlist__44u9_p8_1[] = {
  152563. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152564. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152565. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152566. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152567. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152568. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152569. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152570. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152571. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152572. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152573. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152574. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152575. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152576. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152577. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152578. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152579. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152580. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152581. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152582. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152584. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152585. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152586. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152588. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152589. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152590. 10,10,10,10,10,10,10,10,10,
  152591. };
  152592. static float _vq_quantthresh__44u9_p8_1[] = {
  152593. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152594. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152595. 6.5, 7.5, 8.5, 9.5,
  152596. };
  152597. static long _vq_quantmap__44u9_p8_1[] = {
  152598. 19, 17, 15, 13, 11, 9, 7, 5,
  152599. 3, 1, 0, 2, 4, 6, 8, 10,
  152600. 12, 14, 16, 18, 20,
  152601. };
  152602. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152603. _vq_quantthresh__44u9_p8_1,
  152604. _vq_quantmap__44u9_p8_1,
  152605. 21,
  152606. 21
  152607. };
  152608. static static_codebook _44u9_p8_1 = {
  152609. 2, 441,
  152610. _vq_lengthlist__44u9_p8_1,
  152611. 1, -529268736, 1611661312, 5, 0,
  152612. _vq_quantlist__44u9_p8_1,
  152613. NULL,
  152614. &_vq_auxt__44u9_p8_1,
  152615. NULL,
  152616. 0
  152617. };
  152618. static long _vq_quantlist__44u9_p9_0[] = {
  152619. 7,
  152620. 6,
  152621. 8,
  152622. 5,
  152623. 9,
  152624. 4,
  152625. 10,
  152626. 3,
  152627. 11,
  152628. 2,
  152629. 12,
  152630. 1,
  152631. 13,
  152632. 0,
  152633. 14,
  152634. };
  152635. static long _vq_lengthlist__44u9_p9_0[] = {
  152636. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152637. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152638. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152650. 10,
  152651. };
  152652. static float _vq_quantthresh__44u9_p9_0[] = {
  152653. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152654. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152655. };
  152656. static long _vq_quantmap__44u9_p9_0[] = {
  152657. 13, 11, 9, 7, 5, 3, 1, 0,
  152658. 2, 4, 6, 8, 10, 12, 14,
  152659. };
  152660. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152661. _vq_quantthresh__44u9_p9_0,
  152662. _vq_quantmap__44u9_p9_0,
  152663. 15,
  152664. 15
  152665. };
  152666. static static_codebook _44u9_p9_0 = {
  152667. 2, 225,
  152668. _vq_lengthlist__44u9_p9_0,
  152669. 1, -510036736, 1631393792, 4, 0,
  152670. _vq_quantlist__44u9_p9_0,
  152671. NULL,
  152672. &_vq_auxt__44u9_p9_0,
  152673. NULL,
  152674. 0
  152675. };
  152676. static long _vq_quantlist__44u9_p9_1[] = {
  152677. 9,
  152678. 8,
  152679. 10,
  152680. 7,
  152681. 11,
  152682. 6,
  152683. 12,
  152684. 5,
  152685. 13,
  152686. 4,
  152687. 14,
  152688. 3,
  152689. 15,
  152690. 2,
  152691. 16,
  152692. 1,
  152693. 17,
  152694. 0,
  152695. 18,
  152696. };
  152697. static long _vq_lengthlist__44u9_p9_1[] = {
  152698. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152699. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152700. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152701. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152702. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152703. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152704. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152705. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152706. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152707. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152708. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152709. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152710. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152711. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152712. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152713. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152714. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152715. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152716. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152717. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152718. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152719. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152720. 17,17,15,17,15,17,16,16,17,
  152721. };
  152722. static float _vq_quantthresh__44u9_p9_1[] = {
  152723. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152724. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152725. 367.5, 416.5,
  152726. };
  152727. static long _vq_quantmap__44u9_p9_1[] = {
  152728. 17, 15, 13, 11, 9, 7, 5, 3,
  152729. 1, 0, 2, 4, 6, 8, 10, 12,
  152730. 14, 16, 18,
  152731. };
  152732. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152733. _vq_quantthresh__44u9_p9_1,
  152734. _vq_quantmap__44u9_p9_1,
  152735. 19,
  152736. 19
  152737. };
  152738. static static_codebook _44u9_p9_1 = {
  152739. 2, 361,
  152740. _vq_lengthlist__44u9_p9_1,
  152741. 1, -518287360, 1622704128, 5, 0,
  152742. _vq_quantlist__44u9_p9_1,
  152743. NULL,
  152744. &_vq_auxt__44u9_p9_1,
  152745. NULL,
  152746. 0
  152747. };
  152748. static long _vq_quantlist__44u9_p9_2[] = {
  152749. 24,
  152750. 23,
  152751. 25,
  152752. 22,
  152753. 26,
  152754. 21,
  152755. 27,
  152756. 20,
  152757. 28,
  152758. 19,
  152759. 29,
  152760. 18,
  152761. 30,
  152762. 17,
  152763. 31,
  152764. 16,
  152765. 32,
  152766. 15,
  152767. 33,
  152768. 14,
  152769. 34,
  152770. 13,
  152771. 35,
  152772. 12,
  152773. 36,
  152774. 11,
  152775. 37,
  152776. 10,
  152777. 38,
  152778. 9,
  152779. 39,
  152780. 8,
  152781. 40,
  152782. 7,
  152783. 41,
  152784. 6,
  152785. 42,
  152786. 5,
  152787. 43,
  152788. 4,
  152789. 44,
  152790. 3,
  152791. 45,
  152792. 2,
  152793. 46,
  152794. 1,
  152795. 47,
  152796. 0,
  152797. 48,
  152798. };
  152799. static long _vq_lengthlist__44u9_p9_2[] = {
  152800. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152801. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152802. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152803. 7,
  152804. };
  152805. static float _vq_quantthresh__44u9_p9_2[] = {
  152806. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152807. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152808. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152809. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152810. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152811. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152812. };
  152813. static long _vq_quantmap__44u9_p9_2[] = {
  152814. 47, 45, 43, 41, 39, 37, 35, 33,
  152815. 31, 29, 27, 25, 23, 21, 19, 17,
  152816. 15, 13, 11, 9, 7, 5, 3, 1,
  152817. 0, 2, 4, 6, 8, 10, 12, 14,
  152818. 16, 18, 20, 22, 24, 26, 28, 30,
  152819. 32, 34, 36, 38, 40, 42, 44, 46,
  152820. 48,
  152821. };
  152822. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152823. _vq_quantthresh__44u9_p9_2,
  152824. _vq_quantmap__44u9_p9_2,
  152825. 49,
  152826. 49
  152827. };
  152828. static static_codebook _44u9_p9_2 = {
  152829. 1, 49,
  152830. _vq_lengthlist__44u9_p9_2,
  152831. 1, -526909440, 1611661312, 6, 0,
  152832. _vq_quantlist__44u9_p9_2,
  152833. NULL,
  152834. &_vq_auxt__44u9_p9_2,
  152835. NULL,
  152836. 0
  152837. };
  152838. static long _huff_lengthlist__44un1__long[] = {
  152839. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152840. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152841. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152842. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152843. };
  152844. static static_codebook _huff_book__44un1__long = {
  152845. 2, 64,
  152846. _huff_lengthlist__44un1__long,
  152847. 0, 0, 0, 0, 0,
  152848. NULL,
  152849. NULL,
  152850. NULL,
  152851. NULL,
  152852. 0
  152853. };
  152854. static long _vq_quantlist__44un1__p1_0[] = {
  152855. 1,
  152856. 0,
  152857. 2,
  152858. };
  152859. static long _vq_lengthlist__44un1__p1_0[] = {
  152860. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152861. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152862. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152863. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152864. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152865. 12,
  152866. };
  152867. static float _vq_quantthresh__44un1__p1_0[] = {
  152868. -0.5, 0.5,
  152869. };
  152870. static long _vq_quantmap__44un1__p1_0[] = {
  152871. 1, 0, 2,
  152872. };
  152873. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152874. _vq_quantthresh__44un1__p1_0,
  152875. _vq_quantmap__44un1__p1_0,
  152876. 3,
  152877. 3
  152878. };
  152879. static static_codebook _44un1__p1_0 = {
  152880. 4, 81,
  152881. _vq_lengthlist__44un1__p1_0,
  152882. 1, -535822336, 1611661312, 2, 0,
  152883. _vq_quantlist__44un1__p1_0,
  152884. NULL,
  152885. &_vq_auxt__44un1__p1_0,
  152886. NULL,
  152887. 0
  152888. };
  152889. static long _vq_quantlist__44un1__p2_0[] = {
  152890. 1,
  152891. 0,
  152892. 2,
  152893. };
  152894. static long _vq_lengthlist__44un1__p2_0[] = {
  152895. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152896. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152897. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152898. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152899. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152900. 8,
  152901. };
  152902. static float _vq_quantthresh__44un1__p2_0[] = {
  152903. -0.5, 0.5,
  152904. };
  152905. static long _vq_quantmap__44un1__p2_0[] = {
  152906. 1, 0, 2,
  152907. };
  152908. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152909. _vq_quantthresh__44un1__p2_0,
  152910. _vq_quantmap__44un1__p2_0,
  152911. 3,
  152912. 3
  152913. };
  152914. static static_codebook _44un1__p2_0 = {
  152915. 4, 81,
  152916. _vq_lengthlist__44un1__p2_0,
  152917. 1, -535822336, 1611661312, 2, 0,
  152918. _vq_quantlist__44un1__p2_0,
  152919. NULL,
  152920. &_vq_auxt__44un1__p2_0,
  152921. NULL,
  152922. 0
  152923. };
  152924. static long _vq_quantlist__44un1__p3_0[] = {
  152925. 2,
  152926. 1,
  152927. 3,
  152928. 0,
  152929. 4,
  152930. };
  152931. static long _vq_lengthlist__44un1__p3_0[] = {
  152932. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152933. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152934. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152935. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152936. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152937. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152938. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152939. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152940. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152941. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152942. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152943. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152944. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152945. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152946. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152947. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152948. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152949. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152950. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152951. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152952. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152953. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152954. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152955. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152956. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152957. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152958. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152959. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152960. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152961. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152962. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152963. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152964. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152965. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152966. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152967. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152968. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152969. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152970. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152971. 17,
  152972. };
  152973. static float _vq_quantthresh__44un1__p3_0[] = {
  152974. -1.5, -0.5, 0.5, 1.5,
  152975. };
  152976. static long _vq_quantmap__44un1__p3_0[] = {
  152977. 3, 1, 0, 2, 4,
  152978. };
  152979. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152980. _vq_quantthresh__44un1__p3_0,
  152981. _vq_quantmap__44un1__p3_0,
  152982. 5,
  152983. 5
  152984. };
  152985. static static_codebook _44un1__p3_0 = {
  152986. 4, 625,
  152987. _vq_lengthlist__44un1__p3_0,
  152988. 1, -533725184, 1611661312, 3, 0,
  152989. _vq_quantlist__44un1__p3_0,
  152990. NULL,
  152991. &_vq_auxt__44un1__p3_0,
  152992. NULL,
  152993. 0
  152994. };
  152995. static long _vq_quantlist__44un1__p4_0[] = {
  152996. 2,
  152997. 1,
  152998. 3,
  152999. 0,
  153000. 4,
  153001. };
  153002. static long _vq_lengthlist__44un1__p4_0[] = {
  153003. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153004. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153005. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153006. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153007. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153008. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153009. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153010. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153011. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153012. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153013. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153014. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153015. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153016. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153017. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153018. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153019. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153020. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153021. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153022. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153023. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153024. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153025. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153026. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153027. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153028. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153029. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153030. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153031. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153032. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153033. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153034. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153035. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153036. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153037. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153038. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153039. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153040. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153041. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153042. 12,
  153043. };
  153044. static float _vq_quantthresh__44un1__p4_0[] = {
  153045. -1.5, -0.5, 0.5, 1.5,
  153046. };
  153047. static long _vq_quantmap__44un1__p4_0[] = {
  153048. 3, 1, 0, 2, 4,
  153049. };
  153050. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153051. _vq_quantthresh__44un1__p4_0,
  153052. _vq_quantmap__44un1__p4_0,
  153053. 5,
  153054. 5
  153055. };
  153056. static static_codebook _44un1__p4_0 = {
  153057. 4, 625,
  153058. _vq_lengthlist__44un1__p4_0,
  153059. 1, -533725184, 1611661312, 3, 0,
  153060. _vq_quantlist__44un1__p4_0,
  153061. NULL,
  153062. &_vq_auxt__44un1__p4_0,
  153063. NULL,
  153064. 0
  153065. };
  153066. static long _vq_quantlist__44un1__p5_0[] = {
  153067. 4,
  153068. 3,
  153069. 5,
  153070. 2,
  153071. 6,
  153072. 1,
  153073. 7,
  153074. 0,
  153075. 8,
  153076. };
  153077. static long _vq_lengthlist__44un1__p5_0[] = {
  153078. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153079. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153080. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153081. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153082. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153083. 12,
  153084. };
  153085. static float _vq_quantthresh__44un1__p5_0[] = {
  153086. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153087. };
  153088. static long _vq_quantmap__44un1__p5_0[] = {
  153089. 7, 5, 3, 1, 0, 2, 4, 6,
  153090. 8,
  153091. };
  153092. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153093. _vq_quantthresh__44un1__p5_0,
  153094. _vq_quantmap__44un1__p5_0,
  153095. 9,
  153096. 9
  153097. };
  153098. static static_codebook _44un1__p5_0 = {
  153099. 2, 81,
  153100. _vq_lengthlist__44un1__p5_0,
  153101. 1, -531628032, 1611661312, 4, 0,
  153102. _vq_quantlist__44un1__p5_0,
  153103. NULL,
  153104. &_vq_auxt__44un1__p5_0,
  153105. NULL,
  153106. 0
  153107. };
  153108. static long _vq_quantlist__44un1__p6_0[] = {
  153109. 6,
  153110. 5,
  153111. 7,
  153112. 4,
  153113. 8,
  153114. 3,
  153115. 9,
  153116. 2,
  153117. 10,
  153118. 1,
  153119. 11,
  153120. 0,
  153121. 12,
  153122. };
  153123. static long _vq_lengthlist__44un1__p6_0[] = {
  153124. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153125. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153126. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153127. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153128. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153129. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153130. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153131. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153132. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153133. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153134. 16, 0,15,18,18, 0,16, 0, 0,
  153135. };
  153136. static float _vq_quantthresh__44un1__p6_0[] = {
  153137. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153138. 12.5, 17.5, 22.5, 27.5,
  153139. };
  153140. static long _vq_quantmap__44un1__p6_0[] = {
  153141. 11, 9, 7, 5, 3, 1, 0, 2,
  153142. 4, 6, 8, 10, 12,
  153143. };
  153144. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153145. _vq_quantthresh__44un1__p6_0,
  153146. _vq_quantmap__44un1__p6_0,
  153147. 13,
  153148. 13
  153149. };
  153150. static static_codebook _44un1__p6_0 = {
  153151. 2, 169,
  153152. _vq_lengthlist__44un1__p6_0,
  153153. 1, -526516224, 1616117760, 4, 0,
  153154. _vq_quantlist__44un1__p6_0,
  153155. NULL,
  153156. &_vq_auxt__44un1__p6_0,
  153157. NULL,
  153158. 0
  153159. };
  153160. static long _vq_quantlist__44un1__p6_1[] = {
  153161. 2,
  153162. 1,
  153163. 3,
  153164. 0,
  153165. 4,
  153166. };
  153167. static long _vq_lengthlist__44un1__p6_1[] = {
  153168. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153169. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153170. };
  153171. static float _vq_quantthresh__44un1__p6_1[] = {
  153172. -1.5, -0.5, 0.5, 1.5,
  153173. };
  153174. static long _vq_quantmap__44un1__p6_1[] = {
  153175. 3, 1, 0, 2, 4,
  153176. };
  153177. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153178. _vq_quantthresh__44un1__p6_1,
  153179. _vq_quantmap__44un1__p6_1,
  153180. 5,
  153181. 5
  153182. };
  153183. static static_codebook _44un1__p6_1 = {
  153184. 2, 25,
  153185. _vq_lengthlist__44un1__p6_1,
  153186. 1, -533725184, 1611661312, 3, 0,
  153187. _vq_quantlist__44un1__p6_1,
  153188. NULL,
  153189. &_vq_auxt__44un1__p6_1,
  153190. NULL,
  153191. 0
  153192. };
  153193. static long _vq_quantlist__44un1__p7_0[] = {
  153194. 2,
  153195. 1,
  153196. 3,
  153197. 0,
  153198. 4,
  153199. };
  153200. static long _vq_lengthlist__44un1__p7_0[] = {
  153201. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153202. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153203. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153204. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153205. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153206. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153207. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153208. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153209. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153210. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153211. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153212. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153213. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153214. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153215. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153216. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153217. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153218. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153223. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153225. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153240. 10,
  153241. };
  153242. static float _vq_quantthresh__44un1__p7_0[] = {
  153243. -253.5, -84.5, 84.5, 253.5,
  153244. };
  153245. static long _vq_quantmap__44un1__p7_0[] = {
  153246. 3, 1, 0, 2, 4,
  153247. };
  153248. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153249. _vq_quantthresh__44un1__p7_0,
  153250. _vq_quantmap__44un1__p7_0,
  153251. 5,
  153252. 5
  153253. };
  153254. static static_codebook _44un1__p7_0 = {
  153255. 4, 625,
  153256. _vq_lengthlist__44un1__p7_0,
  153257. 1, -518709248, 1626677248, 3, 0,
  153258. _vq_quantlist__44un1__p7_0,
  153259. NULL,
  153260. &_vq_auxt__44un1__p7_0,
  153261. NULL,
  153262. 0
  153263. };
  153264. static long _vq_quantlist__44un1__p7_1[] = {
  153265. 6,
  153266. 5,
  153267. 7,
  153268. 4,
  153269. 8,
  153270. 3,
  153271. 9,
  153272. 2,
  153273. 10,
  153274. 1,
  153275. 11,
  153276. 0,
  153277. 12,
  153278. };
  153279. static long _vq_lengthlist__44un1__p7_1[] = {
  153280. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153281. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153282. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153283. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153284. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153285. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153286. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153287. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153288. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153289. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153290. 12,13,13,12,13,13,14,14,14,
  153291. };
  153292. static float _vq_quantthresh__44un1__p7_1[] = {
  153293. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153294. 32.5, 45.5, 58.5, 71.5,
  153295. };
  153296. static long _vq_quantmap__44un1__p7_1[] = {
  153297. 11, 9, 7, 5, 3, 1, 0, 2,
  153298. 4, 6, 8, 10, 12,
  153299. };
  153300. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153301. _vq_quantthresh__44un1__p7_1,
  153302. _vq_quantmap__44un1__p7_1,
  153303. 13,
  153304. 13
  153305. };
  153306. static static_codebook _44un1__p7_1 = {
  153307. 2, 169,
  153308. _vq_lengthlist__44un1__p7_1,
  153309. 1, -523010048, 1618608128, 4, 0,
  153310. _vq_quantlist__44un1__p7_1,
  153311. NULL,
  153312. &_vq_auxt__44un1__p7_1,
  153313. NULL,
  153314. 0
  153315. };
  153316. static long _vq_quantlist__44un1__p7_2[] = {
  153317. 6,
  153318. 5,
  153319. 7,
  153320. 4,
  153321. 8,
  153322. 3,
  153323. 9,
  153324. 2,
  153325. 10,
  153326. 1,
  153327. 11,
  153328. 0,
  153329. 12,
  153330. };
  153331. static long _vq_lengthlist__44un1__p7_2[] = {
  153332. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153333. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153334. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153335. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153336. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153337. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153338. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153339. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153340. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153341. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153342. 9, 9, 9,10,10,10,10,10,10,
  153343. };
  153344. static float _vq_quantthresh__44un1__p7_2[] = {
  153345. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153346. 2.5, 3.5, 4.5, 5.5,
  153347. };
  153348. static long _vq_quantmap__44un1__p7_2[] = {
  153349. 11, 9, 7, 5, 3, 1, 0, 2,
  153350. 4, 6, 8, 10, 12,
  153351. };
  153352. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153353. _vq_quantthresh__44un1__p7_2,
  153354. _vq_quantmap__44un1__p7_2,
  153355. 13,
  153356. 13
  153357. };
  153358. static static_codebook _44un1__p7_2 = {
  153359. 2, 169,
  153360. _vq_lengthlist__44un1__p7_2,
  153361. 1, -531103744, 1611661312, 4, 0,
  153362. _vq_quantlist__44un1__p7_2,
  153363. NULL,
  153364. &_vq_auxt__44un1__p7_2,
  153365. NULL,
  153366. 0
  153367. };
  153368. static long _huff_lengthlist__44un1__short[] = {
  153369. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153370. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153371. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153372. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153373. };
  153374. static static_codebook _huff_book__44un1__short = {
  153375. 2, 64,
  153376. _huff_lengthlist__44un1__short,
  153377. 0, 0, 0, 0, 0,
  153378. NULL,
  153379. NULL,
  153380. NULL,
  153381. NULL,
  153382. 0
  153383. };
  153384. /*** End of inlined file: res_books_uncoupled.h ***/
  153385. /***** residue backends *********************************************/
  153386. static vorbis_info_residue0 _residue_44_low_un={
  153387. 0,-1, -1, 8,-1,
  153388. {0},
  153389. {-1},
  153390. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153391. { -1, 25, -1, 45, -1, -1, -1}
  153392. };
  153393. static vorbis_info_residue0 _residue_44_mid_un={
  153394. 0,-1, -1, 10,-1,
  153395. /* 0 1 2 3 4 5 6 7 8 9 */
  153396. {0},
  153397. {-1},
  153398. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153399. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153400. };
  153401. static vorbis_info_residue0 _residue_44_hi_un={
  153402. 0,-1, -1, 10,-1,
  153403. /* 0 1 2 3 4 5 6 7 8 9 */
  153404. {0},
  153405. {-1},
  153406. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153407. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153408. };
  153409. /* mapping conventions:
  153410. only one submap (this would change for efficient 5.1 support for example)*/
  153411. /* Four psychoacoustic profiles are used, one for each blocktype */
  153412. static vorbis_info_mapping0 _map_nominal_u[2]={
  153413. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153414. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153415. };
  153416. static static_bookblock _resbook_44u_n1={
  153417. {
  153418. {0},
  153419. {0,0,&_44un1__p1_0},
  153420. {0,0,&_44un1__p2_0},
  153421. {0,0,&_44un1__p3_0},
  153422. {0,0,&_44un1__p4_0},
  153423. {0,0,&_44un1__p5_0},
  153424. {&_44un1__p6_0,&_44un1__p6_1},
  153425. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153426. }
  153427. };
  153428. static static_bookblock _resbook_44u_0={
  153429. {
  153430. {0},
  153431. {0,0,&_44u0__p1_0},
  153432. {0,0,&_44u0__p2_0},
  153433. {0,0,&_44u0__p3_0},
  153434. {0,0,&_44u0__p4_0},
  153435. {0,0,&_44u0__p5_0},
  153436. {&_44u0__p6_0,&_44u0__p6_1},
  153437. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153438. }
  153439. };
  153440. static static_bookblock _resbook_44u_1={
  153441. {
  153442. {0},
  153443. {0,0,&_44u1__p1_0},
  153444. {0,0,&_44u1__p2_0},
  153445. {0,0,&_44u1__p3_0},
  153446. {0,0,&_44u1__p4_0},
  153447. {0,0,&_44u1__p5_0},
  153448. {&_44u1__p6_0,&_44u1__p6_1},
  153449. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153450. }
  153451. };
  153452. static static_bookblock _resbook_44u_2={
  153453. {
  153454. {0},
  153455. {0,0,&_44u2__p1_0},
  153456. {0,0,&_44u2__p2_0},
  153457. {0,0,&_44u2__p3_0},
  153458. {0,0,&_44u2__p4_0},
  153459. {0,0,&_44u2__p5_0},
  153460. {&_44u2__p6_0,&_44u2__p6_1},
  153461. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153462. }
  153463. };
  153464. static static_bookblock _resbook_44u_3={
  153465. {
  153466. {0},
  153467. {0,0,&_44u3__p1_0},
  153468. {0,0,&_44u3__p2_0},
  153469. {0,0,&_44u3__p3_0},
  153470. {0,0,&_44u3__p4_0},
  153471. {0,0,&_44u3__p5_0},
  153472. {&_44u3__p6_0,&_44u3__p6_1},
  153473. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153474. }
  153475. };
  153476. static static_bookblock _resbook_44u_4={
  153477. {
  153478. {0},
  153479. {0,0,&_44u4__p1_0},
  153480. {0,0,&_44u4__p2_0},
  153481. {0,0,&_44u4__p3_0},
  153482. {0,0,&_44u4__p4_0},
  153483. {0,0,&_44u4__p5_0},
  153484. {&_44u4__p6_0,&_44u4__p6_1},
  153485. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153486. }
  153487. };
  153488. static static_bookblock _resbook_44u_5={
  153489. {
  153490. {0},
  153491. {0,0,&_44u5__p1_0},
  153492. {0,0,&_44u5__p2_0},
  153493. {0,0,&_44u5__p3_0},
  153494. {0,0,&_44u5__p4_0},
  153495. {0,0,&_44u5__p5_0},
  153496. {0,0,&_44u5__p6_0},
  153497. {&_44u5__p7_0,&_44u5__p7_1},
  153498. {&_44u5__p8_0,&_44u5__p8_1},
  153499. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153500. }
  153501. };
  153502. static static_bookblock _resbook_44u_6={
  153503. {
  153504. {0},
  153505. {0,0,&_44u6__p1_0},
  153506. {0,0,&_44u6__p2_0},
  153507. {0,0,&_44u6__p3_0},
  153508. {0,0,&_44u6__p4_0},
  153509. {0,0,&_44u6__p5_0},
  153510. {0,0,&_44u6__p6_0},
  153511. {&_44u6__p7_0,&_44u6__p7_1},
  153512. {&_44u6__p8_0,&_44u6__p8_1},
  153513. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153514. }
  153515. };
  153516. static static_bookblock _resbook_44u_7={
  153517. {
  153518. {0},
  153519. {0,0,&_44u7__p1_0},
  153520. {0,0,&_44u7__p2_0},
  153521. {0,0,&_44u7__p3_0},
  153522. {0,0,&_44u7__p4_0},
  153523. {0,0,&_44u7__p5_0},
  153524. {0,0,&_44u7__p6_0},
  153525. {&_44u7__p7_0,&_44u7__p7_1},
  153526. {&_44u7__p8_0,&_44u7__p8_1},
  153527. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153528. }
  153529. };
  153530. static static_bookblock _resbook_44u_8={
  153531. {
  153532. {0},
  153533. {0,0,&_44u8_p1_0},
  153534. {0,0,&_44u8_p2_0},
  153535. {0,0,&_44u8_p3_0},
  153536. {0,0,&_44u8_p4_0},
  153537. {&_44u8_p5_0,&_44u8_p5_1},
  153538. {&_44u8_p6_0,&_44u8_p6_1},
  153539. {&_44u8_p7_0,&_44u8_p7_1},
  153540. {&_44u8_p8_0,&_44u8_p8_1},
  153541. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153542. }
  153543. };
  153544. static static_bookblock _resbook_44u_9={
  153545. {
  153546. {0},
  153547. {0,0,&_44u9_p1_0},
  153548. {0,0,&_44u9_p2_0},
  153549. {0,0,&_44u9_p3_0},
  153550. {0,0,&_44u9_p4_0},
  153551. {&_44u9_p5_0,&_44u9_p5_1},
  153552. {&_44u9_p6_0,&_44u9_p6_1},
  153553. {&_44u9_p7_0,&_44u9_p7_1},
  153554. {&_44u9_p8_0,&_44u9_p8_1},
  153555. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153556. }
  153557. };
  153558. static vorbis_residue_template _res_44u_n1[]={
  153559. {1,0, &_residue_44_low_un,
  153560. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153561. &_resbook_44u_n1,&_resbook_44u_n1},
  153562. {1,0, &_residue_44_low_un,
  153563. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153564. &_resbook_44u_n1,&_resbook_44u_n1}
  153565. };
  153566. static vorbis_residue_template _res_44u_0[]={
  153567. {1,0, &_residue_44_low_un,
  153568. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153569. &_resbook_44u_0,&_resbook_44u_0},
  153570. {1,0, &_residue_44_low_un,
  153571. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153572. &_resbook_44u_0,&_resbook_44u_0}
  153573. };
  153574. static vorbis_residue_template _res_44u_1[]={
  153575. {1,0, &_residue_44_low_un,
  153576. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153577. &_resbook_44u_1,&_resbook_44u_1},
  153578. {1,0, &_residue_44_low_un,
  153579. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153580. &_resbook_44u_1,&_resbook_44u_1}
  153581. };
  153582. static vorbis_residue_template _res_44u_2[]={
  153583. {1,0, &_residue_44_low_un,
  153584. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153585. &_resbook_44u_2,&_resbook_44u_2},
  153586. {1,0, &_residue_44_low_un,
  153587. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153588. &_resbook_44u_2,&_resbook_44u_2}
  153589. };
  153590. static vorbis_residue_template _res_44u_3[]={
  153591. {1,0, &_residue_44_low_un,
  153592. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153593. &_resbook_44u_3,&_resbook_44u_3},
  153594. {1,0, &_residue_44_low_un,
  153595. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153596. &_resbook_44u_3,&_resbook_44u_3}
  153597. };
  153598. static vorbis_residue_template _res_44u_4[]={
  153599. {1,0, &_residue_44_low_un,
  153600. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153601. &_resbook_44u_4,&_resbook_44u_4},
  153602. {1,0, &_residue_44_low_un,
  153603. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153604. &_resbook_44u_4,&_resbook_44u_4}
  153605. };
  153606. static vorbis_residue_template _res_44u_5[]={
  153607. {1,0, &_residue_44_mid_un,
  153608. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153609. &_resbook_44u_5,&_resbook_44u_5},
  153610. {1,0, &_residue_44_mid_un,
  153611. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153612. &_resbook_44u_5,&_resbook_44u_5}
  153613. };
  153614. static vorbis_residue_template _res_44u_6[]={
  153615. {1,0, &_residue_44_mid_un,
  153616. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153617. &_resbook_44u_6,&_resbook_44u_6},
  153618. {1,0, &_residue_44_mid_un,
  153619. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153620. &_resbook_44u_6,&_resbook_44u_6}
  153621. };
  153622. static vorbis_residue_template _res_44u_7[]={
  153623. {1,0, &_residue_44_mid_un,
  153624. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153625. &_resbook_44u_7,&_resbook_44u_7},
  153626. {1,0, &_residue_44_mid_un,
  153627. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153628. &_resbook_44u_7,&_resbook_44u_7}
  153629. };
  153630. static vorbis_residue_template _res_44u_8[]={
  153631. {1,0, &_residue_44_hi_un,
  153632. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153633. &_resbook_44u_8,&_resbook_44u_8},
  153634. {1,0, &_residue_44_hi_un,
  153635. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153636. &_resbook_44u_8,&_resbook_44u_8}
  153637. };
  153638. static vorbis_residue_template _res_44u_9[]={
  153639. {1,0, &_residue_44_hi_un,
  153640. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153641. &_resbook_44u_9,&_resbook_44u_9},
  153642. {1,0, &_residue_44_hi_un,
  153643. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153644. &_resbook_44u_9,&_resbook_44u_9}
  153645. };
  153646. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153647. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153648. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153649. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153650. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153651. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153652. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153653. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153654. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153655. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153656. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153657. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153658. };
  153659. /*** End of inlined file: residue_44u.h ***/
  153660. static double rate_mapping_44_un[12]={
  153661. 32000.,48000.,60000.,70000.,80000.,86000.,
  153662. 96000.,110000.,120000.,140000.,160000.,240001.
  153663. };
  153664. ve_setup_data_template ve_setup_44_uncoupled={
  153665. 11,
  153666. rate_mapping_44_un,
  153667. quality_mapping_44,
  153668. -1,
  153669. 40000,
  153670. 50000,
  153671. blocksize_short_44,
  153672. blocksize_long_44,
  153673. _psy_tone_masteratt_44,
  153674. _psy_tone_0dB,
  153675. _psy_tone_suppress,
  153676. _vp_tonemask_adj_otherblock,
  153677. _vp_tonemask_adj_longblock,
  153678. _vp_tonemask_adj_otherblock,
  153679. _psy_noiseguards_44,
  153680. _psy_noisebias_impulse,
  153681. _psy_noisebias_padding,
  153682. _psy_noisebias_trans,
  153683. _psy_noisebias_long,
  153684. _psy_noise_suppress,
  153685. _psy_compand_44,
  153686. _psy_compand_short_mapping,
  153687. _psy_compand_long_mapping,
  153688. {_noise_start_short_44,_noise_start_long_44},
  153689. {_noise_part_short_44,_noise_part_long_44},
  153690. _noise_thresh_44,
  153691. _psy_ath_floater,
  153692. _psy_ath_abs,
  153693. _psy_lowpass_44,
  153694. _psy_global_44,
  153695. _global_mapping_44,
  153696. NULL,
  153697. _floor_books,
  153698. _floor,
  153699. _floor_short_mapping_44,
  153700. _floor_long_mapping_44,
  153701. _mapres_template_44_uncoupled
  153702. };
  153703. /*** End of inlined file: setup_44u.h ***/
  153704. /*** Start of inlined file: setup_32.h ***/
  153705. static double rate_mapping_32[12]={
  153706. 18000.,28000.,35000.,45000.,56000.,60000.,
  153707. 75000.,90000.,100000.,115000.,150000.,190000.,
  153708. };
  153709. static double rate_mapping_32_un[12]={
  153710. 30000.,42000.,52000.,64000.,72000.,78000.,
  153711. 86000.,92000.,110000.,120000.,140000.,190000.,
  153712. };
  153713. static double _psy_lowpass_32[12]={
  153714. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153715. };
  153716. ve_setup_data_template ve_setup_32_stereo={
  153717. 11,
  153718. rate_mapping_32,
  153719. quality_mapping_44,
  153720. 2,
  153721. 26000,
  153722. 40000,
  153723. blocksize_short_44,
  153724. blocksize_long_44,
  153725. _psy_tone_masteratt_44,
  153726. _psy_tone_0dB,
  153727. _psy_tone_suppress,
  153728. _vp_tonemask_adj_otherblock,
  153729. _vp_tonemask_adj_longblock,
  153730. _vp_tonemask_adj_otherblock,
  153731. _psy_noiseguards_44,
  153732. _psy_noisebias_impulse,
  153733. _psy_noisebias_padding,
  153734. _psy_noisebias_trans,
  153735. _psy_noisebias_long,
  153736. _psy_noise_suppress,
  153737. _psy_compand_44,
  153738. _psy_compand_short_mapping,
  153739. _psy_compand_long_mapping,
  153740. {_noise_start_short_44,_noise_start_long_44},
  153741. {_noise_part_short_44,_noise_part_long_44},
  153742. _noise_thresh_44,
  153743. _psy_ath_floater,
  153744. _psy_ath_abs,
  153745. _psy_lowpass_32,
  153746. _psy_global_44,
  153747. _global_mapping_44,
  153748. _psy_stereo_modes_44,
  153749. _floor_books,
  153750. _floor,
  153751. _floor_short_mapping_44,
  153752. _floor_long_mapping_44,
  153753. _mapres_template_44_stereo
  153754. };
  153755. ve_setup_data_template ve_setup_32_uncoupled={
  153756. 11,
  153757. rate_mapping_32_un,
  153758. quality_mapping_44,
  153759. -1,
  153760. 26000,
  153761. 40000,
  153762. blocksize_short_44,
  153763. blocksize_long_44,
  153764. _psy_tone_masteratt_44,
  153765. _psy_tone_0dB,
  153766. _psy_tone_suppress,
  153767. _vp_tonemask_adj_otherblock,
  153768. _vp_tonemask_adj_longblock,
  153769. _vp_tonemask_adj_otherblock,
  153770. _psy_noiseguards_44,
  153771. _psy_noisebias_impulse,
  153772. _psy_noisebias_padding,
  153773. _psy_noisebias_trans,
  153774. _psy_noisebias_long,
  153775. _psy_noise_suppress,
  153776. _psy_compand_44,
  153777. _psy_compand_short_mapping,
  153778. _psy_compand_long_mapping,
  153779. {_noise_start_short_44,_noise_start_long_44},
  153780. {_noise_part_short_44,_noise_part_long_44},
  153781. _noise_thresh_44,
  153782. _psy_ath_floater,
  153783. _psy_ath_abs,
  153784. _psy_lowpass_32,
  153785. _psy_global_44,
  153786. _global_mapping_44,
  153787. NULL,
  153788. _floor_books,
  153789. _floor,
  153790. _floor_short_mapping_44,
  153791. _floor_long_mapping_44,
  153792. _mapres_template_44_uncoupled
  153793. };
  153794. /*** End of inlined file: setup_32.h ***/
  153795. /*** Start of inlined file: setup_8.h ***/
  153796. /*** Start of inlined file: psych_8.h ***/
  153797. static att3 _psy_tone_masteratt_8[3]={
  153798. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153799. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153800. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153801. };
  153802. static vp_adjblock _vp_tonemask_adj_8[3]={
  153803. /* adjust for mode zero */
  153804. /* 63 125 250 500 1 2 4 8 16 */
  153805. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153806. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153807. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153808. };
  153809. static noise3 _psy_noisebias_8[3]={
  153810. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153811. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153812. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153813. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153814. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153815. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153816. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153817. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153818. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153819. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153820. };
  153821. /* stereo mode by base quality level */
  153822. static adj_stereo _psy_stereo_modes_8[3]={
  153823. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153824. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153825. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153826. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153827. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153828. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153829. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153830. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153831. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153832. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153833. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153834. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153835. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153836. };
  153837. static noiseguard _psy_noiseguards_8[2]={
  153838. {10,10,-1},
  153839. {10,10,-1},
  153840. };
  153841. static compandblock _psy_compand_8[2]={
  153842. {{
  153843. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153844. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153845. 12,12,13,13,14,14,15, 15, /* 23dB */
  153846. 16,16,17,17,17,18,18, 19, /* 31dB */
  153847. 19,19,20,21,22,23,24, 25, /* 39dB */
  153848. }},
  153849. {{
  153850. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153851. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153852. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153853. 9,10,11,12,13,14,15, 16, /* 31dB */
  153854. 17,18,19,20,21,22,23, 24, /* 39dB */
  153855. }},
  153856. };
  153857. static double _psy_lowpass_8[3]={3.,4.,4.};
  153858. static int _noise_start_8[2]={
  153859. 64,64,
  153860. };
  153861. static int _noise_part_8[2]={
  153862. 8,8,
  153863. };
  153864. static int _psy_ath_floater_8[3]={
  153865. -100,-100,-105,
  153866. };
  153867. static int _psy_ath_abs_8[3]={
  153868. -130,-130,-140,
  153869. };
  153870. /*** End of inlined file: psych_8.h ***/
  153871. /*** Start of inlined file: residue_8.h ***/
  153872. /***** residue backends *********************************************/
  153873. static static_bookblock _resbook_8s_0={
  153874. {
  153875. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153876. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153877. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153878. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153879. }
  153880. };
  153881. static static_bookblock _resbook_8s_1={
  153882. {
  153883. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153884. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153885. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153886. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153887. }
  153888. };
  153889. static vorbis_residue_template _res_8s_0[]={
  153890. {2,0, &_residue_44_mid,
  153891. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153892. &_resbook_8s_0,&_resbook_8s_0},
  153893. };
  153894. static vorbis_residue_template _res_8s_1[]={
  153895. {2,0, &_residue_44_mid,
  153896. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153897. &_resbook_8s_1,&_resbook_8s_1},
  153898. };
  153899. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153900. { _map_nominal, _res_8s_0 }, /* 0 */
  153901. { _map_nominal, _res_8s_1 }, /* 1 */
  153902. };
  153903. static static_bookblock _resbook_8u_0={
  153904. {
  153905. {0},
  153906. {0,0,&_8u0__p1_0},
  153907. {0,0,&_8u0__p2_0},
  153908. {0,0,&_8u0__p3_0},
  153909. {0,0,&_8u0__p4_0},
  153910. {0,0,&_8u0__p5_0},
  153911. {&_8u0__p6_0,&_8u0__p6_1},
  153912. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153913. }
  153914. };
  153915. static static_bookblock _resbook_8u_1={
  153916. {
  153917. {0},
  153918. {0,0,&_8u1__p1_0},
  153919. {0,0,&_8u1__p2_0},
  153920. {0,0,&_8u1__p3_0},
  153921. {0,0,&_8u1__p4_0},
  153922. {0,0,&_8u1__p5_0},
  153923. {0,0,&_8u1__p6_0},
  153924. {&_8u1__p7_0,&_8u1__p7_1},
  153925. {&_8u1__p8_0,&_8u1__p8_1},
  153926. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153927. }
  153928. };
  153929. static vorbis_residue_template _res_8u_0[]={
  153930. {1,0, &_residue_44_low_un,
  153931. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153932. &_resbook_8u_0,&_resbook_8u_0},
  153933. };
  153934. static vorbis_residue_template _res_8u_1[]={
  153935. {1,0, &_residue_44_mid_un,
  153936. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153937. &_resbook_8u_1,&_resbook_8u_1},
  153938. };
  153939. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153940. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153941. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153942. };
  153943. /*** End of inlined file: residue_8.h ***/
  153944. static int blocksize_8[2]={
  153945. 512,512
  153946. };
  153947. static int _floor_mapping_8[2]={
  153948. 6,6,
  153949. };
  153950. static double rate_mapping_8[3]={
  153951. 6000.,9000.,32000.,
  153952. };
  153953. static double rate_mapping_8_uncoupled[3]={
  153954. 8000.,14000.,42000.,
  153955. };
  153956. static double quality_mapping_8[3]={
  153957. -.1,.0,1.
  153958. };
  153959. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153960. static double _global_mapping_8[3]={ 1., 2., 3. };
  153961. ve_setup_data_template ve_setup_8_stereo={
  153962. 2,
  153963. rate_mapping_8,
  153964. quality_mapping_8,
  153965. 2,
  153966. 8000,
  153967. 9000,
  153968. blocksize_8,
  153969. blocksize_8,
  153970. _psy_tone_masteratt_8,
  153971. _psy_tone_0dB,
  153972. _psy_tone_suppress,
  153973. _vp_tonemask_adj_8,
  153974. NULL,
  153975. _vp_tonemask_adj_8,
  153976. _psy_noiseguards_8,
  153977. _psy_noisebias_8,
  153978. _psy_noisebias_8,
  153979. NULL,
  153980. NULL,
  153981. _psy_noise_suppress,
  153982. _psy_compand_8,
  153983. _psy_compand_8_mapping,
  153984. NULL,
  153985. {_noise_start_8,_noise_start_8},
  153986. {_noise_part_8,_noise_part_8},
  153987. _noise_thresh_5only,
  153988. _psy_ath_floater_8,
  153989. _psy_ath_abs_8,
  153990. _psy_lowpass_8,
  153991. _psy_global_44,
  153992. _global_mapping_8,
  153993. _psy_stereo_modes_8,
  153994. _floor_books,
  153995. _floor,
  153996. _floor_mapping_8,
  153997. NULL,
  153998. _mapres_template_8_stereo
  153999. };
  154000. ve_setup_data_template ve_setup_8_uncoupled={
  154001. 2,
  154002. rate_mapping_8_uncoupled,
  154003. quality_mapping_8,
  154004. -1,
  154005. 8000,
  154006. 9000,
  154007. blocksize_8,
  154008. blocksize_8,
  154009. _psy_tone_masteratt_8,
  154010. _psy_tone_0dB,
  154011. _psy_tone_suppress,
  154012. _vp_tonemask_adj_8,
  154013. NULL,
  154014. _vp_tonemask_adj_8,
  154015. _psy_noiseguards_8,
  154016. _psy_noisebias_8,
  154017. _psy_noisebias_8,
  154018. NULL,
  154019. NULL,
  154020. _psy_noise_suppress,
  154021. _psy_compand_8,
  154022. _psy_compand_8_mapping,
  154023. NULL,
  154024. {_noise_start_8,_noise_start_8},
  154025. {_noise_part_8,_noise_part_8},
  154026. _noise_thresh_5only,
  154027. _psy_ath_floater_8,
  154028. _psy_ath_abs_8,
  154029. _psy_lowpass_8,
  154030. _psy_global_44,
  154031. _global_mapping_8,
  154032. _psy_stereo_modes_8,
  154033. _floor_books,
  154034. _floor,
  154035. _floor_mapping_8,
  154036. NULL,
  154037. _mapres_template_8_uncoupled
  154038. };
  154039. /*** End of inlined file: setup_8.h ***/
  154040. /*** Start of inlined file: setup_11.h ***/
  154041. /*** Start of inlined file: psych_11.h ***/
  154042. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154043. static att3 _psy_tone_masteratt_11[3]={
  154044. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154045. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154046. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154047. };
  154048. static vp_adjblock _vp_tonemask_adj_11[3]={
  154049. /* adjust for mode zero */
  154050. /* 63 125 250 500 1 2 4 8 16 */
  154051. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154052. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154053. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154054. };
  154055. static noise3 _psy_noisebias_11[3]={
  154056. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154057. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154058. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154059. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154060. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154061. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154062. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154063. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154064. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154065. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154066. };
  154067. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154068. /*** End of inlined file: psych_11.h ***/
  154069. static int blocksize_11[2]={
  154070. 512,512
  154071. };
  154072. static int _floor_mapping_11[2]={
  154073. 6,6,
  154074. };
  154075. static double rate_mapping_11[3]={
  154076. 8000.,13000.,44000.,
  154077. };
  154078. static double rate_mapping_11_uncoupled[3]={
  154079. 12000.,20000.,50000.,
  154080. };
  154081. static double quality_mapping_11[3]={
  154082. -.1,.0,1.
  154083. };
  154084. ve_setup_data_template ve_setup_11_stereo={
  154085. 2,
  154086. rate_mapping_11,
  154087. quality_mapping_11,
  154088. 2,
  154089. 9000,
  154090. 15000,
  154091. blocksize_11,
  154092. blocksize_11,
  154093. _psy_tone_masteratt_11,
  154094. _psy_tone_0dB,
  154095. _psy_tone_suppress,
  154096. _vp_tonemask_adj_11,
  154097. NULL,
  154098. _vp_tonemask_adj_11,
  154099. _psy_noiseguards_8,
  154100. _psy_noisebias_11,
  154101. _psy_noisebias_11,
  154102. NULL,
  154103. NULL,
  154104. _psy_noise_suppress,
  154105. _psy_compand_8,
  154106. _psy_compand_8_mapping,
  154107. NULL,
  154108. {_noise_start_8,_noise_start_8},
  154109. {_noise_part_8,_noise_part_8},
  154110. _noise_thresh_11,
  154111. _psy_ath_floater_8,
  154112. _psy_ath_abs_8,
  154113. _psy_lowpass_11,
  154114. _psy_global_44,
  154115. _global_mapping_8,
  154116. _psy_stereo_modes_8,
  154117. _floor_books,
  154118. _floor,
  154119. _floor_mapping_11,
  154120. NULL,
  154121. _mapres_template_8_stereo
  154122. };
  154123. ve_setup_data_template ve_setup_11_uncoupled={
  154124. 2,
  154125. rate_mapping_11_uncoupled,
  154126. quality_mapping_11,
  154127. -1,
  154128. 9000,
  154129. 15000,
  154130. blocksize_11,
  154131. blocksize_11,
  154132. _psy_tone_masteratt_11,
  154133. _psy_tone_0dB,
  154134. _psy_tone_suppress,
  154135. _vp_tonemask_adj_11,
  154136. NULL,
  154137. _vp_tonemask_adj_11,
  154138. _psy_noiseguards_8,
  154139. _psy_noisebias_11,
  154140. _psy_noisebias_11,
  154141. NULL,
  154142. NULL,
  154143. _psy_noise_suppress,
  154144. _psy_compand_8,
  154145. _psy_compand_8_mapping,
  154146. NULL,
  154147. {_noise_start_8,_noise_start_8},
  154148. {_noise_part_8,_noise_part_8},
  154149. _noise_thresh_11,
  154150. _psy_ath_floater_8,
  154151. _psy_ath_abs_8,
  154152. _psy_lowpass_11,
  154153. _psy_global_44,
  154154. _global_mapping_8,
  154155. _psy_stereo_modes_8,
  154156. _floor_books,
  154157. _floor,
  154158. _floor_mapping_11,
  154159. NULL,
  154160. _mapres_template_8_uncoupled
  154161. };
  154162. /*** End of inlined file: setup_11.h ***/
  154163. /*** Start of inlined file: setup_16.h ***/
  154164. /*** Start of inlined file: psych_16.h ***/
  154165. /* stereo mode by base quality level */
  154166. static adj_stereo _psy_stereo_modes_16[4]={
  154167. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154168. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154169. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154170. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154171. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154172. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154173. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154174. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154175. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154176. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154177. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154178. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154179. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154180. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154181. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154182. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154183. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154184. };
  154185. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154186. static att3 _psy_tone_masteratt_16[4]={
  154187. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154188. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154189. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154190. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154191. };
  154192. static vp_adjblock _vp_tonemask_adj_16[4]={
  154193. /* adjust for mode zero */
  154194. /* 63 125 250 500 1 2 4 8 16 */
  154195. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154196. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154197. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154198. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154199. };
  154200. static noise3 _psy_noisebias_16_short[4]={
  154201. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154202. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154203. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154204. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154205. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154206. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154207. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154208. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154209. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154210. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154211. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154212. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154213. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154214. };
  154215. static noise3 _psy_noisebias_16_impulse[4]={
  154216. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154217. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154218. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154219. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154220. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154221. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154222. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154223. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154224. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154225. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154226. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154227. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154228. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154229. };
  154230. static noise3 _psy_noisebias_16[4]={
  154231. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154232. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154233. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154234. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154235. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154236. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154237. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154238. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154239. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154240. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154241. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154242. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154243. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154244. };
  154245. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154246. static int _noise_start_16[3]={ 256,256,9999 };
  154247. static int _noise_part_16[4]={ 8,8,8,8 };
  154248. static int _psy_ath_floater_16[4]={
  154249. -100,-100,-100,-105,
  154250. };
  154251. static int _psy_ath_abs_16[4]={
  154252. -130,-130,-130,-140,
  154253. };
  154254. /*** End of inlined file: psych_16.h ***/
  154255. /*** Start of inlined file: residue_16.h ***/
  154256. /***** residue backends *********************************************/
  154257. static static_bookblock _resbook_16s_0={
  154258. {
  154259. {0},
  154260. {0,0,&_16c0_s_p1_0},
  154261. {0,0,&_16c0_s_p2_0},
  154262. {0,0,&_16c0_s_p3_0},
  154263. {0,0,&_16c0_s_p4_0},
  154264. {0,0,&_16c0_s_p5_0},
  154265. {0,0,&_16c0_s_p6_0},
  154266. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154267. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154268. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154269. }
  154270. };
  154271. static static_bookblock _resbook_16s_1={
  154272. {
  154273. {0},
  154274. {0,0,&_16c1_s_p1_0},
  154275. {0,0,&_16c1_s_p2_0},
  154276. {0,0,&_16c1_s_p3_0},
  154277. {0,0,&_16c1_s_p4_0},
  154278. {0,0,&_16c1_s_p5_0},
  154279. {0,0,&_16c1_s_p6_0},
  154280. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154281. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154282. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154283. }
  154284. };
  154285. static static_bookblock _resbook_16s_2={
  154286. {
  154287. {0},
  154288. {0,0,&_16c2_s_p1_0},
  154289. {0,0,&_16c2_s_p2_0},
  154290. {0,0,&_16c2_s_p3_0},
  154291. {0,0,&_16c2_s_p4_0},
  154292. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154293. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154294. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154295. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154296. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154297. }
  154298. };
  154299. static vorbis_residue_template _res_16s_0[]={
  154300. {2,0, &_residue_44_mid,
  154301. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154302. &_resbook_16s_0,&_resbook_16s_0},
  154303. };
  154304. static vorbis_residue_template _res_16s_1[]={
  154305. {2,0, &_residue_44_mid,
  154306. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154307. &_resbook_16s_1,&_resbook_16s_1},
  154308. {2,0, &_residue_44_mid,
  154309. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154310. &_resbook_16s_1,&_resbook_16s_1}
  154311. };
  154312. static vorbis_residue_template _res_16s_2[]={
  154313. {2,0, &_residue_44_high,
  154314. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154315. &_resbook_16s_2,&_resbook_16s_2},
  154316. {2,0, &_residue_44_high,
  154317. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154318. &_resbook_16s_2,&_resbook_16s_2}
  154319. };
  154320. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154321. { _map_nominal, _res_16s_0 }, /* 0 */
  154322. { _map_nominal, _res_16s_1 }, /* 1 */
  154323. { _map_nominal, _res_16s_2 }, /* 2 */
  154324. };
  154325. static static_bookblock _resbook_16u_0={
  154326. {
  154327. {0},
  154328. {0,0,&_16u0__p1_0},
  154329. {0,0,&_16u0__p2_0},
  154330. {0,0,&_16u0__p3_0},
  154331. {0,0,&_16u0__p4_0},
  154332. {0,0,&_16u0__p5_0},
  154333. {&_16u0__p6_0,&_16u0__p6_1},
  154334. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154335. }
  154336. };
  154337. static static_bookblock _resbook_16u_1={
  154338. {
  154339. {0},
  154340. {0,0,&_16u1__p1_0},
  154341. {0,0,&_16u1__p2_0},
  154342. {0,0,&_16u1__p3_0},
  154343. {0,0,&_16u1__p4_0},
  154344. {0,0,&_16u1__p5_0},
  154345. {0,0,&_16u1__p6_0},
  154346. {&_16u1__p7_0,&_16u1__p7_1},
  154347. {&_16u1__p8_0,&_16u1__p8_1},
  154348. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154349. }
  154350. };
  154351. static static_bookblock _resbook_16u_2={
  154352. {
  154353. {0},
  154354. {0,0,&_16u2_p1_0},
  154355. {0,0,&_16u2_p2_0},
  154356. {0,0,&_16u2_p3_0},
  154357. {0,0,&_16u2_p4_0},
  154358. {&_16u2_p5_0,&_16u2_p5_1},
  154359. {&_16u2_p6_0,&_16u2_p6_1},
  154360. {&_16u2_p7_0,&_16u2_p7_1},
  154361. {&_16u2_p8_0,&_16u2_p8_1},
  154362. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154363. }
  154364. };
  154365. static vorbis_residue_template _res_16u_0[]={
  154366. {1,0, &_residue_44_low_un,
  154367. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154368. &_resbook_16u_0,&_resbook_16u_0},
  154369. };
  154370. static vorbis_residue_template _res_16u_1[]={
  154371. {1,0, &_residue_44_mid_un,
  154372. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154373. &_resbook_16u_1,&_resbook_16u_1},
  154374. {1,0, &_residue_44_mid_un,
  154375. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154376. &_resbook_16u_1,&_resbook_16u_1}
  154377. };
  154378. static vorbis_residue_template _res_16u_2[]={
  154379. {1,0, &_residue_44_hi_un,
  154380. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154381. &_resbook_16u_2,&_resbook_16u_2},
  154382. {1,0, &_residue_44_hi_un,
  154383. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154384. &_resbook_16u_2,&_resbook_16u_2}
  154385. };
  154386. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154387. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154388. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154389. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154390. };
  154391. /*** End of inlined file: residue_16.h ***/
  154392. static int blocksize_16_short[3]={
  154393. 1024,512,512
  154394. };
  154395. static int blocksize_16_long[3]={
  154396. 1024,1024,1024
  154397. };
  154398. static int _floor_mapping_16_short[3]={
  154399. 9,3,3
  154400. };
  154401. static int _floor_mapping_16[3]={
  154402. 9,9,9
  154403. };
  154404. static double rate_mapping_16[4]={
  154405. 12000.,20000.,44000.,86000.
  154406. };
  154407. static double rate_mapping_16_uncoupled[4]={
  154408. 16000.,28000.,64000.,100000.
  154409. };
  154410. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154411. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154412. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154413. ve_setup_data_template ve_setup_16_stereo={
  154414. 3,
  154415. rate_mapping_16,
  154416. quality_mapping_16,
  154417. 2,
  154418. 15000,
  154419. 19000,
  154420. blocksize_16_short,
  154421. blocksize_16_long,
  154422. _psy_tone_masteratt_16,
  154423. _psy_tone_0dB,
  154424. _psy_tone_suppress,
  154425. _vp_tonemask_adj_16,
  154426. _vp_tonemask_adj_16,
  154427. _vp_tonemask_adj_16,
  154428. _psy_noiseguards_8,
  154429. _psy_noisebias_16_impulse,
  154430. _psy_noisebias_16_short,
  154431. _psy_noisebias_16_short,
  154432. _psy_noisebias_16,
  154433. _psy_noise_suppress,
  154434. _psy_compand_8,
  154435. _psy_compand_16_mapping,
  154436. _psy_compand_16_mapping,
  154437. {_noise_start_16,_noise_start_16},
  154438. { _noise_part_16, _noise_part_16},
  154439. _noise_thresh_16,
  154440. _psy_ath_floater_16,
  154441. _psy_ath_abs_16,
  154442. _psy_lowpass_16,
  154443. _psy_global_44,
  154444. _global_mapping_16,
  154445. _psy_stereo_modes_16,
  154446. _floor_books,
  154447. _floor,
  154448. _floor_mapping_16_short,
  154449. _floor_mapping_16,
  154450. _mapres_template_16_stereo
  154451. };
  154452. ve_setup_data_template ve_setup_16_uncoupled={
  154453. 3,
  154454. rate_mapping_16_uncoupled,
  154455. quality_mapping_16,
  154456. -1,
  154457. 15000,
  154458. 19000,
  154459. blocksize_16_short,
  154460. blocksize_16_long,
  154461. _psy_tone_masteratt_16,
  154462. _psy_tone_0dB,
  154463. _psy_tone_suppress,
  154464. _vp_tonemask_adj_16,
  154465. _vp_tonemask_adj_16,
  154466. _vp_tonemask_adj_16,
  154467. _psy_noiseguards_8,
  154468. _psy_noisebias_16_impulse,
  154469. _psy_noisebias_16_short,
  154470. _psy_noisebias_16_short,
  154471. _psy_noisebias_16,
  154472. _psy_noise_suppress,
  154473. _psy_compand_8,
  154474. _psy_compand_16_mapping,
  154475. _psy_compand_16_mapping,
  154476. {_noise_start_16,_noise_start_16},
  154477. { _noise_part_16, _noise_part_16},
  154478. _noise_thresh_16,
  154479. _psy_ath_floater_16,
  154480. _psy_ath_abs_16,
  154481. _psy_lowpass_16,
  154482. _psy_global_44,
  154483. _global_mapping_16,
  154484. _psy_stereo_modes_16,
  154485. _floor_books,
  154486. _floor,
  154487. _floor_mapping_16_short,
  154488. _floor_mapping_16,
  154489. _mapres_template_16_uncoupled
  154490. };
  154491. /*** End of inlined file: setup_16.h ***/
  154492. /*** Start of inlined file: setup_22.h ***/
  154493. static double rate_mapping_22[4]={
  154494. 15000.,20000.,44000.,86000.
  154495. };
  154496. static double rate_mapping_22_uncoupled[4]={
  154497. 16000.,28000.,50000.,90000.
  154498. };
  154499. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154500. ve_setup_data_template ve_setup_22_stereo={
  154501. 3,
  154502. rate_mapping_22,
  154503. quality_mapping_16,
  154504. 2,
  154505. 19000,
  154506. 26000,
  154507. blocksize_16_short,
  154508. blocksize_16_long,
  154509. _psy_tone_masteratt_16,
  154510. _psy_tone_0dB,
  154511. _psy_tone_suppress,
  154512. _vp_tonemask_adj_16,
  154513. _vp_tonemask_adj_16,
  154514. _vp_tonemask_adj_16,
  154515. _psy_noiseguards_8,
  154516. _psy_noisebias_16_impulse,
  154517. _psy_noisebias_16_short,
  154518. _psy_noisebias_16_short,
  154519. _psy_noisebias_16,
  154520. _psy_noise_suppress,
  154521. _psy_compand_8,
  154522. _psy_compand_8_mapping,
  154523. _psy_compand_8_mapping,
  154524. {_noise_start_16,_noise_start_16},
  154525. { _noise_part_16, _noise_part_16},
  154526. _noise_thresh_16,
  154527. _psy_ath_floater_16,
  154528. _psy_ath_abs_16,
  154529. _psy_lowpass_22,
  154530. _psy_global_44,
  154531. _global_mapping_16,
  154532. _psy_stereo_modes_16,
  154533. _floor_books,
  154534. _floor,
  154535. _floor_mapping_16_short,
  154536. _floor_mapping_16,
  154537. _mapres_template_16_stereo
  154538. };
  154539. ve_setup_data_template ve_setup_22_uncoupled={
  154540. 3,
  154541. rate_mapping_22_uncoupled,
  154542. quality_mapping_16,
  154543. -1,
  154544. 19000,
  154545. 26000,
  154546. blocksize_16_short,
  154547. blocksize_16_long,
  154548. _psy_tone_masteratt_16,
  154549. _psy_tone_0dB,
  154550. _psy_tone_suppress,
  154551. _vp_tonemask_adj_16,
  154552. _vp_tonemask_adj_16,
  154553. _vp_tonemask_adj_16,
  154554. _psy_noiseguards_8,
  154555. _psy_noisebias_16_impulse,
  154556. _psy_noisebias_16_short,
  154557. _psy_noisebias_16_short,
  154558. _psy_noisebias_16,
  154559. _psy_noise_suppress,
  154560. _psy_compand_8,
  154561. _psy_compand_8_mapping,
  154562. _psy_compand_8_mapping,
  154563. {_noise_start_16,_noise_start_16},
  154564. { _noise_part_16, _noise_part_16},
  154565. _noise_thresh_16,
  154566. _psy_ath_floater_16,
  154567. _psy_ath_abs_16,
  154568. _psy_lowpass_22,
  154569. _psy_global_44,
  154570. _global_mapping_16,
  154571. _psy_stereo_modes_16,
  154572. _floor_books,
  154573. _floor,
  154574. _floor_mapping_16_short,
  154575. _floor_mapping_16,
  154576. _mapres_template_16_uncoupled
  154577. };
  154578. /*** End of inlined file: setup_22.h ***/
  154579. /*** Start of inlined file: setup_X.h ***/
  154580. static double rate_mapping_X[12]={
  154581. -1.,-1.,-1.,-1.,-1.,-1.,
  154582. -1.,-1.,-1.,-1.,-1.,-1.
  154583. };
  154584. ve_setup_data_template ve_setup_X_stereo={
  154585. 11,
  154586. rate_mapping_X,
  154587. quality_mapping_44,
  154588. 2,
  154589. 50000,
  154590. 200000,
  154591. blocksize_short_44,
  154592. blocksize_long_44,
  154593. _psy_tone_masteratt_44,
  154594. _psy_tone_0dB,
  154595. _psy_tone_suppress,
  154596. _vp_tonemask_adj_otherblock,
  154597. _vp_tonemask_adj_longblock,
  154598. _vp_tonemask_adj_otherblock,
  154599. _psy_noiseguards_44,
  154600. _psy_noisebias_impulse,
  154601. _psy_noisebias_padding,
  154602. _psy_noisebias_trans,
  154603. _psy_noisebias_long,
  154604. _psy_noise_suppress,
  154605. _psy_compand_44,
  154606. _psy_compand_short_mapping,
  154607. _psy_compand_long_mapping,
  154608. {_noise_start_short_44,_noise_start_long_44},
  154609. {_noise_part_short_44,_noise_part_long_44},
  154610. _noise_thresh_44,
  154611. _psy_ath_floater,
  154612. _psy_ath_abs,
  154613. _psy_lowpass_44,
  154614. _psy_global_44,
  154615. _global_mapping_44,
  154616. _psy_stereo_modes_44,
  154617. _floor_books,
  154618. _floor,
  154619. _floor_short_mapping_44,
  154620. _floor_long_mapping_44,
  154621. _mapres_template_44_stereo
  154622. };
  154623. ve_setup_data_template ve_setup_X_uncoupled={
  154624. 11,
  154625. rate_mapping_X,
  154626. quality_mapping_44,
  154627. -1,
  154628. 50000,
  154629. 200000,
  154630. blocksize_short_44,
  154631. blocksize_long_44,
  154632. _psy_tone_masteratt_44,
  154633. _psy_tone_0dB,
  154634. _psy_tone_suppress,
  154635. _vp_tonemask_adj_otherblock,
  154636. _vp_tonemask_adj_longblock,
  154637. _vp_tonemask_adj_otherblock,
  154638. _psy_noiseguards_44,
  154639. _psy_noisebias_impulse,
  154640. _psy_noisebias_padding,
  154641. _psy_noisebias_trans,
  154642. _psy_noisebias_long,
  154643. _psy_noise_suppress,
  154644. _psy_compand_44,
  154645. _psy_compand_short_mapping,
  154646. _psy_compand_long_mapping,
  154647. {_noise_start_short_44,_noise_start_long_44},
  154648. {_noise_part_short_44,_noise_part_long_44},
  154649. _noise_thresh_44,
  154650. _psy_ath_floater,
  154651. _psy_ath_abs,
  154652. _psy_lowpass_44,
  154653. _psy_global_44,
  154654. _global_mapping_44,
  154655. NULL,
  154656. _floor_books,
  154657. _floor,
  154658. _floor_short_mapping_44,
  154659. _floor_long_mapping_44,
  154660. _mapres_template_44_uncoupled
  154661. };
  154662. ve_setup_data_template ve_setup_XX_stereo={
  154663. 2,
  154664. rate_mapping_X,
  154665. quality_mapping_8,
  154666. 2,
  154667. 0,
  154668. 8000,
  154669. blocksize_8,
  154670. blocksize_8,
  154671. _psy_tone_masteratt_8,
  154672. _psy_tone_0dB,
  154673. _psy_tone_suppress,
  154674. _vp_tonemask_adj_8,
  154675. NULL,
  154676. _vp_tonemask_adj_8,
  154677. _psy_noiseguards_8,
  154678. _psy_noisebias_8,
  154679. _psy_noisebias_8,
  154680. NULL,
  154681. NULL,
  154682. _psy_noise_suppress,
  154683. _psy_compand_8,
  154684. _psy_compand_8_mapping,
  154685. NULL,
  154686. {_noise_start_8,_noise_start_8},
  154687. {_noise_part_8,_noise_part_8},
  154688. _noise_thresh_5only,
  154689. _psy_ath_floater_8,
  154690. _psy_ath_abs_8,
  154691. _psy_lowpass_8,
  154692. _psy_global_44,
  154693. _global_mapping_8,
  154694. _psy_stereo_modes_8,
  154695. _floor_books,
  154696. _floor,
  154697. _floor_mapping_8,
  154698. NULL,
  154699. _mapres_template_8_stereo
  154700. };
  154701. ve_setup_data_template ve_setup_XX_uncoupled={
  154702. 2,
  154703. rate_mapping_X,
  154704. quality_mapping_8,
  154705. -1,
  154706. 0,
  154707. 8000,
  154708. blocksize_8,
  154709. blocksize_8,
  154710. _psy_tone_masteratt_8,
  154711. _psy_tone_0dB,
  154712. _psy_tone_suppress,
  154713. _vp_tonemask_adj_8,
  154714. NULL,
  154715. _vp_tonemask_adj_8,
  154716. _psy_noiseguards_8,
  154717. _psy_noisebias_8,
  154718. _psy_noisebias_8,
  154719. NULL,
  154720. NULL,
  154721. _psy_noise_suppress,
  154722. _psy_compand_8,
  154723. _psy_compand_8_mapping,
  154724. NULL,
  154725. {_noise_start_8,_noise_start_8},
  154726. {_noise_part_8,_noise_part_8},
  154727. _noise_thresh_5only,
  154728. _psy_ath_floater_8,
  154729. _psy_ath_abs_8,
  154730. _psy_lowpass_8,
  154731. _psy_global_44,
  154732. _global_mapping_8,
  154733. _psy_stereo_modes_8,
  154734. _floor_books,
  154735. _floor,
  154736. _floor_mapping_8,
  154737. NULL,
  154738. _mapres_template_8_uncoupled
  154739. };
  154740. /*** End of inlined file: setup_X.h ***/
  154741. static ve_setup_data_template *setup_list[]={
  154742. &ve_setup_44_stereo,
  154743. &ve_setup_44_uncoupled,
  154744. &ve_setup_32_stereo,
  154745. &ve_setup_32_uncoupled,
  154746. &ve_setup_22_stereo,
  154747. &ve_setup_22_uncoupled,
  154748. &ve_setup_16_stereo,
  154749. &ve_setup_16_uncoupled,
  154750. &ve_setup_11_stereo,
  154751. &ve_setup_11_uncoupled,
  154752. &ve_setup_8_stereo,
  154753. &ve_setup_8_uncoupled,
  154754. &ve_setup_X_stereo,
  154755. &ve_setup_X_uncoupled,
  154756. &ve_setup_XX_stereo,
  154757. &ve_setup_XX_uncoupled,
  154758. 0
  154759. };
  154760. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154761. if(vi && vi->codec_setup){
  154762. vi->version=0;
  154763. vi->channels=ch;
  154764. vi->rate=rate;
  154765. return(0);
  154766. }
  154767. return(OV_EINVAL);
  154768. }
  154769. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154770. static_codebook ***books,
  154771. vorbis_info_floor1 *in,
  154772. int *x){
  154773. int i,k,is=s;
  154774. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154775. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154776. memcpy(f,in+x[is],sizeof(*f));
  154777. /* fill in the lowpass field, even if it's temporary */
  154778. f->n=ci->blocksizes[block]>>1;
  154779. /* books */
  154780. {
  154781. int partitions=f->partitions;
  154782. int maxclass=-1;
  154783. int maxbook=-1;
  154784. for(i=0;i<partitions;i++)
  154785. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154786. for(i=0;i<=maxclass;i++){
  154787. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154788. f->class_book[i]+=ci->books;
  154789. for(k=0;k<(1<<f->class_subs[i]);k++){
  154790. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154791. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154792. }
  154793. }
  154794. for(i=0;i<=maxbook;i++)
  154795. ci->book_param[ci->books++]=books[x[is]][i];
  154796. }
  154797. /* for now, we're only using floor 1 */
  154798. ci->floor_type[ci->floors]=1;
  154799. ci->floor_param[ci->floors]=f;
  154800. ci->floors++;
  154801. return;
  154802. }
  154803. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154804. vorbis_info_psy_global *in,
  154805. double *x){
  154806. int i,is=s;
  154807. double ds=s-is;
  154808. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154809. vorbis_info_psy_global *g=&ci->psy_g_param;
  154810. memcpy(g,in+(int)x[is],sizeof(*g));
  154811. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154812. is=(int)ds;
  154813. ds-=is;
  154814. if(ds==0 && is>0){
  154815. is--;
  154816. ds=1.;
  154817. }
  154818. /* interpolate the trigger threshholds */
  154819. for(i=0;i<4;i++){
  154820. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154821. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154822. }
  154823. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154824. return;
  154825. }
  154826. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154827. highlevel_encode_setup *hi,
  154828. adj_stereo *p){
  154829. float s=hi->stereo_point_setting;
  154830. int i,is=s;
  154831. double ds=s-is;
  154832. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154833. vorbis_info_psy_global *g=&ci->psy_g_param;
  154834. if(p){
  154835. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154836. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154837. if(hi->managed){
  154838. /* interpolate the kHz threshholds */
  154839. for(i=0;i<PACKETBLOBS;i++){
  154840. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154841. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154842. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154843. g->coupling_pkHz[i]=kHz;
  154844. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154845. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154846. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154847. }
  154848. }else{
  154849. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154850. for(i=0;i<PACKETBLOBS;i++){
  154851. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154852. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154853. g->coupling_pkHz[i]=kHz;
  154854. }
  154855. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154856. for(i=0;i<PACKETBLOBS;i++){
  154857. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154858. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154859. }
  154860. }
  154861. }else{
  154862. for(i=0;i<PACKETBLOBS;i++){
  154863. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154864. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154865. }
  154866. }
  154867. return;
  154868. }
  154869. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154870. int *nn_start,
  154871. int *nn_partition,
  154872. double *nn_thresh,
  154873. int block){
  154874. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154875. vorbis_info_psy *p=ci->psy_param[block];
  154876. highlevel_encode_setup *hi=&ci->hi;
  154877. int is=s;
  154878. if(block>=ci->psys)
  154879. ci->psys=block+1;
  154880. if(!p){
  154881. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154882. ci->psy_param[block]=p;
  154883. }
  154884. memcpy(p,&_psy_info_template,sizeof(*p));
  154885. p->blockflag=block>>1;
  154886. if(hi->noise_normalize_p){
  154887. p->normal_channel_p=1;
  154888. p->normal_point_p=1;
  154889. p->normal_start=nn_start[is];
  154890. p->normal_partition=nn_partition[is];
  154891. p->normal_thresh=nn_thresh[is];
  154892. }
  154893. return;
  154894. }
  154895. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154896. att3 *att,
  154897. int *max,
  154898. vp_adjblock *in){
  154899. int i,is=s;
  154900. double ds=s-is;
  154901. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154902. vorbis_info_psy *p=ci->psy_param[block];
  154903. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154904. filling the values in here */
  154905. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154906. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154907. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154908. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154909. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154910. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154911. for(i=0;i<P_BANDS;i++)
  154912. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154913. return;
  154914. }
  154915. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154916. compandblock *in, double *x){
  154917. int i,is=s;
  154918. double ds=s-is;
  154919. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154920. vorbis_info_psy *p=ci->psy_param[block];
  154921. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154922. is=(int)ds;
  154923. ds-=is;
  154924. if(ds==0 && is>0){
  154925. is--;
  154926. ds=1.;
  154927. }
  154928. /* interpolate the compander settings */
  154929. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154930. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154931. return;
  154932. }
  154933. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154934. int *suppress){
  154935. int is=s;
  154936. double ds=s-is;
  154937. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154938. vorbis_info_psy *p=ci->psy_param[block];
  154939. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154940. return;
  154941. }
  154942. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154943. int *suppress,
  154944. noise3 *in,
  154945. noiseguard *guard,
  154946. double userbias){
  154947. int i,is=s,j;
  154948. double ds=s-is;
  154949. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154950. vorbis_info_psy *p=ci->psy_param[block];
  154951. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154952. p->noisewindowlomin=guard[block].lo;
  154953. p->noisewindowhimin=guard[block].hi;
  154954. p->noisewindowfixed=guard[block].fixed;
  154955. for(j=0;j<P_NOISECURVES;j++)
  154956. for(i=0;i<P_BANDS;i++)
  154957. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154958. /* impulse blocks may take a user specified bias to boost the
  154959. nominal/high noise encoding depth */
  154960. for(j=0;j<P_NOISECURVES;j++){
  154961. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154962. for(i=0;i<P_BANDS;i++){
  154963. p->noiseoff[j][i]+=userbias;
  154964. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154965. }
  154966. }
  154967. return;
  154968. }
  154969. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154970. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154971. vorbis_info_psy *p=ci->psy_param[block];
  154972. p->ath_adjatt=ci->hi.ath_floating_dB;
  154973. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154974. return;
  154975. }
  154976. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154977. int i;
  154978. for(i=0;i<ci->books;i++)
  154979. if(ci->book_param[i]==book)return(i);
  154980. return(ci->books++);
  154981. }
  154982. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154983. int *shortb,int *longb){
  154984. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154985. int is=s;
  154986. int blockshort=shortb[is];
  154987. int blocklong=longb[is];
  154988. ci->blocksizes[0]=blockshort;
  154989. ci->blocksizes[1]=blocklong;
  154990. }
  154991. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154992. int number, int block,
  154993. vorbis_residue_template *res){
  154994. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154995. int i,n;
  154996. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154997. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154998. memcpy(r,res->res,sizeof(*r));
  154999. if(ci->residues<=number)ci->residues=number+1;
  155000. switch(ci->blocksizes[block]){
  155001. case 64:case 128:case 256:
  155002. r->grouping=16;
  155003. break;
  155004. default:
  155005. r->grouping=32;
  155006. break;
  155007. }
  155008. ci->residue_type[number]=res->res_type;
  155009. /* to be adjusted by lowpass/pointlimit later */
  155010. n=r->end=ci->blocksizes[block]>>1;
  155011. if(res->res_type==2)
  155012. n=r->end*=vi->channels;
  155013. /* fill in all the books */
  155014. {
  155015. int booklist=0,k;
  155016. if(ci->hi.managed){
  155017. for(i=0;i<r->partitions;i++)
  155018. for(k=0;k<3;k++)
  155019. if(res->books_base_managed->books[i][k])
  155020. r->secondstages[i]|=(1<<k);
  155021. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155022. ci->book_param[r->groupbook]=res->book_aux_managed;
  155023. for(i=0;i<r->partitions;i++){
  155024. for(k=0;k<3;k++){
  155025. if(res->books_base_managed->books[i][k]){
  155026. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155027. r->booklist[booklist++]=bookid;
  155028. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155029. }
  155030. }
  155031. }
  155032. }else{
  155033. for(i=0;i<r->partitions;i++)
  155034. for(k=0;k<3;k++)
  155035. if(res->books_base->books[i][k])
  155036. r->secondstages[i]|=(1<<k);
  155037. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155038. ci->book_param[r->groupbook]=res->book_aux;
  155039. for(i=0;i<r->partitions;i++){
  155040. for(k=0;k<3;k++){
  155041. if(res->books_base->books[i][k]){
  155042. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155043. r->booklist[booklist++]=bookid;
  155044. ci->book_param[bookid]=res->books_base->books[i][k];
  155045. }
  155046. }
  155047. }
  155048. }
  155049. }
  155050. /* lowpass setup/pointlimit */
  155051. {
  155052. double freq=ci->hi.lowpass_kHz*1000.;
  155053. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155054. double nyq=vi->rate/2.;
  155055. long blocksize=ci->blocksizes[block]>>1;
  155056. /* lowpass needs to be set in the floor and the residue. */
  155057. if(freq>nyq)freq=nyq;
  155058. /* in the floor, the granularity can be very fine; it doesn't alter
  155059. the encoding structure, only the samples used to fit the floor
  155060. approximation */
  155061. f->n=freq/nyq*blocksize;
  155062. /* this res may by limited by the maximum pointlimit of the mode,
  155063. not the lowpass. the floor is always lowpass limited. */
  155064. if(res->limit_type){
  155065. if(ci->hi.managed)
  155066. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155067. else
  155068. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155069. if(freq>nyq)freq=nyq;
  155070. }
  155071. /* in the residue, we're constrained, physically, by partition
  155072. boundaries. We still lowpass 'wherever', but we have to round up
  155073. here to next boundary, or the vorbis spec will round it *down* to
  155074. previous boundary in encode/decode */
  155075. if(ci->residue_type[block]==2)
  155076. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155077. r->grouping;
  155078. else
  155079. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155080. r->grouping;
  155081. }
  155082. }
  155083. /* we assume two maps in this encoder */
  155084. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155085. vorbis_mapping_template *maps){
  155086. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155087. int i,j,is=s,modes=2;
  155088. vorbis_info_mapping0 *map=maps[is].map;
  155089. vorbis_info_mode *mode=_mode_template;
  155090. vorbis_residue_template *res=maps[is].res;
  155091. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155092. for(i=0;i<modes;i++){
  155093. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155094. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155095. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155096. if(i>=ci->modes)ci->modes=i+1;
  155097. ci->map_type[i]=0;
  155098. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155099. if(i>=ci->maps)ci->maps=i+1;
  155100. for(j=0;j<map[i].submaps;j++)
  155101. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155102. ,res+map[i].residuesubmap[j]);
  155103. }
  155104. }
  155105. static double setting_to_approx_bitrate(vorbis_info *vi){
  155106. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155107. highlevel_encode_setup *hi=&ci->hi;
  155108. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155109. int is=hi->base_setting;
  155110. double ds=hi->base_setting-is;
  155111. int ch=vi->channels;
  155112. double *r=setup->rate_mapping;
  155113. if(r==NULL)
  155114. return(-1);
  155115. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155116. }
  155117. static void get_setup_template(vorbis_info *vi,
  155118. long ch,long srate,
  155119. double req,int q_or_bitrate){
  155120. int i=0,j;
  155121. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155122. highlevel_encode_setup *hi=&ci->hi;
  155123. if(q_or_bitrate)req/=ch;
  155124. while(setup_list[i]){
  155125. if(setup_list[i]->coupling_restriction==-1 ||
  155126. setup_list[i]->coupling_restriction==ch){
  155127. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155128. srate<=setup_list[i]->samplerate_max_restriction){
  155129. int mappings=setup_list[i]->mappings;
  155130. double *map=(q_or_bitrate?
  155131. setup_list[i]->rate_mapping:
  155132. setup_list[i]->quality_mapping);
  155133. /* the template matches. Does the requested quality mode
  155134. fall within this template's modes? */
  155135. if(req<map[0]){++i;continue;}
  155136. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155137. for(j=0;j<mappings;j++)
  155138. if(req>=map[j] && req<map[j+1])break;
  155139. /* an all-points match */
  155140. hi->setup=setup_list[i];
  155141. if(j==mappings)
  155142. hi->base_setting=j-.001;
  155143. else{
  155144. float low=map[j];
  155145. float high=map[j+1];
  155146. float del=(req-low)/(high-low);
  155147. hi->base_setting=j+del;
  155148. }
  155149. return;
  155150. }
  155151. }
  155152. i++;
  155153. }
  155154. hi->setup=NULL;
  155155. }
  155156. /* encoders will need to use vorbis_info_init beforehand and call
  155157. vorbis_info clear when all done */
  155158. /* two interfaces; this, more detailed one, and later a convenience
  155159. layer on top */
  155160. /* the final setup call */
  155161. int vorbis_encode_setup_init(vorbis_info *vi){
  155162. int i0=0,singleblock=0;
  155163. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155164. ve_setup_data_template *setup=NULL;
  155165. highlevel_encode_setup *hi=&ci->hi;
  155166. if(ci==NULL)return(OV_EINVAL);
  155167. if(!hi->impulse_block_p)i0=1;
  155168. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155169. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155170. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155171. /* again, bound this to avoid the app shooting itself int he foot
  155172. too badly */
  155173. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155174. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155175. /* get the appropriate setup template; matches the fetch in previous
  155176. stages */
  155177. setup=(ve_setup_data_template *)hi->setup;
  155178. if(setup==NULL)return(OV_EINVAL);
  155179. hi->set_in_stone=1;
  155180. /* choose block sizes from configured sizes as well as paying
  155181. attention to long_block_p and short_block_p. If the configured
  155182. short and long blocks are the same length, we set long_block_p
  155183. and unset short_block_p */
  155184. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155185. setup->blocksize_short,
  155186. setup->blocksize_long);
  155187. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155188. /* floor setup; choose proper floor params. Allocated on the floor
  155189. stack in order; if we alloc only long floor, it's 0 */
  155190. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155191. setup->floor_books,
  155192. setup->floor_params,
  155193. setup->floor_short_mapping);
  155194. if(!singleblock)
  155195. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155196. setup->floor_books,
  155197. setup->floor_params,
  155198. setup->floor_long_mapping);
  155199. /* setup of [mostly] short block detection and stereo*/
  155200. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155201. setup->global_params,
  155202. setup->global_mapping);
  155203. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155204. /* basic psych setup and noise normalization */
  155205. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155206. setup->psy_noise_normal_start[0],
  155207. setup->psy_noise_normal_partition[0],
  155208. setup->psy_noise_normal_thresh,
  155209. 0);
  155210. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155211. setup->psy_noise_normal_start[0],
  155212. setup->psy_noise_normal_partition[0],
  155213. setup->psy_noise_normal_thresh,
  155214. 1);
  155215. if(!singleblock){
  155216. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155217. setup->psy_noise_normal_start[1],
  155218. setup->psy_noise_normal_partition[1],
  155219. setup->psy_noise_normal_thresh,
  155220. 2);
  155221. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155222. setup->psy_noise_normal_start[1],
  155223. setup->psy_noise_normal_partition[1],
  155224. setup->psy_noise_normal_thresh,
  155225. 3);
  155226. }
  155227. /* tone masking setup */
  155228. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155229. setup->psy_tone_masteratt,
  155230. setup->psy_tone_0dB,
  155231. setup->psy_tone_adj_impulse);
  155232. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155233. setup->psy_tone_masteratt,
  155234. setup->psy_tone_0dB,
  155235. setup->psy_tone_adj_other);
  155236. if(!singleblock){
  155237. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155238. setup->psy_tone_masteratt,
  155239. setup->psy_tone_0dB,
  155240. setup->psy_tone_adj_other);
  155241. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155242. setup->psy_tone_masteratt,
  155243. setup->psy_tone_0dB,
  155244. setup->psy_tone_adj_long);
  155245. }
  155246. /* noise companding setup */
  155247. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155248. setup->psy_noise_compand,
  155249. setup->psy_noise_compand_short_mapping);
  155250. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155251. setup->psy_noise_compand,
  155252. setup->psy_noise_compand_short_mapping);
  155253. if(!singleblock){
  155254. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155255. setup->psy_noise_compand,
  155256. setup->psy_noise_compand_long_mapping);
  155257. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155258. setup->psy_noise_compand,
  155259. setup->psy_noise_compand_long_mapping);
  155260. }
  155261. /* peak guarding setup */
  155262. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155263. setup->psy_tone_dBsuppress);
  155264. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155265. setup->psy_tone_dBsuppress);
  155266. if(!singleblock){
  155267. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155268. setup->psy_tone_dBsuppress);
  155269. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155270. setup->psy_tone_dBsuppress);
  155271. }
  155272. /* noise bias setup */
  155273. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155274. setup->psy_noise_dBsuppress,
  155275. setup->psy_noise_bias_impulse,
  155276. setup->psy_noiseguards,
  155277. (i0==0?hi->impulse_noisetune:0.));
  155278. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155279. setup->psy_noise_dBsuppress,
  155280. setup->psy_noise_bias_padding,
  155281. setup->psy_noiseguards,0.);
  155282. if(!singleblock){
  155283. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155284. setup->psy_noise_dBsuppress,
  155285. setup->psy_noise_bias_trans,
  155286. setup->psy_noiseguards,0.);
  155287. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155288. setup->psy_noise_dBsuppress,
  155289. setup->psy_noise_bias_long,
  155290. setup->psy_noiseguards,0.);
  155291. }
  155292. vorbis_encode_ath_setup(vi,0);
  155293. vorbis_encode_ath_setup(vi,1);
  155294. if(!singleblock){
  155295. vorbis_encode_ath_setup(vi,2);
  155296. vorbis_encode_ath_setup(vi,3);
  155297. }
  155298. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155299. /* set bitrate readonlies and management */
  155300. if(hi->bitrate_av>0)
  155301. vi->bitrate_nominal=hi->bitrate_av;
  155302. else{
  155303. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155304. }
  155305. vi->bitrate_lower=hi->bitrate_min;
  155306. vi->bitrate_upper=hi->bitrate_max;
  155307. if(hi->bitrate_av)
  155308. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155309. else
  155310. vi->bitrate_window=0.;
  155311. if(hi->managed){
  155312. ci->bi.avg_rate=hi->bitrate_av;
  155313. ci->bi.min_rate=hi->bitrate_min;
  155314. ci->bi.max_rate=hi->bitrate_max;
  155315. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155316. ci->bi.reservoir_bias=
  155317. hi->bitrate_reservoir_bias;
  155318. ci->bi.slew_damp=hi->bitrate_av_damp;
  155319. }
  155320. return(0);
  155321. }
  155322. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155323. long channels,
  155324. long rate){
  155325. int ret=0,i,is;
  155326. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155327. highlevel_encode_setup *hi=&ci->hi;
  155328. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155329. double ds;
  155330. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155331. if(ret)return(ret);
  155332. is=hi->base_setting;
  155333. ds=hi->base_setting-is;
  155334. hi->short_setting=hi->base_setting;
  155335. hi->long_setting=hi->base_setting;
  155336. hi->managed=0;
  155337. hi->impulse_block_p=1;
  155338. hi->noise_normalize_p=1;
  155339. hi->stereo_point_setting=hi->base_setting;
  155340. hi->lowpass_kHz=
  155341. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155342. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155343. setup->psy_ath_float[is+1]*ds;
  155344. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155345. setup->psy_ath_abs[is+1]*ds;
  155346. hi->amplitude_track_dBpersec=-6.;
  155347. hi->trigger_setting=hi->base_setting;
  155348. for(i=0;i<4;i++){
  155349. hi->block[i].tone_mask_setting=hi->base_setting;
  155350. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155351. hi->block[i].noise_bias_setting=hi->base_setting;
  155352. hi->block[i].noise_compand_setting=hi->base_setting;
  155353. }
  155354. return(ret);
  155355. }
  155356. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155357. long channels,
  155358. long rate,
  155359. float quality){
  155360. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155361. highlevel_encode_setup *hi=&ci->hi;
  155362. quality+=.0000001;
  155363. if(quality>=1.)quality=.9999;
  155364. get_setup_template(vi,channels,rate,quality,0);
  155365. if(!hi->setup)return OV_EIMPL;
  155366. return vorbis_encode_setup_setting(vi,channels,rate);
  155367. }
  155368. int vorbis_encode_init_vbr(vorbis_info *vi,
  155369. long channels,
  155370. long rate,
  155371. float base_quality /* 0. to 1. */
  155372. ){
  155373. int ret=0;
  155374. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155375. if(ret){
  155376. vorbis_info_clear(vi);
  155377. return ret;
  155378. }
  155379. ret=vorbis_encode_setup_init(vi);
  155380. if(ret)
  155381. vorbis_info_clear(vi);
  155382. return(ret);
  155383. }
  155384. int vorbis_encode_setup_managed(vorbis_info *vi,
  155385. long channels,
  155386. long rate,
  155387. long max_bitrate,
  155388. long nominal_bitrate,
  155389. long min_bitrate){
  155390. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155391. highlevel_encode_setup *hi=&ci->hi;
  155392. double tnominal=nominal_bitrate;
  155393. int ret=0;
  155394. if(nominal_bitrate<=0.){
  155395. if(max_bitrate>0.){
  155396. if(min_bitrate>0.)
  155397. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155398. else
  155399. nominal_bitrate=max_bitrate*.875;
  155400. }else{
  155401. if(min_bitrate>0.){
  155402. nominal_bitrate=min_bitrate;
  155403. }else{
  155404. return(OV_EINVAL);
  155405. }
  155406. }
  155407. }
  155408. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155409. if(!hi->setup)return OV_EIMPL;
  155410. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155411. if(ret){
  155412. vorbis_info_clear(vi);
  155413. return ret;
  155414. }
  155415. /* initialize management with sane defaults */
  155416. hi->managed=1;
  155417. hi->bitrate_min=min_bitrate;
  155418. hi->bitrate_max=max_bitrate;
  155419. hi->bitrate_av=tnominal;
  155420. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155421. hi->bitrate_reservoir=nominal_bitrate*2;
  155422. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155423. return(ret);
  155424. }
  155425. int vorbis_encode_init(vorbis_info *vi,
  155426. long channels,
  155427. long rate,
  155428. long max_bitrate,
  155429. long nominal_bitrate,
  155430. long min_bitrate){
  155431. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155432. max_bitrate,
  155433. nominal_bitrate,
  155434. min_bitrate);
  155435. if(ret){
  155436. vorbis_info_clear(vi);
  155437. return(ret);
  155438. }
  155439. ret=vorbis_encode_setup_init(vi);
  155440. if(ret)
  155441. vorbis_info_clear(vi);
  155442. return(ret);
  155443. }
  155444. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155445. if(vi){
  155446. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155447. highlevel_encode_setup *hi=&ci->hi;
  155448. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155449. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155450. switch(number){
  155451. /* now deprecated *****************/
  155452. case OV_ECTL_RATEMANAGE_GET:
  155453. {
  155454. struct ovectl_ratemanage_arg *ai=
  155455. (struct ovectl_ratemanage_arg *)arg;
  155456. ai->management_active=hi->managed;
  155457. ai->bitrate_hard_window=ai->bitrate_av_window=
  155458. (double)hi->bitrate_reservoir/vi->rate;
  155459. ai->bitrate_av_window_center=1.;
  155460. ai->bitrate_hard_min=hi->bitrate_min;
  155461. ai->bitrate_hard_max=hi->bitrate_max;
  155462. ai->bitrate_av_lo=hi->bitrate_av;
  155463. ai->bitrate_av_hi=hi->bitrate_av;
  155464. }
  155465. return(0);
  155466. /* now deprecated *****************/
  155467. case OV_ECTL_RATEMANAGE_SET:
  155468. {
  155469. struct ovectl_ratemanage_arg *ai=
  155470. (struct ovectl_ratemanage_arg *)arg;
  155471. if(ai==NULL){
  155472. hi->managed=0;
  155473. }else{
  155474. hi->managed=ai->management_active;
  155475. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155476. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155477. }
  155478. }
  155479. return 0;
  155480. /* now deprecated *****************/
  155481. case OV_ECTL_RATEMANAGE_AVG:
  155482. {
  155483. struct ovectl_ratemanage_arg *ai=
  155484. (struct ovectl_ratemanage_arg *)arg;
  155485. if(ai==NULL){
  155486. hi->bitrate_av=0;
  155487. }else{
  155488. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155489. }
  155490. }
  155491. return(0);
  155492. /* now deprecated *****************/
  155493. case OV_ECTL_RATEMANAGE_HARD:
  155494. {
  155495. struct ovectl_ratemanage_arg *ai=
  155496. (struct ovectl_ratemanage_arg *)arg;
  155497. if(ai==NULL){
  155498. hi->bitrate_min=0;
  155499. hi->bitrate_max=0;
  155500. }else{
  155501. hi->bitrate_min=ai->bitrate_hard_min;
  155502. hi->bitrate_max=ai->bitrate_hard_max;
  155503. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155504. (hi->bitrate_max+hi->bitrate_min)*.5;
  155505. }
  155506. if(hi->bitrate_reservoir<128.)
  155507. hi->bitrate_reservoir=128.;
  155508. }
  155509. return(0);
  155510. /* replacement ratemanage interface */
  155511. case OV_ECTL_RATEMANAGE2_GET:
  155512. {
  155513. struct ovectl_ratemanage2_arg *ai=
  155514. (struct ovectl_ratemanage2_arg *)arg;
  155515. if(ai==NULL)return OV_EINVAL;
  155516. ai->management_active=hi->managed;
  155517. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155518. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155519. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155520. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155521. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155522. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155523. }
  155524. return (0);
  155525. case OV_ECTL_RATEMANAGE2_SET:
  155526. {
  155527. struct ovectl_ratemanage2_arg *ai=
  155528. (struct ovectl_ratemanage2_arg *)arg;
  155529. if(ai==NULL){
  155530. hi->managed=0;
  155531. }else{
  155532. /* sanity check; only catch invariant violations */
  155533. if(ai->bitrate_limit_min_kbps>0 &&
  155534. ai->bitrate_average_kbps>0 &&
  155535. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155536. return OV_EINVAL;
  155537. if(ai->bitrate_limit_max_kbps>0 &&
  155538. ai->bitrate_average_kbps>0 &&
  155539. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155540. return OV_EINVAL;
  155541. if(ai->bitrate_limit_min_kbps>0 &&
  155542. ai->bitrate_limit_max_kbps>0 &&
  155543. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155544. return OV_EINVAL;
  155545. if(ai->bitrate_average_damping <= 0.)
  155546. return OV_EINVAL;
  155547. if(ai->bitrate_limit_reservoir_bits < 0)
  155548. return OV_EINVAL;
  155549. if(ai->bitrate_limit_reservoir_bias < 0.)
  155550. return OV_EINVAL;
  155551. if(ai->bitrate_limit_reservoir_bias > 1.)
  155552. return OV_EINVAL;
  155553. hi->managed=ai->management_active;
  155554. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155555. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155556. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155557. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155558. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155559. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155560. }
  155561. }
  155562. return 0;
  155563. case OV_ECTL_LOWPASS_GET:
  155564. {
  155565. double *farg=(double *)arg;
  155566. *farg=hi->lowpass_kHz;
  155567. }
  155568. return(0);
  155569. case OV_ECTL_LOWPASS_SET:
  155570. {
  155571. double *farg=(double *)arg;
  155572. hi->lowpass_kHz=*farg;
  155573. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155574. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155575. }
  155576. return(0);
  155577. case OV_ECTL_IBLOCK_GET:
  155578. {
  155579. double *farg=(double *)arg;
  155580. *farg=hi->impulse_noisetune;
  155581. }
  155582. return(0);
  155583. case OV_ECTL_IBLOCK_SET:
  155584. {
  155585. double *farg=(double *)arg;
  155586. hi->impulse_noisetune=*farg;
  155587. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155588. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155589. }
  155590. return(0);
  155591. }
  155592. return(OV_EIMPL);
  155593. }
  155594. return(OV_EINVAL);
  155595. }
  155596. #endif
  155597. /*** End of inlined file: vorbisenc.c ***/
  155598. /*** Start of inlined file: vorbisfile.c ***/
  155599. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155600. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155601. // tasks..
  155602. #if JUCE_MSVC
  155603. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155604. #endif
  155605. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155606. #if JUCE_USE_OGGVORBIS
  155607. #include <stdlib.h>
  155608. #include <stdio.h>
  155609. #include <errno.h>
  155610. #include <string.h>
  155611. #include <math.h>
  155612. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155613. one logical bitstream arranged end to end (the only form of Ogg
  155614. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155615. multiplexing] is not allowed in Vorbis) */
  155616. /* A Vorbis file can be played beginning to end (streamed) without
  155617. worrying ahead of time about chaining (see decoder_example.c). If
  155618. we have the whole file, however, and want random access
  155619. (seeking/scrubbing) or desire to know the total length/time of a
  155620. file, we need to account for the possibility of chaining. */
  155621. /* We can handle things a number of ways; we can determine the entire
  155622. bitstream structure right off the bat, or find pieces on demand.
  155623. This example determines and caches structure for the entire
  155624. bitstream, but builds a virtual decoder on the fly when moving
  155625. between links in the chain. */
  155626. /* There are also different ways to implement seeking. Enough
  155627. information exists in an Ogg bitstream to seek to
  155628. sample-granularity positions in the output. Or, one can seek by
  155629. picking some portion of the stream roughly in the desired area if
  155630. we only want coarse navigation through the stream. */
  155631. /*************************************************************************
  155632. * Many, many internal helpers. The intention is not to be confusing;
  155633. * rampant duplication and monolithic function implementation would be
  155634. * harder to understand anyway. The high level functions are last. Begin
  155635. * grokking near the end of the file */
  155636. /* read a little more data from the file/pipe into the ogg_sync framer
  155637. */
  155638. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155639. over 8k gets what they deserve */
  155640. static long _get_data(OggVorbis_File *vf){
  155641. errno=0;
  155642. if(vf->datasource){
  155643. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155644. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155645. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155646. if(bytes==0 && errno)return(-1);
  155647. return(bytes);
  155648. }else
  155649. return(0);
  155650. }
  155651. /* save a tiny smidge of verbosity to make the code more readable */
  155652. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155653. if(vf->datasource){
  155654. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155655. vf->offset=offset;
  155656. ogg_sync_reset(&vf->oy);
  155657. }else{
  155658. /* shouldn't happen unless someone writes a broken callback */
  155659. return;
  155660. }
  155661. }
  155662. /* The read/seek functions track absolute position within the stream */
  155663. /* from the head of the stream, get the next page. boundary specifies
  155664. if the function is allowed to fetch more data from the stream (and
  155665. how much) or only use internally buffered data.
  155666. boundary: -1) unbounded search
  155667. 0) read no additional data; use cached only
  155668. n) search for a new page beginning for n bytes
  155669. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155670. n) found a page at absolute offset n */
  155671. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155672. ogg_int64_t boundary){
  155673. if(boundary>0)boundary+=vf->offset;
  155674. while(1){
  155675. long more;
  155676. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155677. more=ogg_sync_pageseek(&vf->oy,og);
  155678. if(more<0){
  155679. /* skipped n bytes */
  155680. vf->offset-=more;
  155681. }else{
  155682. if(more==0){
  155683. /* send more paramedics */
  155684. if(!boundary)return(OV_FALSE);
  155685. {
  155686. long ret=_get_data(vf);
  155687. if(ret==0)return(OV_EOF);
  155688. if(ret<0)return(OV_EREAD);
  155689. }
  155690. }else{
  155691. /* got a page. Return the offset at the page beginning,
  155692. advance the internal offset past the page end */
  155693. ogg_int64_t ret=vf->offset;
  155694. vf->offset+=more;
  155695. return(ret);
  155696. }
  155697. }
  155698. }
  155699. }
  155700. /* find the latest page beginning before the current stream cursor
  155701. position. Much dirtier than the above as Ogg doesn't have any
  155702. backward search linkage. no 'readp' as it will certainly have to
  155703. read. */
  155704. /* returns offset or OV_EREAD, OV_FAULT */
  155705. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155706. ogg_int64_t begin=vf->offset;
  155707. ogg_int64_t end=begin;
  155708. ogg_int64_t ret;
  155709. ogg_int64_t offset=-1;
  155710. while(offset==-1){
  155711. begin-=CHUNKSIZE;
  155712. if(begin<0)
  155713. begin=0;
  155714. _seek_helper(vf,begin);
  155715. while(vf->offset<end){
  155716. ret=_get_next_page(vf,og,end-vf->offset);
  155717. if(ret==OV_EREAD)return(OV_EREAD);
  155718. if(ret<0){
  155719. break;
  155720. }else{
  155721. offset=ret;
  155722. }
  155723. }
  155724. }
  155725. /* we have the offset. Actually snork and hold the page now */
  155726. _seek_helper(vf,offset);
  155727. ret=_get_next_page(vf,og,CHUNKSIZE);
  155728. if(ret<0)
  155729. /* this shouldn't be possible */
  155730. return(OV_EFAULT);
  155731. return(offset);
  155732. }
  155733. /* finds each bitstream link one at a time using a bisection search
  155734. (has to begin by knowing the offset of the lb's initial page).
  155735. Recurses for each link so it can alloc the link storage after
  155736. finding them all, then unroll and fill the cache at the same time */
  155737. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155738. ogg_int64_t begin,
  155739. ogg_int64_t searched,
  155740. ogg_int64_t end,
  155741. long currentno,
  155742. long m){
  155743. ogg_int64_t endsearched=end;
  155744. ogg_int64_t next=end;
  155745. ogg_page og;
  155746. ogg_int64_t ret;
  155747. /* the below guards against garbage seperating the last and
  155748. first pages of two links. */
  155749. while(searched<endsearched){
  155750. ogg_int64_t bisect;
  155751. if(endsearched-searched<CHUNKSIZE){
  155752. bisect=searched;
  155753. }else{
  155754. bisect=(searched+endsearched)/2;
  155755. }
  155756. _seek_helper(vf,bisect);
  155757. ret=_get_next_page(vf,&og,-1);
  155758. if(ret==OV_EREAD)return(OV_EREAD);
  155759. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155760. endsearched=bisect;
  155761. if(ret>=0)next=ret;
  155762. }else{
  155763. searched=ret+og.header_len+og.body_len;
  155764. }
  155765. }
  155766. _seek_helper(vf,next);
  155767. ret=_get_next_page(vf,&og,-1);
  155768. if(ret==OV_EREAD)return(OV_EREAD);
  155769. if(searched>=end || ret<0){
  155770. vf->links=m+1;
  155771. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155772. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155773. vf->offsets[m+1]=searched;
  155774. }else{
  155775. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155776. end,ogg_page_serialno(&og),m+1);
  155777. if(ret==OV_EREAD)return(OV_EREAD);
  155778. }
  155779. vf->offsets[m]=begin;
  155780. vf->serialnos[m]=currentno;
  155781. return(0);
  155782. }
  155783. /* uses the local ogg_stream storage in vf; this is important for
  155784. non-streaming input sources */
  155785. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155786. long *serialno,ogg_page *og_ptr){
  155787. ogg_page og;
  155788. ogg_packet op;
  155789. int i,ret;
  155790. if(!og_ptr){
  155791. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155792. if(llret==OV_EREAD)return(OV_EREAD);
  155793. if(llret<0)return OV_ENOTVORBIS;
  155794. og_ptr=&og;
  155795. }
  155796. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155797. if(serialno)*serialno=vf->os.serialno;
  155798. vf->ready_state=STREAMSET;
  155799. /* extract the initial header from the first page and verify that the
  155800. Ogg bitstream is in fact Vorbis data */
  155801. vorbis_info_init(vi);
  155802. vorbis_comment_init(vc);
  155803. i=0;
  155804. while(i<3){
  155805. ogg_stream_pagein(&vf->os,og_ptr);
  155806. while(i<3){
  155807. int result=ogg_stream_packetout(&vf->os,&op);
  155808. if(result==0)break;
  155809. if(result==-1){
  155810. ret=OV_EBADHEADER;
  155811. goto bail_header;
  155812. }
  155813. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155814. goto bail_header;
  155815. }
  155816. i++;
  155817. }
  155818. if(i<3)
  155819. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155820. ret=OV_EBADHEADER;
  155821. goto bail_header;
  155822. }
  155823. }
  155824. return 0;
  155825. bail_header:
  155826. vorbis_info_clear(vi);
  155827. vorbis_comment_clear(vc);
  155828. vf->ready_state=OPENED;
  155829. return ret;
  155830. }
  155831. /* last step of the OggVorbis_File initialization; get all the
  155832. vorbis_info structs and PCM positions. Only called by the seekable
  155833. initialization (local stream storage is hacked slightly; pay
  155834. attention to how that's done) */
  155835. /* this is void and does not propogate errors up because we want to be
  155836. able to open and use damaged bitstreams as well as we can. Just
  155837. watch out for missing information for links in the OggVorbis_File
  155838. struct */
  155839. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155840. ogg_page og;
  155841. int i;
  155842. ogg_int64_t ret;
  155843. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155844. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155845. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155846. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155847. for(i=0;i<vf->links;i++){
  155848. if(i==0){
  155849. /* we already grabbed the initial header earlier. Just set the offset */
  155850. vf->dataoffsets[i]=dataoffset;
  155851. _seek_helper(vf,dataoffset);
  155852. }else{
  155853. /* seek to the location of the initial header */
  155854. _seek_helper(vf,vf->offsets[i]);
  155855. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155856. vf->dataoffsets[i]=-1;
  155857. }else{
  155858. vf->dataoffsets[i]=vf->offset;
  155859. }
  155860. }
  155861. /* fetch beginning PCM offset */
  155862. if(vf->dataoffsets[i]!=-1){
  155863. ogg_int64_t accumulated=0;
  155864. long lastblock=-1;
  155865. int result;
  155866. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155867. while(1){
  155868. ogg_packet op;
  155869. ret=_get_next_page(vf,&og,-1);
  155870. if(ret<0)
  155871. /* this should not be possible unless the file is
  155872. truncated/mangled */
  155873. break;
  155874. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155875. break;
  155876. /* count blocksizes of all frames in the page */
  155877. ogg_stream_pagein(&vf->os,&og);
  155878. while((result=ogg_stream_packetout(&vf->os,&op))){
  155879. if(result>0){ /* ignore holes */
  155880. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155881. if(lastblock!=-1)
  155882. accumulated+=(lastblock+thisblock)>>2;
  155883. lastblock=thisblock;
  155884. }
  155885. }
  155886. if(ogg_page_granulepos(&og)!=-1){
  155887. /* pcm offset of last packet on the first audio page */
  155888. accumulated= ogg_page_granulepos(&og)-accumulated;
  155889. break;
  155890. }
  155891. }
  155892. /* less than zero? This is a stream with samples trimmed off
  155893. the beginning, a normal occurrence; set the offset to zero */
  155894. if(accumulated<0)accumulated=0;
  155895. vf->pcmlengths[i*2]=accumulated;
  155896. }
  155897. /* get the PCM length of this link. To do this,
  155898. get the last page of the stream */
  155899. {
  155900. ogg_int64_t end=vf->offsets[i+1];
  155901. _seek_helper(vf,end);
  155902. while(1){
  155903. ret=_get_prev_page(vf,&og);
  155904. if(ret<0){
  155905. /* this should not be possible */
  155906. vorbis_info_clear(vf->vi+i);
  155907. vorbis_comment_clear(vf->vc+i);
  155908. break;
  155909. }
  155910. if(ogg_page_granulepos(&og)!=-1){
  155911. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155912. break;
  155913. }
  155914. vf->offset=ret;
  155915. }
  155916. }
  155917. }
  155918. }
  155919. static int _make_decode_ready(OggVorbis_File *vf){
  155920. if(vf->ready_state>STREAMSET)return 0;
  155921. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155922. if(vf->seekable){
  155923. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155924. return OV_EBADLINK;
  155925. }else{
  155926. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155927. return OV_EBADLINK;
  155928. }
  155929. vorbis_block_init(&vf->vd,&vf->vb);
  155930. vf->ready_state=INITSET;
  155931. vf->bittrack=0.f;
  155932. vf->samptrack=0.f;
  155933. return 0;
  155934. }
  155935. static int _open_seekable2(OggVorbis_File *vf){
  155936. long serialno=vf->current_serialno;
  155937. ogg_int64_t dataoffset=vf->offset, end;
  155938. ogg_page og;
  155939. /* we're partially open and have a first link header state in
  155940. storage in vf */
  155941. /* we can seek, so set out learning all about this file */
  155942. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155943. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155944. /* We get the offset for the last page of the physical bitstream.
  155945. Most OggVorbis files will contain a single logical bitstream */
  155946. end=_get_prev_page(vf,&og);
  155947. if(end<0)return(end);
  155948. /* more than one logical bitstream? */
  155949. if(ogg_page_serialno(&og)!=serialno){
  155950. /* Chained bitstream. Bisect-search each logical bitstream
  155951. section. Do so based on serial number only */
  155952. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155953. }else{
  155954. /* Only one logical bitstream */
  155955. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155956. }
  155957. /* the initial header memory is referenced by vf after; don't free it */
  155958. _prefetch_all_headers(vf,dataoffset);
  155959. return(ov_raw_seek(vf,0));
  155960. }
  155961. /* clear out the current logical bitstream decoder */
  155962. static void _decode_clear(OggVorbis_File *vf){
  155963. vorbis_dsp_clear(&vf->vd);
  155964. vorbis_block_clear(&vf->vb);
  155965. vf->ready_state=OPENED;
  155966. }
  155967. /* fetch and process a packet. Handles the case where we're at a
  155968. bitstream boundary and dumps the decoding machine. If the decoding
  155969. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155970. date (seek and read both use this. seek uses a special hack with
  155971. readp).
  155972. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155973. 0) need more data (only if readp==0)
  155974. 1) got a packet
  155975. */
  155976. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155977. ogg_packet *op_in,
  155978. int readp,
  155979. int spanp){
  155980. ogg_page og;
  155981. /* handle one packet. Try to fetch it from current stream state */
  155982. /* extract packets from page */
  155983. while(1){
  155984. /* process a packet if we can. If the machine isn't loaded,
  155985. neither is a page */
  155986. if(vf->ready_state==INITSET){
  155987. while(1) {
  155988. ogg_packet op;
  155989. ogg_packet *op_ptr=(op_in?op_in:&op);
  155990. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155991. ogg_int64_t granulepos;
  155992. op_in=NULL;
  155993. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155994. if(result>0){
  155995. /* got a packet. process it */
  155996. granulepos=op_ptr->granulepos;
  155997. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155998. header handling. The
  155999. header packets aren't
  156000. audio, so if/when we
  156001. submit them,
  156002. vorbis_synthesis will
  156003. reject them */
  156004. /* suck in the synthesis data and track bitrate */
  156005. {
  156006. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156007. /* for proper use of libvorbis within libvorbisfile,
  156008. oldsamples will always be zero. */
  156009. if(oldsamples)return(OV_EFAULT);
  156010. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156011. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156012. vf->bittrack+=op_ptr->bytes*8;
  156013. }
  156014. /* update the pcm offset. */
  156015. if(granulepos!=-1 && !op_ptr->e_o_s){
  156016. int link=(vf->seekable?vf->current_link:0);
  156017. int i,samples;
  156018. /* this packet has a pcm_offset on it (the last packet
  156019. completed on a page carries the offset) After processing
  156020. (above), we know the pcm position of the *last* sample
  156021. ready to be returned. Find the offset of the *first*
  156022. As an aside, this trick is inaccurate if we begin
  156023. reading anew right at the last page; the end-of-stream
  156024. granulepos declares the last frame in the stream, and the
  156025. last packet of the last page may be a partial frame.
  156026. So, we need a previous granulepos from an in-sequence page
  156027. to have a reference point. Thus the !op_ptr->e_o_s clause
  156028. above */
  156029. if(vf->seekable && link>0)
  156030. granulepos-=vf->pcmlengths[link*2];
  156031. if(granulepos<0)granulepos=0; /* actually, this
  156032. shouldn't be possible
  156033. here unless the stream
  156034. is very broken */
  156035. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156036. granulepos-=samples;
  156037. for(i=0;i<link;i++)
  156038. granulepos+=vf->pcmlengths[i*2+1];
  156039. vf->pcm_offset=granulepos;
  156040. }
  156041. return(1);
  156042. }
  156043. }
  156044. else
  156045. break;
  156046. }
  156047. }
  156048. if(vf->ready_state>=OPENED){
  156049. ogg_int64_t ret;
  156050. if(!readp)return(0);
  156051. if((ret=_get_next_page(vf,&og,-1))<0){
  156052. return(OV_EOF); /* eof.
  156053. leave unitialized */
  156054. }
  156055. /* bitrate tracking; add the header's bytes here, the body bytes
  156056. are done by packet above */
  156057. vf->bittrack+=og.header_len*8;
  156058. /* has our decoding just traversed a bitstream boundary? */
  156059. if(vf->ready_state==INITSET){
  156060. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156061. if(!spanp)
  156062. return(OV_EOF);
  156063. _decode_clear(vf);
  156064. if(!vf->seekable){
  156065. vorbis_info_clear(vf->vi);
  156066. vorbis_comment_clear(vf->vc);
  156067. }
  156068. }
  156069. }
  156070. }
  156071. /* Do we need to load a new machine before submitting the page? */
  156072. /* This is different in the seekable and non-seekable cases.
  156073. In the seekable case, we already have all the header
  156074. information loaded and cached; we just initialize the machine
  156075. with it and continue on our merry way.
  156076. In the non-seekable (streaming) case, we'll only be at a
  156077. boundary if we just left the previous logical bitstream and
  156078. we're now nominally at the header of the next bitstream
  156079. */
  156080. if(vf->ready_state!=INITSET){
  156081. int link;
  156082. if(vf->ready_state<STREAMSET){
  156083. if(vf->seekable){
  156084. vf->current_serialno=ogg_page_serialno(&og);
  156085. /* match the serialno to bitstream section. We use this rather than
  156086. offset positions to avoid problems near logical bitstream
  156087. boundaries */
  156088. for(link=0;link<vf->links;link++)
  156089. if(vf->serialnos[link]==vf->current_serialno)break;
  156090. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156091. stream. error out,
  156092. leave machine
  156093. uninitialized */
  156094. vf->current_link=link;
  156095. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156096. vf->ready_state=STREAMSET;
  156097. }else{
  156098. /* we're streaming */
  156099. /* fetch the three header packets, build the info struct */
  156100. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156101. if(ret)return(ret);
  156102. vf->current_link++;
  156103. link=0;
  156104. }
  156105. }
  156106. {
  156107. int ret=_make_decode_ready(vf);
  156108. if(ret<0)return ret;
  156109. }
  156110. }
  156111. ogg_stream_pagein(&vf->os,&og);
  156112. }
  156113. }
  156114. /* if, eg, 64 bit stdio is configured by default, this will build with
  156115. fseek64 */
  156116. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156117. if(f==NULL)return(-1);
  156118. return fseek(f,off,whence);
  156119. }
  156120. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156121. long ibytes, ov_callbacks callbacks){
  156122. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156123. int ret;
  156124. memset(vf,0,sizeof(*vf));
  156125. vf->datasource=f;
  156126. vf->callbacks = callbacks;
  156127. /* init the framing state */
  156128. ogg_sync_init(&vf->oy);
  156129. /* perhaps some data was previously read into a buffer for testing
  156130. against other stream types. Allow initialization from this
  156131. previously read data (as we may be reading from a non-seekable
  156132. stream) */
  156133. if(initial){
  156134. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156135. memcpy(buffer,initial,ibytes);
  156136. ogg_sync_wrote(&vf->oy,ibytes);
  156137. }
  156138. /* can we seek? Stevens suggests the seek test was portable */
  156139. if(offsettest!=-1)vf->seekable=1;
  156140. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156141. entry for partial open */
  156142. vf->links=1;
  156143. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156144. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156145. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156146. /* Try to fetch the headers, maintaining all the storage */
  156147. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156148. vf->datasource=NULL;
  156149. ov_clear(vf);
  156150. }else
  156151. vf->ready_state=PARTOPEN;
  156152. return(ret);
  156153. }
  156154. static int _ov_open2(OggVorbis_File *vf){
  156155. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156156. vf->ready_state=OPENED;
  156157. if(vf->seekable){
  156158. int ret=_open_seekable2(vf);
  156159. if(ret){
  156160. vf->datasource=NULL;
  156161. ov_clear(vf);
  156162. }
  156163. return(ret);
  156164. }else
  156165. vf->ready_state=STREAMSET;
  156166. return 0;
  156167. }
  156168. /* clear out the OggVorbis_File struct */
  156169. int ov_clear(OggVorbis_File *vf){
  156170. if(vf){
  156171. vorbis_block_clear(&vf->vb);
  156172. vorbis_dsp_clear(&vf->vd);
  156173. ogg_stream_clear(&vf->os);
  156174. if(vf->vi && vf->links){
  156175. int i;
  156176. for(i=0;i<vf->links;i++){
  156177. vorbis_info_clear(vf->vi+i);
  156178. vorbis_comment_clear(vf->vc+i);
  156179. }
  156180. _ogg_free(vf->vi);
  156181. _ogg_free(vf->vc);
  156182. }
  156183. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156184. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156185. if(vf->serialnos)_ogg_free(vf->serialnos);
  156186. if(vf->offsets)_ogg_free(vf->offsets);
  156187. ogg_sync_clear(&vf->oy);
  156188. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156189. memset(vf,0,sizeof(*vf));
  156190. }
  156191. #ifdef DEBUG_LEAKS
  156192. _VDBG_dump();
  156193. #endif
  156194. return(0);
  156195. }
  156196. /* inspects the OggVorbis file and finds/documents all the logical
  156197. bitstreams contained in it. Tries to be tolerant of logical
  156198. bitstream sections that are truncated/woogie.
  156199. return: -1) error
  156200. 0) OK
  156201. */
  156202. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156203. ov_callbacks callbacks){
  156204. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156205. if(ret)return ret;
  156206. return _ov_open2(vf);
  156207. }
  156208. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156209. ov_callbacks callbacks = {
  156210. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156211. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156212. (int (*)(void *)) fclose,
  156213. (long (*)(void *)) ftell
  156214. };
  156215. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156216. }
  156217. /* cheap hack for game usage where downsampling is desirable; there's
  156218. no need for SRC as we can just do it cheaply in libvorbis. */
  156219. int ov_halfrate(OggVorbis_File *vf,int flag){
  156220. int i;
  156221. if(vf->vi==NULL)return OV_EINVAL;
  156222. if(!vf->seekable)return OV_EINVAL;
  156223. if(vf->ready_state>=STREAMSET)
  156224. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156225. will be able to swap this on the fly, but
  156226. for now dumping the decode machine is needed
  156227. to reinit the MDCT lookups. 1.1 libvorbis
  156228. is planned to be able to switch on the fly */
  156229. for(i=0;i<vf->links;i++){
  156230. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156231. ov_halfrate(vf,0);
  156232. return OV_EINVAL;
  156233. }
  156234. }
  156235. return 0;
  156236. }
  156237. int ov_halfrate_p(OggVorbis_File *vf){
  156238. if(vf->vi==NULL)return OV_EINVAL;
  156239. return vorbis_synthesis_halfrate_p(vf->vi);
  156240. }
  156241. /* Only partially open the vorbis file; test for Vorbisness, and load
  156242. the headers for the first chain. Do not seek (although test for
  156243. seekability). Use ov_test_open to finish opening the file, else
  156244. ov_clear to close/free it. Same return codes as open. */
  156245. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156246. ov_callbacks callbacks)
  156247. {
  156248. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156249. }
  156250. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156251. ov_callbacks callbacks = {
  156252. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156253. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156254. (int (*)(void *)) fclose,
  156255. (long (*)(void *)) ftell
  156256. };
  156257. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156258. }
  156259. int ov_test_open(OggVorbis_File *vf){
  156260. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156261. return _ov_open2(vf);
  156262. }
  156263. /* How many logical bitstreams in this physical bitstream? */
  156264. long ov_streams(OggVorbis_File *vf){
  156265. return vf->links;
  156266. }
  156267. /* Is the FILE * associated with vf seekable? */
  156268. long ov_seekable(OggVorbis_File *vf){
  156269. return vf->seekable;
  156270. }
  156271. /* returns the bitrate for a given logical bitstream or the entire
  156272. physical bitstream. If the file is open for random access, it will
  156273. find the *actual* average bitrate. If the file is streaming, it
  156274. returns the nominal bitrate (if set) else the average of the
  156275. upper/lower bounds (if set) else -1 (unset).
  156276. If you want the actual bitrate field settings, get them from the
  156277. vorbis_info structs */
  156278. long ov_bitrate(OggVorbis_File *vf,int i){
  156279. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156280. if(i>=vf->links)return(OV_EINVAL);
  156281. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156282. if(i<0){
  156283. ogg_int64_t bits=0;
  156284. int i;
  156285. float br;
  156286. for(i=0;i<vf->links;i++)
  156287. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156288. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156289. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156290. * so this is slightly transformed to make it work.
  156291. */
  156292. br = bits/ov_time_total(vf,-1);
  156293. return(rint(br));
  156294. }else{
  156295. if(vf->seekable){
  156296. /* return the actual bitrate */
  156297. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156298. }else{
  156299. /* return nominal if set */
  156300. if(vf->vi[i].bitrate_nominal>0){
  156301. return vf->vi[i].bitrate_nominal;
  156302. }else{
  156303. if(vf->vi[i].bitrate_upper>0){
  156304. if(vf->vi[i].bitrate_lower>0){
  156305. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156306. }else{
  156307. return vf->vi[i].bitrate_upper;
  156308. }
  156309. }
  156310. return(OV_FALSE);
  156311. }
  156312. }
  156313. }
  156314. }
  156315. /* returns the actual bitrate since last call. returns -1 if no
  156316. additional data to offer since last call (or at beginning of stream),
  156317. EINVAL if stream is only partially open
  156318. */
  156319. long ov_bitrate_instant(OggVorbis_File *vf){
  156320. int link=(vf->seekable?vf->current_link:0);
  156321. long ret;
  156322. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156323. if(vf->samptrack==0)return(OV_FALSE);
  156324. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156325. vf->bittrack=0.f;
  156326. vf->samptrack=0.f;
  156327. return(ret);
  156328. }
  156329. /* Guess */
  156330. long ov_serialnumber(OggVorbis_File *vf,int i){
  156331. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156332. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156333. if(i<0){
  156334. return(vf->current_serialno);
  156335. }else{
  156336. return(vf->serialnos[i]);
  156337. }
  156338. }
  156339. /* returns: total raw (compressed) length of content if i==-1
  156340. raw (compressed) length of that logical bitstream for i==0 to n
  156341. OV_EINVAL if the stream is not seekable (we can't know the length)
  156342. or if stream is only partially open
  156343. */
  156344. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156345. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156346. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156347. if(i<0){
  156348. ogg_int64_t acc=0;
  156349. int i;
  156350. for(i=0;i<vf->links;i++)
  156351. acc+=ov_raw_total(vf,i);
  156352. return(acc);
  156353. }else{
  156354. return(vf->offsets[i+1]-vf->offsets[i]);
  156355. }
  156356. }
  156357. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156358. (samples) of that logical bitstream for i==0 to n
  156359. OV_EINVAL if the stream is not seekable (we can't know the
  156360. length) or only partially open
  156361. */
  156362. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156363. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156364. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156365. if(i<0){
  156366. ogg_int64_t acc=0;
  156367. int i;
  156368. for(i=0;i<vf->links;i++)
  156369. acc+=ov_pcm_total(vf,i);
  156370. return(acc);
  156371. }else{
  156372. return(vf->pcmlengths[i*2+1]);
  156373. }
  156374. }
  156375. /* returns: total seconds of content if i==-1
  156376. seconds in that logical bitstream for i==0 to n
  156377. OV_EINVAL if the stream is not seekable (we can't know the
  156378. length) or only partially open
  156379. */
  156380. double ov_time_total(OggVorbis_File *vf,int i){
  156381. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156382. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156383. if(i<0){
  156384. double acc=0;
  156385. int i;
  156386. for(i=0;i<vf->links;i++)
  156387. acc+=ov_time_total(vf,i);
  156388. return(acc);
  156389. }else{
  156390. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156391. }
  156392. }
  156393. /* seek to an offset relative to the *compressed* data. This also
  156394. scans packets to update the PCM cursor. It will cross a logical
  156395. bitstream boundary, but only if it can't get any packets out of the
  156396. tail of the bitstream we seek to (so no surprises).
  156397. returns zero on success, nonzero on failure */
  156398. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156399. ogg_stream_state work_os;
  156400. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156401. if(!vf->seekable)
  156402. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156403. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156404. /* don't yet clear out decoding machine (if it's initialized), in
  156405. the case we're in the same link. Restart the decode lapping, and
  156406. let _fetch_and_process_packet deal with a potential bitstream
  156407. boundary */
  156408. vf->pcm_offset=-1;
  156409. ogg_stream_reset_serialno(&vf->os,
  156410. vf->current_serialno); /* must set serialno */
  156411. vorbis_synthesis_restart(&vf->vd);
  156412. _seek_helper(vf,pos);
  156413. /* we need to make sure the pcm_offset is set, but we don't want to
  156414. advance the raw cursor past good packets just to get to the first
  156415. with a granulepos. That's not equivalent behavior to beginning
  156416. decoding as immediately after the seek position as possible.
  156417. So, a hack. We use two stream states; a local scratch state and
  156418. the shared vf->os stream state. We use the local state to
  156419. scan, and the shared state as a buffer for later decode.
  156420. Unfortuantely, on the last page we still advance to last packet
  156421. because the granulepos on the last page is not necessarily on a
  156422. packet boundary, and we need to make sure the granpos is
  156423. correct.
  156424. */
  156425. {
  156426. ogg_page og;
  156427. ogg_packet op;
  156428. int lastblock=0;
  156429. int accblock=0;
  156430. int thisblock;
  156431. int eosflag;
  156432. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156433. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156434. return from not necessarily
  156435. starting from the beginning */
  156436. while(1){
  156437. if(vf->ready_state>=STREAMSET){
  156438. /* snarf/scan a packet if we can */
  156439. int result=ogg_stream_packetout(&work_os,&op);
  156440. if(result>0){
  156441. if(vf->vi[vf->current_link].codec_setup){
  156442. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156443. if(thisblock<0){
  156444. ogg_stream_packetout(&vf->os,NULL);
  156445. thisblock=0;
  156446. }else{
  156447. if(eosflag)
  156448. ogg_stream_packetout(&vf->os,NULL);
  156449. else
  156450. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156451. }
  156452. if(op.granulepos!=-1){
  156453. int i,link=vf->current_link;
  156454. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156455. if(granulepos<0)granulepos=0;
  156456. for(i=0;i<link;i++)
  156457. granulepos+=vf->pcmlengths[i*2+1];
  156458. vf->pcm_offset=granulepos-accblock;
  156459. break;
  156460. }
  156461. lastblock=thisblock;
  156462. continue;
  156463. }else
  156464. ogg_stream_packetout(&vf->os,NULL);
  156465. }
  156466. }
  156467. if(!lastblock){
  156468. if(_get_next_page(vf,&og,-1)<0){
  156469. vf->pcm_offset=ov_pcm_total(vf,-1);
  156470. break;
  156471. }
  156472. }else{
  156473. /* huh? Bogus stream with packets but no granulepos */
  156474. vf->pcm_offset=-1;
  156475. break;
  156476. }
  156477. /* has our decoding just traversed a bitstream boundary? */
  156478. if(vf->ready_state>=STREAMSET)
  156479. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156480. _decode_clear(vf); /* clear out stream state */
  156481. ogg_stream_clear(&work_os);
  156482. }
  156483. if(vf->ready_state<STREAMSET){
  156484. int link;
  156485. vf->current_serialno=ogg_page_serialno(&og);
  156486. for(link=0;link<vf->links;link++)
  156487. if(vf->serialnos[link]==vf->current_serialno)break;
  156488. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156489. error out, leave
  156490. machine uninitialized */
  156491. vf->current_link=link;
  156492. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156493. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156494. vf->ready_state=STREAMSET;
  156495. }
  156496. ogg_stream_pagein(&vf->os,&og);
  156497. ogg_stream_pagein(&work_os,&og);
  156498. eosflag=ogg_page_eos(&og);
  156499. }
  156500. }
  156501. ogg_stream_clear(&work_os);
  156502. vf->bittrack=0.f;
  156503. vf->samptrack=0.f;
  156504. return(0);
  156505. seek_error:
  156506. /* dump the machine so we're in a known state */
  156507. vf->pcm_offset=-1;
  156508. ogg_stream_clear(&work_os);
  156509. _decode_clear(vf);
  156510. return OV_EBADLINK;
  156511. }
  156512. /* Page granularity seek (faster than sample granularity because we
  156513. don't do the last bit of decode to find a specific sample).
  156514. Seek to the last [granule marked] page preceeding the specified pos
  156515. location, such that decoding past the returned point will quickly
  156516. arrive at the requested position. */
  156517. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156518. int link=-1;
  156519. ogg_int64_t result=0;
  156520. ogg_int64_t total=ov_pcm_total(vf,-1);
  156521. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156522. if(!vf->seekable)return(OV_ENOSEEK);
  156523. if(pos<0 || pos>total)return(OV_EINVAL);
  156524. /* which bitstream section does this pcm offset occur in? */
  156525. for(link=vf->links-1;link>=0;link--){
  156526. total-=vf->pcmlengths[link*2+1];
  156527. if(pos>=total)break;
  156528. }
  156529. /* search within the logical bitstream for the page with the highest
  156530. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156531. missing pages or incorrect frame number information in the
  156532. bitstream could make our task impossible. Account for that (it
  156533. would be an error condition) */
  156534. /* new search algorithm by HB (Nicholas Vinen) */
  156535. {
  156536. ogg_int64_t end=vf->offsets[link+1];
  156537. ogg_int64_t begin=vf->offsets[link];
  156538. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156539. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156540. ogg_int64_t target=pos-total+begintime;
  156541. ogg_int64_t best=begin;
  156542. ogg_page og;
  156543. while(begin<end){
  156544. ogg_int64_t bisect;
  156545. if(end-begin<CHUNKSIZE){
  156546. bisect=begin;
  156547. }else{
  156548. /* take a (pretty decent) guess. */
  156549. bisect=begin +
  156550. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156551. if(bisect<=begin)
  156552. bisect=begin+1;
  156553. }
  156554. _seek_helper(vf,bisect);
  156555. while(begin<end){
  156556. result=_get_next_page(vf,&og,end-vf->offset);
  156557. if(result==OV_EREAD) goto seek_error;
  156558. if(result<0){
  156559. if(bisect<=begin+1)
  156560. end=begin; /* found it */
  156561. else{
  156562. if(bisect==0) goto seek_error;
  156563. bisect-=CHUNKSIZE;
  156564. if(bisect<=begin)bisect=begin+1;
  156565. _seek_helper(vf,bisect);
  156566. }
  156567. }else{
  156568. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156569. if(granulepos==-1)continue;
  156570. if(granulepos<target){
  156571. best=result; /* raw offset of packet with granulepos */
  156572. begin=vf->offset; /* raw offset of next page */
  156573. begintime=granulepos;
  156574. if(target-begintime>44100)break;
  156575. bisect=begin; /* *not* begin + 1 */
  156576. }else{
  156577. if(bisect<=begin+1)
  156578. end=begin; /* found it */
  156579. else{
  156580. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156581. end=result;
  156582. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156583. if(bisect<=begin)bisect=begin+1;
  156584. _seek_helper(vf,bisect);
  156585. }else{
  156586. end=result;
  156587. endtime=granulepos;
  156588. break;
  156589. }
  156590. }
  156591. }
  156592. }
  156593. }
  156594. }
  156595. /* found our page. seek to it, update pcm offset. Easier case than
  156596. raw_seek, don't keep packets preceeding granulepos. */
  156597. {
  156598. ogg_page og;
  156599. ogg_packet op;
  156600. /* seek */
  156601. _seek_helper(vf,best);
  156602. vf->pcm_offset=-1;
  156603. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156604. if(link!=vf->current_link){
  156605. /* Different link; dump entire decode machine */
  156606. _decode_clear(vf);
  156607. vf->current_link=link;
  156608. vf->current_serialno=ogg_page_serialno(&og);
  156609. vf->ready_state=STREAMSET;
  156610. }else{
  156611. vorbis_synthesis_restart(&vf->vd);
  156612. }
  156613. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156614. ogg_stream_pagein(&vf->os,&og);
  156615. /* pull out all but last packet; the one with granulepos */
  156616. while(1){
  156617. result=ogg_stream_packetpeek(&vf->os,&op);
  156618. if(result==0){
  156619. /* !!! the packet finishing this page originated on a
  156620. preceeding page. Keep fetching previous pages until we
  156621. get one with a granulepos or without the 'continued' flag
  156622. set. Then just use raw_seek for simplicity. */
  156623. _seek_helper(vf,best);
  156624. while(1){
  156625. result=_get_prev_page(vf,&og);
  156626. if(result<0) goto seek_error;
  156627. if(ogg_page_granulepos(&og)>-1 ||
  156628. !ogg_page_continued(&og)){
  156629. return ov_raw_seek(vf,result);
  156630. }
  156631. vf->offset=result;
  156632. }
  156633. }
  156634. if(result<0){
  156635. result = OV_EBADPACKET;
  156636. goto seek_error;
  156637. }
  156638. if(op.granulepos!=-1){
  156639. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156640. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156641. vf->pcm_offset+=total;
  156642. break;
  156643. }else
  156644. result=ogg_stream_packetout(&vf->os,NULL);
  156645. }
  156646. }
  156647. }
  156648. /* verify result */
  156649. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156650. result=OV_EFAULT;
  156651. goto seek_error;
  156652. }
  156653. vf->bittrack=0.f;
  156654. vf->samptrack=0.f;
  156655. return(0);
  156656. seek_error:
  156657. /* dump machine so we're in a known state */
  156658. vf->pcm_offset=-1;
  156659. _decode_clear(vf);
  156660. return (int)result;
  156661. }
  156662. /* seek to a sample offset relative to the decompressed pcm stream
  156663. returns zero on success, nonzero on failure */
  156664. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156665. int thisblock,lastblock=0;
  156666. int ret=ov_pcm_seek_page(vf,pos);
  156667. if(ret<0)return(ret);
  156668. if((ret=_make_decode_ready(vf)))return ret;
  156669. /* discard leading packets we don't need for the lapping of the
  156670. position we want; don't decode them */
  156671. while(1){
  156672. ogg_packet op;
  156673. ogg_page og;
  156674. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156675. if(ret>0){
  156676. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156677. if(thisblock<0){
  156678. ogg_stream_packetout(&vf->os,NULL);
  156679. continue; /* non audio packet */
  156680. }
  156681. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156682. if(vf->pcm_offset+((thisblock+
  156683. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156684. /* remove the packet from packet queue and track its granulepos */
  156685. ogg_stream_packetout(&vf->os,NULL);
  156686. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156687. only tracking, no
  156688. pcm_decode */
  156689. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156690. /* end of logical stream case is hard, especially with exact
  156691. length positioning. */
  156692. if(op.granulepos>-1){
  156693. int i;
  156694. /* always believe the stream markers */
  156695. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156696. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156697. for(i=0;i<vf->current_link;i++)
  156698. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156699. }
  156700. lastblock=thisblock;
  156701. }else{
  156702. if(ret<0 && ret!=OV_HOLE)break;
  156703. /* suck in a new page */
  156704. if(_get_next_page(vf,&og,-1)<0)break;
  156705. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156706. if(vf->ready_state<STREAMSET){
  156707. int link;
  156708. vf->current_serialno=ogg_page_serialno(&og);
  156709. for(link=0;link<vf->links;link++)
  156710. if(vf->serialnos[link]==vf->current_serialno)break;
  156711. if(link==vf->links)return(OV_EBADLINK);
  156712. vf->current_link=link;
  156713. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156714. vf->ready_state=STREAMSET;
  156715. ret=_make_decode_ready(vf);
  156716. if(ret)return ret;
  156717. lastblock=0;
  156718. }
  156719. ogg_stream_pagein(&vf->os,&og);
  156720. }
  156721. }
  156722. vf->bittrack=0.f;
  156723. vf->samptrack=0.f;
  156724. /* discard samples until we reach the desired position. Crossing a
  156725. logical bitstream boundary with abandon is OK. */
  156726. while(vf->pcm_offset<pos){
  156727. ogg_int64_t target=pos-vf->pcm_offset;
  156728. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156729. if(samples>target)samples=target;
  156730. vorbis_synthesis_read(&vf->vd,samples);
  156731. vf->pcm_offset+=samples;
  156732. if(samples<target)
  156733. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156734. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156735. }
  156736. return 0;
  156737. }
  156738. /* seek to a playback time relative to the decompressed pcm stream
  156739. returns zero on success, nonzero on failure */
  156740. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156741. /* translate time to PCM position and call ov_pcm_seek */
  156742. int link=-1;
  156743. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156744. double time_total=ov_time_total(vf,-1);
  156745. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156746. if(!vf->seekable)return(OV_ENOSEEK);
  156747. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156748. /* which bitstream section does this time offset occur in? */
  156749. for(link=vf->links-1;link>=0;link--){
  156750. pcm_total-=vf->pcmlengths[link*2+1];
  156751. time_total-=ov_time_total(vf,link);
  156752. if(seconds>=time_total)break;
  156753. }
  156754. /* enough information to convert time offset to pcm offset */
  156755. {
  156756. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156757. return(ov_pcm_seek(vf,target));
  156758. }
  156759. }
  156760. /* page-granularity version of ov_time_seek
  156761. returns zero on success, nonzero on failure */
  156762. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156763. /* translate time to PCM position and call ov_pcm_seek */
  156764. int link=-1;
  156765. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156766. double time_total=ov_time_total(vf,-1);
  156767. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156768. if(!vf->seekable)return(OV_ENOSEEK);
  156769. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156770. /* which bitstream section does this time offset occur in? */
  156771. for(link=vf->links-1;link>=0;link--){
  156772. pcm_total-=vf->pcmlengths[link*2+1];
  156773. time_total-=ov_time_total(vf,link);
  156774. if(seconds>=time_total)break;
  156775. }
  156776. /* enough information to convert time offset to pcm offset */
  156777. {
  156778. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156779. return(ov_pcm_seek_page(vf,target));
  156780. }
  156781. }
  156782. /* tell the current stream offset cursor. Note that seek followed by
  156783. tell will likely not give the set offset due to caching */
  156784. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156785. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156786. return(vf->offset);
  156787. }
  156788. /* return PCM offset (sample) of next PCM sample to be read */
  156789. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156790. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156791. return(vf->pcm_offset);
  156792. }
  156793. /* return time offset (seconds) of next PCM sample to be read */
  156794. double ov_time_tell(OggVorbis_File *vf){
  156795. int link=0;
  156796. ogg_int64_t pcm_total=0;
  156797. double time_total=0.f;
  156798. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156799. if(vf->seekable){
  156800. pcm_total=ov_pcm_total(vf,-1);
  156801. time_total=ov_time_total(vf,-1);
  156802. /* which bitstream section does this time offset occur in? */
  156803. for(link=vf->links-1;link>=0;link--){
  156804. pcm_total-=vf->pcmlengths[link*2+1];
  156805. time_total-=ov_time_total(vf,link);
  156806. if(vf->pcm_offset>=pcm_total)break;
  156807. }
  156808. }
  156809. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156810. }
  156811. /* link: -1) return the vorbis_info struct for the bitstream section
  156812. currently being decoded
  156813. 0-n) to request information for a specific bitstream section
  156814. In the case of a non-seekable bitstream, any call returns the
  156815. current bitstream. NULL in the case that the machine is not
  156816. initialized */
  156817. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156818. if(vf->seekable){
  156819. if(link<0)
  156820. if(vf->ready_state>=STREAMSET)
  156821. return vf->vi+vf->current_link;
  156822. else
  156823. return vf->vi;
  156824. else
  156825. if(link>=vf->links)
  156826. return NULL;
  156827. else
  156828. return vf->vi+link;
  156829. }else{
  156830. return vf->vi;
  156831. }
  156832. }
  156833. /* grr, strong typing, grr, no templates/inheritence, grr */
  156834. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156835. if(vf->seekable){
  156836. if(link<0)
  156837. if(vf->ready_state>=STREAMSET)
  156838. return vf->vc+vf->current_link;
  156839. else
  156840. return vf->vc;
  156841. else
  156842. if(link>=vf->links)
  156843. return NULL;
  156844. else
  156845. return vf->vc+link;
  156846. }else{
  156847. return vf->vc;
  156848. }
  156849. }
  156850. static int host_is_big_endian() {
  156851. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156852. unsigned char *bytewise = (unsigned char *)&pattern;
  156853. if (bytewise[0] == 0xfe) return 1;
  156854. return 0;
  156855. }
  156856. /* up to this point, everything could more or less hide the multiple
  156857. logical bitstream nature of chaining from the toplevel application
  156858. if the toplevel application didn't particularly care. However, at
  156859. the point that we actually read audio back, the multiple-section
  156860. nature must surface: Multiple bitstream sections do not necessarily
  156861. have to have the same number of channels or sampling rate.
  156862. ov_read returns the sequential logical bitstream number currently
  156863. being decoded along with the PCM data in order that the toplevel
  156864. application can take action on channel/sample rate changes. This
  156865. number will be incremented even for streamed (non-seekable) streams
  156866. (for seekable streams, it represents the actual logical bitstream
  156867. index within the physical bitstream. Note that the accessor
  156868. functions above are aware of this dichotomy).
  156869. input values: buffer) a buffer to hold packed PCM data for return
  156870. length) the byte length requested to be placed into buffer
  156871. bigendianp) should the data be packed LSB first (0) or
  156872. MSB first (1)
  156873. word) word size for output. currently 1 (byte) or
  156874. 2 (16 bit short)
  156875. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156876. 0) EOF
  156877. n) number of bytes of PCM actually returned. The
  156878. below works on a packet-by-packet basis, so the
  156879. return length is not related to the 'length' passed
  156880. in, just guaranteed to fit.
  156881. *section) set to the logical bitstream number */
  156882. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156883. int bigendianp,int word,int sgned,int *bitstream){
  156884. int i,j;
  156885. int host_endian = host_is_big_endian();
  156886. float **pcm;
  156887. long samples;
  156888. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156889. while(1){
  156890. if(vf->ready_state==INITSET){
  156891. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156892. if(samples)break;
  156893. }
  156894. /* suck in another packet */
  156895. {
  156896. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156897. if(ret==OV_EOF)
  156898. return(0);
  156899. if(ret<=0)
  156900. return(ret);
  156901. }
  156902. }
  156903. if(samples>0){
  156904. /* yay! proceed to pack data into the byte buffer */
  156905. long channels=ov_info(vf,-1)->channels;
  156906. long bytespersample=word * channels;
  156907. vorbis_fpu_control fpu;
  156908. (void) fpu; // (to avoid a warning about it being unused)
  156909. if(samples>length/bytespersample)samples=length/bytespersample;
  156910. if(samples <= 0)
  156911. return OV_EINVAL;
  156912. /* a tight loop to pack each size */
  156913. {
  156914. int val;
  156915. if(word==1){
  156916. int off=(sgned?0:128);
  156917. vorbis_fpu_setround(&fpu);
  156918. for(j=0;j<samples;j++)
  156919. for(i=0;i<channels;i++){
  156920. val=vorbis_ftoi(pcm[i][j]*128.f);
  156921. if(val>127)val=127;
  156922. else if(val<-128)val=-128;
  156923. *buffer++=val+off;
  156924. }
  156925. vorbis_fpu_restore(fpu);
  156926. }else{
  156927. int off=(sgned?0:32768);
  156928. if(host_endian==bigendianp){
  156929. if(sgned){
  156930. vorbis_fpu_setround(&fpu);
  156931. for(i=0;i<channels;i++) { /* It's faster in this order */
  156932. float *src=pcm[i];
  156933. short *dest=((short *)buffer)+i;
  156934. for(j=0;j<samples;j++) {
  156935. val=vorbis_ftoi(src[j]*32768.f);
  156936. if(val>32767)val=32767;
  156937. else if(val<-32768)val=-32768;
  156938. *dest=val;
  156939. dest+=channels;
  156940. }
  156941. }
  156942. vorbis_fpu_restore(fpu);
  156943. }else{
  156944. vorbis_fpu_setround(&fpu);
  156945. for(i=0;i<channels;i++) {
  156946. float *src=pcm[i];
  156947. short *dest=((short *)buffer)+i;
  156948. for(j=0;j<samples;j++) {
  156949. val=vorbis_ftoi(src[j]*32768.f);
  156950. if(val>32767)val=32767;
  156951. else if(val<-32768)val=-32768;
  156952. *dest=val+off;
  156953. dest+=channels;
  156954. }
  156955. }
  156956. vorbis_fpu_restore(fpu);
  156957. }
  156958. }else if(bigendianp){
  156959. vorbis_fpu_setround(&fpu);
  156960. for(j=0;j<samples;j++)
  156961. for(i=0;i<channels;i++){
  156962. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156963. if(val>32767)val=32767;
  156964. else if(val<-32768)val=-32768;
  156965. val+=off;
  156966. *buffer++=(val>>8);
  156967. *buffer++=(val&0xff);
  156968. }
  156969. vorbis_fpu_restore(fpu);
  156970. }else{
  156971. int val;
  156972. vorbis_fpu_setround(&fpu);
  156973. for(j=0;j<samples;j++)
  156974. for(i=0;i<channels;i++){
  156975. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156976. if(val>32767)val=32767;
  156977. else if(val<-32768)val=-32768;
  156978. val+=off;
  156979. *buffer++=(val&0xff);
  156980. *buffer++=(val>>8);
  156981. }
  156982. vorbis_fpu_restore(fpu);
  156983. }
  156984. }
  156985. }
  156986. vorbis_synthesis_read(&vf->vd,samples);
  156987. vf->pcm_offset+=samples;
  156988. if(bitstream)*bitstream=vf->current_link;
  156989. return(samples*bytespersample);
  156990. }else{
  156991. return(samples);
  156992. }
  156993. }
  156994. /* input values: pcm_channels) a float vector per channel of output
  156995. length) the sample length being read by the app
  156996. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156997. 0) EOF
  156998. n) number of samples of PCM actually returned. The
  156999. below works on a packet-by-packet basis, so the
  157000. return length is not related to the 'length' passed
  157001. in, just guaranteed to fit.
  157002. *section) set to the logical bitstream number */
  157003. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157004. int *bitstream){
  157005. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157006. while(1){
  157007. if(vf->ready_state==INITSET){
  157008. float **pcm;
  157009. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157010. if(samples){
  157011. if(pcm_channels)*pcm_channels=pcm;
  157012. if(samples>length)samples=length;
  157013. vorbis_synthesis_read(&vf->vd,samples);
  157014. vf->pcm_offset+=samples;
  157015. if(bitstream)*bitstream=vf->current_link;
  157016. return samples;
  157017. }
  157018. }
  157019. /* suck in another packet */
  157020. {
  157021. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157022. if(ret==OV_EOF)return(0);
  157023. if(ret<=0)return(ret);
  157024. }
  157025. }
  157026. }
  157027. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157028. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157029. ogg_int64_t off);
  157030. static void _ov_splice(float **pcm,float **lappcm,
  157031. int n1, int n2,
  157032. int ch1, int ch2,
  157033. float *w1, float *w2){
  157034. int i,j;
  157035. float *w=w1;
  157036. int n=n1;
  157037. if(n1>n2){
  157038. n=n2;
  157039. w=w2;
  157040. }
  157041. /* splice */
  157042. for(j=0;j<ch1 && j<ch2;j++){
  157043. float *s=lappcm[j];
  157044. float *d=pcm[j];
  157045. for(i=0;i<n;i++){
  157046. float wd=w[i]*w[i];
  157047. float ws=1.-wd;
  157048. d[i]=d[i]*wd + s[i]*ws;
  157049. }
  157050. }
  157051. /* window from zero */
  157052. for(;j<ch2;j++){
  157053. float *d=pcm[j];
  157054. for(i=0;i<n;i++){
  157055. float wd=w[i]*w[i];
  157056. d[i]=d[i]*wd;
  157057. }
  157058. }
  157059. }
  157060. /* make sure vf is INITSET */
  157061. static int _ov_initset(OggVorbis_File *vf){
  157062. while(1){
  157063. if(vf->ready_state==INITSET)break;
  157064. /* suck in another packet */
  157065. {
  157066. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157067. if(ret<0 && ret!=OV_HOLE)return(ret);
  157068. }
  157069. }
  157070. return 0;
  157071. }
  157072. /* make sure vf is INITSET and that we have a primed buffer; if
  157073. we're crosslapping at a stream section boundary, this also makes
  157074. sure we're sanity checking against the right stream information */
  157075. static int _ov_initprime(OggVorbis_File *vf){
  157076. vorbis_dsp_state *vd=&vf->vd;
  157077. while(1){
  157078. if(vf->ready_state==INITSET)
  157079. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157080. /* suck in another packet */
  157081. {
  157082. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157083. if(ret<0 && ret!=OV_HOLE)return(ret);
  157084. }
  157085. }
  157086. return 0;
  157087. }
  157088. /* grab enough data for lapping from vf; this may be in the form of
  157089. unreturned, already-decoded pcm, remaining PCM we will need to
  157090. decode, or synthetic postextrapolation from last packets. */
  157091. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157092. float **lappcm,int lapsize){
  157093. int lapcount=0,i;
  157094. float **pcm;
  157095. /* try first to decode the lapping data */
  157096. while(lapcount<lapsize){
  157097. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157098. if(samples){
  157099. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157100. for(i=0;i<vi->channels;i++)
  157101. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157102. lapcount+=samples;
  157103. vorbis_synthesis_read(vd,samples);
  157104. }else{
  157105. /* suck in another packet */
  157106. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157107. if(ret==OV_EOF)break;
  157108. }
  157109. }
  157110. if(lapcount<lapsize){
  157111. /* failed to get lapping data from normal decode; pry it from the
  157112. postextrapolation buffering, or the second half of the MDCT
  157113. from the last packet */
  157114. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157115. if(samples==0){
  157116. for(i=0;i<vi->channels;i++)
  157117. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157118. lapcount=lapsize;
  157119. }else{
  157120. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157121. for(i=0;i<vi->channels;i++)
  157122. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157123. lapcount+=samples;
  157124. }
  157125. }
  157126. }
  157127. /* this sets up crosslapping of a sample by using trailing data from
  157128. sample 1 and lapping it into the windowing buffer of sample 2 */
  157129. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157130. vorbis_info *vi1,*vi2;
  157131. float **lappcm;
  157132. float **pcm;
  157133. float *w1,*w2;
  157134. int n1,n2,i,ret,hs1,hs2;
  157135. if(vf1==vf2)return(0); /* degenerate case */
  157136. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157137. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157138. /* the relevant overlap buffers must be pre-checked and pre-primed
  157139. before looking at settings in the event that priming would cross
  157140. a bitstream boundary. So, do it now */
  157141. ret=_ov_initset(vf1);
  157142. if(ret)return(ret);
  157143. ret=_ov_initprime(vf2);
  157144. if(ret)return(ret);
  157145. vi1=ov_info(vf1,-1);
  157146. vi2=ov_info(vf2,-1);
  157147. hs1=ov_halfrate_p(vf1);
  157148. hs2=ov_halfrate_p(vf2);
  157149. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157150. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157151. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157152. w1=vorbis_window(&vf1->vd,0);
  157153. w2=vorbis_window(&vf2->vd,0);
  157154. for(i=0;i<vi1->channels;i++)
  157155. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157156. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157157. /* have a lapping buffer from vf1; now to splice it into the lapping
  157158. buffer of vf2 */
  157159. /* consolidate and expose the buffer. */
  157160. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157161. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157162. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157163. /* splice */
  157164. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157165. /* done */
  157166. return(0);
  157167. }
  157168. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157169. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157170. vorbis_info *vi;
  157171. float **lappcm;
  157172. float **pcm;
  157173. float *w1,*w2;
  157174. int n1,n2,ch1,ch2,hs;
  157175. int i,ret;
  157176. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157177. ret=_ov_initset(vf);
  157178. if(ret)return(ret);
  157179. vi=ov_info(vf,-1);
  157180. hs=ov_halfrate_p(vf);
  157181. ch1=vi->channels;
  157182. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157183. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157184. persistent; even if the decode state
  157185. from this link gets dumped, this
  157186. window array continues to exist */
  157187. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157188. for(i=0;i<ch1;i++)
  157189. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157190. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157191. /* have lapping data; seek and prime the buffer */
  157192. ret=localseek(vf,pos);
  157193. if(ret)return ret;
  157194. ret=_ov_initprime(vf);
  157195. if(ret)return(ret);
  157196. /* Guard against cross-link changes; they're perfectly legal */
  157197. vi=ov_info(vf,-1);
  157198. ch2=vi->channels;
  157199. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157200. w2=vorbis_window(&vf->vd,0);
  157201. /* consolidate and expose the buffer. */
  157202. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157203. /* splice */
  157204. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157205. /* done */
  157206. return(0);
  157207. }
  157208. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157209. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157210. }
  157211. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157212. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157213. }
  157214. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157215. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157216. }
  157217. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157218. int (*localseek)(OggVorbis_File *,double)){
  157219. vorbis_info *vi;
  157220. float **lappcm;
  157221. float **pcm;
  157222. float *w1,*w2;
  157223. int n1,n2,ch1,ch2,hs;
  157224. int i,ret;
  157225. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157226. ret=_ov_initset(vf);
  157227. if(ret)return(ret);
  157228. vi=ov_info(vf,-1);
  157229. hs=ov_halfrate_p(vf);
  157230. ch1=vi->channels;
  157231. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157232. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157233. persistent; even if the decode state
  157234. from this link gets dumped, this
  157235. window array continues to exist */
  157236. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157237. for(i=0;i<ch1;i++)
  157238. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157239. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157240. /* have lapping data; seek and prime the buffer */
  157241. ret=localseek(vf,pos);
  157242. if(ret)return ret;
  157243. ret=_ov_initprime(vf);
  157244. if(ret)return(ret);
  157245. /* Guard against cross-link changes; they're perfectly legal */
  157246. vi=ov_info(vf,-1);
  157247. ch2=vi->channels;
  157248. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157249. w2=vorbis_window(&vf->vd,0);
  157250. /* consolidate and expose the buffer. */
  157251. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157252. /* splice */
  157253. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157254. /* done */
  157255. return(0);
  157256. }
  157257. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157258. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157259. }
  157260. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157261. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157262. }
  157263. #endif
  157264. /*** End of inlined file: vorbisfile.c ***/
  157265. /*** Start of inlined file: window.c ***/
  157266. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157267. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157268. // tasks..
  157269. #if JUCE_MSVC
  157270. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157271. #endif
  157272. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157273. #if JUCE_USE_OGGVORBIS
  157274. #include <stdlib.h>
  157275. #include <math.h>
  157276. static float vwin64[32] = {
  157277. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157278. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157279. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157280. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157281. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157282. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157283. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157284. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157285. };
  157286. static float vwin128[64] = {
  157287. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157288. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157289. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157290. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157291. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157292. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157293. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157294. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157295. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157296. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157297. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157298. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157299. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157300. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157301. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157302. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157303. };
  157304. static float vwin256[128] = {
  157305. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157306. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157307. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157308. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157309. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157310. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157311. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157312. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157313. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157314. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157315. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157316. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157317. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157318. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157319. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157320. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157321. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157322. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157323. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157324. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157325. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157326. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157327. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157328. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157329. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157330. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157331. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157332. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157333. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157334. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157335. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157336. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157337. };
  157338. static float vwin512[256] = {
  157339. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157340. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157341. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157342. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157343. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157344. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157345. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157346. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157347. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157348. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157349. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157350. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157351. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157352. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157353. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157354. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157355. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157356. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157357. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157358. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157359. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157360. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157361. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157362. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157363. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157364. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157365. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157366. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157367. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157368. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157369. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157370. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157371. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157372. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157373. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157374. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157375. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157376. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157377. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157378. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157379. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157380. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157381. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157382. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157383. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157384. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157385. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157386. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157387. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157388. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157389. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157390. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157391. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157392. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157393. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157394. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157395. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157396. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157397. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157398. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157399. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157400. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157401. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157402. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157403. };
  157404. static float vwin1024[512] = {
  157405. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157406. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157407. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157408. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157409. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157410. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157411. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157412. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157413. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157414. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157415. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157416. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157417. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157418. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157419. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157420. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157421. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157422. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157423. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157424. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157425. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157426. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157427. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157428. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157429. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157430. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157431. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157432. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157433. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157434. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157435. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157436. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157437. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157438. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157439. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157440. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157441. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157442. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157443. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157444. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157445. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157446. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157447. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157448. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157449. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157450. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157451. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157452. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157453. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157454. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157455. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157456. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157457. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157458. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157459. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157460. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157461. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157462. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157463. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157464. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157465. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157466. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157467. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157468. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157469. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157470. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157471. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157472. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157473. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157474. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157475. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157476. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157477. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157478. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157479. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157480. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157481. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157482. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157483. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157484. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157485. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157486. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157487. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157488. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157489. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157490. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157491. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157492. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157493. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157494. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157495. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157496. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157497. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157498. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157499. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157500. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157501. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157502. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157503. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157504. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157505. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157506. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157507. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157508. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157509. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157510. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157511. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157512. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157513. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157514. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157515. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157516. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157517. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157518. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157519. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157520. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157521. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157522. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157523. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157524. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157525. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157526. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157527. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157528. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157529. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157530. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157531. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157532. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157533. };
  157534. static float vwin2048[1024] = {
  157535. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157536. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157537. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157538. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157539. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157540. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157541. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157542. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157543. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157544. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157545. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157546. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157547. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157548. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157549. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157550. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157551. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157552. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157553. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157554. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157555. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157556. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157557. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157558. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157559. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157560. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157561. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157562. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157563. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157564. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157565. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157566. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157567. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157568. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157569. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157570. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157571. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157572. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157573. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157574. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157575. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157576. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157577. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157578. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157579. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157580. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157581. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157582. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157583. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157584. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157585. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157586. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157587. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157588. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157589. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157590. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157591. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157592. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157593. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157594. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157595. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157596. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157597. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157598. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157599. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157600. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157601. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157602. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157603. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157604. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157605. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157606. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157607. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157608. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157609. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157610. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157611. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157612. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157613. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157614. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157615. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157616. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157617. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157618. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157619. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157620. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157621. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157622. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157623. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157624. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157625. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157626. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157627. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157628. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157629. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157630. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157631. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157632. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157633. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157634. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157635. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157636. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157637. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157638. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157639. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157640. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157641. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157642. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157643. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157644. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157645. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157646. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157647. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157648. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157649. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157650. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157651. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157652. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157653. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157654. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157655. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157656. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157657. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157658. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157659. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157660. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157661. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157662. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157663. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157664. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157665. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157666. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157667. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157668. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157669. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157670. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157671. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157672. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157673. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157674. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157675. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157676. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157677. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157678. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157679. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157680. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157681. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157682. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157683. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157684. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157685. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157686. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157687. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157688. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157689. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157690. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157691. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157692. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157693. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157694. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157695. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157696. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157697. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157698. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157699. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157700. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157701. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157702. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157703. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157704. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157705. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157706. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157707. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157708. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157709. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157710. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157711. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157712. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157713. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157714. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157715. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157716. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157717. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157718. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157719. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157720. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157721. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157722. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157723. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157724. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157725. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157726. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157727. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157728. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157729. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157730. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157731. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157732. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157733. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157734. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157735. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157736. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157737. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157738. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157739. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157740. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157741. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157742. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157743. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157744. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157745. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157746. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157747. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157748. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157749. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157750. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157751. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157752. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157753. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157754. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157755. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157756. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157757. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157758. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157759. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157760. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157761. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157762. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157763. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157764. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157765. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157766. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157767. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157768. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157769. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157770. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157771. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157772. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157773. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157774. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157775. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157776. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157777. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157778. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157779. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157780. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157781. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157782. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157783. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157784. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157785. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157786. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157787. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157788. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157789. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157790. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157791. };
  157792. static float vwin4096[2048] = {
  157793. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157794. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157795. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157796. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157797. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157798. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157799. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157800. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157801. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157802. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157803. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157804. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157805. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157806. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157807. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157808. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157809. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157810. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157811. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157812. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157813. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157814. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157815. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157816. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157817. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157818. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157819. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157820. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157821. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157822. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157823. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157824. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157825. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157826. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157827. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157828. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157829. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157830. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157831. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157832. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157833. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157834. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157835. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157836. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157837. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157838. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157839. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157840. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157841. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157842. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157843. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157844. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157845. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157846. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157847. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157848. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157849. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157850. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157851. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157852. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157853. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157854. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157855. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157856. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157857. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157858. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157859. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157860. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157861. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157862. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157863. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157864. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157865. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157866. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157867. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157868. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157869. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157870. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157871. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157872. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157873. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157874. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157875. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157876. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157877. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157878. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157879. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157880. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157881. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157882. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157883. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157884. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157885. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157886. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157887. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157888. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157889. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157890. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157891. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157892. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157893. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157894. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157895. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157896. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157897. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157898. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157899. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157900. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157901. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157902. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157903. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157904. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157905. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157906. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157907. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157908. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157909. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157910. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157911. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157912. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157913. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157914. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157915. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157916. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157917. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157918. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157919. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157920. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157921. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157922. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157923. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157924. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157925. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157926. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157927. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157928. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157929. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157930. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157931. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157932. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157933. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157934. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157935. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157936. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157937. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157938. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157939. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157940. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157941. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157942. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157943. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157944. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157945. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157946. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157947. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157948. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157949. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157950. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157951. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157952. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157953. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157954. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157955. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157956. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157957. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157958. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157959. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157960. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157961. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157962. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157963. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157964. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157965. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157966. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157967. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157968. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157969. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157970. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157971. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157972. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157973. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157974. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157975. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157976. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157977. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157978. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157979. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157980. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157981. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157982. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157983. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157984. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157985. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157986. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157987. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157988. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157989. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157990. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157991. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157992. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157993. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157994. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157995. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157996. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157997. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157998. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157999. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158000. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158001. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158002. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158003. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158004. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158005. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158006. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158007. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158008. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158009. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158010. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158011. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158012. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158013. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158014. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158015. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158016. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158017. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158018. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158019. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158020. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158021. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158022. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158023. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158024. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158025. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158026. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158027. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158028. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158029. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158030. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158031. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158032. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158033. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158034. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158035. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158036. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158037. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158038. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158039. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158040. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158041. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158042. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158043. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158044. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158045. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158046. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158047. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158048. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158049. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158050. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158051. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158052. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158053. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158054. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158055. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158056. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158057. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158058. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158059. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158060. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158061. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158062. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158063. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158064. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158065. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158066. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158067. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158068. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158069. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158070. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158071. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158072. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158073. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158074. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158075. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158076. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158077. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158078. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158079. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158080. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158081. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158082. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158083. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158084. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158085. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158086. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158087. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158088. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158089. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158090. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158091. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158092. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158093. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158094. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158095. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158096. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158097. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158098. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158099. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158100. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158101. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158102. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158103. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158104. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158105. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158106. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158107. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158108. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158109. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158110. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158111. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158112. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158113. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158114. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158115. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158116. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158117. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158118. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158119. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158120. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158121. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158122. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158123. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158124. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158125. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158126. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158127. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158128. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158129. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158130. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158131. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158132. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158133. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158134. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158135. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158136. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158137. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158138. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158139. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158140. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158141. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158142. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158143. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158144. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158145. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158146. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158147. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158148. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158149. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158150. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158151. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158152. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158153. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158154. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158155. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158156. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158157. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158158. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158159. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158160. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158161. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158162. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158163. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158164. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158165. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158166. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158167. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158168. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158169. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158170. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158171. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158172. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158173. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158174. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158175. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158176. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158177. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158178. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158179. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158180. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158181. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158182. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158183. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158184. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158185. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158186. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158187. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158188. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158189. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158190. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158191. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158192. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158193. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158194. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158195. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158196. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158197. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158198. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158199. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158200. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158201. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158202. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158203. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158204. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158205. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158206. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158207. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158208. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158209. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158210. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158211. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158212. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158213. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158214. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158215. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158216. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158217. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158218. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158219. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158220. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158221. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158222. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158223. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158224. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158225. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158226. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158227. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158228. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158229. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158230. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158231. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158232. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158233. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158234. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158235. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158236. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158237. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158238. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158239. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158240. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158241. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158242. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158243. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158244. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158245. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158246. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158247. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158248. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158249. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158250. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158251. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158252. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158253. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158254. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158255. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158256. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158257. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158258. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158259. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158260. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158261. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158262. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158263. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158264. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158265. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158266. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158267. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158268. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158269. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158270. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158271. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158272. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158273. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158274. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158275. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158276. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158277. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158278. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158279. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158280. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158281. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158282. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158283. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158284. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158285. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158286. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158287. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158288. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158289. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158290. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158291. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158292. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158293. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158294. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158295. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158296. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158297. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158298. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158299. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158300. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158301. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158302. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158303. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158304. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158305. };
  158306. static float vwin8192[4096] = {
  158307. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158308. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158309. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158310. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158311. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158312. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158313. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158314. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158315. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158316. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158317. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158318. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158319. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158320. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158321. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158322. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158323. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158324. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158325. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158326. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158327. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158328. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158329. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158330. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158331. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158332. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158333. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158334. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158335. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158336. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158337. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158338. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158339. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158340. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158341. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158342. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158343. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158344. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158345. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158346. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158347. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158348. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158349. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158350. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158351. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158352. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158353. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158354. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158355. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158356. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158357. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158358. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158359. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158360. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158361. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158362. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158363. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158364. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158365. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158366. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158367. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158368. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158369. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158370. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158371. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158372. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158373. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158374. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158375. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158376. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158377. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158378. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158379. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158380. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158381. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158382. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158383. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158384. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158385. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158386. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158387. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158388. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158389. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158390. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158391. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158392. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158393. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158394. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158395. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158396. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158397. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158398. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158399. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158400. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158401. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158402. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158403. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158404. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158405. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158406. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158407. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158408. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158409. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158410. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158411. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158412. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158413. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158414. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158415. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158416. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158417. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158418. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158419. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158420. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158421. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158422. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158423. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158424. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158425. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158426. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158427. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158428. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158429. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158430. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158431. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158432. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158433. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158434. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158435. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158436. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158437. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158438. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158439. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158440. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158441. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158442. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158443. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158444. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158445. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158446. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158447. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158448. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158449. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158450. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158451. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158452. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158453. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158454. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158455. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158456. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158457. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158458. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158459. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158460. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158461. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158462. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158463. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158464. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158465. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158466. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158467. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158468. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158469. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158470. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158471. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158472. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158473. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158474. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158475. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158476. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158477. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158478. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158479. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158480. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158481. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158482. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158483. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158484. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158485. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158486. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158487. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158488. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158489. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158490. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158491. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158492. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158493. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158494. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158495. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158496. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158497. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158498. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158499. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158500. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158501. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158502. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158503. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158504. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158505. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158506. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158507. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158508. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158509. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158510. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158511. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158512. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158513. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158514. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158515. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158516. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158517. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158518. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158519. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158520. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158521. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158522. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158523. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158524. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158525. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158526. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158527. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158528. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158529. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158530. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158531. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158532. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158533. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158534. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158535. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158536. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158537. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158538. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158539. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158540. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158541. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158542. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158543. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158544. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158545. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158546. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158547. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158548. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158549. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158550. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158551. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158552. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158553. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158554. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158555. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158556. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158557. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158558. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158559. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158560. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158561. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158562. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158563. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158564. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158565. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158566. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158567. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158568. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158569. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158570. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158571. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158572. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158573. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158574. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158575. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158576. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158577. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158578. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158579. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158580. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158581. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158582. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158583. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158584. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158585. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158586. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158587. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158588. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158589. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158590. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158591. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158592. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158593. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158594. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158595. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158596. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158597. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158598. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158599. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158600. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158601. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158602. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158603. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158604. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158605. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158606. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158607. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158608. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158609. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158610. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158611. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158612. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158613. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158614. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158615. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158616. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158617. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158618. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158619. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158620. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158621. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158622. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158623. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158624. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158625. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158626. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158627. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158628. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158629. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158630. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158631. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158632. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158633. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158634. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158635. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158636. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158637. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158638. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158639. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158640. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158641. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158642. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158643. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158644. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158645. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158646. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158647. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158648. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158649. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158650. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158651. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158652. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158653. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158654. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158655. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158656. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158657. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158658. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158659. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158660. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158661. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158662. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158663. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158664. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158665. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158666. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158667. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158668. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158669. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158670. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158671. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158672. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158673. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158674. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158675. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158676. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158677. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158678. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158679. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158680. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158681. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158682. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158683. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158684. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158685. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158686. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158687. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158688. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158689. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158690. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158691. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158692. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158693. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158694. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158695. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158696. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158697. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158698. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158699. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158700. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158701. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158702. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158703. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158704. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158705. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158706. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158707. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158708. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158709. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158710. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158711. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158712. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158713. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158714. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158715. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158716. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158717. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158718. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158719. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158720. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158721. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158722. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158723. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158724. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158725. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158726. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158727. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158728. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158729. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158730. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158731. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158732. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158733. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158734. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158735. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158736. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158737. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158738. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158739. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158740. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158741. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158742. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158743. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158744. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158745. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158746. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158747. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158748. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158749. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158750. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158751. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158752. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158753. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158754. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158755. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158756. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158757. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158758. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158759. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158760. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158761. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158762. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158763. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158764. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158765. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158766. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158767. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158768. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158769. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158770. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158771. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158772. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158773. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158774. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158775. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158776. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158777. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158778. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158779. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158780. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158781. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158782. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158783. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158784. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158785. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158786. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158787. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158788. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158789. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158790. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158791. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158792. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158793. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158794. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158795. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158796. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158797. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158798. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158799. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158800. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158801. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158802. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158803. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158804. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158805. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158806. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158807. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158808. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158809. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158810. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158811. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158812. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158813. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158814. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158815. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158816. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158817. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158818. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158819. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158820. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158821. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158822. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158823. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158824. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158825. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158826. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158827. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158828. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158829. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158830. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158831. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158832. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158833. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158834. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158835. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158836. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158837. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158838. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158839. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158840. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158841. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158842. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158843. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158844. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158845. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158846. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158847. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158848. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158849. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158850. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158851. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158852. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158853. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158854. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158855. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158856. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158857. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158858. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158859. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158860. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158861. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158862. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158863. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158864. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158865. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158866. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158867. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158868. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158869. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158870. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158871. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158872. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158873. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158874. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158875. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158876. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158877. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158878. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158879. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158880. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158881. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158882. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158883. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158884. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158885. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158886. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158887. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158888. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158889. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158890. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158891. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158892. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158893. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158894. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158895. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158896. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158897. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158898. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158899. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158900. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158901. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158902. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158903. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158904. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158905. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158906. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158907. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158908. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158909. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158910. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158911. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158912. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158913. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158914. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158915. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158916. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158917. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158918. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158919. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158920. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158921. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158922. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158923. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158924. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158925. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158926. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158927. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158928. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158929. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158930. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158931. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158932. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158933. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158934. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158935. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158936. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158937. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158938. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158939. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158940. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158941. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158942. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158943. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158944. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158945. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158946. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158947. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158948. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158949. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158950. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158951. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158952. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158953. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158954. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158955. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158956. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158957. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158958. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158959. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158960. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158961. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158962. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158963. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158964. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158965. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158966. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158967. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158968. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158969. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158970. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158971. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158972. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158973. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158974. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158975. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158976. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158977. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158978. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158979. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158980. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158981. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158982. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158983. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158984. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158985. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158986. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158987. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158988. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158989. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158990. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158991. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158992. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158993. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158994. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158995. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158996. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158997. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158998. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158999. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159000. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159001. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159002. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159003. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159004. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159005. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159006. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159007. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159008. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159009. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159010. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159011. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159012. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159013. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159014. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159015. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159016. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159017. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159018. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159019. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159020. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159021. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159022. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159023. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159024. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159025. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159026. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159027. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159028. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159029. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159030. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159031. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159032. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159033. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159034. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159035. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159036. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159037. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159038. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159039. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159040. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159041. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159042. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159043. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159044. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159045. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159046. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159047. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159048. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159049. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159050. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159051. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159052. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159053. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159054. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159055. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159056. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159057. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159058. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159059. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159060. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159061. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159062. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159063. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159064. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159065. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159066. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159067. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159068. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159069. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159070. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159071. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159072. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159073. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159074. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159075. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159076. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159077. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159078. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159079. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159080. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159081. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159082. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159083. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159084. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159085. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159086. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159087. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159088. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159089. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159090. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159091. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159092. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159093. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159094. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159095. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159096. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159097. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159098. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159099. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159100. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159101. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159102. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159103. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159104. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159105. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159106. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159107. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159108. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159109. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159110. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159111. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159112. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159113. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159114. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159115. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159116. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159117. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159118. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159119. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159120. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159121. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159122. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159123. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159124. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159125. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159126. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159127. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159128. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159129. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159130. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159131. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159132. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159133. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159134. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159135. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159136. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159137. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159138. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159139. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159140. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159141. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159142. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159143. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159144. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159145. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159146. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159147. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159148. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159149. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159150. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159151. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159152. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159153. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159154. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159155. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159156. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159157. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159158. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159159. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159160. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159161. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159162. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159163. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159164. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159165. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159166. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159167. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159168. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159169. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159170. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159171. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159172. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159173. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159174. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159175. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159176. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159177. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159178. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159179. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159180. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159181. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159182. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159183. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159184. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159185. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159186. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159187. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159188. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159189. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159190. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159191. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159192. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159193. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159194. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159195. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159196. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159197. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159198. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159199. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159200. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159201. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159202. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159203. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159204. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159205. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159206. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159207. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159208. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159209. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159210. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159211. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159212. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159213. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159214. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159215. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159216. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159217. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159218. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159219. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159220. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159221. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159222. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159223. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159224. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159225. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159226. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159227. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159228. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159229. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159230. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159231. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159232. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159233. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159234. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159235. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159236. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159237. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159238. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159239. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159240. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159241. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159242. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159243. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159244. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159245. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159246. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159247. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159248. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159249. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159250. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159251. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159252. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159253. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159254. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159255. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159256. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159257. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159258. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159259. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159260. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159261. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159262. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159263. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159264. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159265. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159266. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159267. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159268. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159269. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159270. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159271. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159272. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159273. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159274. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159275. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159276. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159277. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159278. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159279. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159280. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159281. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159282. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159283. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159284. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159285. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159286. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159287. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159288. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159289. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159290. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159291. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159292. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159293. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159294. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159295. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159296. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159297. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159298. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159299. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159300. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159301. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159302. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159303. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159304. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159305. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159306. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159307. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159308. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159309. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159310. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159311. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159312. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159313. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159314. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159315. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159316. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159317. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159318. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159319. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159320. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159321. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159322. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159323. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159324. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159325. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159326. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159327. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159328. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159329. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159330. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159331. };
  159332. static float *vwin[8] = {
  159333. vwin64,
  159334. vwin128,
  159335. vwin256,
  159336. vwin512,
  159337. vwin1024,
  159338. vwin2048,
  159339. vwin4096,
  159340. vwin8192,
  159341. };
  159342. float *_vorbis_window_get(int n){
  159343. return vwin[n];
  159344. }
  159345. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159346. int lW,int W,int nW){
  159347. lW=(W?lW:0);
  159348. nW=(W?nW:0);
  159349. {
  159350. float *windowLW=vwin[winno[lW]];
  159351. float *windowNW=vwin[winno[nW]];
  159352. long n=blocksizes[W];
  159353. long ln=blocksizes[lW];
  159354. long rn=blocksizes[nW];
  159355. long leftbegin=n/4-ln/4;
  159356. long leftend=leftbegin+ln/2;
  159357. long rightbegin=n/2+n/4-rn/4;
  159358. long rightend=rightbegin+rn/2;
  159359. int i,p;
  159360. for(i=0;i<leftbegin;i++)
  159361. d[i]=0.f;
  159362. for(p=0;i<leftend;i++,p++)
  159363. d[i]*=windowLW[p];
  159364. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159365. d[i]*=windowNW[p];
  159366. for(;i<n;i++)
  159367. d[i]=0.f;
  159368. }
  159369. }
  159370. #endif
  159371. /*** End of inlined file: window.c ***/
  159372. #else
  159373. #include <vorbis/vorbisenc.h>
  159374. #include <vorbis/codec.h>
  159375. #include <vorbis/vorbisfile.h>
  159376. #endif
  159377. }
  159378. #undef max
  159379. #undef min
  159380. BEGIN_JUCE_NAMESPACE
  159381. static const char* const oggFormatName = "Ogg-Vorbis file";
  159382. static const char* const oggExtensions[] = { ".ogg", 0 };
  159383. class OggReader : public AudioFormatReader
  159384. {
  159385. OggVorbisNamespace::OggVorbis_File ovFile;
  159386. OggVorbisNamespace::ov_callbacks callbacks;
  159387. AudioSampleBuffer reservoir;
  159388. int reservoirStart, samplesInReservoir;
  159389. public:
  159390. OggReader (InputStream* const inp)
  159391. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159392. reservoir (2, 4096),
  159393. reservoirStart (0),
  159394. samplesInReservoir (0)
  159395. {
  159396. using namespace OggVorbisNamespace;
  159397. sampleRate = 0;
  159398. usesFloatingPointData = true;
  159399. callbacks.read_func = &oggReadCallback;
  159400. callbacks.seek_func = &oggSeekCallback;
  159401. callbacks.close_func = &oggCloseCallback;
  159402. callbacks.tell_func = &oggTellCallback;
  159403. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159404. if (err == 0)
  159405. {
  159406. vorbis_info* info = ov_info (&ovFile, -1);
  159407. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159408. numChannels = info->channels;
  159409. bitsPerSample = 16;
  159410. sampleRate = info->rate;
  159411. reservoir.setSize (numChannels,
  159412. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159413. }
  159414. }
  159415. ~OggReader()
  159416. {
  159417. OggVorbisNamespace::ov_clear (&ovFile);
  159418. }
  159419. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159420. int64 startSampleInFile, int numSamples)
  159421. {
  159422. while (numSamples > 0)
  159423. {
  159424. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159425. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159426. {
  159427. // got a few samples overlapping, so use them before seeking..
  159428. const int numToUse = jmin (numSamples, numAvailable);
  159429. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159430. if (destSamples[i] != 0)
  159431. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159432. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159433. sizeof (float) * numToUse);
  159434. startSampleInFile += numToUse;
  159435. numSamples -= numToUse;
  159436. startOffsetInDestBuffer += numToUse;
  159437. if (numSamples == 0)
  159438. break;
  159439. }
  159440. if (startSampleInFile < reservoirStart
  159441. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159442. {
  159443. // buffer miss, so refill the reservoir
  159444. int bitStream = 0;
  159445. reservoirStart = jmax (0, (int) startSampleInFile);
  159446. samplesInReservoir = reservoir.getNumSamples();
  159447. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159448. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159449. int offset = 0;
  159450. int numToRead = samplesInReservoir;
  159451. while (numToRead > 0)
  159452. {
  159453. float** dataIn = 0;
  159454. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159455. if (samps <= 0)
  159456. break;
  159457. jassert (samps <= numToRead);
  159458. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159459. {
  159460. memcpy (reservoir.getSampleData (i, offset),
  159461. dataIn[i],
  159462. sizeof (float) * samps);
  159463. }
  159464. numToRead -= samps;
  159465. offset += samps;
  159466. }
  159467. if (numToRead > 0)
  159468. reservoir.clear (offset, numToRead);
  159469. }
  159470. }
  159471. if (numSamples > 0)
  159472. {
  159473. for (int i = numDestChannels; --i >= 0;)
  159474. if (destSamples[i] != 0)
  159475. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159476. sizeof (int) * numSamples);
  159477. }
  159478. return true;
  159479. }
  159480. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159481. {
  159482. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159483. }
  159484. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159485. {
  159486. InputStream* const in = static_cast <InputStream*> (datasource);
  159487. if (whence == SEEK_CUR)
  159488. offset += in->getPosition();
  159489. else if (whence == SEEK_END)
  159490. offset += in->getTotalLength();
  159491. in->setPosition (offset);
  159492. return 0;
  159493. }
  159494. static int oggCloseCallback (void*)
  159495. {
  159496. return 0;
  159497. }
  159498. static long oggTellCallback (void* datasource)
  159499. {
  159500. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159501. }
  159502. private:
  159503. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159504. };
  159505. class OggWriter : public AudioFormatWriter
  159506. {
  159507. OggVorbisNamespace::ogg_stream_state os;
  159508. OggVorbisNamespace::ogg_page og;
  159509. OggVorbisNamespace::ogg_packet op;
  159510. OggVorbisNamespace::vorbis_info vi;
  159511. OggVorbisNamespace::vorbis_comment vc;
  159512. OggVorbisNamespace::vorbis_dsp_state vd;
  159513. OggVorbisNamespace::vorbis_block vb;
  159514. public:
  159515. bool ok;
  159516. OggWriter (OutputStream* const out,
  159517. const double sampleRate,
  159518. const int numChannels,
  159519. const int bitsPerSample,
  159520. const int qualityIndex)
  159521. : AudioFormatWriter (out, TRANS (oggFormatName),
  159522. sampleRate,
  159523. numChannels,
  159524. bitsPerSample)
  159525. {
  159526. using namespace OggVorbisNamespace;
  159527. ok = false;
  159528. vorbis_info_init (&vi);
  159529. if (vorbis_encode_init_vbr (&vi,
  159530. numChannels,
  159531. (int) sampleRate,
  159532. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159533. {
  159534. vorbis_comment_init (&vc);
  159535. if (JUCEApplication::getInstance() != 0)
  159536. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  159537. vorbis_analysis_init (&vd, &vi);
  159538. vorbis_block_init (&vd, &vb);
  159539. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159540. ogg_packet header;
  159541. ogg_packet header_comm;
  159542. ogg_packet header_code;
  159543. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159544. ogg_stream_packetin (&os, &header);
  159545. ogg_stream_packetin (&os, &header_comm);
  159546. ogg_stream_packetin (&os, &header_code);
  159547. for (;;)
  159548. {
  159549. if (ogg_stream_flush (&os, &og) == 0)
  159550. break;
  159551. output->write (og.header, og.header_len);
  159552. output->write (og.body, og.body_len);
  159553. }
  159554. ok = true;
  159555. }
  159556. }
  159557. ~OggWriter()
  159558. {
  159559. using namespace OggVorbisNamespace;
  159560. if (ok)
  159561. {
  159562. // write a zero-length packet to show ogg that we're finished..
  159563. write (0, 0);
  159564. ogg_stream_clear (&os);
  159565. vorbis_block_clear (&vb);
  159566. vorbis_dsp_clear (&vd);
  159567. vorbis_comment_clear (&vc);
  159568. vorbis_info_clear (&vi);
  159569. output->flush();
  159570. }
  159571. else
  159572. {
  159573. vorbis_info_clear (&vi);
  159574. output = 0; // to stop the base class deleting this, as it needs to be returned
  159575. // to the caller of createWriter()
  159576. }
  159577. }
  159578. bool write (const int** samplesToWrite, int numSamples)
  159579. {
  159580. using namespace OggVorbisNamespace;
  159581. if (! ok)
  159582. return false;
  159583. if (numSamples > 0)
  159584. {
  159585. const double gain = 1.0 / 0x80000000u;
  159586. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159587. for (int i = numChannels; --i >= 0;)
  159588. {
  159589. float* const dst = vorbisBuffer[i];
  159590. const int* const src = samplesToWrite [i];
  159591. if (src != 0 && dst != 0)
  159592. {
  159593. for (int j = 0; j < numSamples; ++j)
  159594. dst[j] = (float) (src[j] * gain);
  159595. }
  159596. }
  159597. }
  159598. vorbis_analysis_wrote (&vd, numSamples);
  159599. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159600. {
  159601. vorbis_analysis (&vb, 0);
  159602. vorbis_bitrate_addblock (&vb);
  159603. while (vorbis_bitrate_flushpacket (&vd, &op))
  159604. {
  159605. ogg_stream_packetin (&os, &op);
  159606. for (;;)
  159607. {
  159608. if (ogg_stream_pageout (&os, &og) == 0)
  159609. break;
  159610. output->write (og.header, og.header_len);
  159611. output->write (og.body, og.body_len);
  159612. if (ogg_page_eos (&og))
  159613. break;
  159614. }
  159615. }
  159616. }
  159617. return true;
  159618. }
  159619. private:
  159620. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159621. };
  159622. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159623. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159624. {
  159625. }
  159626. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159627. {
  159628. }
  159629. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159630. {
  159631. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159632. return Array <int> (rates);
  159633. }
  159634. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159635. {
  159636. const int depths[] = { 32, 0 };
  159637. return Array <int> (depths);
  159638. }
  159639. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159640. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159641. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159642. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159643. const bool deleteStreamIfOpeningFails)
  159644. {
  159645. ScopedPointer <OggReader> r (new OggReader (in));
  159646. if (r->sampleRate > 0)
  159647. return r.release();
  159648. if (! deleteStreamIfOpeningFails)
  159649. r->input = 0;
  159650. return 0;
  159651. }
  159652. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159653. double sampleRate,
  159654. unsigned int numChannels,
  159655. int bitsPerSample,
  159656. const StringPairArray& /*metadataValues*/,
  159657. int qualityOptionIndex)
  159658. {
  159659. ScopedPointer <OggWriter> w (new OggWriter (out,
  159660. sampleRate,
  159661. numChannels,
  159662. bitsPerSample,
  159663. qualityOptionIndex));
  159664. return w->ok ? w.release() : 0;
  159665. }
  159666. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159667. {
  159668. StringArray s;
  159669. s.add ("Low Quality");
  159670. s.add ("Medium Quality");
  159671. s.add ("High Quality");
  159672. return s;
  159673. }
  159674. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159675. {
  159676. FileInputStream* const in = source.createInputStream();
  159677. if (in != 0)
  159678. {
  159679. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159680. if (r != 0)
  159681. {
  159682. const int64 numSamps = r->lengthInSamples;
  159683. r = 0;
  159684. const int64 fileNumSamps = source.getSize() / 4;
  159685. const double ratio = numSamps / (double) fileNumSamps;
  159686. if (ratio > 12.0)
  159687. return 0;
  159688. else if (ratio > 6.0)
  159689. return 1;
  159690. else
  159691. return 2;
  159692. }
  159693. }
  159694. return 1;
  159695. }
  159696. END_JUCE_NAMESPACE
  159697. #endif
  159698. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159699. #endif
  159700. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159701. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159702. #if JUCE_MSVC
  159703. #pragma warning (push)
  159704. #endif
  159705. namespace jpeglibNamespace
  159706. {
  159707. #if JUCE_INCLUDE_JPEGLIB_CODE
  159708. #if JUCE_MINGW
  159709. typedef unsigned char boolean;
  159710. #endif
  159711. #define JPEG_INTERNALS
  159712. #undef FAR
  159713. /*** Start of inlined file: jpeglib.h ***/
  159714. #ifndef JPEGLIB_H
  159715. #define JPEGLIB_H
  159716. /*
  159717. * First we include the configuration files that record how this
  159718. * installation of the JPEG library is set up. jconfig.h can be
  159719. * generated automatically for many systems. jmorecfg.h contains
  159720. * manual configuration options that most people need not worry about.
  159721. */
  159722. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159723. /*** Start of inlined file: jconfig.h ***/
  159724. /* see jconfig.doc for explanations */
  159725. // disable all the warnings under MSVC
  159726. #ifdef _MSC_VER
  159727. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159728. #endif
  159729. #ifdef __BORLANDC__
  159730. #pragma warn -8057
  159731. #pragma warn -8019
  159732. #pragma warn -8004
  159733. #pragma warn -8008
  159734. #endif
  159735. #define HAVE_PROTOTYPES
  159736. #define HAVE_UNSIGNED_CHAR
  159737. #define HAVE_UNSIGNED_SHORT
  159738. /* #define void char */
  159739. /* #define const */
  159740. #undef CHAR_IS_UNSIGNED
  159741. #define HAVE_STDDEF_H
  159742. #define HAVE_STDLIB_H
  159743. #undef NEED_BSD_STRINGS
  159744. #undef NEED_SYS_TYPES_H
  159745. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159746. #undef NEED_SHORT_EXTERNAL_NAMES
  159747. #undef INCOMPLETE_TYPES_BROKEN
  159748. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159749. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159750. typedef unsigned char boolean;
  159751. #endif
  159752. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159753. #ifdef JPEG_INTERNALS
  159754. #undef RIGHT_SHIFT_IS_UNSIGNED
  159755. #endif /* JPEG_INTERNALS */
  159756. #ifdef JPEG_CJPEG_DJPEG
  159757. #define BMP_SUPPORTED /* BMP image file format */
  159758. #define GIF_SUPPORTED /* GIF image file format */
  159759. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159760. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159761. #define TARGA_SUPPORTED /* Targa image file format */
  159762. #define TWO_FILE_COMMANDLINE /* optional */
  159763. #define USE_SETMODE /* Microsoft has setmode() */
  159764. #undef NEED_SIGNAL_CATCHER
  159765. #undef DONT_USE_B_MODE
  159766. #undef PROGRESS_REPORT /* optional */
  159767. #endif /* JPEG_CJPEG_DJPEG */
  159768. /*** End of inlined file: jconfig.h ***/
  159769. /* widely used configuration options */
  159770. #endif
  159771. /*** Start of inlined file: jmorecfg.h ***/
  159772. /*
  159773. * Define BITS_IN_JSAMPLE as either
  159774. * 8 for 8-bit sample values (the usual setting)
  159775. * 12 for 12-bit sample values
  159776. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159777. * JPEG standard, and the IJG code does not support anything else!
  159778. * We do not support run-time selection of data precision, sorry.
  159779. */
  159780. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159781. /*
  159782. * Maximum number of components (color channels) allowed in JPEG image.
  159783. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159784. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159785. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159786. * really short on memory. (Each allowed component costs a hundred or so
  159787. * bytes of storage, whether actually used in an image or not.)
  159788. */
  159789. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159790. /*
  159791. * Basic data types.
  159792. * You may need to change these if you have a machine with unusual data
  159793. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159794. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159795. * but it had better be at least 16.
  159796. */
  159797. /* Representation of a single sample (pixel element value).
  159798. * We frequently allocate large arrays of these, so it's important to keep
  159799. * them small. But if you have memory to burn and access to char or short
  159800. * arrays is very slow on your hardware, you might want to change these.
  159801. */
  159802. #if BITS_IN_JSAMPLE == 8
  159803. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159804. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159805. */
  159806. #ifdef HAVE_UNSIGNED_CHAR
  159807. typedef unsigned char JSAMPLE;
  159808. #define GETJSAMPLE(value) ((int) (value))
  159809. #else /* not HAVE_UNSIGNED_CHAR */
  159810. typedef char JSAMPLE;
  159811. #ifdef CHAR_IS_UNSIGNED
  159812. #define GETJSAMPLE(value) ((int) (value))
  159813. #else
  159814. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159815. #endif /* CHAR_IS_UNSIGNED */
  159816. #endif /* HAVE_UNSIGNED_CHAR */
  159817. #define MAXJSAMPLE 255
  159818. #define CENTERJSAMPLE 128
  159819. #endif /* BITS_IN_JSAMPLE == 8 */
  159820. #if BITS_IN_JSAMPLE == 12
  159821. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159822. * On nearly all machines "short" will do nicely.
  159823. */
  159824. typedef short JSAMPLE;
  159825. #define GETJSAMPLE(value) ((int) (value))
  159826. #define MAXJSAMPLE 4095
  159827. #define CENTERJSAMPLE 2048
  159828. #endif /* BITS_IN_JSAMPLE == 12 */
  159829. /* Representation of a DCT frequency coefficient.
  159830. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159831. * Again, we allocate large arrays of these, but you can change to int
  159832. * if you have memory to burn and "short" is really slow.
  159833. */
  159834. typedef short JCOEF;
  159835. /* Compressed datastreams are represented as arrays of JOCTET.
  159836. * These must be EXACTLY 8 bits wide, at least once they are written to
  159837. * external storage. Note that when using the stdio data source/destination
  159838. * managers, this is also the data type passed to fread/fwrite.
  159839. */
  159840. #ifdef HAVE_UNSIGNED_CHAR
  159841. typedef unsigned char JOCTET;
  159842. #define GETJOCTET(value) (value)
  159843. #else /* not HAVE_UNSIGNED_CHAR */
  159844. typedef char JOCTET;
  159845. #ifdef CHAR_IS_UNSIGNED
  159846. #define GETJOCTET(value) (value)
  159847. #else
  159848. #define GETJOCTET(value) ((value) & 0xFF)
  159849. #endif /* CHAR_IS_UNSIGNED */
  159850. #endif /* HAVE_UNSIGNED_CHAR */
  159851. /* These typedefs are used for various table entries and so forth.
  159852. * They must be at least as wide as specified; but making them too big
  159853. * won't cost a huge amount of memory, so we don't provide special
  159854. * extraction code like we did for JSAMPLE. (In other words, these
  159855. * typedefs live at a different point on the speed/space tradeoff curve.)
  159856. */
  159857. /* UINT8 must hold at least the values 0..255. */
  159858. #ifdef HAVE_UNSIGNED_CHAR
  159859. typedef unsigned char UINT8;
  159860. #else /* not HAVE_UNSIGNED_CHAR */
  159861. #ifdef CHAR_IS_UNSIGNED
  159862. typedef char UINT8;
  159863. #else /* not CHAR_IS_UNSIGNED */
  159864. typedef short UINT8;
  159865. #endif /* CHAR_IS_UNSIGNED */
  159866. #endif /* HAVE_UNSIGNED_CHAR */
  159867. /* UINT16 must hold at least the values 0..65535. */
  159868. #ifdef HAVE_UNSIGNED_SHORT
  159869. typedef unsigned short UINT16;
  159870. #else /* not HAVE_UNSIGNED_SHORT */
  159871. typedef unsigned int UINT16;
  159872. #endif /* HAVE_UNSIGNED_SHORT */
  159873. /* INT16 must hold at least the values -32768..32767. */
  159874. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159875. typedef short INT16;
  159876. #endif
  159877. /* INT32 must hold at least signed 32-bit values. */
  159878. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159879. typedef long INT32;
  159880. #endif
  159881. /* Datatype used for image dimensions. The JPEG standard only supports
  159882. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159883. * "unsigned int" is sufficient on all machines. However, if you need to
  159884. * handle larger images and you don't mind deviating from the spec, you
  159885. * can change this datatype.
  159886. */
  159887. typedef unsigned int JDIMENSION;
  159888. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159889. /* These macros are used in all function definitions and extern declarations.
  159890. * You could modify them if you need to change function linkage conventions;
  159891. * in particular, you'll need to do that to make the library a Windows DLL.
  159892. * Another application is to make all functions global for use with debuggers
  159893. * or code profilers that require it.
  159894. */
  159895. /* a function called through method pointers: */
  159896. #define METHODDEF(type) static type
  159897. /* a function used only in its module: */
  159898. #define LOCAL(type) static type
  159899. /* a function referenced thru EXTERNs: */
  159900. #define GLOBAL(type) type
  159901. /* a reference to a GLOBAL function: */
  159902. #define EXTERN(type) extern type
  159903. /* This macro is used to declare a "method", that is, a function pointer.
  159904. * We want to supply prototype parameters if the compiler can cope.
  159905. * Note that the arglist parameter must be parenthesized!
  159906. * Again, you can customize this if you need special linkage keywords.
  159907. */
  159908. #ifdef HAVE_PROTOTYPES
  159909. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159910. #else
  159911. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159912. #endif
  159913. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159914. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159915. * by just saying "FAR *" where such a pointer is needed. In a few places
  159916. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159917. */
  159918. #ifdef NEED_FAR_POINTERS
  159919. #define FAR far
  159920. #else
  159921. #define FAR
  159922. #endif
  159923. /*
  159924. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159925. * in standard header files. Or you may have conflicts with application-
  159926. * specific header files that you want to include together with these files.
  159927. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159928. */
  159929. #ifndef HAVE_BOOLEAN
  159930. typedef int boolean;
  159931. #endif
  159932. #ifndef FALSE /* in case these macros already exist */
  159933. #define FALSE 0 /* values of boolean */
  159934. #endif
  159935. #ifndef TRUE
  159936. #define TRUE 1
  159937. #endif
  159938. /*
  159939. * The remaining options affect code selection within the JPEG library,
  159940. * but they don't need to be visible to most applications using the library.
  159941. * To minimize application namespace pollution, the symbols won't be
  159942. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159943. */
  159944. #ifdef JPEG_INTERNALS
  159945. #define JPEG_INTERNAL_OPTIONS
  159946. #endif
  159947. #ifdef JPEG_INTERNAL_OPTIONS
  159948. /*
  159949. * These defines indicate whether to include various optional functions.
  159950. * Undefining some of these symbols will produce a smaller but less capable
  159951. * library. Note that you can leave certain source files out of the
  159952. * compilation/linking process if you've #undef'd the corresponding symbols.
  159953. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159954. */
  159955. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159956. /* Capability options common to encoder and decoder: */
  159957. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159958. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159959. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159960. /* Encoder capability options: */
  159961. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159962. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159963. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159964. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159965. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159966. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159967. * precision, so jchuff.c normally uses entropy optimization to compute
  159968. * usable tables for higher precision. If you don't want to do optimization,
  159969. * you'll have to supply different default Huffman tables.
  159970. * The exact same statements apply for progressive JPEG: the default tables
  159971. * don't work for progressive mode. (This may get fixed, however.)
  159972. */
  159973. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159974. /* Decoder capability options: */
  159975. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159976. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159977. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159978. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159979. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159980. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159981. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159982. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159983. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159984. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159985. /* more capability options later, no doubt */
  159986. /*
  159987. * Ordering of RGB data in scanlines passed to or from the application.
  159988. * If your application wants to deal with data in the order B,G,R, just
  159989. * change these macros. You can also deal with formats such as R,G,B,X
  159990. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159991. * the offsets will also change the order in which colormap data is organized.
  159992. * RESTRICTIONS:
  159993. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159994. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159995. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159996. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159997. * is not 3 (they don't understand about dummy color components!). So you
  159998. * can't use color quantization if you change that value.
  159999. */
  160000. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160001. #define RGB_GREEN 1 /* Offset of Green */
  160002. #define RGB_BLUE 2 /* Offset of Blue */
  160003. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160004. /* Definitions for speed-related optimizations. */
  160005. /* If your compiler supports inline functions, define INLINE
  160006. * as the inline keyword; otherwise define it as empty.
  160007. */
  160008. #ifndef INLINE
  160009. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160010. #define INLINE __inline__
  160011. #endif
  160012. #ifndef INLINE
  160013. #define INLINE /* default is to define it as empty */
  160014. #endif
  160015. #endif
  160016. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160017. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160018. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160019. */
  160020. #ifndef MULTIPLIER
  160021. #define MULTIPLIER int /* type for fastest integer multiply */
  160022. #endif
  160023. /* FAST_FLOAT should be either float or double, whichever is done faster
  160024. * by your compiler. (Note that this type is only used in the floating point
  160025. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160026. * Typically, float is faster in ANSI C compilers, while double is faster in
  160027. * pre-ANSI compilers (because they insist on converting to double anyway).
  160028. * The code below therefore chooses float if we have ANSI-style prototypes.
  160029. */
  160030. #ifndef FAST_FLOAT
  160031. #ifdef HAVE_PROTOTYPES
  160032. #define FAST_FLOAT float
  160033. #else
  160034. #define FAST_FLOAT double
  160035. #endif
  160036. #endif
  160037. #endif /* JPEG_INTERNAL_OPTIONS */
  160038. /*** End of inlined file: jmorecfg.h ***/
  160039. /* seldom changed options */
  160040. /* Version ID for the JPEG library.
  160041. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160042. */
  160043. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160044. /* Various constants determining the sizes of things.
  160045. * All of these are specified by the JPEG standard, so don't change them
  160046. * if you want to be compatible.
  160047. */
  160048. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160049. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160050. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160051. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160052. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160053. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160054. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160055. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160056. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160057. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160058. * to handle it. We even let you do this from the jconfig.h file. However,
  160059. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160060. * sometimes emits noncompliant files doesn't mean you should too.
  160061. */
  160062. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160063. #ifndef D_MAX_BLOCKS_IN_MCU
  160064. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160065. #endif
  160066. /* Data structures for images (arrays of samples and of DCT coefficients).
  160067. * On 80x86 machines, the image arrays are too big for near pointers,
  160068. * but the pointer arrays can fit in near memory.
  160069. */
  160070. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160071. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160072. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160073. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160074. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160075. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160076. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160077. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160078. /* Types for JPEG compression parameters and working tables. */
  160079. /* DCT coefficient quantization tables. */
  160080. typedef struct {
  160081. /* This array gives the coefficient quantizers in natural array order
  160082. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160083. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160084. */
  160085. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160086. /* This field is used only during compression. It's initialized FALSE when
  160087. * the table is created, and set TRUE when it's been output to the file.
  160088. * You could suppress output of a table by setting this to TRUE.
  160089. * (See jpeg_suppress_tables for an example.)
  160090. */
  160091. boolean sent_table; /* TRUE when table has been output */
  160092. } JQUANT_TBL;
  160093. /* Huffman coding tables. */
  160094. typedef struct {
  160095. /* These two fields directly represent the contents of a JPEG DHT marker */
  160096. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160097. /* length k bits; bits[0] is unused */
  160098. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160099. /* This field is used only during compression. It's initialized FALSE when
  160100. * the table is created, and set TRUE when it's been output to the file.
  160101. * You could suppress output of a table by setting this to TRUE.
  160102. * (See jpeg_suppress_tables for an example.)
  160103. */
  160104. boolean sent_table; /* TRUE when table has been output */
  160105. } JHUFF_TBL;
  160106. /* Basic info about one component (color channel). */
  160107. typedef struct {
  160108. /* These values are fixed over the whole image. */
  160109. /* For compression, they must be supplied by parameter setup; */
  160110. /* for decompression, they are read from the SOF marker. */
  160111. int component_id; /* identifier for this component (0..255) */
  160112. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160113. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160114. int v_samp_factor; /* vertical sampling factor (1..4) */
  160115. int quant_tbl_no; /* quantization table selector (0..3) */
  160116. /* These values may vary between scans. */
  160117. /* For compression, they must be supplied by parameter setup; */
  160118. /* for decompression, they are read from the SOS marker. */
  160119. /* The decompressor output side may not use these variables. */
  160120. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160121. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160122. /* Remaining fields should be treated as private by applications. */
  160123. /* These values are computed during compression or decompression startup: */
  160124. /* Component's size in DCT blocks.
  160125. * Any dummy blocks added to complete an MCU are not counted; therefore
  160126. * these values do not depend on whether a scan is interleaved or not.
  160127. */
  160128. JDIMENSION width_in_blocks;
  160129. JDIMENSION height_in_blocks;
  160130. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160131. * For decompression this is the size of the output from one DCT block,
  160132. * reflecting any scaling we choose to apply during the IDCT step.
  160133. * Values of 1,2,4,8 are likely to be supported. Note that different
  160134. * components may receive different IDCT scalings.
  160135. */
  160136. int DCT_scaled_size;
  160137. /* The downsampled dimensions are the component's actual, unpadded number
  160138. * of samples at the main buffer (preprocessing/compression interface), thus
  160139. * downsampled_width = ceil(image_width * Hi/Hmax)
  160140. * and similarly for height. For decompression, IDCT scaling is included, so
  160141. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160142. */
  160143. JDIMENSION downsampled_width; /* actual width in samples */
  160144. JDIMENSION downsampled_height; /* actual height in samples */
  160145. /* This flag is used only for decompression. In cases where some of the
  160146. * components will be ignored (eg grayscale output from YCbCr image),
  160147. * we can skip most computations for the unused components.
  160148. */
  160149. boolean component_needed; /* do we need the value of this component? */
  160150. /* These values are computed before starting a scan of the component. */
  160151. /* The decompressor output side may not use these variables. */
  160152. int MCU_width; /* number of blocks per MCU, horizontally */
  160153. int MCU_height; /* number of blocks per MCU, vertically */
  160154. int MCU_blocks; /* MCU_width * MCU_height */
  160155. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160156. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160157. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160158. /* Saved quantization table for component; NULL if none yet saved.
  160159. * See jdinput.c comments about the need for this information.
  160160. * This field is currently used only for decompression.
  160161. */
  160162. JQUANT_TBL * quant_table;
  160163. /* Private per-component storage for DCT or IDCT subsystem. */
  160164. void * dct_table;
  160165. } jpeg_component_info;
  160166. /* The script for encoding a multiple-scan file is an array of these: */
  160167. typedef struct {
  160168. int comps_in_scan; /* number of components encoded in this scan */
  160169. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160170. int Ss, Se; /* progressive JPEG spectral selection parms */
  160171. int Ah, Al; /* progressive JPEG successive approx. parms */
  160172. } jpeg_scan_info;
  160173. /* The decompressor can save APPn and COM markers in a list of these: */
  160174. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160175. struct jpeg_marker_struct {
  160176. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160177. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160178. unsigned int original_length; /* # bytes of data in the file */
  160179. unsigned int data_length; /* # bytes of data saved at data[] */
  160180. JOCTET FAR * data; /* the data contained in the marker */
  160181. /* the marker length word is not counted in data_length or original_length */
  160182. };
  160183. /* Known color spaces. */
  160184. typedef enum {
  160185. JCS_UNKNOWN, /* error/unspecified */
  160186. JCS_GRAYSCALE, /* monochrome */
  160187. JCS_RGB, /* red/green/blue */
  160188. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160189. JCS_CMYK, /* C/M/Y/K */
  160190. JCS_YCCK /* Y/Cb/Cr/K */
  160191. } J_COLOR_SPACE;
  160192. /* DCT/IDCT algorithm options. */
  160193. typedef enum {
  160194. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160195. JDCT_IFAST, /* faster, less accurate integer method */
  160196. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160197. } J_DCT_METHOD;
  160198. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160199. #define JDCT_DEFAULT JDCT_ISLOW
  160200. #endif
  160201. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160202. #define JDCT_FASTEST JDCT_IFAST
  160203. #endif
  160204. /* Dithering options for decompression. */
  160205. typedef enum {
  160206. JDITHER_NONE, /* no dithering */
  160207. JDITHER_ORDERED, /* simple ordered dither */
  160208. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160209. } J_DITHER_MODE;
  160210. /* Common fields between JPEG compression and decompression master structs. */
  160211. #define jpeg_common_fields \
  160212. struct jpeg_error_mgr * err; /* Error handler module */\
  160213. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160214. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160215. void * client_data; /* Available for use by application */\
  160216. boolean is_decompressor; /* So common code can tell which is which */\
  160217. int global_state /* For checking call sequence validity */
  160218. /* Routines that are to be used by both halves of the library are declared
  160219. * to receive a pointer to this structure. There are no actual instances of
  160220. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160221. */
  160222. struct jpeg_common_struct {
  160223. jpeg_common_fields; /* Fields common to both master struct types */
  160224. /* Additional fields follow in an actual jpeg_compress_struct or
  160225. * jpeg_decompress_struct. All three structs must agree on these
  160226. * initial fields! (This would be a lot cleaner in C++.)
  160227. */
  160228. };
  160229. typedef struct jpeg_common_struct * j_common_ptr;
  160230. typedef struct jpeg_compress_struct * j_compress_ptr;
  160231. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160232. /* Master record for a compression instance */
  160233. struct jpeg_compress_struct {
  160234. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160235. /* Destination for compressed data */
  160236. struct jpeg_destination_mgr * dest;
  160237. /* Description of source image --- these fields must be filled in by
  160238. * outer application before starting compression. in_color_space must
  160239. * be correct before you can even call jpeg_set_defaults().
  160240. */
  160241. JDIMENSION image_width; /* input image width */
  160242. JDIMENSION image_height; /* input image height */
  160243. int input_components; /* # of color components in input image */
  160244. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160245. double input_gamma; /* image gamma of input image */
  160246. /* Compression parameters --- these fields must be set before calling
  160247. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160248. * initialize everything to reasonable defaults, then changing anything
  160249. * the application specifically wants to change. That way you won't get
  160250. * burnt when new parameters are added. Also note that there are several
  160251. * helper routines to simplify changing parameters.
  160252. */
  160253. int data_precision; /* bits of precision in image data */
  160254. int num_components; /* # of color components in JPEG image */
  160255. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160256. jpeg_component_info * comp_info;
  160257. /* comp_info[i] describes component that appears i'th in SOF */
  160258. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160259. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160260. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160261. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160262. /* ptrs to Huffman coding tables, or NULL if not defined */
  160263. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160264. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160265. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160266. int num_scans; /* # of entries in scan_info array */
  160267. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160268. /* The default value of scan_info is NULL, which causes a single-scan
  160269. * sequential JPEG file to be emitted. To create a multi-scan file,
  160270. * set num_scans and scan_info to point to an array of scan definitions.
  160271. */
  160272. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160273. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160274. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160275. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160276. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160277. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160278. /* The restart interval can be specified in absolute MCUs by setting
  160279. * restart_interval, or in MCU rows by setting restart_in_rows
  160280. * (in which case the correct restart_interval will be figured
  160281. * for each scan).
  160282. */
  160283. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160284. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160285. /* Parameters controlling emission of special markers. */
  160286. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160287. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160288. UINT8 JFIF_minor_version;
  160289. /* These three values are not used by the JPEG code, merely copied */
  160290. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160291. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160292. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160293. UINT8 density_unit; /* JFIF code for pixel size units */
  160294. UINT16 X_density; /* Horizontal pixel density */
  160295. UINT16 Y_density; /* Vertical pixel density */
  160296. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160297. /* State variable: index of next scanline to be written to
  160298. * jpeg_write_scanlines(). Application may use this to control its
  160299. * processing loop, e.g., "while (next_scanline < image_height)".
  160300. */
  160301. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160302. /* Remaining fields are known throughout compressor, but generally
  160303. * should not be touched by a surrounding application.
  160304. */
  160305. /*
  160306. * These fields are computed during compression startup
  160307. */
  160308. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160309. int max_h_samp_factor; /* largest h_samp_factor */
  160310. int max_v_samp_factor; /* largest v_samp_factor */
  160311. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160312. /* The coefficient controller receives data in units of MCU rows as defined
  160313. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160314. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160315. * "iMCU" (interleaved MCU) row.
  160316. */
  160317. /*
  160318. * These fields are valid during any one scan.
  160319. * They describe the components and MCUs actually appearing in the scan.
  160320. */
  160321. int comps_in_scan; /* # of JPEG components in this scan */
  160322. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160323. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160324. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160325. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160326. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160327. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160328. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160329. /* i'th block in an MCU */
  160330. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160331. /*
  160332. * Links to compression subobjects (methods and private variables of modules)
  160333. */
  160334. struct jpeg_comp_master * master;
  160335. struct jpeg_c_main_controller * main;
  160336. struct jpeg_c_prep_controller * prep;
  160337. struct jpeg_c_coef_controller * coef;
  160338. struct jpeg_marker_writer * marker;
  160339. struct jpeg_color_converter * cconvert;
  160340. struct jpeg_downsampler * downsample;
  160341. struct jpeg_forward_dct * fdct;
  160342. struct jpeg_entropy_encoder * entropy;
  160343. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160344. int script_space_size;
  160345. };
  160346. /* Master record for a decompression instance */
  160347. struct jpeg_decompress_struct {
  160348. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160349. /* Source of compressed data */
  160350. struct jpeg_source_mgr * src;
  160351. /* Basic description of image --- filled in by jpeg_read_header(). */
  160352. /* Application may inspect these values to decide how to process image. */
  160353. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160354. JDIMENSION image_height; /* nominal image height */
  160355. int num_components; /* # of color components in JPEG image */
  160356. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160357. /* Decompression processing parameters --- these fields must be set before
  160358. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160359. * them to default values.
  160360. */
  160361. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160362. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160363. double output_gamma; /* image gamma wanted in output */
  160364. boolean buffered_image; /* TRUE=multiple output passes */
  160365. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160366. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160367. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160368. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160369. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160370. /* the following are ignored if not quantize_colors: */
  160371. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160372. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160373. int desired_number_of_colors; /* max # colors to use in created colormap */
  160374. /* these are significant only in buffered-image mode: */
  160375. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160376. boolean enable_external_quant;/* enable future use of external colormap */
  160377. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160378. /* Description of actual output image that will be returned to application.
  160379. * These fields are computed by jpeg_start_decompress().
  160380. * You can also use jpeg_calc_output_dimensions() to determine these values
  160381. * in advance of calling jpeg_start_decompress().
  160382. */
  160383. JDIMENSION output_width; /* scaled image width */
  160384. JDIMENSION output_height; /* scaled image height */
  160385. int out_color_components; /* # of color components in out_color_space */
  160386. int output_components; /* # of color components returned */
  160387. /* output_components is 1 (a colormap index) when quantizing colors;
  160388. * otherwise it equals out_color_components.
  160389. */
  160390. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160391. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160392. * high, space and time will be wasted due to unnecessary data copying.
  160393. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160394. */
  160395. /* When quantizing colors, the output colormap is described by these fields.
  160396. * The application can supply a colormap by setting colormap non-NULL before
  160397. * calling jpeg_start_decompress; otherwise a colormap is created during
  160398. * jpeg_start_decompress or jpeg_start_output.
  160399. * The map has out_color_components rows and actual_number_of_colors columns.
  160400. */
  160401. int actual_number_of_colors; /* number of entries in use */
  160402. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160403. /* State variables: these variables indicate the progress of decompression.
  160404. * The application may examine these but must not modify them.
  160405. */
  160406. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160407. * Application may use this to control its processing loop, e.g.,
  160408. * "while (output_scanline < output_height)".
  160409. */
  160410. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160411. /* Current input scan number and number of iMCU rows completed in scan.
  160412. * These indicate the progress of the decompressor input side.
  160413. */
  160414. int input_scan_number; /* Number of SOS markers seen so far */
  160415. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160416. /* The "output scan number" is the notional scan being displayed by the
  160417. * output side. The decompressor will not allow output scan/row number
  160418. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160419. */
  160420. int output_scan_number; /* Nominal scan number being displayed */
  160421. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160422. /* Current progression status. coef_bits[c][i] indicates the precision
  160423. * with which component c's DCT coefficient i (in zigzag order) is known.
  160424. * It is -1 when no data has yet been received, otherwise it is the point
  160425. * transform (shift) value for the most recent scan of the coefficient
  160426. * (thus, 0 at completion of the progression).
  160427. * This pointer is NULL when reading a non-progressive file.
  160428. */
  160429. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160430. /* Internal JPEG parameters --- the application usually need not look at
  160431. * these fields. Note that the decompressor output side may not use
  160432. * any parameters that can change between scans.
  160433. */
  160434. /* Quantization and Huffman tables are carried forward across input
  160435. * datastreams when processing abbreviated JPEG datastreams.
  160436. */
  160437. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160438. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160439. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160440. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160441. /* ptrs to Huffman coding tables, or NULL if not defined */
  160442. /* These parameters are never carried across datastreams, since they
  160443. * are given in SOF/SOS markers or defined to be reset by SOI.
  160444. */
  160445. int data_precision; /* bits of precision in image data */
  160446. jpeg_component_info * comp_info;
  160447. /* comp_info[i] describes component that appears i'th in SOF */
  160448. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160449. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160450. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160451. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160452. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160453. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160454. /* These fields record data obtained from optional markers recognized by
  160455. * the JPEG library.
  160456. */
  160457. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160458. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160459. UINT8 JFIF_major_version; /* JFIF version number */
  160460. UINT8 JFIF_minor_version;
  160461. UINT8 density_unit; /* JFIF code for pixel size units */
  160462. UINT16 X_density; /* Horizontal pixel density */
  160463. UINT16 Y_density; /* Vertical pixel density */
  160464. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160465. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160466. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160467. /* Aside from the specific data retained from APPn markers known to the
  160468. * library, the uninterpreted contents of any or all APPn and COM markers
  160469. * can be saved in a list for examination by the application.
  160470. */
  160471. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160472. /* Remaining fields are known throughout decompressor, but generally
  160473. * should not be touched by a surrounding application.
  160474. */
  160475. /*
  160476. * These fields are computed during decompression startup
  160477. */
  160478. int max_h_samp_factor; /* largest h_samp_factor */
  160479. int max_v_samp_factor; /* largest v_samp_factor */
  160480. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160481. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160482. /* The coefficient controller's input and output progress is measured in
  160483. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160484. * in fully interleaved JPEG scans, but are used whether the scan is
  160485. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160486. * rows of each component. Therefore, the IDCT output contains
  160487. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160488. */
  160489. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160490. /*
  160491. * These fields are valid during any one scan.
  160492. * They describe the components and MCUs actually appearing in the scan.
  160493. * Note that the decompressor output side must not use these fields.
  160494. */
  160495. int comps_in_scan; /* # of JPEG components in this scan */
  160496. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160497. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160498. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160499. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160500. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160501. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160502. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160503. /* i'th block in an MCU */
  160504. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160505. /* This field is shared between entropy decoder and marker parser.
  160506. * It is either zero or the code of a JPEG marker that has been
  160507. * read from the data source, but has not yet been processed.
  160508. */
  160509. int unread_marker;
  160510. /*
  160511. * Links to decompression subobjects (methods, private variables of modules)
  160512. */
  160513. struct jpeg_decomp_master * master;
  160514. struct jpeg_d_main_controller * main;
  160515. struct jpeg_d_coef_controller * coef;
  160516. struct jpeg_d_post_controller * post;
  160517. struct jpeg_input_controller * inputctl;
  160518. struct jpeg_marker_reader * marker;
  160519. struct jpeg_entropy_decoder * entropy;
  160520. struct jpeg_inverse_dct * idct;
  160521. struct jpeg_upsampler * upsample;
  160522. struct jpeg_color_deconverter * cconvert;
  160523. struct jpeg_color_quantizer * cquantize;
  160524. };
  160525. /* "Object" declarations for JPEG modules that may be supplied or called
  160526. * directly by the surrounding application.
  160527. * As with all objects in the JPEG library, these structs only define the
  160528. * publicly visible methods and state variables of a module. Additional
  160529. * private fields may exist after the public ones.
  160530. */
  160531. /* Error handler object */
  160532. struct jpeg_error_mgr {
  160533. /* Error exit handler: does not return to caller */
  160534. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160535. /* Conditionally emit a trace or warning message */
  160536. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160537. /* Routine that actually outputs a trace or error message */
  160538. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160539. /* Format a message string for the most recent JPEG error or message */
  160540. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160541. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160542. /* Reset error state variables at start of a new image */
  160543. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160544. /* The message ID code and any parameters are saved here.
  160545. * A message can have one string parameter or up to 8 int parameters.
  160546. */
  160547. int msg_code;
  160548. #define JMSG_STR_PARM_MAX 80
  160549. union {
  160550. int i[8];
  160551. char s[JMSG_STR_PARM_MAX];
  160552. } msg_parm;
  160553. /* Standard state variables for error facility */
  160554. int trace_level; /* max msg_level that will be displayed */
  160555. /* For recoverable corrupt-data errors, we emit a warning message,
  160556. * but keep going unless emit_message chooses to abort. emit_message
  160557. * should count warnings in num_warnings. The surrounding application
  160558. * can check for bad data by seeing if num_warnings is nonzero at the
  160559. * end of processing.
  160560. */
  160561. long num_warnings; /* number of corrupt-data warnings */
  160562. /* These fields point to the table(s) of error message strings.
  160563. * An application can change the table pointer to switch to a different
  160564. * message list (typically, to change the language in which errors are
  160565. * reported). Some applications may wish to add additional error codes
  160566. * that will be handled by the JPEG library error mechanism; the second
  160567. * table pointer is used for this purpose.
  160568. *
  160569. * First table includes all errors generated by JPEG library itself.
  160570. * Error code 0 is reserved for a "no such error string" message.
  160571. */
  160572. const char * const * jpeg_message_table; /* Library errors */
  160573. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160574. /* Second table can be added by application (see cjpeg/djpeg for example).
  160575. * It contains strings numbered first_addon_message..last_addon_message.
  160576. */
  160577. const char * const * addon_message_table; /* Non-library errors */
  160578. int first_addon_message; /* code for first string in addon table */
  160579. int last_addon_message; /* code for last string in addon table */
  160580. };
  160581. /* Progress monitor object */
  160582. struct jpeg_progress_mgr {
  160583. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160584. long pass_counter; /* work units completed in this pass */
  160585. long pass_limit; /* total number of work units in this pass */
  160586. int completed_passes; /* passes completed so far */
  160587. int total_passes; /* total number of passes expected */
  160588. };
  160589. /* Data destination object for compression */
  160590. struct jpeg_destination_mgr {
  160591. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160592. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160593. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160594. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160595. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160596. };
  160597. /* Data source object for decompression */
  160598. struct jpeg_source_mgr {
  160599. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160600. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160601. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160602. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160603. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160604. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160605. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160606. };
  160607. /* Memory manager object.
  160608. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160609. * and "really big" objects (virtual arrays with backing store if needed).
  160610. * The memory manager does not allow individual objects to be freed; rather,
  160611. * each created object is assigned to a pool, and whole pools can be freed
  160612. * at once. This is faster and more convenient than remembering exactly what
  160613. * to free, especially where malloc()/free() are not too speedy.
  160614. * NB: alloc routines never return NULL. They exit to error_exit if not
  160615. * successful.
  160616. */
  160617. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160618. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160619. #define JPOOL_NUMPOOLS 2
  160620. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160621. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160622. struct jpeg_memory_mgr {
  160623. /* Method pointers */
  160624. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160625. size_t sizeofobject));
  160626. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160627. size_t sizeofobject));
  160628. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160629. JDIMENSION samplesperrow,
  160630. JDIMENSION numrows));
  160631. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160632. JDIMENSION blocksperrow,
  160633. JDIMENSION numrows));
  160634. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160635. int pool_id,
  160636. boolean pre_zero,
  160637. JDIMENSION samplesperrow,
  160638. JDIMENSION numrows,
  160639. JDIMENSION maxaccess));
  160640. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160641. int pool_id,
  160642. boolean pre_zero,
  160643. JDIMENSION blocksperrow,
  160644. JDIMENSION numrows,
  160645. JDIMENSION maxaccess));
  160646. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160647. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160648. jvirt_sarray_ptr ptr,
  160649. JDIMENSION start_row,
  160650. JDIMENSION num_rows,
  160651. boolean writable));
  160652. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160653. jvirt_barray_ptr ptr,
  160654. JDIMENSION start_row,
  160655. JDIMENSION num_rows,
  160656. boolean writable));
  160657. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160658. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160659. /* Limit on memory allocation for this JPEG object. (Note that this is
  160660. * merely advisory, not a guaranteed maximum; it only affects the space
  160661. * used for virtual-array buffers.) May be changed by outer application
  160662. * after creating the JPEG object.
  160663. */
  160664. long max_memory_to_use;
  160665. /* Maximum allocation request accepted by alloc_large. */
  160666. long max_alloc_chunk;
  160667. };
  160668. /* Routine signature for application-supplied marker processing methods.
  160669. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160670. */
  160671. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160672. /* Declarations for routines called by application.
  160673. * The JPP macro hides prototype parameters from compilers that can't cope.
  160674. * Note JPP requires double parentheses.
  160675. */
  160676. #ifdef HAVE_PROTOTYPES
  160677. #define JPP(arglist) arglist
  160678. #else
  160679. #define JPP(arglist) ()
  160680. #endif
  160681. /* Short forms of external names for systems with brain-damaged linkers.
  160682. * We shorten external names to be unique in the first six letters, which
  160683. * is good enough for all known systems.
  160684. * (If your compiler itself needs names to be unique in less than 15
  160685. * characters, you are out of luck. Get a better compiler.)
  160686. */
  160687. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160688. #define jpeg_std_error jStdError
  160689. #define jpeg_CreateCompress jCreaCompress
  160690. #define jpeg_CreateDecompress jCreaDecompress
  160691. #define jpeg_destroy_compress jDestCompress
  160692. #define jpeg_destroy_decompress jDestDecompress
  160693. #define jpeg_stdio_dest jStdDest
  160694. #define jpeg_stdio_src jStdSrc
  160695. #define jpeg_set_defaults jSetDefaults
  160696. #define jpeg_set_colorspace jSetColorspace
  160697. #define jpeg_default_colorspace jDefColorspace
  160698. #define jpeg_set_quality jSetQuality
  160699. #define jpeg_set_linear_quality jSetLQuality
  160700. #define jpeg_add_quant_table jAddQuantTable
  160701. #define jpeg_quality_scaling jQualityScaling
  160702. #define jpeg_simple_progression jSimProgress
  160703. #define jpeg_suppress_tables jSuppressTables
  160704. #define jpeg_alloc_quant_table jAlcQTable
  160705. #define jpeg_alloc_huff_table jAlcHTable
  160706. #define jpeg_start_compress jStrtCompress
  160707. #define jpeg_write_scanlines jWrtScanlines
  160708. #define jpeg_finish_compress jFinCompress
  160709. #define jpeg_write_raw_data jWrtRawData
  160710. #define jpeg_write_marker jWrtMarker
  160711. #define jpeg_write_m_header jWrtMHeader
  160712. #define jpeg_write_m_byte jWrtMByte
  160713. #define jpeg_write_tables jWrtTables
  160714. #define jpeg_read_header jReadHeader
  160715. #define jpeg_start_decompress jStrtDecompress
  160716. #define jpeg_read_scanlines jReadScanlines
  160717. #define jpeg_finish_decompress jFinDecompress
  160718. #define jpeg_read_raw_data jReadRawData
  160719. #define jpeg_has_multiple_scans jHasMultScn
  160720. #define jpeg_start_output jStrtOutput
  160721. #define jpeg_finish_output jFinOutput
  160722. #define jpeg_input_complete jInComplete
  160723. #define jpeg_new_colormap jNewCMap
  160724. #define jpeg_consume_input jConsumeInput
  160725. #define jpeg_calc_output_dimensions jCalcDimensions
  160726. #define jpeg_save_markers jSaveMarkers
  160727. #define jpeg_set_marker_processor jSetMarker
  160728. #define jpeg_read_coefficients jReadCoefs
  160729. #define jpeg_write_coefficients jWrtCoefs
  160730. #define jpeg_copy_critical_parameters jCopyCrit
  160731. #define jpeg_abort_compress jAbrtCompress
  160732. #define jpeg_abort_decompress jAbrtDecompress
  160733. #define jpeg_abort jAbort
  160734. #define jpeg_destroy jDestroy
  160735. #define jpeg_resync_to_restart jResyncRestart
  160736. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160737. /* Default error-management setup */
  160738. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160739. JPP((struct jpeg_error_mgr * err));
  160740. /* Initialization of JPEG compression objects.
  160741. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160742. * names that applications should call. These expand to calls on
  160743. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160744. * passed for version mismatch checking.
  160745. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160746. */
  160747. #define jpeg_create_compress(cinfo) \
  160748. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160749. (size_t) sizeof(struct jpeg_compress_struct))
  160750. #define jpeg_create_decompress(cinfo) \
  160751. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160752. (size_t) sizeof(struct jpeg_decompress_struct))
  160753. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160754. int version, size_t structsize));
  160755. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160756. int version, size_t structsize));
  160757. /* Destruction of JPEG compression objects */
  160758. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160759. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160760. /* Standard data source and destination managers: stdio streams. */
  160761. /* Caller is responsible for opening the file before and closing after. */
  160762. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160763. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160764. /* Default parameter setup for compression */
  160765. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160766. /* Compression parameter setup aids */
  160767. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160768. J_COLOR_SPACE colorspace));
  160769. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160770. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160771. boolean force_baseline));
  160772. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160773. int scale_factor,
  160774. boolean force_baseline));
  160775. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160776. const unsigned int *basic_table,
  160777. int scale_factor,
  160778. boolean force_baseline));
  160779. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160780. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160781. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160782. boolean suppress));
  160783. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160784. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160785. /* Main entry points for compression */
  160786. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160787. boolean write_all_tables));
  160788. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160789. JSAMPARRAY scanlines,
  160790. JDIMENSION num_lines));
  160791. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160792. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160793. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160794. JSAMPIMAGE data,
  160795. JDIMENSION num_lines));
  160796. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160797. EXTERN(void) jpeg_write_marker
  160798. JPP((j_compress_ptr cinfo, int marker,
  160799. const JOCTET * dataptr, unsigned int datalen));
  160800. /* Same, but piecemeal. */
  160801. EXTERN(void) jpeg_write_m_header
  160802. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160803. EXTERN(void) jpeg_write_m_byte
  160804. JPP((j_compress_ptr cinfo, int val));
  160805. /* Alternate compression function: just write an abbreviated table file */
  160806. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160807. /* Decompression startup: read start of JPEG datastream to see what's there */
  160808. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160809. boolean require_image));
  160810. /* Return value is one of: */
  160811. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160812. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160813. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160814. /* If you pass require_image = TRUE (normal case), you need not check for
  160815. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160816. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160817. * give a suspension return (the stdio source module doesn't).
  160818. */
  160819. /* Main entry points for decompression */
  160820. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160821. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160822. JSAMPARRAY scanlines,
  160823. JDIMENSION max_lines));
  160824. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160825. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160826. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160827. JSAMPIMAGE data,
  160828. JDIMENSION max_lines));
  160829. /* Additional entry points for buffered-image mode. */
  160830. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160831. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160832. int scan_number));
  160833. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160834. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160835. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160836. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160837. /* Return value is one of: */
  160838. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160839. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160840. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160841. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160842. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160843. /* Precalculate output dimensions for current decompression parameters. */
  160844. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160845. /* Control saving of COM and APPn markers into marker_list. */
  160846. EXTERN(void) jpeg_save_markers
  160847. JPP((j_decompress_ptr cinfo, int marker_code,
  160848. unsigned int length_limit));
  160849. /* Install a special processing method for COM or APPn markers. */
  160850. EXTERN(void) jpeg_set_marker_processor
  160851. JPP((j_decompress_ptr cinfo, int marker_code,
  160852. jpeg_marker_parser_method routine));
  160853. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160854. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160855. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160856. jvirt_barray_ptr * coef_arrays));
  160857. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160858. j_compress_ptr dstinfo));
  160859. /* If you choose to abort compression or decompression before completing
  160860. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160861. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160862. * if you're done with the JPEG object, but if you want to clean it up and
  160863. * reuse it, call this:
  160864. */
  160865. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160866. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160867. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160868. * flavor of JPEG object. These may be more convenient in some places.
  160869. */
  160870. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160871. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160872. /* Default restart-marker-resync procedure for use by data source modules */
  160873. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160874. int desired));
  160875. /* These marker codes are exported since applications and data source modules
  160876. * are likely to want to use them.
  160877. */
  160878. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160879. #define JPEG_EOI 0xD9 /* EOI marker code */
  160880. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160881. #define JPEG_COM 0xFE /* COM marker code */
  160882. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160883. * for structure definitions that are never filled in, keep it quiet by
  160884. * supplying dummy definitions for the various substructures.
  160885. */
  160886. #ifdef INCOMPLETE_TYPES_BROKEN
  160887. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160888. struct jvirt_sarray_control { long dummy; };
  160889. struct jvirt_barray_control { long dummy; };
  160890. struct jpeg_comp_master { long dummy; };
  160891. struct jpeg_c_main_controller { long dummy; };
  160892. struct jpeg_c_prep_controller { long dummy; };
  160893. struct jpeg_c_coef_controller { long dummy; };
  160894. struct jpeg_marker_writer { long dummy; };
  160895. struct jpeg_color_converter { long dummy; };
  160896. struct jpeg_downsampler { long dummy; };
  160897. struct jpeg_forward_dct { long dummy; };
  160898. struct jpeg_entropy_encoder { long dummy; };
  160899. struct jpeg_decomp_master { long dummy; };
  160900. struct jpeg_d_main_controller { long dummy; };
  160901. struct jpeg_d_coef_controller { long dummy; };
  160902. struct jpeg_d_post_controller { long dummy; };
  160903. struct jpeg_input_controller { long dummy; };
  160904. struct jpeg_marker_reader { long dummy; };
  160905. struct jpeg_entropy_decoder { long dummy; };
  160906. struct jpeg_inverse_dct { long dummy; };
  160907. struct jpeg_upsampler { long dummy; };
  160908. struct jpeg_color_deconverter { long dummy; };
  160909. struct jpeg_color_quantizer { long dummy; };
  160910. #endif /* JPEG_INTERNALS */
  160911. #endif /* INCOMPLETE_TYPES_BROKEN */
  160912. /*
  160913. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160914. * The internal structure declarations are read only when that is true.
  160915. * Applications using the library should not include jpegint.h, but may wish
  160916. * to include jerror.h.
  160917. */
  160918. #ifdef JPEG_INTERNALS
  160919. /*** Start of inlined file: jpegint.h ***/
  160920. /* Declarations for both compression & decompression */
  160921. typedef enum { /* Operating modes for buffer controllers */
  160922. JBUF_PASS_THRU, /* Plain stripwise operation */
  160923. /* Remaining modes require a full-image buffer to have been created */
  160924. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160925. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160926. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160927. } J_BUF_MODE;
  160928. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160929. #define CSTATE_START 100 /* after create_compress */
  160930. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160931. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160932. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160933. #define DSTATE_START 200 /* after create_decompress */
  160934. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160935. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160936. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160937. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160938. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160939. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160940. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160941. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160942. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160943. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160944. /* Declarations for compression modules */
  160945. /* Master control module */
  160946. struct jpeg_comp_master {
  160947. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160948. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160949. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160950. /* State variables made visible to other modules */
  160951. boolean call_pass_startup; /* True if pass_startup must be called */
  160952. boolean is_last_pass; /* True during last pass */
  160953. };
  160954. /* Main buffer control (downsampled-data buffer) */
  160955. struct jpeg_c_main_controller {
  160956. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160957. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160958. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160959. JDIMENSION in_rows_avail));
  160960. };
  160961. /* Compression preprocessing (downsampling input buffer control) */
  160962. struct jpeg_c_prep_controller {
  160963. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160964. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160965. JSAMPARRAY input_buf,
  160966. JDIMENSION *in_row_ctr,
  160967. JDIMENSION in_rows_avail,
  160968. JSAMPIMAGE output_buf,
  160969. JDIMENSION *out_row_group_ctr,
  160970. JDIMENSION out_row_groups_avail));
  160971. };
  160972. /* Coefficient buffer control */
  160973. struct jpeg_c_coef_controller {
  160974. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160975. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160976. JSAMPIMAGE input_buf));
  160977. };
  160978. /* Colorspace conversion */
  160979. struct jpeg_color_converter {
  160980. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160981. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160982. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160983. JDIMENSION output_row, int num_rows));
  160984. };
  160985. /* Downsampling */
  160986. struct jpeg_downsampler {
  160987. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160988. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160989. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160990. JSAMPIMAGE output_buf,
  160991. JDIMENSION out_row_group_index));
  160992. boolean need_context_rows; /* TRUE if need rows above & below */
  160993. };
  160994. /* Forward DCT (also controls coefficient quantization) */
  160995. struct jpeg_forward_dct {
  160996. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160997. /* perhaps this should be an array??? */
  160998. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160999. jpeg_component_info * compptr,
  161000. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161001. JDIMENSION start_row, JDIMENSION start_col,
  161002. JDIMENSION num_blocks));
  161003. };
  161004. /* Entropy encoding */
  161005. struct jpeg_entropy_encoder {
  161006. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161007. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161008. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161009. };
  161010. /* Marker writing */
  161011. struct jpeg_marker_writer {
  161012. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161013. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161014. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161015. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161016. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161017. /* These routines are exported to allow insertion of extra markers */
  161018. /* Probably only COM and APPn markers should be written this way */
  161019. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161020. unsigned int datalen));
  161021. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161022. };
  161023. /* Declarations for decompression modules */
  161024. /* Master control module */
  161025. struct jpeg_decomp_master {
  161026. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161027. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161028. /* State variables made visible to other modules */
  161029. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161030. };
  161031. /* Input control module */
  161032. struct jpeg_input_controller {
  161033. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161034. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161035. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161036. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161037. /* State variables made visible to other modules */
  161038. boolean has_multiple_scans; /* True if file has multiple scans */
  161039. boolean eoi_reached; /* True when EOI has been consumed */
  161040. };
  161041. /* Main buffer control (downsampled-data buffer) */
  161042. struct jpeg_d_main_controller {
  161043. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161044. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161045. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161046. JDIMENSION out_rows_avail));
  161047. };
  161048. /* Coefficient buffer control */
  161049. struct jpeg_d_coef_controller {
  161050. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161051. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161052. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161053. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161054. JSAMPIMAGE output_buf));
  161055. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161056. jvirt_barray_ptr *coef_arrays;
  161057. };
  161058. /* Decompression postprocessing (color quantization buffer control) */
  161059. struct jpeg_d_post_controller {
  161060. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161061. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161062. JSAMPIMAGE input_buf,
  161063. JDIMENSION *in_row_group_ctr,
  161064. JDIMENSION in_row_groups_avail,
  161065. JSAMPARRAY output_buf,
  161066. JDIMENSION *out_row_ctr,
  161067. JDIMENSION out_rows_avail));
  161068. };
  161069. /* Marker reading & parsing */
  161070. struct jpeg_marker_reader {
  161071. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161072. /* Read markers until SOS or EOI.
  161073. * Returns same codes as are defined for jpeg_consume_input:
  161074. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161075. */
  161076. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161077. /* Read a restart marker --- exported for use by entropy decoder only */
  161078. jpeg_marker_parser_method read_restart_marker;
  161079. /* State of marker reader --- nominally internal, but applications
  161080. * supplying COM or APPn handlers might like to know the state.
  161081. */
  161082. boolean saw_SOI; /* found SOI? */
  161083. boolean saw_SOF; /* found SOF? */
  161084. int next_restart_num; /* next restart number expected (0-7) */
  161085. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161086. };
  161087. /* Entropy decoding */
  161088. struct jpeg_entropy_decoder {
  161089. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161090. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161091. JBLOCKROW *MCU_data));
  161092. /* This is here to share code between baseline and progressive decoders; */
  161093. /* other modules probably should not use it */
  161094. boolean insufficient_data; /* set TRUE after emitting warning */
  161095. };
  161096. /* Inverse DCT (also performs dequantization) */
  161097. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161098. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161099. JCOEFPTR coef_block,
  161100. JSAMPARRAY output_buf, JDIMENSION output_col));
  161101. struct jpeg_inverse_dct {
  161102. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161103. /* It is useful to allow each component to have a separate IDCT method. */
  161104. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161105. };
  161106. /* Upsampling (note that upsampler must also call color converter) */
  161107. struct jpeg_upsampler {
  161108. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161109. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161110. JSAMPIMAGE input_buf,
  161111. JDIMENSION *in_row_group_ctr,
  161112. JDIMENSION in_row_groups_avail,
  161113. JSAMPARRAY output_buf,
  161114. JDIMENSION *out_row_ctr,
  161115. JDIMENSION out_rows_avail));
  161116. boolean need_context_rows; /* TRUE if need rows above & below */
  161117. };
  161118. /* Colorspace conversion */
  161119. struct jpeg_color_deconverter {
  161120. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161121. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161122. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161123. JSAMPARRAY output_buf, int num_rows));
  161124. };
  161125. /* Color quantization or color precision reduction */
  161126. struct jpeg_color_quantizer {
  161127. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161128. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161129. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161130. int num_rows));
  161131. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161132. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161133. };
  161134. /* Miscellaneous useful macros */
  161135. #undef MAX
  161136. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161137. #undef MIN
  161138. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161139. /* We assume that right shift corresponds to signed division by 2 with
  161140. * rounding towards minus infinity. This is correct for typical "arithmetic
  161141. * shift" instructions that shift in copies of the sign bit. But some
  161142. * C compilers implement >> with an unsigned shift. For these machines you
  161143. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161144. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161145. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161146. * included in the variables of any routine using RIGHT_SHIFT.
  161147. */
  161148. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161149. #define SHIFT_TEMPS INT32 shift_temp;
  161150. #define RIGHT_SHIFT(x,shft) \
  161151. ((shift_temp = (x)) < 0 ? \
  161152. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161153. (shift_temp >> (shft)))
  161154. #else
  161155. #define SHIFT_TEMPS
  161156. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161157. #endif
  161158. /* Short forms of external names for systems with brain-damaged linkers. */
  161159. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161160. #define jinit_compress_master jICompress
  161161. #define jinit_c_master_control jICMaster
  161162. #define jinit_c_main_controller jICMainC
  161163. #define jinit_c_prep_controller jICPrepC
  161164. #define jinit_c_coef_controller jICCoefC
  161165. #define jinit_color_converter jICColor
  161166. #define jinit_downsampler jIDownsampler
  161167. #define jinit_forward_dct jIFDCT
  161168. #define jinit_huff_encoder jIHEncoder
  161169. #define jinit_phuff_encoder jIPHEncoder
  161170. #define jinit_marker_writer jIMWriter
  161171. #define jinit_master_decompress jIDMaster
  161172. #define jinit_d_main_controller jIDMainC
  161173. #define jinit_d_coef_controller jIDCoefC
  161174. #define jinit_d_post_controller jIDPostC
  161175. #define jinit_input_controller jIInCtlr
  161176. #define jinit_marker_reader jIMReader
  161177. #define jinit_huff_decoder jIHDecoder
  161178. #define jinit_phuff_decoder jIPHDecoder
  161179. #define jinit_inverse_dct jIIDCT
  161180. #define jinit_upsampler jIUpsampler
  161181. #define jinit_color_deconverter jIDColor
  161182. #define jinit_1pass_quantizer jI1Quant
  161183. #define jinit_2pass_quantizer jI2Quant
  161184. #define jinit_merged_upsampler jIMUpsampler
  161185. #define jinit_memory_mgr jIMemMgr
  161186. #define jdiv_round_up jDivRound
  161187. #define jround_up jRound
  161188. #define jcopy_sample_rows jCopySamples
  161189. #define jcopy_block_row jCopyBlocks
  161190. #define jzero_far jZeroFar
  161191. #define jpeg_zigzag_order jZIGTable
  161192. #define jpeg_natural_order jZAGTable
  161193. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161194. /* Compression module initialization routines */
  161195. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161196. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161197. boolean transcode_only));
  161198. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161199. boolean need_full_buffer));
  161200. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161201. boolean need_full_buffer));
  161202. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161203. boolean need_full_buffer));
  161204. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161205. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161206. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161207. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161208. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161209. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161210. /* Decompression module initialization routines */
  161211. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161212. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161213. boolean need_full_buffer));
  161214. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161215. boolean need_full_buffer));
  161216. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161217. boolean need_full_buffer));
  161218. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161219. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161220. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161221. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161222. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161223. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161224. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161225. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161226. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161227. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161228. /* Memory manager initialization */
  161229. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161230. /* Utility routines in jutils.c */
  161231. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161232. EXTERN(long) jround_up JPP((long a, long b));
  161233. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161234. JSAMPARRAY output_array, int dest_row,
  161235. int num_rows, JDIMENSION num_cols));
  161236. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161237. JDIMENSION num_blocks));
  161238. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161239. /* Constant tables in jutils.c */
  161240. #if 0 /* This table is not actually needed in v6a */
  161241. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161242. #endif
  161243. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161244. /* Suppress undefined-structure complaints if necessary. */
  161245. #ifdef INCOMPLETE_TYPES_BROKEN
  161246. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161247. struct jvirt_sarray_control { long dummy; };
  161248. struct jvirt_barray_control { long dummy; };
  161249. #endif
  161250. #endif /* INCOMPLETE_TYPES_BROKEN */
  161251. /*** End of inlined file: jpegint.h ***/
  161252. /* fetch private declarations */
  161253. /*** Start of inlined file: jerror.h ***/
  161254. /*
  161255. * To define the enum list of message codes, include this file without
  161256. * defining macro JMESSAGE. To create a message string table, include it
  161257. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161258. */
  161259. #ifndef JMESSAGE
  161260. #ifndef JERROR_H
  161261. /* First time through, define the enum list */
  161262. #define JMAKE_ENUM_LIST
  161263. #else
  161264. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161265. #define JMESSAGE(code,string)
  161266. #endif /* JERROR_H */
  161267. #endif /* JMESSAGE */
  161268. #ifdef JMAKE_ENUM_LIST
  161269. typedef enum {
  161270. #define JMESSAGE(code,string) code ,
  161271. #endif /* JMAKE_ENUM_LIST */
  161272. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161273. /* For maintenance convenience, list is alphabetical by message code name */
  161274. JMESSAGE(JERR_ARITH_NOTIMPL,
  161275. "Sorry, there are legal restrictions on arithmetic coding")
  161276. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161277. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161278. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161279. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161280. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161281. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161282. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161283. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161284. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161285. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161286. JMESSAGE(JERR_BAD_LIB_VERSION,
  161287. "Wrong JPEG library version: library is %d, caller expects %d")
  161288. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161289. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161290. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161291. JMESSAGE(JERR_BAD_PROGRESSION,
  161292. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161293. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161294. "Invalid progressive parameters at scan script entry %d")
  161295. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161296. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161297. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161298. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161299. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161300. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161301. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161302. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161303. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161304. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161305. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161306. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161307. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161308. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161309. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161310. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161311. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161312. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161313. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161314. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161315. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161316. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161317. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161318. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161319. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161320. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161321. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161322. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161323. "Cannot transcode due to multiple use of quantization table %d")
  161324. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161325. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161326. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161327. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161328. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161329. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161330. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161331. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161332. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161333. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161334. JMESSAGE(JERR_QUANT_COMPONENTS,
  161335. "Cannot quantize more than %d color components")
  161336. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161337. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161338. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161339. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161340. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161341. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161342. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161343. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161344. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161345. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161346. JMESSAGE(JERR_TFILE_WRITE,
  161347. "Write failed on temporary file --- out of disk space?")
  161348. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161349. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161350. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161351. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161352. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161353. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161354. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161355. JMESSAGE(JMSG_VERSION, JVERSION)
  161356. JMESSAGE(JTRC_16BIT_TABLES,
  161357. "Caution: quantization tables are too coarse for baseline JPEG")
  161358. JMESSAGE(JTRC_ADOBE,
  161359. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161360. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161361. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161362. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161363. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161364. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161365. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161366. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161367. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161368. JMESSAGE(JTRC_EOI, "End Of Image")
  161369. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161370. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161371. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161372. "Warning: thumbnail image size does not match data length %u")
  161373. JMESSAGE(JTRC_JFIF_EXTENSION,
  161374. "JFIF extension marker: type 0x%02x, length %u")
  161375. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161376. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161377. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161378. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161379. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161380. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161381. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161382. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161383. JMESSAGE(JTRC_RST, "RST%d")
  161384. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161385. "Smoothing not supported with nonstandard sampling ratios")
  161386. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161387. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161388. JMESSAGE(JTRC_SOI, "Start of Image")
  161389. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161390. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161391. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161392. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161393. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161394. JMESSAGE(JTRC_THUMB_JPEG,
  161395. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161396. JMESSAGE(JTRC_THUMB_PALETTE,
  161397. "JFIF extension marker: palette thumbnail image, length %u")
  161398. JMESSAGE(JTRC_THUMB_RGB,
  161399. "JFIF extension marker: RGB thumbnail image, length %u")
  161400. JMESSAGE(JTRC_UNKNOWN_IDS,
  161401. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161402. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161403. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161404. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161405. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161406. "Inconsistent progression sequence for component %d coefficient %d")
  161407. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161408. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161409. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161410. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161411. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161412. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161413. JMESSAGE(JWRN_MUST_RESYNC,
  161414. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161415. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161416. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161417. #ifdef JMAKE_ENUM_LIST
  161418. JMSG_LASTMSGCODE
  161419. } J_MESSAGE_CODE;
  161420. #undef JMAKE_ENUM_LIST
  161421. #endif /* JMAKE_ENUM_LIST */
  161422. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161423. #undef JMESSAGE
  161424. #ifndef JERROR_H
  161425. #define JERROR_H
  161426. /* Macros to simplify using the error and trace message stuff */
  161427. /* The first parameter is either type of cinfo pointer */
  161428. /* Fatal errors (print message and exit) */
  161429. #define ERREXIT(cinfo,code) \
  161430. ((cinfo)->err->msg_code = (code), \
  161431. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161432. #define ERREXIT1(cinfo,code,p1) \
  161433. ((cinfo)->err->msg_code = (code), \
  161434. (cinfo)->err->msg_parm.i[0] = (p1), \
  161435. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161436. #define ERREXIT2(cinfo,code,p1,p2) \
  161437. ((cinfo)->err->msg_code = (code), \
  161438. (cinfo)->err->msg_parm.i[0] = (p1), \
  161439. (cinfo)->err->msg_parm.i[1] = (p2), \
  161440. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161441. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161442. ((cinfo)->err->msg_code = (code), \
  161443. (cinfo)->err->msg_parm.i[0] = (p1), \
  161444. (cinfo)->err->msg_parm.i[1] = (p2), \
  161445. (cinfo)->err->msg_parm.i[2] = (p3), \
  161446. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161447. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161448. ((cinfo)->err->msg_code = (code), \
  161449. (cinfo)->err->msg_parm.i[0] = (p1), \
  161450. (cinfo)->err->msg_parm.i[1] = (p2), \
  161451. (cinfo)->err->msg_parm.i[2] = (p3), \
  161452. (cinfo)->err->msg_parm.i[3] = (p4), \
  161453. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161454. #define ERREXITS(cinfo,code,str) \
  161455. ((cinfo)->err->msg_code = (code), \
  161456. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161457. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161458. #define MAKESTMT(stuff) do { stuff } while (0)
  161459. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161460. #define WARNMS(cinfo,code) \
  161461. ((cinfo)->err->msg_code = (code), \
  161462. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161463. #define WARNMS1(cinfo,code,p1) \
  161464. ((cinfo)->err->msg_code = (code), \
  161465. (cinfo)->err->msg_parm.i[0] = (p1), \
  161466. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161467. #define WARNMS2(cinfo,code,p1,p2) \
  161468. ((cinfo)->err->msg_code = (code), \
  161469. (cinfo)->err->msg_parm.i[0] = (p1), \
  161470. (cinfo)->err->msg_parm.i[1] = (p2), \
  161471. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161472. /* Informational/debugging messages */
  161473. #define TRACEMS(cinfo,lvl,code) \
  161474. ((cinfo)->err->msg_code = (code), \
  161475. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161476. #define TRACEMS1(cinfo,lvl,code,p1) \
  161477. ((cinfo)->err->msg_code = (code), \
  161478. (cinfo)->err->msg_parm.i[0] = (p1), \
  161479. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161480. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161481. ((cinfo)->err->msg_code = (code), \
  161482. (cinfo)->err->msg_parm.i[0] = (p1), \
  161483. (cinfo)->err->msg_parm.i[1] = (p2), \
  161484. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161485. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161486. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161487. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161488. (cinfo)->err->msg_code = (code); \
  161489. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161490. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161491. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161492. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161493. (cinfo)->err->msg_code = (code); \
  161494. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161495. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161496. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161497. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161498. _mp[4] = (p5); \
  161499. (cinfo)->err->msg_code = (code); \
  161500. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161501. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161502. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161503. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161504. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161505. (cinfo)->err->msg_code = (code); \
  161506. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161507. #define TRACEMSS(cinfo,lvl,code,str) \
  161508. ((cinfo)->err->msg_code = (code), \
  161509. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161510. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161511. #endif /* JERROR_H */
  161512. /*** End of inlined file: jerror.h ***/
  161513. /* fetch error codes too */
  161514. #endif
  161515. #endif /* JPEGLIB_H */
  161516. /*** End of inlined file: jpeglib.h ***/
  161517. /*** Start of inlined file: jcapimin.c ***/
  161518. #define JPEG_INTERNALS
  161519. /*** Start of inlined file: jinclude.h ***/
  161520. /* Include auto-config file to find out which system include files we need. */
  161521. #ifndef __jinclude_h__
  161522. #define __jinclude_h__
  161523. /*** Start of inlined file: jconfig.h ***/
  161524. /* see jconfig.doc for explanations */
  161525. // disable all the warnings under MSVC
  161526. #ifdef _MSC_VER
  161527. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161528. #endif
  161529. #ifdef __BORLANDC__
  161530. #pragma warn -8057
  161531. #pragma warn -8019
  161532. #pragma warn -8004
  161533. #pragma warn -8008
  161534. #endif
  161535. #define HAVE_PROTOTYPES
  161536. #define HAVE_UNSIGNED_CHAR
  161537. #define HAVE_UNSIGNED_SHORT
  161538. /* #define void char */
  161539. /* #define const */
  161540. #undef CHAR_IS_UNSIGNED
  161541. #define HAVE_STDDEF_H
  161542. #define HAVE_STDLIB_H
  161543. #undef NEED_BSD_STRINGS
  161544. #undef NEED_SYS_TYPES_H
  161545. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161546. #undef NEED_SHORT_EXTERNAL_NAMES
  161547. #undef INCOMPLETE_TYPES_BROKEN
  161548. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161549. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161550. typedef unsigned char boolean;
  161551. #endif
  161552. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161553. #ifdef JPEG_INTERNALS
  161554. #undef RIGHT_SHIFT_IS_UNSIGNED
  161555. #endif /* JPEG_INTERNALS */
  161556. #ifdef JPEG_CJPEG_DJPEG
  161557. #define BMP_SUPPORTED /* BMP image file format */
  161558. #define GIF_SUPPORTED /* GIF image file format */
  161559. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161560. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161561. #define TARGA_SUPPORTED /* Targa image file format */
  161562. #define TWO_FILE_COMMANDLINE /* optional */
  161563. #define USE_SETMODE /* Microsoft has setmode() */
  161564. #undef NEED_SIGNAL_CATCHER
  161565. #undef DONT_USE_B_MODE
  161566. #undef PROGRESS_REPORT /* optional */
  161567. #endif /* JPEG_CJPEG_DJPEG */
  161568. /*** End of inlined file: jconfig.h ***/
  161569. /* auto configuration options */
  161570. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161571. /*
  161572. * We need the NULL macro and size_t typedef.
  161573. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161574. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161575. * pull in <sys/types.h> as well.
  161576. * Note that the core JPEG library does not require <stdio.h>;
  161577. * only the default error handler and data source/destination modules do.
  161578. * But we must pull it in because of the references to FILE in jpeglib.h.
  161579. * You can remove those references if you want to compile without <stdio.h>.
  161580. */
  161581. #ifdef HAVE_STDDEF_H
  161582. #include <stddef.h>
  161583. #endif
  161584. #ifdef HAVE_STDLIB_H
  161585. #include <stdlib.h>
  161586. #endif
  161587. #ifdef NEED_SYS_TYPES_H
  161588. #include <sys/types.h>
  161589. #endif
  161590. #include <stdio.h>
  161591. /*
  161592. * We need memory copying and zeroing functions, plus strncpy().
  161593. * ANSI and System V implementations declare these in <string.h>.
  161594. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161595. * Some systems may declare memset and memcpy in <memory.h>.
  161596. *
  161597. * NOTE: we assume the size parameters to these functions are of type size_t.
  161598. * Change the casts in these macros if not!
  161599. */
  161600. #ifdef NEED_BSD_STRINGS
  161601. #include <strings.h>
  161602. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161603. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161604. #else /* not BSD, assume ANSI/SysV string lib */
  161605. #include <string.h>
  161606. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161607. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161608. #endif
  161609. /*
  161610. * In ANSI C, and indeed any rational implementation, size_t is also the
  161611. * type returned by sizeof(). However, it seems there are some irrational
  161612. * implementations out there, in which sizeof() returns an int even though
  161613. * size_t is defined as long or unsigned long. To ensure consistent results
  161614. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161615. */
  161616. #define SIZEOF(object) ((size_t) sizeof(object))
  161617. /*
  161618. * The modules that use fread() and fwrite() always invoke them through
  161619. * these macros. On some systems you may need to twiddle the argument casts.
  161620. * CAUTION: argument order is different from underlying functions!
  161621. */
  161622. #define JFREAD(file,buf,sizeofbuf) \
  161623. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161624. #define JFWRITE(file,buf,sizeofbuf) \
  161625. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161626. typedef enum { /* JPEG marker codes */
  161627. M_SOF0 = 0xc0,
  161628. M_SOF1 = 0xc1,
  161629. M_SOF2 = 0xc2,
  161630. M_SOF3 = 0xc3,
  161631. M_SOF5 = 0xc5,
  161632. M_SOF6 = 0xc6,
  161633. M_SOF7 = 0xc7,
  161634. M_JPG = 0xc8,
  161635. M_SOF9 = 0xc9,
  161636. M_SOF10 = 0xca,
  161637. M_SOF11 = 0xcb,
  161638. M_SOF13 = 0xcd,
  161639. M_SOF14 = 0xce,
  161640. M_SOF15 = 0xcf,
  161641. M_DHT = 0xc4,
  161642. M_DAC = 0xcc,
  161643. M_RST0 = 0xd0,
  161644. M_RST1 = 0xd1,
  161645. M_RST2 = 0xd2,
  161646. M_RST3 = 0xd3,
  161647. M_RST4 = 0xd4,
  161648. M_RST5 = 0xd5,
  161649. M_RST6 = 0xd6,
  161650. M_RST7 = 0xd7,
  161651. M_SOI = 0xd8,
  161652. M_EOI = 0xd9,
  161653. M_SOS = 0xda,
  161654. M_DQT = 0xdb,
  161655. M_DNL = 0xdc,
  161656. M_DRI = 0xdd,
  161657. M_DHP = 0xde,
  161658. M_EXP = 0xdf,
  161659. M_APP0 = 0xe0,
  161660. M_APP1 = 0xe1,
  161661. M_APP2 = 0xe2,
  161662. M_APP3 = 0xe3,
  161663. M_APP4 = 0xe4,
  161664. M_APP5 = 0xe5,
  161665. M_APP6 = 0xe6,
  161666. M_APP7 = 0xe7,
  161667. M_APP8 = 0xe8,
  161668. M_APP9 = 0xe9,
  161669. M_APP10 = 0xea,
  161670. M_APP11 = 0xeb,
  161671. M_APP12 = 0xec,
  161672. M_APP13 = 0xed,
  161673. M_APP14 = 0xee,
  161674. M_APP15 = 0xef,
  161675. M_JPG0 = 0xf0,
  161676. M_JPG13 = 0xfd,
  161677. M_COM = 0xfe,
  161678. M_TEM = 0x01,
  161679. M_ERROR = 0x100
  161680. } JPEG_MARKER;
  161681. /*
  161682. * Figure F.12: extend sign bit.
  161683. * On some machines, a shift and add will be faster than a table lookup.
  161684. */
  161685. #ifdef AVOID_TABLES
  161686. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161687. #else
  161688. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161689. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161690. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161691. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161692. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161693. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161694. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161695. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161696. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161697. #endif /* AVOID_TABLES */
  161698. #endif
  161699. /*** End of inlined file: jinclude.h ***/
  161700. /*
  161701. * Initialization of a JPEG compression object.
  161702. * The error manager must already be set up (in case memory manager fails).
  161703. */
  161704. GLOBAL(void)
  161705. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161706. {
  161707. int i;
  161708. /* Guard against version mismatches between library and caller. */
  161709. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161710. if (version != JPEG_LIB_VERSION)
  161711. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161712. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161713. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161714. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161715. /* For debugging purposes, we zero the whole master structure.
  161716. * But the application has already set the err pointer, and may have set
  161717. * client_data, so we have to save and restore those fields.
  161718. * Note: if application hasn't set client_data, tools like Purify may
  161719. * complain here.
  161720. */
  161721. {
  161722. struct jpeg_error_mgr * err = cinfo->err;
  161723. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161724. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161725. cinfo->err = err;
  161726. cinfo->client_data = client_data;
  161727. }
  161728. cinfo->is_decompressor = FALSE;
  161729. /* Initialize a memory manager instance for this object */
  161730. jinit_memory_mgr((j_common_ptr) cinfo);
  161731. /* Zero out pointers to permanent structures. */
  161732. cinfo->progress = NULL;
  161733. cinfo->dest = NULL;
  161734. cinfo->comp_info = NULL;
  161735. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161736. cinfo->quant_tbl_ptrs[i] = NULL;
  161737. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161738. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161739. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161740. }
  161741. cinfo->script_space = NULL;
  161742. cinfo->input_gamma = 1.0; /* in case application forgets */
  161743. /* OK, I'm ready */
  161744. cinfo->global_state = CSTATE_START;
  161745. }
  161746. /*
  161747. * Destruction of a JPEG compression object
  161748. */
  161749. GLOBAL(void)
  161750. jpeg_destroy_compress (j_compress_ptr cinfo)
  161751. {
  161752. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161753. }
  161754. /*
  161755. * Abort processing of a JPEG compression operation,
  161756. * but don't destroy the object itself.
  161757. */
  161758. GLOBAL(void)
  161759. jpeg_abort_compress (j_compress_ptr cinfo)
  161760. {
  161761. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161762. }
  161763. /*
  161764. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161765. * Marks all currently defined tables as already written (if suppress)
  161766. * or not written (if !suppress). This will control whether they get emitted
  161767. * by a subsequent jpeg_start_compress call.
  161768. *
  161769. * This routine is exported for use by applications that want to produce
  161770. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161771. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161772. * jcparam.o would be linked whether the application used it or not.
  161773. */
  161774. GLOBAL(void)
  161775. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161776. {
  161777. int i;
  161778. JQUANT_TBL * qtbl;
  161779. JHUFF_TBL * htbl;
  161780. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161781. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161782. qtbl->sent_table = suppress;
  161783. }
  161784. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161785. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161786. htbl->sent_table = suppress;
  161787. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161788. htbl->sent_table = suppress;
  161789. }
  161790. }
  161791. /*
  161792. * Finish JPEG compression.
  161793. *
  161794. * If a multipass operating mode was selected, this may do a great deal of
  161795. * work including most of the actual output.
  161796. */
  161797. GLOBAL(void)
  161798. jpeg_finish_compress (j_compress_ptr cinfo)
  161799. {
  161800. JDIMENSION iMCU_row;
  161801. if (cinfo->global_state == CSTATE_SCANNING ||
  161802. cinfo->global_state == CSTATE_RAW_OK) {
  161803. /* Terminate first pass */
  161804. if (cinfo->next_scanline < cinfo->image_height)
  161805. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161806. (*cinfo->master->finish_pass) (cinfo);
  161807. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161808. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161809. /* Perform any remaining passes */
  161810. while (! cinfo->master->is_last_pass) {
  161811. (*cinfo->master->prepare_for_pass) (cinfo);
  161812. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161813. if (cinfo->progress != NULL) {
  161814. cinfo->progress->pass_counter = (long) iMCU_row;
  161815. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161816. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161817. }
  161818. /* We bypass the main controller and invoke coef controller directly;
  161819. * all work is being done from the coefficient buffer.
  161820. */
  161821. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161822. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161823. }
  161824. (*cinfo->master->finish_pass) (cinfo);
  161825. }
  161826. /* Write EOI, do final cleanup */
  161827. (*cinfo->marker->write_file_trailer) (cinfo);
  161828. (*cinfo->dest->term_destination) (cinfo);
  161829. /* We can use jpeg_abort to release memory and reset global_state */
  161830. jpeg_abort((j_common_ptr) cinfo);
  161831. }
  161832. /*
  161833. * Write a special marker.
  161834. * This is only recommended for writing COM or APPn markers.
  161835. * Must be called after jpeg_start_compress() and before
  161836. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161837. */
  161838. GLOBAL(void)
  161839. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161840. const JOCTET *dataptr, unsigned int datalen)
  161841. {
  161842. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161843. if (cinfo->next_scanline != 0 ||
  161844. (cinfo->global_state != CSTATE_SCANNING &&
  161845. cinfo->global_state != CSTATE_RAW_OK &&
  161846. cinfo->global_state != CSTATE_WRCOEFS))
  161847. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161848. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161849. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161850. while (datalen--) {
  161851. (*write_marker_byte) (cinfo, *dataptr);
  161852. dataptr++;
  161853. }
  161854. }
  161855. /* Same, but piecemeal. */
  161856. GLOBAL(void)
  161857. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161858. {
  161859. if (cinfo->next_scanline != 0 ||
  161860. (cinfo->global_state != CSTATE_SCANNING &&
  161861. cinfo->global_state != CSTATE_RAW_OK &&
  161862. cinfo->global_state != CSTATE_WRCOEFS))
  161863. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161864. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161865. }
  161866. GLOBAL(void)
  161867. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161868. {
  161869. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161870. }
  161871. /*
  161872. * Alternate compression function: just write an abbreviated table file.
  161873. * Before calling this, all parameters and a data destination must be set up.
  161874. *
  161875. * To produce a pair of files containing abbreviated tables and abbreviated
  161876. * image data, one would proceed as follows:
  161877. *
  161878. * initialize JPEG object
  161879. * set JPEG parameters
  161880. * set destination to table file
  161881. * jpeg_write_tables(cinfo);
  161882. * set destination to image file
  161883. * jpeg_start_compress(cinfo, FALSE);
  161884. * write data...
  161885. * jpeg_finish_compress(cinfo);
  161886. *
  161887. * jpeg_write_tables has the side effect of marking all tables written
  161888. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161889. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161890. */
  161891. GLOBAL(void)
  161892. jpeg_write_tables (j_compress_ptr cinfo)
  161893. {
  161894. if (cinfo->global_state != CSTATE_START)
  161895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161896. /* (Re)initialize error mgr and destination modules */
  161897. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161898. (*cinfo->dest->init_destination) (cinfo);
  161899. /* Initialize the marker writer ... bit of a crock to do it here. */
  161900. jinit_marker_writer(cinfo);
  161901. /* Write them tables! */
  161902. (*cinfo->marker->write_tables_only) (cinfo);
  161903. /* And clean up. */
  161904. (*cinfo->dest->term_destination) (cinfo);
  161905. /*
  161906. * In library releases up through v6a, we called jpeg_abort() here to free
  161907. * any working memory allocated by the destination manager and marker
  161908. * writer. Some applications had a problem with that: they allocated space
  161909. * of their own from the library memory manager, and didn't want it to go
  161910. * away during write_tables. So now we do nothing. This will cause a
  161911. * memory leak if an app calls write_tables repeatedly without doing a full
  161912. * compression cycle or otherwise resetting the JPEG object. However, that
  161913. * seems less bad than unexpectedly freeing memory in the normal case.
  161914. * An app that prefers the old behavior can call jpeg_abort for itself after
  161915. * each call to jpeg_write_tables().
  161916. */
  161917. }
  161918. /*** End of inlined file: jcapimin.c ***/
  161919. /*** Start of inlined file: jcapistd.c ***/
  161920. #define JPEG_INTERNALS
  161921. /*
  161922. * Compression initialization.
  161923. * Before calling this, all parameters and a data destination must be set up.
  161924. *
  161925. * We require a write_all_tables parameter as a failsafe check when writing
  161926. * multiple datastreams from the same compression object. Since prior runs
  161927. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161928. * would emit an abbreviated stream (no tables) by default. This may be what
  161929. * is wanted, but for safety's sake it should not be the default behavior:
  161930. * programmers should have to make a deliberate choice to emit abbreviated
  161931. * images. Therefore the documentation and examples should encourage people
  161932. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161933. * wrong thing.
  161934. */
  161935. GLOBAL(void)
  161936. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161937. {
  161938. if (cinfo->global_state != CSTATE_START)
  161939. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161940. if (write_all_tables)
  161941. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161942. /* (Re)initialize error mgr and destination modules */
  161943. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161944. (*cinfo->dest->init_destination) (cinfo);
  161945. /* Perform master selection of active modules */
  161946. jinit_compress_master(cinfo);
  161947. /* Set up for the first pass */
  161948. (*cinfo->master->prepare_for_pass) (cinfo);
  161949. /* Ready for application to drive first pass through jpeg_write_scanlines
  161950. * or jpeg_write_raw_data.
  161951. */
  161952. cinfo->next_scanline = 0;
  161953. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161954. }
  161955. /*
  161956. * Write some scanlines of data to the JPEG compressor.
  161957. *
  161958. * The return value will be the number of lines actually written.
  161959. * This should be less than the supplied num_lines only in case that
  161960. * the data destination module has requested suspension of the compressor,
  161961. * or if more than image_height scanlines are passed in.
  161962. *
  161963. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161964. * this likely signals an application programmer error. However,
  161965. * excess scanlines passed in the last valid call are *silently* ignored,
  161966. * so that the application need not adjust num_lines for end-of-image
  161967. * when using a multiple-scanline buffer.
  161968. */
  161969. GLOBAL(JDIMENSION)
  161970. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161971. JDIMENSION num_lines)
  161972. {
  161973. JDIMENSION row_ctr, rows_left;
  161974. if (cinfo->global_state != CSTATE_SCANNING)
  161975. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161976. if (cinfo->next_scanline >= cinfo->image_height)
  161977. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161978. /* Call progress monitor hook if present */
  161979. if (cinfo->progress != NULL) {
  161980. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161981. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161982. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161983. }
  161984. /* Give master control module another chance if this is first call to
  161985. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161986. * delayed so that application can write COM, etc, markers between
  161987. * jpeg_start_compress and jpeg_write_scanlines.
  161988. */
  161989. if (cinfo->master->call_pass_startup)
  161990. (*cinfo->master->pass_startup) (cinfo);
  161991. /* Ignore any extra scanlines at bottom of image. */
  161992. rows_left = cinfo->image_height - cinfo->next_scanline;
  161993. if (num_lines > rows_left)
  161994. num_lines = rows_left;
  161995. row_ctr = 0;
  161996. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161997. cinfo->next_scanline += row_ctr;
  161998. return row_ctr;
  161999. }
  162000. /*
  162001. * Alternate entry point to write raw data.
  162002. * Processes exactly one iMCU row per call, unless suspended.
  162003. */
  162004. GLOBAL(JDIMENSION)
  162005. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162006. JDIMENSION num_lines)
  162007. {
  162008. JDIMENSION lines_per_iMCU_row;
  162009. if (cinfo->global_state != CSTATE_RAW_OK)
  162010. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162011. if (cinfo->next_scanline >= cinfo->image_height) {
  162012. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162013. return 0;
  162014. }
  162015. /* Call progress monitor hook if present */
  162016. if (cinfo->progress != NULL) {
  162017. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162018. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162019. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162020. }
  162021. /* Give master control module another chance if this is first call to
  162022. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162023. * delayed so that application can write COM, etc, markers between
  162024. * jpeg_start_compress and jpeg_write_raw_data.
  162025. */
  162026. if (cinfo->master->call_pass_startup)
  162027. (*cinfo->master->pass_startup) (cinfo);
  162028. /* Verify that at least one iMCU row has been passed. */
  162029. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162030. if (num_lines < lines_per_iMCU_row)
  162031. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162032. /* Directly compress the row. */
  162033. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162034. /* If compressor did not consume the whole row, suspend processing. */
  162035. return 0;
  162036. }
  162037. /* OK, we processed one iMCU row. */
  162038. cinfo->next_scanline += lines_per_iMCU_row;
  162039. return lines_per_iMCU_row;
  162040. }
  162041. /*** End of inlined file: jcapistd.c ***/
  162042. /*** Start of inlined file: jccoefct.c ***/
  162043. #define JPEG_INTERNALS
  162044. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162045. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162046. * step is run during the first pass, and subsequent passes need only read
  162047. * the buffered coefficients.
  162048. */
  162049. #ifdef ENTROPY_OPT_SUPPORTED
  162050. #define FULL_COEF_BUFFER_SUPPORTED
  162051. #else
  162052. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162053. #define FULL_COEF_BUFFER_SUPPORTED
  162054. #endif
  162055. #endif
  162056. /* Private buffer controller object */
  162057. typedef struct {
  162058. struct jpeg_c_coef_controller pub; /* public fields */
  162059. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162060. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162061. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162062. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162063. /* For single-pass compression, it's sufficient to buffer just one MCU
  162064. * (although this may prove a bit slow in practice). We allocate a
  162065. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162066. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162067. * it's not really very big; this is to keep the module interfaces unchanged
  162068. * when a large coefficient buffer is necessary.)
  162069. * In multi-pass modes, this array points to the current MCU's blocks
  162070. * within the virtual arrays.
  162071. */
  162072. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162073. /* In multi-pass modes, we need a virtual block array for each component. */
  162074. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162075. } my_coef_controller;
  162076. typedef my_coef_controller * my_coef_ptr;
  162077. /* Forward declarations */
  162078. METHODDEF(boolean) compress_data
  162079. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162080. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162081. METHODDEF(boolean) compress_first_pass
  162082. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162083. METHODDEF(boolean) compress_output
  162084. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162085. #endif
  162086. LOCAL(void)
  162087. start_iMCU_row (j_compress_ptr cinfo)
  162088. /* Reset within-iMCU-row counters for a new row */
  162089. {
  162090. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162091. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162092. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162093. * But at the bottom of the image, process only what's left.
  162094. */
  162095. if (cinfo->comps_in_scan > 1) {
  162096. coef->MCU_rows_per_iMCU_row = 1;
  162097. } else {
  162098. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162099. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162100. else
  162101. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162102. }
  162103. coef->mcu_ctr = 0;
  162104. coef->MCU_vert_offset = 0;
  162105. }
  162106. /*
  162107. * Initialize for a processing pass.
  162108. */
  162109. METHODDEF(void)
  162110. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162111. {
  162112. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162113. coef->iMCU_row_num = 0;
  162114. start_iMCU_row(cinfo);
  162115. switch (pass_mode) {
  162116. case JBUF_PASS_THRU:
  162117. if (coef->whole_image[0] != NULL)
  162118. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162119. coef->pub.compress_data = compress_data;
  162120. break;
  162121. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162122. case JBUF_SAVE_AND_PASS:
  162123. if (coef->whole_image[0] == NULL)
  162124. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162125. coef->pub.compress_data = compress_first_pass;
  162126. break;
  162127. case JBUF_CRANK_DEST:
  162128. if (coef->whole_image[0] == NULL)
  162129. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162130. coef->pub.compress_data = compress_output;
  162131. break;
  162132. #endif
  162133. default:
  162134. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162135. break;
  162136. }
  162137. }
  162138. /*
  162139. * Process some data in the single-pass case.
  162140. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162141. * per call, ie, v_samp_factor block rows for each component in the image.
  162142. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162143. *
  162144. * NB: input_buf contains a plane for each component in image,
  162145. * which we index according to the component's SOF position.
  162146. */
  162147. METHODDEF(boolean)
  162148. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162149. {
  162150. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162151. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162152. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162153. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162154. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162155. JDIMENSION ypos, xpos;
  162156. jpeg_component_info *compptr;
  162157. /* Loop to write as much as one whole iMCU row */
  162158. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162159. yoffset++) {
  162160. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162161. MCU_col_num++) {
  162162. /* Determine where data comes from in input_buf and do the DCT thing.
  162163. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162164. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162165. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162166. * specially. The data in them does not matter for image reconstruction,
  162167. * so we fill them with values that will encode to the smallest amount of
  162168. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162169. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162170. */
  162171. blkn = 0;
  162172. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162173. compptr = cinfo->cur_comp_info[ci];
  162174. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162175. : compptr->last_col_width;
  162176. xpos = MCU_col_num * compptr->MCU_sample_width;
  162177. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162178. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162179. if (coef->iMCU_row_num < last_iMCU_row ||
  162180. yoffset+yindex < compptr->last_row_height) {
  162181. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162182. input_buf[compptr->component_index],
  162183. coef->MCU_buffer[blkn],
  162184. ypos, xpos, (JDIMENSION) blockcnt);
  162185. if (blockcnt < compptr->MCU_width) {
  162186. /* Create some dummy blocks at the right edge of the image. */
  162187. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162188. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162189. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162190. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162191. }
  162192. }
  162193. } else {
  162194. /* Create a row of dummy blocks at the bottom of the image. */
  162195. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162196. compptr->MCU_width * SIZEOF(JBLOCK));
  162197. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162198. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162199. }
  162200. }
  162201. blkn += compptr->MCU_width;
  162202. ypos += DCTSIZE;
  162203. }
  162204. }
  162205. /* Try to write the MCU. In event of a suspension failure, we will
  162206. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162207. */
  162208. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162209. /* Suspension forced; update state counters and exit */
  162210. coef->MCU_vert_offset = yoffset;
  162211. coef->mcu_ctr = MCU_col_num;
  162212. return FALSE;
  162213. }
  162214. }
  162215. /* Completed an MCU row, but perhaps not an iMCU row */
  162216. coef->mcu_ctr = 0;
  162217. }
  162218. /* Completed the iMCU row, advance counters for next one */
  162219. coef->iMCU_row_num++;
  162220. start_iMCU_row(cinfo);
  162221. return TRUE;
  162222. }
  162223. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162224. /*
  162225. * Process some data in the first pass of a multi-pass case.
  162226. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162227. * per call, ie, v_samp_factor block rows for each component in the image.
  162228. * This amount of data is read from the source buffer, DCT'd and quantized,
  162229. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162230. * as needed at the right and lower edges. (The dummy blocks are constructed
  162231. * in the virtual arrays, which have been padded appropriately.) This makes
  162232. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162233. *
  162234. * We must also emit the data to the entropy encoder. This is conveniently
  162235. * done by calling compress_output() after we've loaded the current strip
  162236. * of the virtual arrays.
  162237. *
  162238. * NB: input_buf contains a plane for each component in image. All
  162239. * components are DCT'd and loaded into the virtual arrays in this pass.
  162240. * However, it may be that only a subset of the components are emitted to
  162241. * the entropy encoder during this first pass; be careful about looking
  162242. * at the scan-dependent variables (MCU dimensions, etc).
  162243. */
  162244. METHODDEF(boolean)
  162245. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162246. {
  162247. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162248. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162249. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162250. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162251. JCOEF lastDC;
  162252. jpeg_component_info *compptr;
  162253. JBLOCKARRAY buffer;
  162254. JBLOCKROW thisblockrow, lastblockrow;
  162255. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162256. ci++, compptr++) {
  162257. /* Align the virtual buffer for this component. */
  162258. buffer = (*cinfo->mem->access_virt_barray)
  162259. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162260. coef->iMCU_row_num * compptr->v_samp_factor,
  162261. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162262. /* Count non-dummy DCT block rows in this iMCU row. */
  162263. if (coef->iMCU_row_num < last_iMCU_row)
  162264. block_rows = compptr->v_samp_factor;
  162265. else {
  162266. /* NB: can't use last_row_height here, since may not be set! */
  162267. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162268. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162269. }
  162270. blocks_across = compptr->width_in_blocks;
  162271. h_samp_factor = compptr->h_samp_factor;
  162272. /* Count number of dummy blocks to be added at the right margin. */
  162273. ndummy = (int) (blocks_across % h_samp_factor);
  162274. if (ndummy > 0)
  162275. ndummy = h_samp_factor - ndummy;
  162276. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162277. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162278. */
  162279. for (block_row = 0; block_row < block_rows; block_row++) {
  162280. thisblockrow = buffer[block_row];
  162281. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162282. input_buf[ci], thisblockrow,
  162283. (JDIMENSION) (block_row * DCTSIZE),
  162284. (JDIMENSION) 0, blocks_across);
  162285. if (ndummy > 0) {
  162286. /* Create dummy blocks at the right edge of the image. */
  162287. thisblockrow += blocks_across; /* => first dummy block */
  162288. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162289. lastDC = thisblockrow[-1][0];
  162290. for (bi = 0; bi < ndummy; bi++) {
  162291. thisblockrow[bi][0] = lastDC;
  162292. }
  162293. }
  162294. }
  162295. /* If at end of image, create dummy block rows as needed.
  162296. * The tricky part here is that within each MCU, we want the DC values
  162297. * of the dummy blocks to match the last real block's DC value.
  162298. * This squeezes a few more bytes out of the resulting file...
  162299. */
  162300. if (coef->iMCU_row_num == last_iMCU_row) {
  162301. blocks_across += ndummy; /* include lower right corner */
  162302. MCUs_across = blocks_across / h_samp_factor;
  162303. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162304. block_row++) {
  162305. thisblockrow = buffer[block_row];
  162306. lastblockrow = buffer[block_row-1];
  162307. jzero_far((void FAR *) thisblockrow,
  162308. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162309. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162310. lastDC = lastblockrow[h_samp_factor-1][0];
  162311. for (bi = 0; bi < h_samp_factor; bi++) {
  162312. thisblockrow[bi][0] = lastDC;
  162313. }
  162314. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162315. lastblockrow += h_samp_factor;
  162316. }
  162317. }
  162318. }
  162319. }
  162320. /* NB: compress_output will increment iMCU_row_num if successful.
  162321. * A suspension return will result in redoing all the work above next time.
  162322. */
  162323. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162324. return compress_output(cinfo, input_buf);
  162325. }
  162326. /*
  162327. * Process some data in subsequent passes of a multi-pass case.
  162328. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162329. * per call, ie, v_samp_factor block rows for each component in the scan.
  162330. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162331. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162332. *
  162333. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162334. */
  162335. METHODDEF(boolean)
  162336. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162337. {
  162338. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162339. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162340. int blkn, ci, xindex, yindex, yoffset;
  162341. JDIMENSION start_col;
  162342. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162343. JBLOCKROW buffer_ptr;
  162344. jpeg_component_info *compptr;
  162345. /* Align the virtual buffers for the components used in this scan.
  162346. * NB: during first pass, this is safe only because the buffers will
  162347. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162348. */
  162349. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162350. compptr = cinfo->cur_comp_info[ci];
  162351. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162352. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162353. coef->iMCU_row_num * compptr->v_samp_factor,
  162354. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162355. }
  162356. /* Loop to process one whole iMCU row */
  162357. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162358. yoffset++) {
  162359. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162360. MCU_col_num++) {
  162361. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162362. blkn = 0; /* index of current DCT block within MCU */
  162363. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162364. compptr = cinfo->cur_comp_info[ci];
  162365. start_col = MCU_col_num * compptr->MCU_width;
  162366. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162367. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162368. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162369. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162370. }
  162371. }
  162372. }
  162373. /* Try to write the MCU. */
  162374. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162375. /* Suspension forced; update state counters and exit */
  162376. coef->MCU_vert_offset = yoffset;
  162377. coef->mcu_ctr = MCU_col_num;
  162378. return FALSE;
  162379. }
  162380. }
  162381. /* Completed an MCU row, but perhaps not an iMCU row */
  162382. coef->mcu_ctr = 0;
  162383. }
  162384. /* Completed the iMCU row, advance counters for next one */
  162385. coef->iMCU_row_num++;
  162386. start_iMCU_row(cinfo);
  162387. return TRUE;
  162388. }
  162389. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162390. /*
  162391. * Initialize coefficient buffer controller.
  162392. */
  162393. GLOBAL(void)
  162394. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162395. {
  162396. my_coef_ptr coef;
  162397. coef = (my_coef_ptr)
  162398. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162399. SIZEOF(my_coef_controller));
  162400. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162401. coef->pub.start_pass = start_pass_coef;
  162402. /* Create the coefficient buffer. */
  162403. if (need_full_buffer) {
  162404. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162405. /* Allocate a full-image virtual array for each component, */
  162406. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162407. int ci;
  162408. jpeg_component_info *compptr;
  162409. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162410. ci++, compptr++) {
  162411. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162412. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162413. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162414. (long) compptr->h_samp_factor),
  162415. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162416. (long) compptr->v_samp_factor),
  162417. (JDIMENSION) compptr->v_samp_factor);
  162418. }
  162419. #else
  162420. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162421. #endif
  162422. } else {
  162423. /* We only need a single-MCU buffer. */
  162424. JBLOCKROW buffer;
  162425. int i;
  162426. buffer = (JBLOCKROW)
  162427. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162428. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162429. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162430. coef->MCU_buffer[i] = buffer + i;
  162431. }
  162432. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162433. }
  162434. }
  162435. /*** End of inlined file: jccoefct.c ***/
  162436. /*** Start of inlined file: jccolor.c ***/
  162437. #define JPEG_INTERNALS
  162438. /* Private subobject */
  162439. typedef struct {
  162440. struct jpeg_color_converter pub; /* public fields */
  162441. /* Private state for RGB->YCC conversion */
  162442. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162443. } my_color_converter;
  162444. typedef my_color_converter * my_cconvert_ptr;
  162445. /**************** RGB -> YCbCr conversion: most common case **************/
  162446. /*
  162447. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162448. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162449. * The conversion equations to be implemented are therefore
  162450. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162451. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162452. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162453. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162454. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162455. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162456. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162457. * were not represented exactly. Now we sacrifice exact representation of
  162458. * maximum red and maximum blue in order to get exact grayscales.
  162459. *
  162460. * To avoid floating-point arithmetic, we represent the fractional constants
  162461. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162462. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162463. *
  162464. * For even more speed, we avoid doing any multiplications in the inner loop
  162465. * by precalculating the constants times R,G,B for all possible values.
  162466. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162467. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162468. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162469. * colorspace anyway.
  162470. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162471. * in the tables to save adding them separately in the inner loop.
  162472. */
  162473. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162474. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162475. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162476. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162477. /* We allocate one big table and divide it up into eight parts, instead of
  162478. * doing eight alloc_small requests. This lets us use a single table base
  162479. * address, which can be held in a register in the inner loops on many
  162480. * machines (more than can hold all eight addresses, anyway).
  162481. */
  162482. #define R_Y_OFF 0 /* offset to R => Y section */
  162483. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162484. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162485. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162486. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162487. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162488. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162489. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162490. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162491. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162492. /*
  162493. * Initialize for RGB->YCC colorspace conversion.
  162494. */
  162495. METHODDEF(void)
  162496. rgb_ycc_start (j_compress_ptr cinfo)
  162497. {
  162498. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162499. INT32 * rgb_ycc_tab;
  162500. INT32 i;
  162501. /* Allocate and fill in the conversion tables. */
  162502. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162503. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162504. (TABLE_SIZE * SIZEOF(INT32)));
  162505. for (i = 0; i <= MAXJSAMPLE; i++) {
  162506. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162507. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162508. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162509. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162510. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162511. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162512. * This ensures that the maximum output will round to MAXJSAMPLE
  162513. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162514. */
  162515. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162516. /* B=>Cb and R=>Cr tables are the same
  162517. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162518. */
  162519. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162520. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162521. }
  162522. }
  162523. /*
  162524. * Convert some rows of samples to the JPEG colorspace.
  162525. *
  162526. * Note that we change from the application's interleaved-pixel format
  162527. * to our internal noninterleaved, one-plane-per-component format.
  162528. * The input buffer is therefore three times as wide as the output buffer.
  162529. *
  162530. * A starting row offset is provided only for the output buffer. The caller
  162531. * can easily adjust the passed input_buf value to accommodate any row
  162532. * offset required on that side.
  162533. */
  162534. METHODDEF(void)
  162535. rgb_ycc_convert (j_compress_ptr cinfo,
  162536. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162537. JDIMENSION output_row, int num_rows)
  162538. {
  162539. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162540. register int r, g, b;
  162541. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162542. register JSAMPROW inptr;
  162543. register JSAMPROW outptr0, outptr1, outptr2;
  162544. register JDIMENSION col;
  162545. JDIMENSION num_cols = cinfo->image_width;
  162546. while (--num_rows >= 0) {
  162547. inptr = *input_buf++;
  162548. outptr0 = output_buf[0][output_row];
  162549. outptr1 = output_buf[1][output_row];
  162550. outptr2 = output_buf[2][output_row];
  162551. output_row++;
  162552. for (col = 0; col < num_cols; col++) {
  162553. r = GETJSAMPLE(inptr[RGB_RED]);
  162554. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162555. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162556. inptr += RGB_PIXELSIZE;
  162557. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162558. * must be too; we do not need an explicit range-limiting operation.
  162559. * Hence the value being shifted is never negative, and we don't
  162560. * need the general RIGHT_SHIFT macro.
  162561. */
  162562. /* Y */
  162563. outptr0[col] = (JSAMPLE)
  162564. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162565. >> SCALEBITS);
  162566. /* Cb */
  162567. outptr1[col] = (JSAMPLE)
  162568. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162569. >> SCALEBITS);
  162570. /* Cr */
  162571. outptr2[col] = (JSAMPLE)
  162572. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162573. >> SCALEBITS);
  162574. }
  162575. }
  162576. }
  162577. /**************** Cases other than RGB -> YCbCr **************/
  162578. /*
  162579. * Convert some rows of samples to the JPEG colorspace.
  162580. * This version handles RGB->grayscale conversion, which is the same
  162581. * as the RGB->Y portion of RGB->YCbCr.
  162582. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162583. */
  162584. METHODDEF(void)
  162585. rgb_gray_convert (j_compress_ptr cinfo,
  162586. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162587. JDIMENSION output_row, int num_rows)
  162588. {
  162589. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162590. register int r, g, b;
  162591. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162592. register JSAMPROW inptr;
  162593. register JSAMPROW outptr;
  162594. register JDIMENSION col;
  162595. JDIMENSION num_cols = cinfo->image_width;
  162596. while (--num_rows >= 0) {
  162597. inptr = *input_buf++;
  162598. outptr = output_buf[0][output_row];
  162599. output_row++;
  162600. for (col = 0; col < num_cols; col++) {
  162601. r = GETJSAMPLE(inptr[RGB_RED]);
  162602. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162603. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162604. inptr += RGB_PIXELSIZE;
  162605. /* Y */
  162606. outptr[col] = (JSAMPLE)
  162607. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162608. >> SCALEBITS);
  162609. }
  162610. }
  162611. }
  162612. /*
  162613. * Convert some rows of samples to the JPEG colorspace.
  162614. * This version handles Adobe-style CMYK->YCCK conversion,
  162615. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162616. * conversion as above, while passing K (black) unchanged.
  162617. * We assume rgb_ycc_start has been called.
  162618. */
  162619. METHODDEF(void)
  162620. cmyk_ycck_convert (j_compress_ptr cinfo,
  162621. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162622. JDIMENSION output_row, int num_rows)
  162623. {
  162624. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162625. register int r, g, b;
  162626. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162627. register JSAMPROW inptr;
  162628. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162629. register JDIMENSION col;
  162630. JDIMENSION num_cols = cinfo->image_width;
  162631. while (--num_rows >= 0) {
  162632. inptr = *input_buf++;
  162633. outptr0 = output_buf[0][output_row];
  162634. outptr1 = output_buf[1][output_row];
  162635. outptr2 = output_buf[2][output_row];
  162636. outptr3 = output_buf[3][output_row];
  162637. output_row++;
  162638. for (col = 0; col < num_cols; col++) {
  162639. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162640. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162641. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162642. /* K passes through as-is */
  162643. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162644. inptr += 4;
  162645. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162646. * must be too; we do not need an explicit range-limiting operation.
  162647. * Hence the value being shifted is never negative, and we don't
  162648. * need the general RIGHT_SHIFT macro.
  162649. */
  162650. /* Y */
  162651. outptr0[col] = (JSAMPLE)
  162652. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162653. >> SCALEBITS);
  162654. /* Cb */
  162655. outptr1[col] = (JSAMPLE)
  162656. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162657. >> SCALEBITS);
  162658. /* Cr */
  162659. outptr2[col] = (JSAMPLE)
  162660. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162661. >> SCALEBITS);
  162662. }
  162663. }
  162664. }
  162665. /*
  162666. * Convert some rows of samples to the JPEG colorspace.
  162667. * This version handles grayscale output with no conversion.
  162668. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162669. */
  162670. METHODDEF(void)
  162671. grayscale_convert (j_compress_ptr cinfo,
  162672. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162673. JDIMENSION output_row, int num_rows)
  162674. {
  162675. register JSAMPROW inptr;
  162676. register JSAMPROW outptr;
  162677. register JDIMENSION col;
  162678. JDIMENSION num_cols = cinfo->image_width;
  162679. int instride = cinfo->input_components;
  162680. while (--num_rows >= 0) {
  162681. inptr = *input_buf++;
  162682. outptr = output_buf[0][output_row];
  162683. output_row++;
  162684. for (col = 0; col < num_cols; col++) {
  162685. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162686. inptr += instride;
  162687. }
  162688. }
  162689. }
  162690. /*
  162691. * Convert some rows of samples to the JPEG colorspace.
  162692. * This version handles multi-component colorspaces without conversion.
  162693. * We assume input_components == num_components.
  162694. */
  162695. METHODDEF(void)
  162696. null_convert (j_compress_ptr cinfo,
  162697. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162698. JDIMENSION output_row, int num_rows)
  162699. {
  162700. register JSAMPROW inptr;
  162701. register JSAMPROW outptr;
  162702. register JDIMENSION col;
  162703. register int ci;
  162704. int nc = cinfo->num_components;
  162705. JDIMENSION num_cols = cinfo->image_width;
  162706. while (--num_rows >= 0) {
  162707. /* It seems fastest to make a separate pass for each component. */
  162708. for (ci = 0; ci < nc; ci++) {
  162709. inptr = *input_buf;
  162710. outptr = output_buf[ci][output_row];
  162711. for (col = 0; col < num_cols; col++) {
  162712. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162713. inptr += nc;
  162714. }
  162715. }
  162716. input_buf++;
  162717. output_row++;
  162718. }
  162719. }
  162720. /*
  162721. * Empty method for start_pass.
  162722. */
  162723. METHODDEF(void)
  162724. null_method (j_compress_ptr)
  162725. {
  162726. /* no work needed */
  162727. }
  162728. /*
  162729. * Module initialization routine for input colorspace conversion.
  162730. */
  162731. GLOBAL(void)
  162732. jinit_color_converter (j_compress_ptr cinfo)
  162733. {
  162734. my_cconvert_ptr cconvert;
  162735. cconvert = (my_cconvert_ptr)
  162736. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162737. SIZEOF(my_color_converter));
  162738. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162739. /* set start_pass to null method until we find out differently */
  162740. cconvert->pub.start_pass = null_method;
  162741. /* Make sure input_components agrees with in_color_space */
  162742. switch (cinfo->in_color_space) {
  162743. case JCS_GRAYSCALE:
  162744. if (cinfo->input_components != 1)
  162745. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162746. break;
  162747. case JCS_RGB:
  162748. #if RGB_PIXELSIZE != 3
  162749. if (cinfo->input_components != RGB_PIXELSIZE)
  162750. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162751. break;
  162752. #endif /* else share code with YCbCr */
  162753. case JCS_YCbCr:
  162754. if (cinfo->input_components != 3)
  162755. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162756. break;
  162757. case JCS_CMYK:
  162758. case JCS_YCCK:
  162759. if (cinfo->input_components != 4)
  162760. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162761. break;
  162762. default: /* JCS_UNKNOWN can be anything */
  162763. if (cinfo->input_components < 1)
  162764. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162765. break;
  162766. }
  162767. /* Check num_components, set conversion method based on requested space */
  162768. switch (cinfo->jpeg_color_space) {
  162769. case JCS_GRAYSCALE:
  162770. if (cinfo->num_components != 1)
  162771. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162772. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162773. cconvert->pub.color_convert = grayscale_convert;
  162774. else if (cinfo->in_color_space == JCS_RGB) {
  162775. cconvert->pub.start_pass = rgb_ycc_start;
  162776. cconvert->pub.color_convert = rgb_gray_convert;
  162777. } else if (cinfo->in_color_space == JCS_YCbCr)
  162778. cconvert->pub.color_convert = grayscale_convert;
  162779. else
  162780. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162781. break;
  162782. case JCS_RGB:
  162783. if (cinfo->num_components != 3)
  162784. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162785. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162786. cconvert->pub.color_convert = null_convert;
  162787. else
  162788. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162789. break;
  162790. case JCS_YCbCr:
  162791. if (cinfo->num_components != 3)
  162792. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162793. if (cinfo->in_color_space == JCS_RGB) {
  162794. cconvert->pub.start_pass = rgb_ycc_start;
  162795. cconvert->pub.color_convert = rgb_ycc_convert;
  162796. } else if (cinfo->in_color_space == JCS_YCbCr)
  162797. cconvert->pub.color_convert = null_convert;
  162798. else
  162799. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162800. break;
  162801. case JCS_CMYK:
  162802. if (cinfo->num_components != 4)
  162803. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162804. if (cinfo->in_color_space == JCS_CMYK)
  162805. cconvert->pub.color_convert = null_convert;
  162806. else
  162807. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162808. break;
  162809. case JCS_YCCK:
  162810. if (cinfo->num_components != 4)
  162811. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162812. if (cinfo->in_color_space == JCS_CMYK) {
  162813. cconvert->pub.start_pass = rgb_ycc_start;
  162814. cconvert->pub.color_convert = cmyk_ycck_convert;
  162815. } else if (cinfo->in_color_space == JCS_YCCK)
  162816. cconvert->pub.color_convert = null_convert;
  162817. else
  162818. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162819. break;
  162820. default: /* allow null conversion of JCS_UNKNOWN */
  162821. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162822. cinfo->num_components != cinfo->input_components)
  162823. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162824. cconvert->pub.color_convert = null_convert;
  162825. break;
  162826. }
  162827. }
  162828. /*** End of inlined file: jccolor.c ***/
  162829. #undef FIX
  162830. /*** Start of inlined file: jcdctmgr.c ***/
  162831. #define JPEG_INTERNALS
  162832. /*** Start of inlined file: jdct.h ***/
  162833. /*
  162834. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162835. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162836. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162837. * implementations use an array of type FAST_FLOAT, instead.)
  162838. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162839. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162840. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162841. * convention improves accuracy in integer implementations and saves some
  162842. * work in floating-point ones.
  162843. * Quantization of the output coefficients is done by jcdctmgr.c.
  162844. */
  162845. #ifndef __jdct_h__
  162846. #define __jdct_h__
  162847. #if BITS_IN_JSAMPLE == 8
  162848. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162849. #else
  162850. typedef INT32 DCTELEM; /* must have 32 bits */
  162851. #endif
  162852. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162853. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162854. /*
  162855. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162856. * to an output sample array. The routine must dequantize the input data as
  162857. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162858. * pointed to by compptr->dct_table. The output data is to be placed into the
  162859. * sample array starting at a specified column. (Any row offset needed will
  162860. * be applied to the array pointer before it is passed to the IDCT code.)
  162861. * Note that the number of samples emitted by the IDCT routine is
  162862. * DCT_scaled_size * DCT_scaled_size.
  162863. */
  162864. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162865. /*
  162866. * Each IDCT routine has its own ideas about the best dct_table element type.
  162867. */
  162868. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162869. #if BITS_IN_JSAMPLE == 8
  162870. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162871. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162872. #else
  162873. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162874. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162875. #endif
  162876. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162877. /*
  162878. * Each IDCT routine is responsible for range-limiting its results and
  162879. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162880. * be quite far out of range if the input data is corrupt, so a bulletproof
  162881. * range-limiting step is required. We use a mask-and-table-lookup method
  162882. * to do the combined operations quickly. See the comments with
  162883. * prepare_range_limit_table (in jdmaster.c) for more info.
  162884. */
  162885. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162886. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162887. /* Short forms of external names for systems with brain-damaged linkers. */
  162888. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162889. #define jpeg_fdct_islow jFDislow
  162890. #define jpeg_fdct_ifast jFDifast
  162891. #define jpeg_fdct_float jFDfloat
  162892. #define jpeg_idct_islow jRDislow
  162893. #define jpeg_idct_ifast jRDifast
  162894. #define jpeg_idct_float jRDfloat
  162895. #define jpeg_idct_4x4 jRD4x4
  162896. #define jpeg_idct_2x2 jRD2x2
  162897. #define jpeg_idct_1x1 jRD1x1
  162898. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162899. /* Extern declarations for the forward and inverse DCT routines. */
  162900. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162901. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162902. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162903. EXTERN(void) jpeg_idct_islow
  162904. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162905. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162906. EXTERN(void) jpeg_idct_ifast
  162907. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162908. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162909. EXTERN(void) jpeg_idct_float
  162910. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162911. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162912. EXTERN(void) jpeg_idct_4x4
  162913. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162914. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162915. EXTERN(void) jpeg_idct_2x2
  162916. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162917. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162918. EXTERN(void) jpeg_idct_1x1
  162919. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162920. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162921. /*
  162922. * Macros for handling fixed-point arithmetic; these are used by many
  162923. * but not all of the DCT/IDCT modules.
  162924. *
  162925. * All values are expected to be of type INT32.
  162926. * Fractional constants are scaled left by CONST_BITS bits.
  162927. * CONST_BITS is defined within each module using these macros,
  162928. * and may differ from one module to the next.
  162929. */
  162930. #define ONE ((INT32) 1)
  162931. #define CONST_SCALE (ONE << CONST_BITS)
  162932. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162933. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162934. * thus causing a lot of useless floating-point operations at run time.
  162935. */
  162936. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162937. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162938. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162939. * the fudge factor is correct for either sign of X.
  162940. */
  162941. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162942. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162943. * This macro is used only when the two inputs will actually be no more than
  162944. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162945. * full 32x32 multiply. This provides a useful speedup on many machines.
  162946. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162947. * in C, but some C compilers will do the right thing if you provide the
  162948. * correct combination of casts.
  162949. */
  162950. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162951. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162952. #endif
  162953. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162954. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162955. #endif
  162956. #ifndef MULTIPLY16C16 /* default definition */
  162957. #define MULTIPLY16C16(var,const) ((var) * (const))
  162958. #endif
  162959. /* Same except both inputs are variables. */
  162960. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162961. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162962. #endif
  162963. #ifndef MULTIPLY16V16 /* default definition */
  162964. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162965. #endif
  162966. #endif
  162967. /*** End of inlined file: jdct.h ***/
  162968. /* Private declarations for DCT subsystem */
  162969. /* Private subobject for this module */
  162970. typedef struct {
  162971. struct jpeg_forward_dct pub; /* public fields */
  162972. /* Pointer to the DCT routine actually in use */
  162973. forward_DCT_method_ptr do_dct;
  162974. /* The actual post-DCT divisors --- not identical to the quant table
  162975. * entries, because of scaling (especially for an unnormalized DCT).
  162976. * Each table is given in normal array order.
  162977. */
  162978. DCTELEM * divisors[NUM_QUANT_TBLS];
  162979. #ifdef DCT_FLOAT_SUPPORTED
  162980. /* Same as above for the floating-point case. */
  162981. float_DCT_method_ptr do_float_dct;
  162982. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162983. #endif
  162984. } my_fdct_controller;
  162985. typedef my_fdct_controller * my_fdct_ptr;
  162986. /*
  162987. * Initialize for a processing pass.
  162988. * Verify that all referenced Q-tables are present, and set up
  162989. * the divisor table for each one.
  162990. * In the current implementation, DCT of all components is done during
  162991. * the first pass, even if only some components will be output in the
  162992. * first scan. Hence all components should be examined here.
  162993. */
  162994. METHODDEF(void)
  162995. start_pass_fdctmgr (j_compress_ptr cinfo)
  162996. {
  162997. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162998. int ci, qtblno, i;
  162999. jpeg_component_info *compptr;
  163000. JQUANT_TBL * qtbl;
  163001. DCTELEM * dtbl;
  163002. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163003. ci++, compptr++) {
  163004. qtblno = compptr->quant_tbl_no;
  163005. /* Make sure specified quantization table is present */
  163006. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163007. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163008. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163009. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163010. /* Compute divisors for this quant table */
  163011. /* We may do this more than once for same table, but it's not a big deal */
  163012. switch (cinfo->dct_method) {
  163013. #ifdef DCT_ISLOW_SUPPORTED
  163014. case JDCT_ISLOW:
  163015. /* For LL&M IDCT method, divisors are equal to raw quantization
  163016. * coefficients multiplied by 8 (to counteract scaling).
  163017. */
  163018. if (fdct->divisors[qtblno] == NULL) {
  163019. fdct->divisors[qtblno] = (DCTELEM *)
  163020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163021. DCTSIZE2 * SIZEOF(DCTELEM));
  163022. }
  163023. dtbl = fdct->divisors[qtblno];
  163024. for (i = 0; i < DCTSIZE2; i++) {
  163025. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163026. }
  163027. break;
  163028. #endif
  163029. #ifdef DCT_IFAST_SUPPORTED
  163030. case JDCT_IFAST:
  163031. {
  163032. /* For AA&N IDCT method, divisors are equal to quantization
  163033. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163034. * scalefactor[0] = 1
  163035. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163036. * We apply a further scale factor of 8.
  163037. */
  163038. #define CONST_BITS 14
  163039. static const INT16 aanscales[DCTSIZE2] = {
  163040. /* precomputed values scaled up by 14 bits */
  163041. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163042. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163043. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163044. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163045. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163046. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163047. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163048. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163049. };
  163050. SHIFT_TEMPS
  163051. if (fdct->divisors[qtblno] == NULL) {
  163052. fdct->divisors[qtblno] = (DCTELEM *)
  163053. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163054. DCTSIZE2 * SIZEOF(DCTELEM));
  163055. }
  163056. dtbl = fdct->divisors[qtblno];
  163057. for (i = 0; i < DCTSIZE2; i++) {
  163058. dtbl[i] = (DCTELEM)
  163059. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163060. (INT32) aanscales[i]),
  163061. CONST_BITS-3);
  163062. }
  163063. }
  163064. break;
  163065. #endif
  163066. #ifdef DCT_FLOAT_SUPPORTED
  163067. case JDCT_FLOAT:
  163068. {
  163069. /* For float AA&N IDCT method, divisors are equal to quantization
  163070. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163071. * scalefactor[0] = 1
  163072. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163073. * We apply a further scale factor of 8.
  163074. * What's actually stored is 1/divisor so that the inner loop can
  163075. * use a multiplication rather than a division.
  163076. */
  163077. FAST_FLOAT * fdtbl;
  163078. int row, col;
  163079. static const double aanscalefactor[DCTSIZE] = {
  163080. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163081. 1.0, 0.785694958, 0.541196100, 0.275899379
  163082. };
  163083. if (fdct->float_divisors[qtblno] == NULL) {
  163084. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163085. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163086. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163087. }
  163088. fdtbl = fdct->float_divisors[qtblno];
  163089. i = 0;
  163090. for (row = 0; row < DCTSIZE; row++) {
  163091. for (col = 0; col < DCTSIZE; col++) {
  163092. fdtbl[i] = (FAST_FLOAT)
  163093. (1.0 / (((double) qtbl->quantval[i] *
  163094. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163095. i++;
  163096. }
  163097. }
  163098. }
  163099. break;
  163100. #endif
  163101. default:
  163102. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163103. break;
  163104. }
  163105. }
  163106. }
  163107. /*
  163108. * Perform forward DCT on one or more blocks of a component.
  163109. *
  163110. * The input samples are taken from the sample_data[] array starting at
  163111. * position start_row/start_col, and moving to the right for any additional
  163112. * blocks. The quantized coefficients are returned in coef_blocks[].
  163113. */
  163114. METHODDEF(void)
  163115. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163116. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163117. JDIMENSION start_row, JDIMENSION start_col,
  163118. JDIMENSION num_blocks)
  163119. /* This version is used for integer DCT implementations. */
  163120. {
  163121. /* This routine is heavily used, so it's worth coding it tightly. */
  163122. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163123. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163124. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163125. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163126. JDIMENSION bi;
  163127. sample_data += start_row; /* fold in the vertical offset once */
  163128. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163129. /* Load data into workspace, applying unsigned->signed conversion */
  163130. { register DCTELEM *workspaceptr;
  163131. register JSAMPROW elemptr;
  163132. register int elemr;
  163133. workspaceptr = workspace;
  163134. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163135. elemptr = sample_data[elemr] + start_col;
  163136. #if DCTSIZE == 8 /* unroll the inner loop */
  163137. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163138. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163139. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163140. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163141. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163142. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163143. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163144. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163145. #else
  163146. { register int elemc;
  163147. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163148. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163149. }
  163150. }
  163151. #endif
  163152. }
  163153. }
  163154. /* Perform the DCT */
  163155. (*do_dct) (workspace);
  163156. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163157. { register DCTELEM temp, qval;
  163158. register int i;
  163159. register JCOEFPTR output_ptr = coef_blocks[bi];
  163160. for (i = 0; i < DCTSIZE2; i++) {
  163161. qval = divisors[i];
  163162. temp = workspace[i];
  163163. /* Divide the coefficient value by qval, ensuring proper rounding.
  163164. * Since C does not specify the direction of rounding for negative
  163165. * quotients, we have to force the dividend positive for portability.
  163166. *
  163167. * In most files, at least half of the output values will be zero
  163168. * (at default quantization settings, more like three-quarters...)
  163169. * so we should ensure that this case is fast. On many machines,
  163170. * a comparison is enough cheaper than a divide to make a special test
  163171. * a win. Since both inputs will be nonnegative, we need only test
  163172. * for a < b to discover whether a/b is 0.
  163173. * If your machine's division is fast enough, define FAST_DIVIDE.
  163174. */
  163175. #ifdef FAST_DIVIDE
  163176. #define DIVIDE_BY(a,b) a /= b
  163177. #else
  163178. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163179. #endif
  163180. if (temp < 0) {
  163181. temp = -temp;
  163182. temp += qval>>1; /* for rounding */
  163183. DIVIDE_BY(temp, qval);
  163184. temp = -temp;
  163185. } else {
  163186. temp += qval>>1; /* for rounding */
  163187. DIVIDE_BY(temp, qval);
  163188. }
  163189. output_ptr[i] = (JCOEF) temp;
  163190. }
  163191. }
  163192. }
  163193. }
  163194. #ifdef DCT_FLOAT_SUPPORTED
  163195. METHODDEF(void)
  163196. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163197. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163198. JDIMENSION start_row, JDIMENSION start_col,
  163199. JDIMENSION num_blocks)
  163200. /* This version is used for floating-point DCT implementations. */
  163201. {
  163202. /* This routine is heavily used, so it's worth coding it tightly. */
  163203. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163204. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163205. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163206. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163207. JDIMENSION bi;
  163208. sample_data += start_row; /* fold in the vertical offset once */
  163209. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163210. /* Load data into workspace, applying unsigned->signed conversion */
  163211. { register FAST_FLOAT *workspaceptr;
  163212. register JSAMPROW elemptr;
  163213. register int elemr;
  163214. workspaceptr = workspace;
  163215. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163216. elemptr = sample_data[elemr] + start_col;
  163217. #if DCTSIZE == 8 /* unroll the inner loop */
  163218. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163219. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163220. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163221. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163222. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163223. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163224. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163225. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163226. #else
  163227. { register int elemc;
  163228. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163229. *workspaceptr++ = (FAST_FLOAT)
  163230. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163231. }
  163232. }
  163233. #endif
  163234. }
  163235. }
  163236. /* Perform the DCT */
  163237. (*do_dct) (workspace);
  163238. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163239. { register FAST_FLOAT temp;
  163240. register int i;
  163241. register JCOEFPTR output_ptr = coef_blocks[bi];
  163242. for (i = 0; i < DCTSIZE2; i++) {
  163243. /* Apply the quantization and scaling factor */
  163244. temp = workspace[i] * divisors[i];
  163245. /* Round to nearest integer.
  163246. * Since C does not specify the direction of rounding for negative
  163247. * quotients, we have to force the dividend positive for portability.
  163248. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163249. * code should work for either 16-bit or 32-bit ints.
  163250. */
  163251. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163252. }
  163253. }
  163254. }
  163255. }
  163256. #endif /* DCT_FLOAT_SUPPORTED */
  163257. /*
  163258. * Initialize FDCT manager.
  163259. */
  163260. GLOBAL(void)
  163261. jinit_forward_dct (j_compress_ptr cinfo)
  163262. {
  163263. my_fdct_ptr fdct;
  163264. int i;
  163265. fdct = (my_fdct_ptr)
  163266. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163267. SIZEOF(my_fdct_controller));
  163268. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163269. fdct->pub.start_pass = start_pass_fdctmgr;
  163270. switch (cinfo->dct_method) {
  163271. #ifdef DCT_ISLOW_SUPPORTED
  163272. case JDCT_ISLOW:
  163273. fdct->pub.forward_DCT = forward_DCT;
  163274. fdct->do_dct = jpeg_fdct_islow;
  163275. break;
  163276. #endif
  163277. #ifdef DCT_IFAST_SUPPORTED
  163278. case JDCT_IFAST:
  163279. fdct->pub.forward_DCT = forward_DCT;
  163280. fdct->do_dct = jpeg_fdct_ifast;
  163281. break;
  163282. #endif
  163283. #ifdef DCT_FLOAT_SUPPORTED
  163284. case JDCT_FLOAT:
  163285. fdct->pub.forward_DCT = forward_DCT_float;
  163286. fdct->do_float_dct = jpeg_fdct_float;
  163287. break;
  163288. #endif
  163289. default:
  163290. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163291. break;
  163292. }
  163293. /* Mark divisor tables unallocated */
  163294. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163295. fdct->divisors[i] = NULL;
  163296. #ifdef DCT_FLOAT_SUPPORTED
  163297. fdct->float_divisors[i] = NULL;
  163298. #endif
  163299. }
  163300. }
  163301. /*** End of inlined file: jcdctmgr.c ***/
  163302. #undef CONST_BITS
  163303. /*** Start of inlined file: jchuff.c ***/
  163304. #define JPEG_INTERNALS
  163305. /*** Start of inlined file: jchuff.h ***/
  163306. /* The legal range of a DCT coefficient is
  163307. * -1024 .. +1023 for 8-bit data;
  163308. * -16384 .. +16383 for 12-bit data.
  163309. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163310. */
  163311. #ifndef _jchuff_h_
  163312. #define _jchuff_h_
  163313. #if BITS_IN_JSAMPLE == 8
  163314. #define MAX_COEF_BITS 10
  163315. #else
  163316. #define MAX_COEF_BITS 14
  163317. #endif
  163318. /* Derived data constructed for each Huffman table */
  163319. typedef struct {
  163320. unsigned int ehufco[256]; /* code for each symbol */
  163321. char ehufsi[256]; /* length of code for each symbol */
  163322. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163323. } c_derived_tbl;
  163324. /* Short forms of external names for systems with brain-damaged linkers. */
  163325. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163326. #define jpeg_make_c_derived_tbl jMkCDerived
  163327. #define jpeg_gen_optimal_table jGenOptTbl
  163328. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163329. /* Expand a Huffman table definition into the derived format */
  163330. EXTERN(void) jpeg_make_c_derived_tbl
  163331. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163332. c_derived_tbl ** pdtbl));
  163333. /* Generate an optimal table definition given the specified counts */
  163334. EXTERN(void) jpeg_gen_optimal_table
  163335. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163336. #endif
  163337. /*** End of inlined file: jchuff.h ***/
  163338. /* Declarations shared with jcphuff.c */
  163339. /* Expanded entropy encoder object for Huffman encoding.
  163340. *
  163341. * The savable_state subrecord contains fields that change within an MCU,
  163342. * but must not be updated permanently until we complete the MCU.
  163343. */
  163344. typedef struct {
  163345. INT32 put_buffer; /* current bit-accumulation buffer */
  163346. int put_bits; /* # of bits now in it */
  163347. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163348. } savable_state;
  163349. /* This macro is to work around compilers with missing or broken
  163350. * structure assignment. You'll need to fix this code if you have
  163351. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163352. */
  163353. #ifndef NO_STRUCT_ASSIGN
  163354. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163355. #else
  163356. #if MAX_COMPS_IN_SCAN == 4
  163357. #define ASSIGN_STATE(dest,src) \
  163358. ((dest).put_buffer = (src).put_buffer, \
  163359. (dest).put_bits = (src).put_bits, \
  163360. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163361. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163362. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163363. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163364. #endif
  163365. #endif
  163366. typedef struct {
  163367. struct jpeg_entropy_encoder pub; /* public fields */
  163368. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163369. /* These fields are NOT loaded into local working state. */
  163370. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163371. int next_restart_num; /* next restart number to write (0-7) */
  163372. /* Pointers to derived tables (these workspaces have image lifespan) */
  163373. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163374. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163375. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163376. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163377. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163378. #endif
  163379. } huff_entropy_encoder;
  163380. typedef huff_entropy_encoder * huff_entropy_ptr;
  163381. /* Working state while writing an MCU.
  163382. * This struct contains all the fields that are needed by subroutines.
  163383. */
  163384. typedef struct {
  163385. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163386. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163387. savable_state cur; /* Current bit buffer & DC state */
  163388. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163389. } working_state;
  163390. /* Forward declarations */
  163391. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163392. JBLOCKROW *MCU_data));
  163393. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163394. #ifdef ENTROPY_OPT_SUPPORTED
  163395. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163396. JBLOCKROW *MCU_data));
  163397. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163398. #endif
  163399. /*
  163400. * Initialize for a Huffman-compressed scan.
  163401. * If gather_statistics is TRUE, we do not output anything during the scan,
  163402. * just count the Huffman symbols used and generate Huffman code tables.
  163403. */
  163404. METHODDEF(void)
  163405. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163406. {
  163407. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163408. int ci, dctbl, actbl;
  163409. jpeg_component_info * compptr;
  163410. if (gather_statistics) {
  163411. #ifdef ENTROPY_OPT_SUPPORTED
  163412. entropy->pub.encode_mcu = encode_mcu_gather;
  163413. entropy->pub.finish_pass = finish_pass_gather;
  163414. #else
  163415. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163416. #endif
  163417. } else {
  163418. entropy->pub.encode_mcu = encode_mcu_huff;
  163419. entropy->pub.finish_pass = finish_pass_huff;
  163420. }
  163421. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163422. compptr = cinfo->cur_comp_info[ci];
  163423. dctbl = compptr->dc_tbl_no;
  163424. actbl = compptr->ac_tbl_no;
  163425. if (gather_statistics) {
  163426. #ifdef ENTROPY_OPT_SUPPORTED
  163427. /* Check for invalid table indexes */
  163428. /* (make_c_derived_tbl does this in the other path) */
  163429. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163430. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163431. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163432. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163433. /* Allocate and zero the statistics tables */
  163434. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163435. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163436. entropy->dc_count_ptrs[dctbl] = (long *)
  163437. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163438. 257 * SIZEOF(long));
  163439. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163440. if (entropy->ac_count_ptrs[actbl] == NULL)
  163441. entropy->ac_count_ptrs[actbl] = (long *)
  163442. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163443. 257 * SIZEOF(long));
  163444. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163445. #endif
  163446. } else {
  163447. /* Compute derived values for Huffman tables */
  163448. /* We may do this more than once for a table, but it's not expensive */
  163449. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163450. & entropy->dc_derived_tbls[dctbl]);
  163451. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163452. & entropy->ac_derived_tbls[actbl]);
  163453. }
  163454. /* Initialize DC predictions to 0 */
  163455. entropy->saved.last_dc_val[ci] = 0;
  163456. }
  163457. /* Initialize bit buffer to empty */
  163458. entropy->saved.put_buffer = 0;
  163459. entropy->saved.put_bits = 0;
  163460. /* Initialize restart stuff */
  163461. entropy->restarts_to_go = cinfo->restart_interval;
  163462. entropy->next_restart_num = 0;
  163463. }
  163464. /*
  163465. * Compute the derived values for a Huffman table.
  163466. * This routine also performs some validation checks on the table.
  163467. *
  163468. * Note this is also used by jcphuff.c.
  163469. */
  163470. GLOBAL(void)
  163471. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163472. c_derived_tbl ** pdtbl)
  163473. {
  163474. JHUFF_TBL *htbl;
  163475. c_derived_tbl *dtbl;
  163476. int p, i, l, lastp, si, maxsymbol;
  163477. char huffsize[257];
  163478. unsigned int huffcode[257];
  163479. unsigned int code;
  163480. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163481. * paralleling the order of the symbols themselves in htbl->huffval[].
  163482. */
  163483. /* Find the input Huffman table */
  163484. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163485. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163486. htbl =
  163487. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163488. if (htbl == NULL)
  163489. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163490. /* Allocate a workspace if we haven't already done so. */
  163491. if (*pdtbl == NULL)
  163492. *pdtbl = (c_derived_tbl *)
  163493. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163494. SIZEOF(c_derived_tbl));
  163495. dtbl = *pdtbl;
  163496. /* Figure C.1: make table of Huffman code length for each symbol */
  163497. p = 0;
  163498. for (l = 1; l <= 16; l++) {
  163499. i = (int) htbl->bits[l];
  163500. if (i < 0 || p + i > 256) /* protect against table overrun */
  163501. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163502. while (i--)
  163503. huffsize[p++] = (char) l;
  163504. }
  163505. huffsize[p] = 0;
  163506. lastp = p;
  163507. /* Figure C.2: generate the codes themselves */
  163508. /* We also validate that the counts represent a legal Huffman code tree. */
  163509. code = 0;
  163510. si = huffsize[0];
  163511. p = 0;
  163512. while (huffsize[p]) {
  163513. while (((int) huffsize[p]) == si) {
  163514. huffcode[p++] = code;
  163515. code++;
  163516. }
  163517. /* code is now 1 more than the last code used for codelength si; but
  163518. * it must still fit in si bits, since no code is allowed to be all ones.
  163519. */
  163520. if (((INT32) code) >= (((INT32) 1) << si))
  163521. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163522. code <<= 1;
  163523. si++;
  163524. }
  163525. /* Figure C.3: generate encoding tables */
  163526. /* These are code and size indexed by symbol value */
  163527. /* Set all codeless symbols to have code length 0;
  163528. * this lets us detect duplicate VAL entries here, and later
  163529. * allows emit_bits to detect any attempt to emit such symbols.
  163530. */
  163531. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163532. /* This is also a convenient place to check for out-of-range
  163533. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163534. * but only 0..15 for DC. (We could constrain them further
  163535. * based on data depth and mode, but this seems enough.)
  163536. */
  163537. maxsymbol = isDC ? 15 : 255;
  163538. for (p = 0; p < lastp; p++) {
  163539. i = htbl->huffval[p];
  163540. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163541. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163542. dtbl->ehufco[i] = huffcode[p];
  163543. dtbl->ehufsi[i] = huffsize[p];
  163544. }
  163545. }
  163546. /* Outputting bytes to the file */
  163547. /* Emit a byte, taking 'action' if must suspend. */
  163548. #define emit_byte(state,val,action) \
  163549. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163550. if (--(state)->free_in_buffer == 0) \
  163551. if (! dump_buffer(state)) \
  163552. { action; } }
  163553. LOCAL(boolean)
  163554. dump_buffer (working_state * state)
  163555. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163556. {
  163557. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163558. if (! (*dest->empty_output_buffer) (state->cinfo))
  163559. return FALSE;
  163560. /* After a successful buffer dump, must reset buffer pointers */
  163561. state->next_output_byte = dest->next_output_byte;
  163562. state->free_in_buffer = dest->free_in_buffer;
  163563. return TRUE;
  163564. }
  163565. /* Outputting bits to the file */
  163566. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163567. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163568. * in one call, and we never retain more than 7 bits in put_buffer
  163569. * between calls, so 24 bits are sufficient.
  163570. */
  163571. INLINE
  163572. LOCAL(boolean)
  163573. emit_bits (working_state * state, unsigned int code, int size)
  163574. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163575. {
  163576. /* This routine is heavily used, so it's worth coding tightly. */
  163577. register INT32 put_buffer = (INT32) code;
  163578. register int put_bits = state->cur.put_bits;
  163579. /* if size is 0, caller used an invalid Huffman table entry */
  163580. if (size == 0)
  163581. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163582. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163583. put_bits += size; /* new number of bits in buffer */
  163584. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163585. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163586. while (put_bits >= 8) {
  163587. int c = (int) ((put_buffer >> 16) & 0xFF);
  163588. emit_byte(state, c, return FALSE);
  163589. if (c == 0xFF) { /* need to stuff a zero byte? */
  163590. emit_byte(state, 0, return FALSE);
  163591. }
  163592. put_buffer <<= 8;
  163593. put_bits -= 8;
  163594. }
  163595. state->cur.put_buffer = put_buffer; /* update state variables */
  163596. state->cur.put_bits = put_bits;
  163597. return TRUE;
  163598. }
  163599. LOCAL(boolean)
  163600. flush_bits (working_state * state)
  163601. {
  163602. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163603. return FALSE;
  163604. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163605. state->cur.put_bits = 0;
  163606. return TRUE;
  163607. }
  163608. /* Encode a single block's worth of coefficients */
  163609. LOCAL(boolean)
  163610. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163611. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163612. {
  163613. register int temp, temp2;
  163614. register int nbits;
  163615. register int k, r, i;
  163616. /* Encode the DC coefficient difference per section F.1.2.1 */
  163617. temp = temp2 = block[0] - last_dc_val;
  163618. if (temp < 0) {
  163619. temp = -temp; /* temp is abs value of input */
  163620. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163621. /* This code assumes we are on a two's complement machine */
  163622. temp2--;
  163623. }
  163624. /* Find the number of bits needed for the magnitude of the coefficient */
  163625. nbits = 0;
  163626. while (temp) {
  163627. nbits++;
  163628. temp >>= 1;
  163629. }
  163630. /* Check for out-of-range coefficient values.
  163631. * Since we're encoding a difference, the range limit is twice as much.
  163632. */
  163633. if (nbits > MAX_COEF_BITS+1)
  163634. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163635. /* Emit the Huffman-coded symbol for the number of bits */
  163636. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163637. return FALSE;
  163638. /* Emit that number of bits of the value, if positive, */
  163639. /* or the complement of its magnitude, if negative. */
  163640. if (nbits) /* emit_bits rejects calls with size 0 */
  163641. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163642. return FALSE;
  163643. /* Encode the AC coefficients per section F.1.2.2 */
  163644. r = 0; /* r = run length of zeros */
  163645. for (k = 1; k < DCTSIZE2; k++) {
  163646. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163647. r++;
  163648. } else {
  163649. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163650. while (r > 15) {
  163651. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163652. return FALSE;
  163653. r -= 16;
  163654. }
  163655. temp2 = temp;
  163656. if (temp < 0) {
  163657. temp = -temp; /* temp is abs value of input */
  163658. /* This code assumes we are on a two's complement machine */
  163659. temp2--;
  163660. }
  163661. /* Find the number of bits needed for the magnitude of the coefficient */
  163662. nbits = 1; /* there must be at least one 1 bit */
  163663. while ((temp >>= 1))
  163664. nbits++;
  163665. /* Check for out-of-range coefficient values */
  163666. if (nbits > MAX_COEF_BITS)
  163667. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163668. /* Emit Huffman symbol for run length / number of bits */
  163669. i = (r << 4) + nbits;
  163670. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163671. return FALSE;
  163672. /* Emit that number of bits of the value, if positive, */
  163673. /* or the complement of its magnitude, if negative. */
  163674. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163675. return FALSE;
  163676. r = 0;
  163677. }
  163678. }
  163679. /* If the last coef(s) were zero, emit an end-of-block code */
  163680. if (r > 0)
  163681. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163682. return FALSE;
  163683. return TRUE;
  163684. }
  163685. /*
  163686. * Emit a restart marker & resynchronize predictions.
  163687. */
  163688. LOCAL(boolean)
  163689. emit_restart (working_state * state, int restart_num)
  163690. {
  163691. int ci;
  163692. if (! flush_bits(state))
  163693. return FALSE;
  163694. emit_byte(state, 0xFF, return FALSE);
  163695. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163696. /* Re-initialize DC predictions to 0 */
  163697. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163698. state->cur.last_dc_val[ci] = 0;
  163699. /* The restart counter is not updated until we successfully write the MCU. */
  163700. return TRUE;
  163701. }
  163702. /*
  163703. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163704. */
  163705. METHODDEF(boolean)
  163706. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163707. {
  163708. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163709. working_state state;
  163710. int blkn, ci;
  163711. jpeg_component_info * compptr;
  163712. /* Load up working state */
  163713. state.next_output_byte = cinfo->dest->next_output_byte;
  163714. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163715. ASSIGN_STATE(state.cur, entropy->saved);
  163716. state.cinfo = cinfo;
  163717. /* Emit restart marker if needed */
  163718. if (cinfo->restart_interval) {
  163719. if (entropy->restarts_to_go == 0)
  163720. if (! emit_restart(&state, entropy->next_restart_num))
  163721. return FALSE;
  163722. }
  163723. /* Encode the MCU data blocks */
  163724. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163725. ci = cinfo->MCU_membership[blkn];
  163726. compptr = cinfo->cur_comp_info[ci];
  163727. if (! encode_one_block(&state,
  163728. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163729. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163730. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163731. return FALSE;
  163732. /* Update last_dc_val */
  163733. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163734. }
  163735. /* Completed MCU, so update state */
  163736. cinfo->dest->next_output_byte = state.next_output_byte;
  163737. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163738. ASSIGN_STATE(entropy->saved, state.cur);
  163739. /* Update restart-interval state too */
  163740. if (cinfo->restart_interval) {
  163741. if (entropy->restarts_to_go == 0) {
  163742. entropy->restarts_to_go = cinfo->restart_interval;
  163743. entropy->next_restart_num++;
  163744. entropy->next_restart_num &= 7;
  163745. }
  163746. entropy->restarts_to_go--;
  163747. }
  163748. return TRUE;
  163749. }
  163750. /*
  163751. * Finish up at the end of a Huffman-compressed scan.
  163752. */
  163753. METHODDEF(void)
  163754. finish_pass_huff (j_compress_ptr cinfo)
  163755. {
  163756. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163757. working_state state;
  163758. /* Load up working state ... flush_bits needs it */
  163759. state.next_output_byte = cinfo->dest->next_output_byte;
  163760. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163761. ASSIGN_STATE(state.cur, entropy->saved);
  163762. state.cinfo = cinfo;
  163763. /* Flush out the last data */
  163764. if (! flush_bits(&state))
  163765. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163766. /* Update state */
  163767. cinfo->dest->next_output_byte = state.next_output_byte;
  163768. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163769. ASSIGN_STATE(entropy->saved, state.cur);
  163770. }
  163771. /*
  163772. * Huffman coding optimization.
  163773. *
  163774. * We first scan the supplied data and count the number of uses of each symbol
  163775. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163776. * Then we build a Huffman coding tree for the observed counts.
  163777. * Symbols which are not needed at all for the particular image are not
  163778. * assigned any code, which saves space in the DHT marker as well as in
  163779. * the compressed data.
  163780. */
  163781. #ifdef ENTROPY_OPT_SUPPORTED
  163782. /* Process a single block's worth of coefficients */
  163783. LOCAL(void)
  163784. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163785. long dc_counts[], long ac_counts[])
  163786. {
  163787. register int temp;
  163788. register int nbits;
  163789. register int k, r;
  163790. /* Encode the DC coefficient difference per section F.1.2.1 */
  163791. temp = block[0] - last_dc_val;
  163792. if (temp < 0)
  163793. temp = -temp;
  163794. /* Find the number of bits needed for the magnitude of the coefficient */
  163795. nbits = 0;
  163796. while (temp) {
  163797. nbits++;
  163798. temp >>= 1;
  163799. }
  163800. /* Check for out-of-range coefficient values.
  163801. * Since we're encoding a difference, the range limit is twice as much.
  163802. */
  163803. if (nbits > MAX_COEF_BITS+1)
  163804. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163805. /* Count the Huffman symbol for the number of bits */
  163806. dc_counts[nbits]++;
  163807. /* Encode the AC coefficients per section F.1.2.2 */
  163808. r = 0; /* r = run length of zeros */
  163809. for (k = 1; k < DCTSIZE2; k++) {
  163810. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163811. r++;
  163812. } else {
  163813. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163814. while (r > 15) {
  163815. ac_counts[0xF0]++;
  163816. r -= 16;
  163817. }
  163818. /* Find the number of bits needed for the magnitude of the coefficient */
  163819. if (temp < 0)
  163820. temp = -temp;
  163821. /* Find the number of bits needed for the magnitude of the coefficient */
  163822. nbits = 1; /* there must be at least one 1 bit */
  163823. while ((temp >>= 1))
  163824. nbits++;
  163825. /* Check for out-of-range coefficient values */
  163826. if (nbits > MAX_COEF_BITS)
  163827. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163828. /* Count Huffman symbol for run length / number of bits */
  163829. ac_counts[(r << 4) + nbits]++;
  163830. r = 0;
  163831. }
  163832. }
  163833. /* If the last coef(s) were zero, emit an end-of-block code */
  163834. if (r > 0)
  163835. ac_counts[0]++;
  163836. }
  163837. /*
  163838. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163839. * No data is actually output, so no suspension return is possible.
  163840. */
  163841. METHODDEF(boolean)
  163842. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163843. {
  163844. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163845. int blkn, ci;
  163846. jpeg_component_info * compptr;
  163847. /* Take care of restart intervals if needed */
  163848. if (cinfo->restart_interval) {
  163849. if (entropy->restarts_to_go == 0) {
  163850. /* Re-initialize DC predictions to 0 */
  163851. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163852. entropy->saved.last_dc_val[ci] = 0;
  163853. /* Update restart state */
  163854. entropy->restarts_to_go = cinfo->restart_interval;
  163855. }
  163856. entropy->restarts_to_go--;
  163857. }
  163858. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163859. ci = cinfo->MCU_membership[blkn];
  163860. compptr = cinfo->cur_comp_info[ci];
  163861. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163862. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163863. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163864. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163865. }
  163866. return TRUE;
  163867. }
  163868. /*
  163869. * Generate the best Huffman code table for the given counts, fill htbl.
  163870. * Note this is also used by jcphuff.c.
  163871. *
  163872. * The JPEG standard requires that no symbol be assigned a codeword of all
  163873. * one bits (so that padding bits added at the end of a compressed segment
  163874. * can't look like a valid code). Because of the canonical ordering of
  163875. * codewords, this just means that there must be an unused slot in the
  163876. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163877. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163878. * with count 1. In theory that's not optimal; giving it count zero but
  163879. * including it in the symbol set anyway should give a better Huffman code.
  163880. * But the theoretically better code actually seems to come out worse in
  163881. * practice, because it produces more all-ones bytes (which incur stuffed
  163882. * zero bytes in the final file). In any case the difference is tiny.
  163883. *
  163884. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163885. * If some symbols have a very small but nonzero probability, the Huffman tree
  163886. * must be adjusted to meet the code length restriction. We currently use
  163887. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163888. * optimal; it may not choose the best possible limited-length code. But
  163889. * typically only very-low-frequency symbols will be given less-than-optimal
  163890. * lengths, so the code is almost optimal. Experimental comparisons against
  163891. * an optimal limited-length-code algorithm indicate that the difference is
  163892. * microscopic --- usually less than a hundredth of a percent of total size.
  163893. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163894. */
  163895. GLOBAL(void)
  163896. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163897. {
  163898. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163899. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163900. int codesize[257]; /* codesize[k] = code length of symbol k */
  163901. int others[257]; /* next symbol in current branch of tree */
  163902. int c1, c2;
  163903. int p, i, j;
  163904. long v;
  163905. /* This algorithm is explained in section K.2 of the JPEG standard */
  163906. MEMZERO(bits, SIZEOF(bits));
  163907. MEMZERO(codesize, SIZEOF(codesize));
  163908. for (i = 0; i < 257; i++)
  163909. others[i] = -1; /* init links to empty */
  163910. freq[256] = 1; /* make sure 256 has a nonzero count */
  163911. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163912. * that no real symbol is given code-value of all ones, because 256
  163913. * will be placed last in the largest codeword category.
  163914. */
  163915. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163916. for (;;) {
  163917. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163918. /* In case of ties, take the larger symbol number */
  163919. c1 = -1;
  163920. v = 1000000000L;
  163921. for (i = 0; i <= 256; i++) {
  163922. if (freq[i] && freq[i] <= v) {
  163923. v = freq[i];
  163924. c1 = i;
  163925. }
  163926. }
  163927. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163928. /* In case of ties, take the larger symbol number */
  163929. c2 = -1;
  163930. v = 1000000000L;
  163931. for (i = 0; i <= 256; i++) {
  163932. if (freq[i] && freq[i] <= v && i != c1) {
  163933. v = freq[i];
  163934. c2 = i;
  163935. }
  163936. }
  163937. /* Done if we've merged everything into one frequency */
  163938. if (c2 < 0)
  163939. break;
  163940. /* Else merge the two counts/trees */
  163941. freq[c1] += freq[c2];
  163942. freq[c2] = 0;
  163943. /* Increment the codesize of everything in c1's tree branch */
  163944. codesize[c1]++;
  163945. while (others[c1] >= 0) {
  163946. c1 = others[c1];
  163947. codesize[c1]++;
  163948. }
  163949. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163950. /* Increment the codesize of everything in c2's tree branch */
  163951. codesize[c2]++;
  163952. while (others[c2] >= 0) {
  163953. c2 = others[c2];
  163954. codesize[c2]++;
  163955. }
  163956. }
  163957. /* Now count the number of symbols of each code length */
  163958. for (i = 0; i <= 256; i++) {
  163959. if (codesize[i]) {
  163960. /* The JPEG standard seems to think that this can't happen, */
  163961. /* but I'm paranoid... */
  163962. if (codesize[i] > MAX_CLEN)
  163963. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163964. bits[codesize[i]]++;
  163965. }
  163966. }
  163967. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163968. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163969. * Here is what the JPEG spec says about how this next bit works:
  163970. * Since symbols are paired for the longest Huffman code, the symbols are
  163971. * removed from this length category two at a time. The prefix for the pair
  163972. * (which is one bit shorter) is allocated to one of the pair; then,
  163973. * skipping the BITS entry for that prefix length, a code word from the next
  163974. * shortest nonzero BITS entry is converted into a prefix for two code words
  163975. * one bit longer.
  163976. */
  163977. for (i = MAX_CLEN; i > 16; i--) {
  163978. while (bits[i] > 0) {
  163979. j = i - 2; /* find length of new prefix to be used */
  163980. while (bits[j] == 0)
  163981. j--;
  163982. bits[i] -= 2; /* remove two symbols */
  163983. bits[i-1]++; /* one goes in this length */
  163984. bits[j+1] += 2; /* two new symbols in this length */
  163985. bits[j]--; /* symbol of this length is now a prefix */
  163986. }
  163987. }
  163988. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163989. while (bits[i] == 0) /* find largest codelength still in use */
  163990. i--;
  163991. bits[i]--;
  163992. /* Return final symbol counts (only for lengths 0..16) */
  163993. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163994. /* Return a list of the symbols sorted by code length */
  163995. /* It's not real clear to me why we don't need to consider the codelength
  163996. * changes made above, but the JPEG spec seems to think this works.
  163997. */
  163998. p = 0;
  163999. for (i = 1; i <= MAX_CLEN; i++) {
  164000. for (j = 0; j <= 255; j++) {
  164001. if (codesize[j] == i) {
  164002. htbl->huffval[p] = (UINT8) j;
  164003. p++;
  164004. }
  164005. }
  164006. }
  164007. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164008. htbl->sent_table = FALSE;
  164009. }
  164010. /*
  164011. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164012. */
  164013. METHODDEF(void)
  164014. finish_pass_gather (j_compress_ptr cinfo)
  164015. {
  164016. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164017. int ci, dctbl, actbl;
  164018. jpeg_component_info * compptr;
  164019. JHUFF_TBL **htblptr;
  164020. boolean did_dc[NUM_HUFF_TBLS];
  164021. boolean did_ac[NUM_HUFF_TBLS];
  164022. /* It's important not to apply jpeg_gen_optimal_table more than once
  164023. * per table, because it clobbers the input frequency counts!
  164024. */
  164025. MEMZERO(did_dc, SIZEOF(did_dc));
  164026. MEMZERO(did_ac, SIZEOF(did_ac));
  164027. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164028. compptr = cinfo->cur_comp_info[ci];
  164029. dctbl = compptr->dc_tbl_no;
  164030. actbl = compptr->ac_tbl_no;
  164031. if (! did_dc[dctbl]) {
  164032. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164033. if (*htblptr == NULL)
  164034. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164035. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164036. did_dc[dctbl] = TRUE;
  164037. }
  164038. if (! did_ac[actbl]) {
  164039. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164040. if (*htblptr == NULL)
  164041. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164042. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164043. did_ac[actbl] = TRUE;
  164044. }
  164045. }
  164046. }
  164047. #endif /* ENTROPY_OPT_SUPPORTED */
  164048. /*
  164049. * Module initialization routine for Huffman entropy encoding.
  164050. */
  164051. GLOBAL(void)
  164052. jinit_huff_encoder (j_compress_ptr cinfo)
  164053. {
  164054. huff_entropy_ptr entropy;
  164055. int i;
  164056. entropy = (huff_entropy_ptr)
  164057. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164058. SIZEOF(huff_entropy_encoder));
  164059. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164060. entropy->pub.start_pass = start_pass_huff;
  164061. /* Mark tables unallocated */
  164062. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164063. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164064. #ifdef ENTROPY_OPT_SUPPORTED
  164065. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164066. #endif
  164067. }
  164068. }
  164069. /*** End of inlined file: jchuff.c ***/
  164070. #undef emit_byte
  164071. /*** Start of inlined file: jcinit.c ***/
  164072. #define JPEG_INTERNALS
  164073. /*
  164074. * Master selection of compression modules.
  164075. * This is done once at the start of processing an image. We determine
  164076. * which modules will be used and give them appropriate initialization calls.
  164077. */
  164078. GLOBAL(void)
  164079. jinit_compress_master (j_compress_ptr cinfo)
  164080. {
  164081. /* Initialize master control (includes parameter checking/processing) */
  164082. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164083. /* Preprocessing */
  164084. if (! cinfo->raw_data_in) {
  164085. jinit_color_converter(cinfo);
  164086. jinit_downsampler(cinfo);
  164087. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164088. }
  164089. /* Forward DCT */
  164090. jinit_forward_dct(cinfo);
  164091. /* Entropy encoding: either Huffman or arithmetic coding. */
  164092. if (cinfo->arith_code) {
  164093. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164094. } else {
  164095. if (cinfo->progressive_mode) {
  164096. #ifdef C_PROGRESSIVE_SUPPORTED
  164097. jinit_phuff_encoder(cinfo);
  164098. #else
  164099. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164100. #endif
  164101. } else
  164102. jinit_huff_encoder(cinfo);
  164103. }
  164104. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164105. jinit_c_coef_controller(cinfo,
  164106. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164107. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164108. jinit_marker_writer(cinfo);
  164109. /* We can now tell the memory manager to allocate virtual arrays. */
  164110. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164111. /* Write the datastream header (SOI) immediately.
  164112. * Frame and scan headers are postponed till later.
  164113. * This lets application insert special markers after the SOI.
  164114. */
  164115. (*cinfo->marker->write_file_header) (cinfo);
  164116. }
  164117. /*** End of inlined file: jcinit.c ***/
  164118. /*** Start of inlined file: jcmainct.c ***/
  164119. #define JPEG_INTERNALS
  164120. /* Note: currently, there is no operating mode in which a full-image buffer
  164121. * is needed at this step. If there were, that mode could not be used with
  164122. * "raw data" input, since this module is bypassed in that case. However,
  164123. * we've left the code here for possible use in special applications.
  164124. */
  164125. #undef FULL_MAIN_BUFFER_SUPPORTED
  164126. /* Private buffer controller object */
  164127. typedef struct {
  164128. struct jpeg_c_main_controller pub; /* public fields */
  164129. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164130. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164131. boolean suspended; /* remember if we suspended output */
  164132. J_BUF_MODE pass_mode; /* current operating mode */
  164133. /* If using just a strip buffer, this points to the entire set of buffers
  164134. * (we allocate one for each component). In the full-image case, this
  164135. * points to the currently accessible strips of the virtual arrays.
  164136. */
  164137. JSAMPARRAY buffer[MAX_COMPONENTS];
  164138. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164139. /* If using full-image storage, this array holds pointers to virtual-array
  164140. * control blocks for each component. Unused if not full-image storage.
  164141. */
  164142. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164143. #endif
  164144. } my_main_controller;
  164145. typedef my_main_controller * my_main_ptr;
  164146. /* Forward declarations */
  164147. METHODDEF(void) process_data_simple_main
  164148. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164149. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164150. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164151. METHODDEF(void) process_data_buffer_main
  164152. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164153. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164154. #endif
  164155. /*
  164156. * Initialize for a processing pass.
  164157. */
  164158. METHODDEF(void)
  164159. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164160. {
  164161. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164162. /* Do nothing in raw-data mode. */
  164163. if (cinfo->raw_data_in)
  164164. return;
  164165. main_->cur_iMCU_row = 0; /* initialize counters */
  164166. main_->rowgroup_ctr = 0;
  164167. main_->suspended = FALSE;
  164168. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164169. switch (pass_mode) {
  164170. case JBUF_PASS_THRU:
  164171. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164172. if (main_->whole_image[0] != NULL)
  164173. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164174. #endif
  164175. main_->pub.process_data = process_data_simple_main;
  164176. break;
  164177. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164178. case JBUF_SAVE_SOURCE:
  164179. case JBUF_CRANK_DEST:
  164180. case JBUF_SAVE_AND_PASS:
  164181. if (main_->whole_image[0] == NULL)
  164182. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164183. main_->pub.process_data = process_data_buffer_main;
  164184. break;
  164185. #endif
  164186. default:
  164187. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164188. break;
  164189. }
  164190. }
  164191. /*
  164192. * Process some data.
  164193. * This routine handles the simple pass-through mode,
  164194. * where we have only a strip buffer.
  164195. */
  164196. METHODDEF(void)
  164197. process_data_simple_main (j_compress_ptr cinfo,
  164198. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164199. JDIMENSION in_rows_avail)
  164200. {
  164201. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164202. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164203. /* Read input data if we haven't filled the main buffer yet */
  164204. if (main_->rowgroup_ctr < DCTSIZE)
  164205. (*cinfo->prep->pre_process_data) (cinfo,
  164206. input_buf, in_row_ctr, in_rows_avail,
  164207. main_->buffer, &main_->rowgroup_ctr,
  164208. (JDIMENSION) DCTSIZE);
  164209. /* If we don't have a full iMCU row buffered, return to application for
  164210. * more data. Note that preprocessor will always pad to fill the iMCU row
  164211. * at the bottom of the image.
  164212. */
  164213. if (main_->rowgroup_ctr != DCTSIZE)
  164214. return;
  164215. /* Send the completed row to the compressor */
  164216. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164217. /* If compressor did not consume the whole row, then we must need to
  164218. * suspend processing and return to the application. In this situation
  164219. * we pretend we didn't yet consume the last input row; otherwise, if
  164220. * it happened to be the last row of the image, the application would
  164221. * think we were done.
  164222. */
  164223. if (! main_->suspended) {
  164224. (*in_row_ctr)--;
  164225. main_->suspended = TRUE;
  164226. }
  164227. return;
  164228. }
  164229. /* We did finish the row. Undo our little suspension hack if a previous
  164230. * call suspended; then mark the main buffer empty.
  164231. */
  164232. if (main_->suspended) {
  164233. (*in_row_ctr)++;
  164234. main_->suspended = FALSE;
  164235. }
  164236. main_->rowgroup_ctr = 0;
  164237. main_->cur_iMCU_row++;
  164238. }
  164239. }
  164240. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164241. /*
  164242. * Process some data.
  164243. * This routine handles all of the modes that use a full-size buffer.
  164244. */
  164245. METHODDEF(void)
  164246. process_data_buffer_main (j_compress_ptr cinfo,
  164247. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164248. JDIMENSION in_rows_avail)
  164249. {
  164250. my_main_ptr main = (my_main_ptr) cinfo->main;
  164251. int ci;
  164252. jpeg_component_info *compptr;
  164253. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164254. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164255. /* Realign the virtual buffers if at the start of an iMCU row. */
  164256. if (main->rowgroup_ctr == 0) {
  164257. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164258. ci++, compptr++) {
  164259. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164260. ((j_common_ptr) cinfo, main->whole_image[ci],
  164261. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164262. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164263. }
  164264. /* In a read pass, pretend we just read some source data. */
  164265. if (! writing) {
  164266. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164267. main->rowgroup_ctr = DCTSIZE;
  164268. }
  164269. }
  164270. /* If a write pass, read input data until the current iMCU row is full. */
  164271. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164272. if (writing) {
  164273. (*cinfo->prep->pre_process_data) (cinfo,
  164274. input_buf, in_row_ctr, in_rows_avail,
  164275. main->buffer, &main->rowgroup_ctr,
  164276. (JDIMENSION) DCTSIZE);
  164277. /* Return to application if we need more data to fill the iMCU row. */
  164278. if (main->rowgroup_ctr < DCTSIZE)
  164279. return;
  164280. }
  164281. /* Emit data, unless this is a sink-only pass. */
  164282. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164283. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164284. /* If compressor did not consume the whole row, then we must need to
  164285. * suspend processing and return to the application. In this situation
  164286. * we pretend we didn't yet consume the last input row; otherwise, if
  164287. * it happened to be the last row of the image, the application would
  164288. * think we were done.
  164289. */
  164290. if (! main->suspended) {
  164291. (*in_row_ctr)--;
  164292. main->suspended = TRUE;
  164293. }
  164294. return;
  164295. }
  164296. /* We did finish the row. Undo our little suspension hack if a previous
  164297. * call suspended; then mark the main buffer empty.
  164298. */
  164299. if (main->suspended) {
  164300. (*in_row_ctr)++;
  164301. main->suspended = FALSE;
  164302. }
  164303. }
  164304. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164305. main->rowgroup_ctr = 0;
  164306. main->cur_iMCU_row++;
  164307. }
  164308. }
  164309. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164310. /*
  164311. * Initialize main buffer controller.
  164312. */
  164313. GLOBAL(void)
  164314. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164315. {
  164316. my_main_ptr main_;
  164317. int ci;
  164318. jpeg_component_info *compptr;
  164319. main_ = (my_main_ptr)
  164320. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164321. SIZEOF(my_main_controller));
  164322. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164323. main_->pub.start_pass = start_pass_main;
  164324. /* We don't need to create a buffer in raw-data mode. */
  164325. if (cinfo->raw_data_in)
  164326. return;
  164327. /* Create the buffer. It holds downsampled data, so each component
  164328. * may be of a different size.
  164329. */
  164330. if (need_full_buffer) {
  164331. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164332. /* Allocate a full-image virtual array for each component */
  164333. /* Note we pad the bottom to a multiple of the iMCU height */
  164334. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164335. ci++, compptr++) {
  164336. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164337. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164338. compptr->width_in_blocks * DCTSIZE,
  164339. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164340. (long) compptr->v_samp_factor) * DCTSIZE,
  164341. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164342. }
  164343. #else
  164344. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164345. #endif
  164346. } else {
  164347. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164348. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164349. #endif
  164350. /* Allocate a strip buffer for each component */
  164351. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164352. ci++, compptr++) {
  164353. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164354. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164355. compptr->width_in_blocks * DCTSIZE,
  164356. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164357. }
  164358. }
  164359. }
  164360. /*** End of inlined file: jcmainct.c ***/
  164361. /*** Start of inlined file: jcmarker.c ***/
  164362. #define JPEG_INTERNALS
  164363. /* Private state */
  164364. typedef struct {
  164365. struct jpeg_marker_writer pub; /* public fields */
  164366. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164367. } my_marker_writer;
  164368. typedef my_marker_writer * my_marker_ptr;
  164369. /*
  164370. * Basic output routines.
  164371. *
  164372. * Note that we do not support suspension while writing a marker.
  164373. * Therefore, an application using suspension must ensure that there is
  164374. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164375. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164376. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164377. * modes are not supported at all with suspension, so those two are the only
  164378. * points where markers will be written.
  164379. */
  164380. LOCAL(void)
  164381. emit_byte (j_compress_ptr cinfo, int val)
  164382. /* Emit a byte */
  164383. {
  164384. struct jpeg_destination_mgr * dest = cinfo->dest;
  164385. *(dest->next_output_byte)++ = (JOCTET) val;
  164386. if (--dest->free_in_buffer == 0) {
  164387. if (! (*dest->empty_output_buffer) (cinfo))
  164388. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164389. }
  164390. }
  164391. LOCAL(void)
  164392. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164393. /* Emit a marker code */
  164394. {
  164395. emit_byte(cinfo, 0xFF);
  164396. emit_byte(cinfo, (int) mark);
  164397. }
  164398. LOCAL(void)
  164399. emit_2bytes (j_compress_ptr cinfo, int value)
  164400. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164401. {
  164402. emit_byte(cinfo, (value >> 8) & 0xFF);
  164403. emit_byte(cinfo, value & 0xFF);
  164404. }
  164405. /*
  164406. * Routines to write specific marker types.
  164407. */
  164408. LOCAL(int)
  164409. emit_dqt (j_compress_ptr cinfo, int index)
  164410. /* Emit a DQT marker */
  164411. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164412. {
  164413. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164414. int prec;
  164415. int i;
  164416. if (qtbl == NULL)
  164417. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164418. prec = 0;
  164419. for (i = 0; i < DCTSIZE2; i++) {
  164420. if (qtbl->quantval[i] > 255)
  164421. prec = 1;
  164422. }
  164423. if (! qtbl->sent_table) {
  164424. emit_marker(cinfo, M_DQT);
  164425. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164426. emit_byte(cinfo, index + (prec<<4));
  164427. for (i = 0; i < DCTSIZE2; i++) {
  164428. /* The table entries must be emitted in zigzag order. */
  164429. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164430. if (prec)
  164431. emit_byte(cinfo, (int) (qval >> 8));
  164432. emit_byte(cinfo, (int) (qval & 0xFF));
  164433. }
  164434. qtbl->sent_table = TRUE;
  164435. }
  164436. return prec;
  164437. }
  164438. LOCAL(void)
  164439. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164440. /* Emit a DHT marker */
  164441. {
  164442. JHUFF_TBL * htbl;
  164443. int length, i;
  164444. if (is_ac) {
  164445. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164446. index += 0x10; /* output index has AC bit set */
  164447. } else {
  164448. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164449. }
  164450. if (htbl == NULL)
  164451. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164452. if (! htbl->sent_table) {
  164453. emit_marker(cinfo, M_DHT);
  164454. length = 0;
  164455. for (i = 1; i <= 16; i++)
  164456. length += htbl->bits[i];
  164457. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164458. emit_byte(cinfo, index);
  164459. for (i = 1; i <= 16; i++)
  164460. emit_byte(cinfo, htbl->bits[i]);
  164461. for (i = 0; i < length; i++)
  164462. emit_byte(cinfo, htbl->huffval[i]);
  164463. htbl->sent_table = TRUE;
  164464. }
  164465. }
  164466. LOCAL(void)
  164467. emit_dac (j_compress_ptr)
  164468. /* Emit a DAC marker */
  164469. /* Since the useful info is so small, we want to emit all the tables in */
  164470. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164471. {
  164472. #ifdef C_ARITH_CODING_SUPPORTED
  164473. char dc_in_use[NUM_ARITH_TBLS];
  164474. char ac_in_use[NUM_ARITH_TBLS];
  164475. int length, i;
  164476. jpeg_component_info *compptr;
  164477. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164478. dc_in_use[i] = ac_in_use[i] = 0;
  164479. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164480. compptr = cinfo->cur_comp_info[i];
  164481. dc_in_use[compptr->dc_tbl_no] = 1;
  164482. ac_in_use[compptr->ac_tbl_no] = 1;
  164483. }
  164484. length = 0;
  164485. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164486. length += dc_in_use[i] + ac_in_use[i];
  164487. emit_marker(cinfo, M_DAC);
  164488. emit_2bytes(cinfo, length*2 + 2);
  164489. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164490. if (dc_in_use[i]) {
  164491. emit_byte(cinfo, i);
  164492. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164493. }
  164494. if (ac_in_use[i]) {
  164495. emit_byte(cinfo, i + 0x10);
  164496. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164497. }
  164498. }
  164499. #endif /* C_ARITH_CODING_SUPPORTED */
  164500. }
  164501. LOCAL(void)
  164502. emit_dri (j_compress_ptr cinfo)
  164503. /* Emit a DRI marker */
  164504. {
  164505. emit_marker(cinfo, M_DRI);
  164506. emit_2bytes(cinfo, 4); /* fixed length */
  164507. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164508. }
  164509. LOCAL(void)
  164510. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164511. /* Emit a SOF marker */
  164512. {
  164513. int ci;
  164514. jpeg_component_info *compptr;
  164515. emit_marker(cinfo, code);
  164516. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164517. /* Make sure image isn't bigger than SOF field can handle */
  164518. if ((long) cinfo->image_height > 65535L ||
  164519. (long) cinfo->image_width > 65535L)
  164520. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164521. emit_byte(cinfo, cinfo->data_precision);
  164522. emit_2bytes(cinfo, (int) cinfo->image_height);
  164523. emit_2bytes(cinfo, (int) cinfo->image_width);
  164524. emit_byte(cinfo, cinfo->num_components);
  164525. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164526. ci++, compptr++) {
  164527. emit_byte(cinfo, compptr->component_id);
  164528. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164529. emit_byte(cinfo, compptr->quant_tbl_no);
  164530. }
  164531. }
  164532. LOCAL(void)
  164533. emit_sos (j_compress_ptr cinfo)
  164534. /* Emit a SOS marker */
  164535. {
  164536. int i, td, ta;
  164537. jpeg_component_info *compptr;
  164538. emit_marker(cinfo, M_SOS);
  164539. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164540. emit_byte(cinfo, cinfo->comps_in_scan);
  164541. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164542. compptr = cinfo->cur_comp_info[i];
  164543. emit_byte(cinfo, compptr->component_id);
  164544. td = compptr->dc_tbl_no;
  164545. ta = compptr->ac_tbl_no;
  164546. if (cinfo->progressive_mode) {
  164547. /* Progressive mode: only DC or only AC tables are used in one scan;
  164548. * furthermore, Huffman coding of DC refinement uses no table at all.
  164549. * We emit 0 for unused field(s); this is recommended by the P&M text
  164550. * but does not seem to be specified in the standard.
  164551. */
  164552. if (cinfo->Ss == 0) {
  164553. ta = 0; /* DC scan */
  164554. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164555. td = 0; /* no DC table either */
  164556. } else {
  164557. td = 0; /* AC scan */
  164558. }
  164559. }
  164560. emit_byte(cinfo, (td << 4) + ta);
  164561. }
  164562. emit_byte(cinfo, cinfo->Ss);
  164563. emit_byte(cinfo, cinfo->Se);
  164564. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164565. }
  164566. LOCAL(void)
  164567. emit_jfif_app0 (j_compress_ptr cinfo)
  164568. /* Emit a JFIF-compliant APP0 marker */
  164569. {
  164570. /*
  164571. * Length of APP0 block (2 bytes)
  164572. * Block ID (4 bytes - ASCII "JFIF")
  164573. * Zero byte (1 byte to terminate the ID string)
  164574. * Version Major, Minor (2 bytes - major first)
  164575. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164576. * Xdpu (2 bytes - dots per unit horizontal)
  164577. * Ydpu (2 bytes - dots per unit vertical)
  164578. * Thumbnail X size (1 byte)
  164579. * Thumbnail Y size (1 byte)
  164580. */
  164581. emit_marker(cinfo, M_APP0);
  164582. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164583. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164584. emit_byte(cinfo, 0x46);
  164585. emit_byte(cinfo, 0x49);
  164586. emit_byte(cinfo, 0x46);
  164587. emit_byte(cinfo, 0);
  164588. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164589. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164590. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164591. emit_2bytes(cinfo, (int) cinfo->X_density);
  164592. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164593. emit_byte(cinfo, 0); /* No thumbnail image */
  164594. emit_byte(cinfo, 0);
  164595. }
  164596. LOCAL(void)
  164597. emit_adobe_app14 (j_compress_ptr cinfo)
  164598. /* Emit an Adobe APP14 marker */
  164599. {
  164600. /*
  164601. * Length of APP14 block (2 bytes)
  164602. * Block ID (5 bytes - ASCII "Adobe")
  164603. * Version Number (2 bytes - currently 100)
  164604. * Flags0 (2 bytes - currently 0)
  164605. * Flags1 (2 bytes - currently 0)
  164606. * Color transform (1 byte)
  164607. *
  164608. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164609. * now in circulation seem to use Version = 100, so that's what we write.
  164610. *
  164611. * We write the color transform byte as 1 if the JPEG color space is
  164612. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164613. * whether the encoder performed a transformation, which is pretty useless.
  164614. */
  164615. emit_marker(cinfo, M_APP14);
  164616. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164617. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164618. emit_byte(cinfo, 0x64);
  164619. emit_byte(cinfo, 0x6F);
  164620. emit_byte(cinfo, 0x62);
  164621. emit_byte(cinfo, 0x65);
  164622. emit_2bytes(cinfo, 100); /* Version */
  164623. emit_2bytes(cinfo, 0); /* Flags0 */
  164624. emit_2bytes(cinfo, 0); /* Flags1 */
  164625. switch (cinfo->jpeg_color_space) {
  164626. case JCS_YCbCr:
  164627. emit_byte(cinfo, 1); /* Color transform = 1 */
  164628. break;
  164629. case JCS_YCCK:
  164630. emit_byte(cinfo, 2); /* Color transform = 2 */
  164631. break;
  164632. default:
  164633. emit_byte(cinfo, 0); /* Color transform = 0 */
  164634. break;
  164635. }
  164636. }
  164637. /*
  164638. * These routines allow writing an arbitrary marker with parameters.
  164639. * The only intended use is to emit COM or APPn markers after calling
  164640. * write_file_header and before calling write_frame_header.
  164641. * Other uses are not guaranteed to produce desirable results.
  164642. * Counting the parameter bytes properly is the caller's responsibility.
  164643. */
  164644. METHODDEF(void)
  164645. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164646. /* Emit an arbitrary marker header */
  164647. {
  164648. if (datalen > (unsigned int) 65533) /* safety check */
  164649. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164650. emit_marker(cinfo, (JPEG_MARKER) marker);
  164651. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164652. }
  164653. METHODDEF(void)
  164654. write_marker_byte (j_compress_ptr cinfo, int val)
  164655. /* Emit one byte of marker parameters following write_marker_header */
  164656. {
  164657. emit_byte(cinfo, val);
  164658. }
  164659. /*
  164660. * Write datastream header.
  164661. * This consists of an SOI and optional APPn markers.
  164662. * We recommend use of the JFIF marker, but not the Adobe marker,
  164663. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164664. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164665. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164666. * Note that an application can write additional header markers after
  164667. * jpeg_start_compress returns.
  164668. */
  164669. METHODDEF(void)
  164670. write_file_header (j_compress_ptr cinfo)
  164671. {
  164672. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164673. emit_marker(cinfo, M_SOI); /* first the SOI */
  164674. /* SOI is defined to reset restart interval to 0 */
  164675. marker->last_restart_interval = 0;
  164676. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164677. emit_jfif_app0(cinfo);
  164678. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164679. emit_adobe_app14(cinfo);
  164680. }
  164681. /*
  164682. * Write frame header.
  164683. * This consists of DQT and SOFn markers.
  164684. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164685. * This avoids compatibility problems with incorrect implementations that
  164686. * try to error-check the quant table numbers as soon as they see the SOF.
  164687. */
  164688. METHODDEF(void)
  164689. write_frame_header (j_compress_ptr cinfo)
  164690. {
  164691. int ci, prec;
  164692. boolean is_baseline;
  164693. jpeg_component_info *compptr;
  164694. /* Emit DQT for each quantization table.
  164695. * Note that emit_dqt() suppresses any duplicate tables.
  164696. */
  164697. prec = 0;
  164698. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164699. ci++, compptr++) {
  164700. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164701. }
  164702. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164703. /* Check for a non-baseline specification.
  164704. * Note we assume that Huffman table numbers won't be changed later.
  164705. */
  164706. if (cinfo->arith_code || cinfo->progressive_mode ||
  164707. cinfo->data_precision != 8) {
  164708. is_baseline = FALSE;
  164709. } else {
  164710. is_baseline = TRUE;
  164711. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164712. ci++, compptr++) {
  164713. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164714. is_baseline = FALSE;
  164715. }
  164716. if (prec && is_baseline) {
  164717. is_baseline = FALSE;
  164718. /* If it's baseline except for quantizer size, warn the user */
  164719. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164720. }
  164721. }
  164722. /* Emit the proper SOF marker */
  164723. if (cinfo->arith_code) {
  164724. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164725. } else {
  164726. if (cinfo->progressive_mode)
  164727. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164728. else if (is_baseline)
  164729. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164730. else
  164731. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164732. }
  164733. }
  164734. /*
  164735. * Write scan header.
  164736. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164737. * Compressed data will be written following the SOS.
  164738. */
  164739. METHODDEF(void)
  164740. write_scan_header (j_compress_ptr cinfo)
  164741. {
  164742. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164743. int i;
  164744. jpeg_component_info *compptr;
  164745. if (cinfo->arith_code) {
  164746. /* Emit arith conditioning info. We may have some duplication
  164747. * if the file has multiple scans, but it's so small it's hardly
  164748. * worth worrying about.
  164749. */
  164750. emit_dac(cinfo);
  164751. } else {
  164752. /* Emit Huffman tables.
  164753. * Note that emit_dht() suppresses any duplicate tables.
  164754. */
  164755. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164756. compptr = cinfo->cur_comp_info[i];
  164757. if (cinfo->progressive_mode) {
  164758. /* Progressive mode: only DC or only AC tables are used in one scan */
  164759. if (cinfo->Ss == 0) {
  164760. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164761. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164762. } else {
  164763. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164764. }
  164765. } else {
  164766. /* Sequential mode: need both DC and AC tables */
  164767. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164768. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164769. }
  164770. }
  164771. }
  164772. /* Emit DRI if required --- note that DRI value could change for each scan.
  164773. * We avoid wasting space with unnecessary DRIs, however.
  164774. */
  164775. if (cinfo->restart_interval != marker->last_restart_interval) {
  164776. emit_dri(cinfo);
  164777. marker->last_restart_interval = cinfo->restart_interval;
  164778. }
  164779. emit_sos(cinfo);
  164780. }
  164781. /*
  164782. * Write datastream trailer.
  164783. */
  164784. METHODDEF(void)
  164785. write_file_trailer (j_compress_ptr cinfo)
  164786. {
  164787. emit_marker(cinfo, M_EOI);
  164788. }
  164789. /*
  164790. * Write an abbreviated table-specification datastream.
  164791. * This consists of SOI, DQT and DHT tables, and EOI.
  164792. * Any table that is defined and not marked sent_table = TRUE will be
  164793. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164794. */
  164795. METHODDEF(void)
  164796. write_tables_only (j_compress_ptr cinfo)
  164797. {
  164798. int i;
  164799. emit_marker(cinfo, M_SOI);
  164800. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164801. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164802. (void) emit_dqt(cinfo, i);
  164803. }
  164804. if (! cinfo->arith_code) {
  164805. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164806. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164807. emit_dht(cinfo, i, FALSE);
  164808. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164809. emit_dht(cinfo, i, TRUE);
  164810. }
  164811. }
  164812. emit_marker(cinfo, M_EOI);
  164813. }
  164814. /*
  164815. * Initialize the marker writer module.
  164816. */
  164817. GLOBAL(void)
  164818. jinit_marker_writer (j_compress_ptr cinfo)
  164819. {
  164820. my_marker_ptr marker;
  164821. /* Create the subobject */
  164822. marker = (my_marker_ptr)
  164823. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164824. SIZEOF(my_marker_writer));
  164825. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164826. /* Initialize method pointers */
  164827. marker->pub.write_file_header = write_file_header;
  164828. marker->pub.write_frame_header = write_frame_header;
  164829. marker->pub.write_scan_header = write_scan_header;
  164830. marker->pub.write_file_trailer = write_file_trailer;
  164831. marker->pub.write_tables_only = write_tables_only;
  164832. marker->pub.write_marker_header = write_marker_header;
  164833. marker->pub.write_marker_byte = write_marker_byte;
  164834. /* Initialize private state */
  164835. marker->last_restart_interval = 0;
  164836. }
  164837. /*** End of inlined file: jcmarker.c ***/
  164838. /*** Start of inlined file: jcmaster.c ***/
  164839. #define JPEG_INTERNALS
  164840. /* Private state */
  164841. typedef enum {
  164842. main_pass, /* input data, also do first output step */
  164843. huff_opt_pass, /* Huffman code optimization pass */
  164844. output_pass /* data output pass */
  164845. } c_pass_type;
  164846. typedef struct {
  164847. struct jpeg_comp_master pub; /* public fields */
  164848. c_pass_type pass_type; /* the type of the current pass */
  164849. int pass_number; /* # of passes completed */
  164850. int total_passes; /* total # of passes needed */
  164851. int scan_number; /* current index in scan_info[] */
  164852. } my_comp_master;
  164853. typedef my_comp_master * my_master_ptr;
  164854. /*
  164855. * Support routines that do various essential calculations.
  164856. */
  164857. LOCAL(void)
  164858. initial_setup (j_compress_ptr cinfo)
  164859. /* Do computations that are needed before master selection phase */
  164860. {
  164861. int ci;
  164862. jpeg_component_info *compptr;
  164863. long samplesperrow;
  164864. JDIMENSION jd_samplesperrow;
  164865. /* Sanity check on image dimensions */
  164866. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164867. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164868. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164869. /* Make sure image isn't bigger than I can handle */
  164870. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164871. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164872. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164873. /* Width of an input scanline must be representable as JDIMENSION. */
  164874. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164875. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164876. if ((long) jd_samplesperrow != samplesperrow)
  164877. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164878. /* For now, precision must match compiled-in value... */
  164879. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164880. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164881. /* Check that number of components won't exceed internal array sizes */
  164882. if (cinfo->num_components > MAX_COMPONENTS)
  164883. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164884. MAX_COMPONENTS);
  164885. /* Compute maximum sampling factors; check factor validity */
  164886. cinfo->max_h_samp_factor = 1;
  164887. cinfo->max_v_samp_factor = 1;
  164888. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164889. ci++, compptr++) {
  164890. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164891. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164892. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164893. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164894. compptr->h_samp_factor);
  164895. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164896. compptr->v_samp_factor);
  164897. }
  164898. /* Compute dimensions of components */
  164899. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164900. ci++, compptr++) {
  164901. /* Fill in the correct component_index value; don't rely on application */
  164902. compptr->component_index = ci;
  164903. /* For compression, we never do DCT scaling. */
  164904. compptr->DCT_scaled_size = DCTSIZE;
  164905. /* Size in DCT blocks */
  164906. compptr->width_in_blocks = (JDIMENSION)
  164907. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164908. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164909. compptr->height_in_blocks = (JDIMENSION)
  164910. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164911. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164912. /* Size in samples */
  164913. compptr->downsampled_width = (JDIMENSION)
  164914. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164915. (long) cinfo->max_h_samp_factor);
  164916. compptr->downsampled_height = (JDIMENSION)
  164917. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164918. (long) cinfo->max_v_samp_factor);
  164919. /* Mark component needed (this flag isn't actually used for compression) */
  164920. compptr->component_needed = TRUE;
  164921. }
  164922. /* Compute number of fully interleaved MCU rows (number of times that
  164923. * main controller will call coefficient controller).
  164924. */
  164925. cinfo->total_iMCU_rows = (JDIMENSION)
  164926. jdiv_round_up((long) cinfo->image_height,
  164927. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164928. }
  164929. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164930. LOCAL(void)
  164931. validate_script (j_compress_ptr cinfo)
  164932. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164933. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164934. */
  164935. {
  164936. const jpeg_scan_info * scanptr;
  164937. int scanno, ncomps, ci, coefi, thisi;
  164938. int Ss, Se, Ah, Al;
  164939. boolean component_sent[MAX_COMPONENTS];
  164940. #ifdef C_PROGRESSIVE_SUPPORTED
  164941. int * last_bitpos_ptr;
  164942. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164943. /* -1 until that coefficient has been seen; then last Al for it */
  164944. #endif
  164945. if (cinfo->num_scans <= 0)
  164946. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164947. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164948. * for progressive JPEG, no scan can have this.
  164949. */
  164950. scanptr = cinfo->scan_info;
  164951. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164952. #ifdef C_PROGRESSIVE_SUPPORTED
  164953. cinfo->progressive_mode = TRUE;
  164954. last_bitpos_ptr = & last_bitpos[0][0];
  164955. for (ci = 0; ci < cinfo->num_components; ci++)
  164956. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164957. *last_bitpos_ptr++ = -1;
  164958. #else
  164959. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164960. #endif
  164961. } else {
  164962. cinfo->progressive_mode = FALSE;
  164963. for (ci = 0; ci < cinfo->num_components; ci++)
  164964. component_sent[ci] = FALSE;
  164965. }
  164966. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164967. /* Validate component indexes */
  164968. ncomps = scanptr->comps_in_scan;
  164969. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164970. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164971. for (ci = 0; ci < ncomps; ci++) {
  164972. thisi = scanptr->component_index[ci];
  164973. if (thisi < 0 || thisi >= cinfo->num_components)
  164974. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164975. /* Components must appear in SOF order within each scan */
  164976. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164977. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164978. }
  164979. /* Validate progression parameters */
  164980. Ss = scanptr->Ss;
  164981. Se = scanptr->Se;
  164982. Ah = scanptr->Ah;
  164983. Al = scanptr->Al;
  164984. if (cinfo->progressive_mode) {
  164985. #ifdef C_PROGRESSIVE_SUPPORTED
  164986. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164987. * seems wrong: the upper bound ought to depend on data precision.
  164988. * Perhaps they really meant 0..N+1 for N-bit precision.
  164989. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164990. * out-of-range reconstructed DC values during the first DC scan,
  164991. * which might cause problems for some decoders.
  164992. */
  164993. #if BITS_IN_JSAMPLE == 8
  164994. #define MAX_AH_AL 10
  164995. #else
  164996. #define MAX_AH_AL 13
  164997. #endif
  164998. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164999. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165000. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165001. if (Ss == 0) {
  165002. if (Se != 0) /* DC and AC together not OK */
  165003. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165004. } else {
  165005. if (ncomps != 1) /* AC scans must be for only one component */
  165006. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165007. }
  165008. for (ci = 0; ci < ncomps; ci++) {
  165009. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165010. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165011. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165012. for (coefi = Ss; coefi <= Se; coefi++) {
  165013. if (last_bitpos_ptr[coefi] < 0) {
  165014. /* first scan of this coefficient */
  165015. if (Ah != 0)
  165016. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165017. } else {
  165018. /* not first scan */
  165019. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165020. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165021. }
  165022. last_bitpos_ptr[coefi] = Al;
  165023. }
  165024. }
  165025. #endif
  165026. } else {
  165027. /* For sequential JPEG, all progression parameters must be these: */
  165028. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165029. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165030. /* Make sure components are not sent twice */
  165031. for (ci = 0; ci < ncomps; ci++) {
  165032. thisi = scanptr->component_index[ci];
  165033. if (component_sent[thisi])
  165034. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165035. component_sent[thisi] = TRUE;
  165036. }
  165037. }
  165038. }
  165039. /* Now verify that everything got sent. */
  165040. if (cinfo->progressive_mode) {
  165041. #ifdef C_PROGRESSIVE_SUPPORTED
  165042. /* For progressive mode, we only check that at least some DC data
  165043. * got sent for each component; the spec does not require that all bits
  165044. * of all coefficients be transmitted. Would it be wiser to enforce
  165045. * transmission of all coefficient bits??
  165046. */
  165047. for (ci = 0; ci < cinfo->num_components; ci++) {
  165048. if (last_bitpos[ci][0] < 0)
  165049. ERREXIT(cinfo, JERR_MISSING_DATA);
  165050. }
  165051. #endif
  165052. } else {
  165053. for (ci = 0; ci < cinfo->num_components; ci++) {
  165054. if (! component_sent[ci])
  165055. ERREXIT(cinfo, JERR_MISSING_DATA);
  165056. }
  165057. }
  165058. }
  165059. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165060. LOCAL(void)
  165061. select_scan_parameters (j_compress_ptr cinfo)
  165062. /* Set up the scan parameters for the current scan */
  165063. {
  165064. int ci;
  165065. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165066. if (cinfo->scan_info != NULL) {
  165067. /* Prepare for current scan --- the script is already validated */
  165068. my_master_ptr master = (my_master_ptr) cinfo->master;
  165069. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165070. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165071. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165072. cinfo->cur_comp_info[ci] =
  165073. &cinfo->comp_info[scanptr->component_index[ci]];
  165074. }
  165075. cinfo->Ss = scanptr->Ss;
  165076. cinfo->Se = scanptr->Se;
  165077. cinfo->Ah = scanptr->Ah;
  165078. cinfo->Al = scanptr->Al;
  165079. }
  165080. else
  165081. #endif
  165082. {
  165083. /* Prepare for single sequential-JPEG scan containing all components */
  165084. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165085. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165086. MAX_COMPS_IN_SCAN);
  165087. cinfo->comps_in_scan = cinfo->num_components;
  165088. for (ci = 0; ci < cinfo->num_components; ci++) {
  165089. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165090. }
  165091. cinfo->Ss = 0;
  165092. cinfo->Se = DCTSIZE2-1;
  165093. cinfo->Ah = 0;
  165094. cinfo->Al = 0;
  165095. }
  165096. }
  165097. LOCAL(void)
  165098. per_scan_setup (j_compress_ptr cinfo)
  165099. /* Do computations that are needed before processing a JPEG scan */
  165100. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165101. {
  165102. int ci, mcublks, tmp;
  165103. jpeg_component_info *compptr;
  165104. if (cinfo->comps_in_scan == 1) {
  165105. /* Noninterleaved (single-component) scan */
  165106. compptr = cinfo->cur_comp_info[0];
  165107. /* Overall image size in MCUs */
  165108. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165109. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165110. /* For noninterleaved scan, always one block per MCU */
  165111. compptr->MCU_width = 1;
  165112. compptr->MCU_height = 1;
  165113. compptr->MCU_blocks = 1;
  165114. compptr->MCU_sample_width = DCTSIZE;
  165115. compptr->last_col_width = 1;
  165116. /* For noninterleaved scans, it is convenient to define last_row_height
  165117. * as the number of block rows present in the last iMCU row.
  165118. */
  165119. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165120. if (tmp == 0) tmp = compptr->v_samp_factor;
  165121. compptr->last_row_height = tmp;
  165122. /* Prepare array describing MCU composition */
  165123. cinfo->blocks_in_MCU = 1;
  165124. cinfo->MCU_membership[0] = 0;
  165125. } else {
  165126. /* Interleaved (multi-component) scan */
  165127. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165128. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165129. MAX_COMPS_IN_SCAN);
  165130. /* Overall image size in MCUs */
  165131. cinfo->MCUs_per_row = (JDIMENSION)
  165132. jdiv_round_up((long) cinfo->image_width,
  165133. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165134. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165135. jdiv_round_up((long) cinfo->image_height,
  165136. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165137. cinfo->blocks_in_MCU = 0;
  165138. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165139. compptr = cinfo->cur_comp_info[ci];
  165140. /* Sampling factors give # of blocks of component in each MCU */
  165141. compptr->MCU_width = compptr->h_samp_factor;
  165142. compptr->MCU_height = compptr->v_samp_factor;
  165143. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165144. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165145. /* Figure number of non-dummy blocks in last MCU column & row */
  165146. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165147. if (tmp == 0) tmp = compptr->MCU_width;
  165148. compptr->last_col_width = tmp;
  165149. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165150. if (tmp == 0) tmp = compptr->MCU_height;
  165151. compptr->last_row_height = tmp;
  165152. /* Prepare array describing MCU composition */
  165153. mcublks = compptr->MCU_blocks;
  165154. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165155. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165156. while (mcublks-- > 0) {
  165157. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165158. }
  165159. }
  165160. }
  165161. /* Convert restart specified in rows to actual MCU count. */
  165162. /* Note that count must fit in 16 bits, so we provide limiting. */
  165163. if (cinfo->restart_in_rows > 0) {
  165164. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165165. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165166. }
  165167. }
  165168. /*
  165169. * Per-pass setup.
  165170. * This is called at the beginning of each pass. We determine which modules
  165171. * will be active during this pass and give them appropriate start_pass calls.
  165172. * We also set is_last_pass to indicate whether any more passes will be
  165173. * required.
  165174. */
  165175. METHODDEF(void)
  165176. prepare_for_pass (j_compress_ptr cinfo)
  165177. {
  165178. my_master_ptr master = (my_master_ptr) cinfo->master;
  165179. switch (master->pass_type) {
  165180. case main_pass:
  165181. /* Initial pass: will collect input data, and do either Huffman
  165182. * optimization or data output for the first scan.
  165183. */
  165184. select_scan_parameters(cinfo);
  165185. per_scan_setup(cinfo);
  165186. if (! cinfo->raw_data_in) {
  165187. (*cinfo->cconvert->start_pass) (cinfo);
  165188. (*cinfo->downsample->start_pass) (cinfo);
  165189. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165190. }
  165191. (*cinfo->fdct->start_pass) (cinfo);
  165192. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165193. (*cinfo->coef->start_pass) (cinfo,
  165194. (master->total_passes > 1 ?
  165195. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165196. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165197. if (cinfo->optimize_coding) {
  165198. /* No immediate data output; postpone writing frame/scan headers */
  165199. master->pub.call_pass_startup = FALSE;
  165200. } else {
  165201. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165202. master->pub.call_pass_startup = TRUE;
  165203. }
  165204. break;
  165205. #ifdef ENTROPY_OPT_SUPPORTED
  165206. case huff_opt_pass:
  165207. /* Do Huffman optimization for a scan after the first one. */
  165208. select_scan_parameters(cinfo);
  165209. per_scan_setup(cinfo);
  165210. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165211. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165212. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165213. master->pub.call_pass_startup = FALSE;
  165214. break;
  165215. }
  165216. /* Special case: Huffman DC refinement scans need no Huffman table
  165217. * and therefore we can skip the optimization pass for them.
  165218. */
  165219. master->pass_type = output_pass;
  165220. master->pass_number++;
  165221. /*FALLTHROUGH*/
  165222. #endif
  165223. case output_pass:
  165224. /* Do a data-output pass. */
  165225. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165226. if (! cinfo->optimize_coding) {
  165227. select_scan_parameters(cinfo);
  165228. per_scan_setup(cinfo);
  165229. }
  165230. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165231. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165232. /* We emit frame/scan headers now */
  165233. if (master->scan_number == 0)
  165234. (*cinfo->marker->write_frame_header) (cinfo);
  165235. (*cinfo->marker->write_scan_header) (cinfo);
  165236. master->pub.call_pass_startup = FALSE;
  165237. break;
  165238. default:
  165239. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165240. }
  165241. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165242. /* Set up progress monitor's pass info if present */
  165243. if (cinfo->progress != NULL) {
  165244. cinfo->progress->completed_passes = master->pass_number;
  165245. cinfo->progress->total_passes = master->total_passes;
  165246. }
  165247. }
  165248. /*
  165249. * Special start-of-pass hook.
  165250. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165251. * In single-pass processing, we need this hook because we don't want to
  165252. * write frame/scan headers during jpeg_start_compress; we want to let the
  165253. * application write COM markers etc. between jpeg_start_compress and the
  165254. * jpeg_write_scanlines loop.
  165255. * In multi-pass processing, this routine is not used.
  165256. */
  165257. METHODDEF(void)
  165258. pass_startup (j_compress_ptr cinfo)
  165259. {
  165260. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165261. (*cinfo->marker->write_frame_header) (cinfo);
  165262. (*cinfo->marker->write_scan_header) (cinfo);
  165263. }
  165264. /*
  165265. * Finish up at end of pass.
  165266. */
  165267. METHODDEF(void)
  165268. finish_pass_master (j_compress_ptr cinfo)
  165269. {
  165270. my_master_ptr master = (my_master_ptr) cinfo->master;
  165271. /* The entropy coder always needs an end-of-pass call,
  165272. * either to analyze statistics or to flush its output buffer.
  165273. */
  165274. (*cinfo->entropy->finish_pass) (cinfo);
  165275. /* Update state for next pass */
  165276. switch (master->pass_type) {
  165277. case main_pass:
  165278. /* next pass is either output of scan 0 (after optimization)
  165279. * or output of scan 1 (if no optimization).
  165280. */
  165281. master->pass_type = output_pass;
  165282. if (! cinfo->optimize_coding)
  165283. master->scan_number++;
  165284. break;
  165285. case huff_opt_pass:
  165286. /* next pass is always output of current scan */
  165287. master->pass_type = output_pass;
  165288. break;
  165289. case output_pass:
  165290. /* next pass is either optimization or output of next scan */
  165291. if (cinfo->optimize_coding)
  165292. master->pass_type = huff_opt_pass;
  165293. master->scan_number++;
  165294. break;
  165295. }
  165296. master->pass_number++;
  165297. }
  165298. /*
  165299. * Initialize master compression control.
  165300. */
  165301. GLOBAL(void)
  165302. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165303. {
  165304. my_master_ptr master;
  165305. master = (my_master_ptr)
  165306. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165307. SIZEOF(my_comp_master));
  165308. cinfo->master = (struct jpeg_comp_master *) master;
  165309. master->pub.prepare_for_pass = prepare_for_pass;
  165310. master->pub.pass_startup = pass_startup;
  165311. master->pub.finish_pass = finish_pass_master;
  165312. master->pub.is_last_pass = FALSE;
  165313. /* Validate parameters, determine derived values */
  165314. initial_setup(cinfo);
  165315. if (cinfo->scan_info != NULL) {
  165316. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165317. validate_script(cinfo);
  165318. #else
  165319. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165320. #endif
  165321. } else {
  165322. cinfo->progressive_mode = FALSE;
  165323. cinfo->num_scans = 1;
  165324. }
  165325. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165326. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165327. /* Initialize my private state */
  165328. if (transcode_only) {
  165329. /* no main pass in transcoding */
  165330. if (cinfo->optimize_coding)
  165331. master->pass_type = huff_opt_pass;
  165332. else
  165333. master->pass_type = output_pass;
  165334. } else {
  165335. /* for normal compression, first pass is always this type: */
  165336. master->pass_type = main_pass;
  165337. }
  165338. master->scan_number = 0;
  165339. master->pass_number = 0;
  165340. if (cinfo->optimize_coding)
  165341. master->total_passes = cinfo->num_scans * 2;
  165342. else
  165343. master->total_passes = cinfo->num_scans;
  165344. }
  165345. /*** End of inlined file: jcmaster.c ***/
  165346. /*** Start of inlined file: jcomapi.c ***/
  165347. #define JPEG_INTERNALS
  165348. /*
  165349. * Abort processing of a JPEG compression or decompression operation,
  165350. * but don't destroy the object itself.
  165351. *
  165352. * For this, we merely clean up all the nonpermanent memory pools.
  165353. * Note that temp files (virtual arrays) are not allowed to belong to
  165354. * the permanent pool, so we will be able to close all temp files here.
  165355. * Closing a data source or destination, if necessary, is the application's
  165356. * responsibility.
  165357. */
  165358. GLOBAL(void)
  165359. jpeg_abort (j_common_ptr cinfo)
  165360. {
  165361. int pool;
  165362. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165363. if (cinfo->mem == NULL)
  165364. return;
  165365. /* Releasing pools in reverse order might help avoid fragmentation
  165366. * with some (brain-damaged) malloc libraries.
  165367. */
  165368. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165369. (*cinfo->mem->free_pool) (cinfo, pool);
  165370. }
  165371. /* Reset overall state for possible reuse of object */
  165372. if (cinfo->is_decompressor) {
  165373. cinfo->global_state = DSTATE_START;
  165374. /* Try to keep application from accessing now-deleted marker list.
  165375. * A bit kludgy to do it here, but this is the most central place.
  165376. */
  165377. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165378. } else {
  165379. cinfo->global_state = CSTATE_START;
  165380. }
  165381. }
  165382. /*
  165383. * Destruction of a JPEG object.
  165384. *
  165385. * Everything gets deallocated except the master jpeg_compress_struct itself
  165386. * and the error manager struct. Both of these are supplied by the application
  165387. * and must be freed, if necessary, by the application. (Often they are on
  165388. * the stack and so don't need to be freed anyway.)
  165389. * Closing a data source or destination, if necessary, is the application's
  165390. * responsibility.
  165391. */
  165392. GLOBAL(void)
  165393. jpeg_destroy (j_common_ptr cinfo)
  165394. {
  165395. /* We need only tell the memory manager to release everything. */
  165396. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165397. if (cinfo->mem != NULL)
  165398. (*cinfo->mem->self_destruct) (cinfo);
  165399. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165400. cinfo->global_state = 0; /* mark it destroyed */
  165401. }
  165402. /*
  165403. * Convenience routines for allocating quantization and Huffman tables.
  165404. * (Would jutils.c be a more reasonable place to put these?)
  165405. */
  165406. GLOBAL(JQUANT_TBL *)
  165407. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165408. {
  165409. JQUANT_TBL *tbl;
  165410. tbl = (JQUANT_TBL *)
  165411. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165412. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165413. return tbl;
  165414. }
  165415. GLOBAL(JHUFF_TBL *)
  165416. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165417. {
  165418. JHUFF_TBL *tbl;
  165419. tbl = (JHUFF_TBL *)
  165420. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165421. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165422. return tbl;
  165423. }
  165424. /*** End of inlined file: jcomapi.c ***/
  165425. /*** Start of inlined file: jcparam.c ***/
  165426. #define JPEG_INTERNALS
  165427. /*
  165428. * Quantization table setup routines
  165429. */
  165430. GLOBAL(void)
  165431. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165432. const unsigned int *basic_table,
  165433. int scale_factor, boolean force_baseline)
  165434. /* Define a quantization table equal to the basic_table times
  165435. * a scale factor (given as a percentage).
  165436. * If force_baseline is TRUE, the computed quantization table entries
  165437. * are limited to 1..255 for JPEG baseline compatibility.
  165438. */
  165439. {
  165440. JQUANT_TBL ** qtblptr;
  165441. int i;
  165442. long temp;
  165443. /* Safety check to ensure start_compress not called yet. */
  165444. if (cinfo->global_state != CSTATE_START)
  165445. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165446. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165447. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165448. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165449. if (*qtblptr == NULL)
  165450. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165451. for (i = 0; i < DCTSIZE2; i++) {
  165452. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165453. /* limit the values to the valid range */
  165454. if (temp <= 0L) temp = 1L;
  165455. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165456. if (force_baseline && temp > 255L)
  165457. temp = 255L; /* limit to baseline range if requested */
  165458. (*qtblptr)->quantval[i] = (UINT16) temp;
  165459. }
  165460. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165461. (*qtblptr)->sent_table = FALSE;
  165462. }
  165463. GLOBAL(void)
  165464. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165465. boolean force_baseline)
  165466. /* Set or change the 'quality' (quantization) setting, using default tables
  165467. * and a straight percentage-scaling quality scale. In most cases it's better
  165468. * to use jpeg_set_quality (below); this entry point is provided for
  165469. * applications that insist on a linear percentage scaling.
  165470. */
  165471. {
  165472. /* These are the sample quantization tables given in JPEG spec section K.1.
  165473. * The spec says that the values given produce "good" quality, and
  165474. * when divided by 2, "very good" quality.
  165475. */
  165476. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165477. 16, 11, 10, 16, 24, 40, 51, 61,
  165478. 12, 12, 14, 19, 26, 58, 60, 55,
  165479. 14, 13, 16, 24, 40, 57, 69, 56,
  165480. 14, 17, 22, 29, 51, 87, 80, 62,
  165481. 18, 22, 37, 56, 68, 109, 103, 77,
  165482. 24, 35, 55, 64, 81, 104, 113, 92,
  165483. 49, 64, 78, 87, 103, 121, 120, 101,
  165484. 72, 92, 95, 98, 112, 100, 103, 99
  165485. };
  165486. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165487. 17, 18, 24, 47, 99, 99, 99, 99,
  165488. 18, 21, 26, 66, 99, 99, 99, 99,
  165489. 24, 26, 56, 99, 99, 99, 99, 99,
  165490. 47, 66, 99, 99, 99, 99, 99, 99,
  165491. 99, 99, 99, 99, 99, 99, 99, 99,
  165492. 99, 99, 99, 99, 99, 99, 99, 99,
  165493. 99, 99, 99, 99, 99, 99, 99, 99,
  165494. 99, 99, 99, 99, 99, 99, 99, 99
  165495. };
  165496. /* Set up two quantization tables using the specified scaling */
  165497. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165498. scale_factor, force_baseline);
  165499. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165500. scale_factor, force_baseline);
  165501. }
  165502. GLOBAL(int)
  165503. jpeg_quality_scaling (int quality)
  165504. /* Convert a user-specified quality rating to a percentage scaling factor
  165505. * for an underlying quantization table, using our recommended scaling curve.
  165506. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165507. */
  165508. {
  165509. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165510. if (quality <= 0) quality = 1;
  165511. if (quality > 100) quality = 100;
  165512. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165513. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165514. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165515. * to make all the table entries 1 (hence, minimum quantization loss).
  165516. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165517. */
  165518. if (quality < 50)
  165519. quality = 5000 / quality;
  165520. else
  165521. quality = 200 - quality*2;
  165522. return quality;
  165523. }
  165524. GLOBAL(void)
  165525. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165526. /* Set or change the 'quality' (quantization) setting, using default tables.
  165527. * This is the standard quality-adjusting entry point for typical user
  165528. * interfaces; only those who want detailed control over quantization tables
  165529. * would use the preceding three routines directly.
  165530. */
  165531. {
  165532. /* Convert user 0-100 rating to percentage scaling */
  165533. quality = jpeg_quality_scaling(quality);
  165534. /* Set up standard quality tables */
  165535. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165536. }
  165537. /*
  165538. * Huffman table setup routines
  165539. */
  165540. LOCAL(void)
  165541. add_huff_table (j_compress_ptr cinfo,
  165542. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165543. /* Define a Huffman table */
  165544. {
  165545. int nsymbols, len;
  165546. if (*htblptr == NULL)
  165547. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165548. /* Copy the number-of-symbols-of-each-code-length counts */
  165549. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165550. /* Validate the counts. We do this here mainly so we can copy the right
  165551. * number of symbols from the val[] array, without risking marching off
  165552. * the end of memory. jchuff.c will do a more thorough test later.
  165553. */
  165554. nsymbols = 0;
  165555. for (len = 1; len <= 16; len++)
  165556. nsymbols += bits[len];
  165557. if (nsymbols < 1 || nsymbols > 256)
  165558. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165559. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165560. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165561. (*htblptr)->sent_table = FALSE;
  165562. }
  165563. LOCAL(void)
  165564. std_huff_tables (j_compress_ptr cinfo)
  165565. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165566. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165567. {
  165568. static const UINT8 bits_dc_luminance[17] =
  165569. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165570. static const UINT8 val_dc_luminance[] =
  165571. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165572. static const UINT8 bits_dc_chrominance[17] =
  165573. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165574. static const UINT8 val_dc_chrominance[] =
  165575. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165576. static const UINT8 bits_ac_luminance[17] =
  165577. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165578. static const UINT8 val_ac_luminance[] =
  165579. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165580. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165581. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165582. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165583. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165584. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165585. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165586. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165587. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165588. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165589. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165590. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165591. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165592. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165593. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165594. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165595. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165596. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165597. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165598. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165599. 0xf9, 0xfa };
  165600. static const UINT8 bits_ac_chrominance[17] =
  165601. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165602. static const UINT8 val_ac_chrominance[] =
  165603. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165604. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165605. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165606. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165607. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165608. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165609. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165610. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165611. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165612. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165613. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165614. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165615. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165616. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165617. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165618. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165619. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165620. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165621. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165622. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165623. 0xf9, 0xfa };
  165624. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165625. bits_dc_luminance, val_dc_luminance);
  165626. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165627. bits_ac_luminance, val_ac_luminance);
  165628. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165629. bits_dc_chrominance, val_dc_chrominance);
  165630. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165631. bits_ac_chrominance, val_ac_chrominance);
  165632. }
  165633. /*
  165634. * Default parameter setup for compression.
  165635. *
  165636. * Applications that don't choose to use this routine must do their
  165637. * own setup of all these parameters. Alternately, you can call this
  165638. * to establish defaults and then alter parameters selectively. This
  165639. * is the recommended approach since, if we add any new parameters,
  165640. * your code will still work (they'll be set to reasonable defaults).
  165641. */
  165642. GLOBAL(void)
  165643. jpeg_set_defaults (j_compress_ptr cinfo)
  165644. {
  165645. int i;
  165646. /* Safety check to ensure start_compress not called yet. */
  165647. if (cinfo->global_state != CSTATE_START)
  165648. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165649. /* Allocate comp_info array large enough for maximum component count.
  165650. * Array is made permanent in case application wants to compress
  165651. * multiple images at same param settings.
  165652. */
  165653. if (cinfo->comp_info == NULL)
  165654. cinfo->comp_info = (jpeg_component_info *)
  165655. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165656. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165657. /* Initialize everything not dependent on the color space */
  165658. cinfo->data_precision = BITS_IN_JSAMPLE;
  165659. /* Set up two quantization tables using default quality of 75 */
  165660. jpeg_set_quality(cinfo, 75, TRUE);
  165661. /* Set up two Huffman tables */
  165662. std_huff_tables(cinfo);
  165663. /* Initialize default arithmetic coding conditioning */
  165664. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165665. cinfo->arith_dc_L[i] = 0;
  165666. cinfo->arith_dc_U[i] = 1;
  165667. cinfo->arith_ac_K[i] = 5;
  165668. }
  165669. /* Default is no multiple-scan output */
  165670. cinfo->scan_info = NULL;
  165671. cinfo->num_scans = 0;
  165672. /* Expect normal source image, not raw downsampled data */
  165673. cinfo->raw_data_in = FALSE;
  165674. /* Use Huffman coding, not arithmetic coding, by default */
  165675. cinfo->arith_code = FALSE;
  165676. /* By default, don't do extra passes to optimize entropy coding */
  165677. cinfo->optimize_coding = FALSE;
  165678. /* The standard Huffman tables are only valid for 8-bit data precision.
  165679. * If the precision is higher, force optimization on so that usable
  165680. * tables will be computed. This test can be removed if default tables
  165681. * are supplied that are valid for the desired precision.
  165682. */
  165683. if (cinfo->data_precision > 8)
  165684. cinfo->optimize_coding = TRUE;
  165685. /* By default, use the simpler non-cosited sampling alignment */
  165686. cinfo->CCIR601_sampling = FALSE;
  165687. /* No input smoothing */
  165688. cinfo->smoothing_factor = 0;
  165689. /* DCT algorithm preference */
  165690. cinfo->dct_method = JDCT_DEFAULT;
  165691. /* No restart markers */
  165692. cinfo->restart_interval = 0;
  165693. cinfo->restart_in_rows = 0;
  165694. /* Fill in default JFIF marker parameters. Note that whether the marker
  165695. * will actually be written is determined by jpeg_set_colorspace.
  165696. *
  165697. * By default, the library emits JFIF version code 1.01.
  165698. * An application that wants to emit JFIF 1.02 extension markers should set
  165699. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165700. * to 1.02, but there may still be some decoders in use that will complain
  165701. * about that; saying 1.01 should minimize compatibility problems.
  165702. */
  165703. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165704. cinfo->JFIF_minor_version = 1;
  165705. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165706. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165707. cinfo->Y_density = 1;
  165708. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165709. jpeg_default_colorspace(cinfo);
  165710. }
  165711. /*
  165712. * Select an appropriate JPEG colorspace for in_color_space.
  165713. */
  165714. GLOBAL(void)
  165715. jpeg_default_colorspace (j_compress_ptr cinfo)
  165716. {
  165717. switch (cinfo->in_color_space) {
  165718. case JCS_GRAYSCALE:
  165719. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165720. break;
  165721. case JCS_RGB:
  165722. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165723. break;
  165724. case JCS_YCbCr:
  165725. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165726. break;
  165727. case JCS_CMYK:
  165728. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165729. break;
  165730. case JCS_YCCK:
  165731. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165732. break;
  165733. case JCS_UNKNOWN:
  165734. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165735. break;
  165736. default:
  165737. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165738. }
  165739. }
  165740. /*
  165741. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165742. */
  165743. GLOBAL(void)
  165744. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165745. {
  165746. jpeg_component_info * compptr;
  165747. int ci;
  165748. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165749. (compptr = &cinfo->comp_info[index], \
  165750. compptr->component_id = (id), \
  165751. compptr->h_samp_factor = (hsamp), \
  165752. compptr->v_samp_factor = (vsamp), \
  165753. compptr->quant_tbl_no = (quant), \
  165754. compptr->dc_tbl_no = (dctbl), \
  165755. compptr->ac_tbl_no = (actbl) )
  165756. /* Safety check to ensure start_compress not called yet. */
  165757. if (cinfo->global_state != CSTATE_START)
  165758. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165759. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165760. * tables 1 for chrominance components.
  165761. */
  165762. cinfo->jpeg_color_space = colorspace;
  165763. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165764. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165765. switch (colorspace) {
  165766. case JCS_GRAYSCALE:
  165767. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165768. cinfo->num_components = 1;
  165769. /* JFIF specifies component ID 1 */
  165770. SET_COMP(0, 1, 1,1, 0, 0,0);
  165771. break;
  165772. case JCS_RGB:
  165773. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165774. cinfo->num_components = 3;
  165775. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165776. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165777. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165778. break;
  165779. case JCS_YCbCr:
  165780. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165781. cinfo->num_components = 3;
  165782. /* JFIF specifies component IDs 1,2,3 */
  165783. /* We default to 2x2 subsamples of chrominance */
  165784. SET_COMP(0, 1, 2,2, 0, 0,0);
  165785. SET_COMP(1, 2, 1,1, 1, 1,1);
  165786. SET_COMP(2, 3, 1,1, 1, 1,1);
  165787. break;
  165788. case JCS_CMYK:
  165789. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165790. cinfo->num_components = 4;
  165791. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165792. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165793. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165794. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165795. break;
  165796. case JCS_YCCK:
  165797. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165798. cinfo->num_components = 4;
  165799. SET_COMP(0, 1, 2,2, 0, 0,0);
  165800. SET_COMP(1, 2, 1,1, 1, 1,1);
  165801. SET_COMP(2, 3, 1,1, 1, 1,1);
  165802. SET_COMP(3, 4, 2,2, 0, 0,0);
  165803. break;
  165804. case JCS_UNKNOWN:
  165805. cinfo->num_components = cinfo->input_components;
  165806. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165807. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165808. MAX_COMPONENTS);
  165809. for (ci = 0; ci < cinfo->num_components; ci++) {
  165810. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165811. }
  165812. break;
  165813. default:
  165814. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165815. }
  165816. }
  165817. #ifdef C_PROGRESSIVE_SUPPORTED
  165818. LOCAL(jpeg_scan_info *)
  165819. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165820. int Ss, int Se, int Ah, int Al)
  165821. /* Support routine: generate one scan for specified component */
  165822. {
  165823. scanptr->comps_in_scan = 1;
  165824. scanptr->component_index[0] = ci;
  165825. scanptr->Ss = Ss;
  165826. scanptr->Se = Se;
  165827. scanptr->Ah = Ah;
  165828. scanptr->Al = Al;
  165829. scanptr++;
  165830. return scanptr;
  165831. }
  165832. LOCAL(jpeg_scan_info *)
  165833. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165834. int Ss, int Se, int Ah, int Al)
  165835. /* Support routine: generate one scan for each component */
  165836. {
  165837. int ci;
  165838. for (ci = 0; ci < ncomps; ci++) {
  165839. scanptr->comps_in_scan = 1;
  165840. scanptr->component_index[0] = ci;
  165841. scanptr->Ss = Ss;
  165842. scanptr->Se = Se;
  165843. scanptr->Ah = Ah;
  165844. scanptr->Al = Al;
  165845. scanptr++;
  165846. }
  165847. return scanptr;
  165848. }
  165849. LOCAL(jpeg_scan_info *)
  165850. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165851. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165852. {
  165853. int ci;
  165854. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165855. /* Single interleaved DC scan */
  165856. scanptr->comps_in_scan = ncomps;
  165857. for (ci = 0; ci < ncomps; ci++)
  165858. scanptr->component_index[ci] = ci;
  165859. scanptr->Ss = scanptr->Se = 0;
  165860. scanptr->Ah = Ah;
  165861. scanptr->Al = Al;
  165862. scanptr++;
  165863. } else {
  165864. /* Noninterleaved DC scan for each component */
  165865. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165866. }
  165867. return scanptr;
  165868. }
  165869. /*
  165870. * Create a recommended progressive-JPEG script.
  165871. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165872. */
  165873. GLOBAL(void)
  165874. jpeg_simple_progression (j_compress_ptr cinfo)
  165875. {
  165876. int ncomps = cinfo->num_components;
  165877. int nscans;
  165878. jpeg_scan_info * scanptr;
  165879. /* Safety check to ensure start_compress not called yet. */
  165880. if (cinfo->global_state != CSTATE_START)
  165881. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165882. /* Figure space needed for script. Calculation must match code below! */
  165883. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165884. /* Custom script for YCbCr color images. */
  165885. nscans = 10;
  165886. } else {
  165887. /* All-purpose script for other color spaces. */
  165888. if (ncomps > MAX_COMPS_IN_SCAN)
  165889. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165890. else
  165891. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165892. }
  165893. /* Allocate space for script.
  165894. * We need to put it in the permanent pool in case the application performs
  165895. * multiple compressions without changing the settings. To avoid a memory
  165896. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165897. * object, we try to re-use previously allocated space, and we allocate
  165898. * enough space to handle YCbCr even if initially asked for grayscale.
  165899. */
  165900. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165901. cinfo->script_space_size = MAX(nscans, 10);
  165902. cinfo->script_space = (jpeg_scan_info *)
  165903. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165904. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165905. }
  165906. scanptr = cinfo->script_space;
  165907. cinfo->scan_info = scanptr;
  165908. cinfo->num_scans = nscans;
  165909. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165910. /* Custom script for YCbCr color images. */
  165911. /* Initial DC scan */
  165912. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165913. /* Initial AC scan: get some luma data out in a hurry */
  165914. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165915. /* Chroma data is too small to be worth expending many scans on */
  165916. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165917. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165918. /* Complete spectral selection for luma AC */
  165919. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165920. /* Refine next bit of luma AC */
  165921. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165922. /* Finish DC successive approximation */
  165923. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165924. /* Finish AC successive approximation */
  165925. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165926. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165927. /* Luma bottom bit comes last since it's usually largest scan */
  165928. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165929. } else {
  165930. /* All-purpose script for other color spaces. */
  165931. /* Successive approximation first pass */
  165932. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165933. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165934. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165935. /* Successive approximation second pass */
  165936. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165937. /* Successive approximation final pass */
  165938. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165939. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165940. }
  165941. }
  165942. #endif /* C_PROGRESSIVE_SUPPORTED */
  165943. /*** End of inlined file: jcparam.c ***/
  165944. /*** Start of inlined file: jcphuff.c ***/
  165945. #define JPEG_INTERNALS
  165946. #ifdef C_PROGRESSIVE_SUPPORTED
  165947. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165948. typedef struct {
  165949. struct jpeg_entropy_encoder pub; /* public fields */
  165950. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165951. boolean gather_statistics;
  165952. /* Bit-level coding status.
  165953. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165954. */
  165955. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165956. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165957. INT32 put_buffer; /* current bit-accumulation buffer */
  165958. int put_bits; /* # of bits now in it */
  165959. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165960. /* Coding status for DC components */
  165961. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165962. /* Coding status for AC components */
  165963. int ac_tbl_no; /* the table number of the single component */
  165964. unsigned int EOBRUN; /* run length of EOBs */
  165965. unsigned int BE; /* # of buffered correction bits before MCU */
  165966. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165967. /* packing correction bits tightly would save some space but cost time... */
  165968. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165969. int next_restart_num; /* next restart number to write (0-7) */
  165970. /* Pointers to derived tables (these workspaces have image lifespan).
  165971. * Since any one scan codes only DC or only AC, we only need one set
  165972. * of tables, not one for DC and one for AC.
  165973. */
  165974. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165975. /* Statistics tables for optimization; again, one set is enough */
  165976. long * count_ptrs[NUM_HUFF_TBLS];
  165977. } phuff_entropy_encoder;
  165978. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165979. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165980. * buffer can hold. Larger sizes may slightly improve compression, but
  165981. * 1000 is already well into the realm of overkill.
  165982. * The minimum safe size is 64 bits.
  165983. */
  165984. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165985. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165986. * We assume that int right shift is unsigned if INT32 right shift is,
  165987. * which should be safe.
  165988. */
  165989. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165990. #define ISHIFT_TEMPS int ishift_temp;
  165991. #define IRIGHT_SHIFT(x,shft) \
  165992. ((ishift_temp = (x)) < 0 ? \
  165993. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165994. (ishift_temp >> (shft)))
  165995. #else
  165996. #define ISHIFT_TEMPS
  165997. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165998. #endif
  165999. /* Forward declarations */
  166000. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166001. JBLOCKROW *MCU_data));
  166002. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166003. JBLOCKROW *MCU_data));
  166004. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166005. JBLOCKROW *MCU_data));
  166006. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166007. JBLOCKROW *MCU_data));
  166008. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166009. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166010. /*
  166011. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166012. */
  166013. METHODDEF(void)
  166014. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166015. {
  166016. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166017. boolean is_DC_band;
  166018. int ci, tbl;
  166019. jpeg_component_info * compptr;
  166020. entropy->cinfo = cinfo;
  166021. entropy->gather_statistics = gather_statistics;
  166022. is_DC_band = (cinfo->Ss == 0);
  166023. /* We assume jcmaster.c already validated the scan parameters. */
  166024. /* Select execution routines */
  166025. if (cinfo->Ah == 0) {
  166026. if (is_DC_band)
  166027. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166028. else
  166029. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166030. } else {
  166031. if (is_DC_band)
  166032. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166033. else {
  166034. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166035. /* AC refinement needs a correction bit buffer */
  166036. if (entropy->bit_buffer == NULL)
  166037. entropy->bit_buffer = (char *)
  166038. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166039. MAX_CORR_BITS * SIZEOF(char));
  166040. }
  166041. }
  166042. if (gather_statistics)
  166043. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166044. else
  166045. entropy->pub.finish_pass = finish_pass_phuff;
  166046. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166047. * for AC coefficients.
  166048. */
  166049. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166050. compptr = cinfo->cur_comp_info[ci];
  166051. /* Initialize DC predictions to 0 */
  166052. entropy->last_dc_val[ci] = 0;
  166053. /* Get table index */
  166054. if (is_DC_band) {
  166055. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166056. continue;
  166057. tbl = compptr->dc_tbl_no;
  166058. } else {
  166059. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166060. }
  166061. if (gather_statistics) {
  166062. /* Check for invalid table index */
  166063. /* (make_c_derived_tbl does this in the other path) */
  166064. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166065. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166066. /* Allocate and zero the statistics tables */
  166067. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166068. if (entropy->count_ptrs[tbl] == NULL)
  166069. entropy->count_ptrs[tbl] = (long *)
  166070. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166071. 257 * SIZEOF(long));
  166072. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166073. } else {
  166074. /* Compute derived values for Huffman table */
  166075. /* We may do this more than once for a table, but it's not expensive */
  166076. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166077. & entropy->derived_tbls[tbl]);
  166078. }
  166079. }
  166080. /* Initialize AC stuff */
  166081. entropy->EOBRUN = 0;
  166082. entropy->BE = 0;
  166083. /* Initialize bit buffer to empty */
  166084. entropy->put_buffer = 0;
  166085. entropy->put_bits = 0;
  166086. /* Initialize restart stuff */
  166087. entropy->restarts_to_go = cinfo->restart_interval;
  166088. entropy->next_restart_num = 0;
  166089. }
  166090. /* Outputting bytes to the file.
  166091. * NB: these must be called only when actually outputting,
  166092. * that is, entropy->gather_statistics == FALSE.
  166093. */
  166094. /* Emit a byte */
  166095. #define emit_byte(entropy,val) \
  166096. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166097. if (--(entropy)->free_in_buffer == 0) \
  166098. dump_buffer_p(entropy); }
  166099. LOCAL(void)
  166100. dump_buffer_p (phuff_entropy_ptr entropy)
  166101. /* Empty the output buffer; we do not support suspension in this module. */
  166102. {
  166103. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166104. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166105. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166106. /* After a successful buffer dump, must reset buffer pointers */
  166107. entropy->next_output_byte = dest->next_output_byte;
  166108. entropy->free_in_buffer = dest->free_in_buffer;
  166109. }
  166110. /* Outputting bits to the file */
  166111. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166112. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166113. * in one call, and we never retain more than 7 bits in put_buffer
  166114. * between calls, so 24 bits are sufficient.
  166115. */
  166116. INLINE
  166117. LOCAL(void)
  166118. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166119. /* Emit some bits, unless we are in gather mode */
  166120. {
  166121. /* This routine is heavily used, so it's worth coding tightly. */
  166122. register INT32 put_buffer = (INT32) code;
  166123. register int put_bits = entropy->put_bits;
  166124. /* if size is 0, caller used an invalid Huffman table entry */
  166125. if (size == 0)
  166126. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166127. if (entropy->gather_statistics)
  166128. return; /* do nothing if we're only getting stats */
  166129. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166130. put_bits += size; /* new number of bits in buffer */
  166131. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166132. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166133. while (put_bits >= 8) {
  166134. int c = (int) ((put_buffer >> 16) & 0xFF);
  166135. emit_byte(entropy, c);
  166136. if (c == 0xFF) { /* need to stuff a zero byte? */
  166137. emit_byte(entropy, 0);
  166138. }
  166139. put_buffer <<= 8;
  166140. put_bits -= 8;
  166141. }
  166142. entropy->put_buffer = put_buffer; /* update variables */
  166143. entropy->put_bits = put_bits;
  166144. }
  166145. LOCAL(void)
  166146. flush_bits_p (phuff_entropy_ptr entropy)
  166147. {
  166148. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166149. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166150. entropy->put_bits = 0;
  166151. }
  166152. /*
  166153. * Emit (or just count) a Huffman symbol.
  166154. */
  166155. INLINE
  166156. LOCAL(void)
  166157. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166158. {
  166159. if (entropy->gather_statistics)
  166160. entropy->count_ptrs[tbl_no][symbol]++;
  166161. else {
  166162. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166163. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166164. }
  166165. }
  166166. /*
  166167. * Emit bits from a correction bit buffer.
  166168. */
  166169. LOCAL(void)
  166170. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166171. unsigned int nbits)
  166172. {
  166173. if (entropy->gather_statistics)
  166174. return; /* no real work */
  166175. while (nbits > 0) {
  166176. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166177. bufstart++;
  166178. nbits--;
  166179. }
  166180. }
  166181. /*
  166182. * Emit any pending EOBRUN symbol.
  166183. */
  166184. LOCAL(void)
  166185. emit_eobrun (phuff_entropy_ptr entropy)
  166186. {
  166187. register int temp, nbits;
  166188. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166189. temp = entropy->EOBRUN;
  166190. nbits = 0;
  166191. while ((temp >>= 1))
  166192. nbits++;
  166193. /* safety check: shouldn't happen given limited correction-bit buffer */
  166194. if (nbits > 14)
  166195. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166196. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166197. if (nbits)
  166198. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166199. entropy->EOBRUN = 0;
  166200. /* Emit any buffered correction bits */
  166201. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166202. entropy->BE = 0;
  166203. }
  166204. }
  166205. /*
  166206. * Emit a restart marker & resynchronize predictions.
  166207. */
  166208. LOCAL(void)
  166209. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166210. {
  166211. int ci;
  166212. emit_eobrun(entropy);
  166213. if (! entropy->gather_statistics) {
  166214. flush_bits_p(entropy);
  166215. emit_byte(entropy, 0xFF);
  166216. emit_byte(entropy, JPEG_RST0 + restart_num);
  166217. }
  166218. if (entropy->cinfo->Ss == 0) {
  166219. /* Re-initialize DC predictions to 0 */
  166220. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166221. entropy->last_dc_val[ci] = 0;
  166222. } else {
  166223. /* Re-initialize all AC-related fields to 0 */
  166224. entropy->EOBRUN = 0;
  166225. entropy->BE = 0;
  166226. }
  166227. }
  166228. /*
  166229. * MCU encoding for DC initial scan (either spectral selection,
  166230. * or first pass of successive approximation).
  166231. */
  166232. METHODDEF(boolean)
  166233. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166234. {
  166235. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166236. register int temp, temp2;
  166237. register int nbits;
  166238. int blkn, ci;
  166239. int Al = cinfo->Al;
  166240. JBLOCKROW block;
  166241. jpeg_component_info * compptr;
  166242. ISHIFT_TEMPS
  166243. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166244. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166245. /* Emit restart marker if needed */
  166246. if (cinfo->restart_interval)
  166247. if (entropy->restarts_to_go == 0)
  166248. emit_restart_p(entropy, entropy->next_restart_num);
  166249. /* Encode the MCU data blocks */
  166250. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166251. block = MCU_data[blkn];
  166252. ci = cinfo->MCU_membership[blkn];
  166253. compptr = cinfo->cur_comp_info[ci];
  166254. /* Compute the DC value after the required point transform by Al.
  166255. * This is simply an arithmetic right shift.
  166256. */
  166257. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166258. /* DC differences are figured on the point-transformed values. */
  166259. temp = temp2 - entropy->last_dc_val[ci];
  166260. entropy->last_dc_val[ci] = temp2;
  166261. /* Encode the DC coefficient difference per section G.1.2.1 */
  166262. temp2 = temp;
  166263. if (temp < 0) {
  166264. temp = -temp; /* temp is abs value of input */
  166265. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166266. /* This code assumes we are on a two's complement machine */
  166267. temp2--;
  166268. }
  166269. /* Find the number of bits needed for the magnitude of the coefficient */
  166270. nbits = 0;
  166271. while (temp) {
  166272. nbits++;
  166273. temp >>= 1;
  166274. }
  166275. /* Check for out-of-range coefficient values.
  166276. * Since we're encoding a difference, the range limit is twice as much.
  166277. */
  166278. if (nbits > MAX_COEF_BITS+1)
  166279. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166280. /* Count/emit the Huffman-coded symbol for the number of bits */
  166281. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166282. /* Emit that number of bits of the value, if positive, */
  166283. /* or the complement of its magnitude, if negative. */
  166284. if (nbits) /* emit_bits rejects calls with size 0 */
  166285. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166286. }
  166287. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166288. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166289. /* Update restart-interval state too */
  166290. if (cinfo->restart_interval) {
  166291. if (entropy->restarts_to_go == 0) {
  166292. entropy->restarts_to_go = cinfo->restart_interval;
  166293. entropy->next_restart_num++;
  166294. entropy->next_restart_num &= 7;
  166295. }
  166296. entropy->restarts_to_go--;
  166297. }
  166298. return TRUE;
  166299. }
  166300. /*
  166301. * MCU encoding for AC initial scan (either spectral selection,
  166302. * or first pass of successive approximation).
  166303. */
  166304. METHODDEF(boolean)
  166305. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166306. {
  166307. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166308. register int temp, temp2;
  166309. register int nbits;
  166310. register int r, k;
  166311. int Se = cinfo->Se;
  166312. int Al = cinfo->Al;
  166313. JBLOCKROW block;
  166314. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166315. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166316. /* Emit restart marker if needed */
  166317. if (cinfo->restart_interval)
  166318. if (entropy->restarts_to_go == 0)
  166319. emit_restart_p(entropy, entropy->next_restart_num);
  166320. /* Encode the MCU data block */
  166321. block = MCU_data[0];
  166322. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166323. r = 0; /* r = run length of zeros */
  166324. for (k = cinfo->Ss; k <= Se; k++) {
  166325. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166326. r++;
  166327. continue;
  166328. }
  166329. /* We must apply the point transform by Al. For AC coefficients this
  166330. * is an integer division with rounding towards 0. To do this portably
  166331. * in C, we shift after obtaining the absolute value; so the code is
  166332. * interwoven with finding the abs value (temp) and output bits (temp2).
  166333. */
  166334. if (temp < 0) {
  166335. temp = -temp; /* temp is abs value of input */
  166336. temp >>= Al; /* apply the point transform */
  166337. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166338. temp2 = ~temp;
  166339. } else {
  166340. temp >>= Al; /* apply the point transform */
  166341. temp2 = temp;
  166342. }
  166343. /* Watch out for case that nonzero coef is zero after point transform */
  166344. if (temp == 0) {
  166345. r++;
  166346. continue;
  166347. }
  166348. /* Emit any pending EOBRUN */
  166349. if (entropy->EOBRUN > 0)
  166350. emit_eobrun(entropy);
  166351. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166352. while (r > 15) {
  166353. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166354. r -= 16;
  166355. }
  166356. /* Find the number of bits needed for the magnitude of the coefficient */
  166357. nbits = 1; /* there must be at least one 1 bit */
  166358. while ((temp >>= 1))
  166359. nbits++;
  166360. /* Check for out-of-range coefficient values */
  166361. if (nbits > MAX_COEF_BITS)
  166362. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166363. /* Count/emit Huffman symbol for run length / number of bits */
  166364. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166365. /* Emit that number of bits of the value, if positive, */
  166366. /* or the complement of its magnitude, if negative. */
  166367. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166368. r = 0; /* reset zero run length */
  166369. }
  166370. if (r > 0) { /* If there are trailing zeroes, */
  166371. entropy->EOBRUN++; /* count an EOB */
  166372. if (entropy->EOBRUN == 0x7FFF)
  166373. emit_eobrun(entropy); /* force it out to avoid overflow */
  166374. }
  166375. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166376. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166377. /* Update restart-interval state too */
  166378. if (cinfo->restart_interval) {
  166379. if (entropy->restarts_to_go == 0) {
  166380. entropy->restarts_to_go = cinfo->restart_interval;
  166381. entropy->next_restart_num++;
  166382. entropy->next_restart_num &= 7;
  166383. }
  166384. entropy->restarts_to_go--;
  166385. }
  166386. return TRUE;
  166387. }
  166388. /*
  166389. * MCU encoding for DC successive approximation refinement scan.
  166390. * Note: we assume such scans can be multi-component, although the spec
  166391. * is not very clear on the point.
  166392. */
  166393. METHODDEF(boolean)
  166394. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166395. {
  166396. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166397. register int temp;
  166398. int blkn;
  166399. int Al = cinfo->Al;
  166400. JBLOCKROW block;
  166401. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166402. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166403. /* Emit restart marker if needed */
  166404. if (cinfo->restart_interval)
  166405. if (entropy->restarts_to_go == 0)
  166406. emit_restart_p(entropy, entropy->next_restart_num);
  166407. /* Encode the MCU data blocks */
  166408. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166409. block = MCU_data[blkn];
  166410. /* We simply emit the Al'th bit of the DC coefficient value. */
  166411. temp = (*block)[0];
  166412. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166413. }
  166414. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166415. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166416. /* Update restart-interval state too */
  166417. if (cinfo->restart_interval) {
  166418. if (entropy->restarts_to_go == 0) {
  166419. entropy->restarts_to_go = cinfo->restart_interval;
  166420. entropy->next_restart_num++;
  166421. entropy->next_restart_num &= 7;
  166422. }
  166423. entropy->restarts_to_go--;
  166424. }
  166425. return TRUE;
  166426. }
  166427. /*
  166428. * MCU encoding for AC successive approximation refinement scan.
  166429. */
  166430. METHODDEF(boolean)
  166431. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166432. {
  166433. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166434. register int temp;
  166435. register int r, k;
  166436. int EOB;
  166437. char *BR_buffer;
  166438. unsigned int BR;
  166439. int Se = cinfo->Se;
  166440. int Al = cinfo->Al;
  166441. JBLOCKROW block;
  166442. int absvalues[DCTSIZE2];
  166443. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166444. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166445. /* Emit restart marker if needed */
  166446. if (cinfo->restart_interval)
  166447. if (entropy->restarts_to_go == 0)
  166448. emit_restart_p(entropy, entropy->next_restart_num);
  166449. /* Encode the MCU data block */
  166450. block = MCU_data[0];
  166451. /* It is convenient to make a pre-pass to determine the transformed
  166452. * coefficients' absolute values and the EOB position.
  166453. */
  166454. EOB = 0;
  166455. for (k = cinfo->Ss; k <= Se; k++) {
  166456. temp = (*block)[jpeg_natural_order[k]];
  166457. /* We must apply the point transform by Al. For AC coefficients this
  166458. * is an integer division with rounding towards 0. To do this portably
  166459. * in C, we shift after obtaining the absolute value.
  166460. */
  166461. if (temp < 0)
  166462. temp = -temp; /* temp is abs value of input */
  166463. temp >>= Al; /* apply the point transform */
  166464. absvalues[k] = temp; /* save abs value for main pass */
  166465. if (temp == 1)
  166466. EOB = k; /* EOB = index of last newly-nonzero coef */
  166467. }
  166468. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166469. r = 0; /* r = run length of zeros */
  166470. BR = 0; /* BR = count of buffered bits added now */
  166471. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166472. for (k = cinfo->Ss; k <= Se; k++) {
  166473. if ((temp = absvalues[k]) == 0) {
  166474. r++;
  166475. continue;
  166476. }
  166477. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166478. while (r > 15 && k <= EOB) {
  166479. /* emit any pending EOBRUN and the BE correction bits */
  166480. emit_eobrun(entropy);
  166481. /* Emit ZRL */
  166482. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166483. r -= 16;
  166484. /* Emit buffered correction bits that must be associated with ZRL */
  166485. emit_buffered_bits(entropy, BR_buffer, BR);
  166486. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166487. BR = 0;
  166488. }
  166489. /* If the coef was previously nonzero, it only needs a correction bit.
  166490. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166491. * that we also need to test r > 15. But if r > 15, we can only get here
  166492. * if k > EOB, which implies that this coefficient is not 1.
  166493. */
  166494. if (temp > 1) {
  166495. /* The correction bit is the next bit of the absolute value. */
  166496. BR_buffer[BR++] = (char) (temp & 1);
  166497. continue;
  166498. }
  166499. /* Emit any pending EOBRUN and the BE correction bits */
  166500. emit_eobrun(entropy);
  166501. /* Count/emit Huffman symbol for run length / number of bits */
  166502. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166503. /* Emit output bit for newly-nonzero coef */
  166504. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166505. emit_bits_p(entropy, (unsigned int) temp, 1);
  166506. /* Emit buffered correction bits that must be associated with this code */
  166507. emit_buffered_bits(entropy, BR_buffer, BR);
  166508. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166509. BR = 0;
  166510. r = 0; /* reset zero run length */
  166511. }
  166512. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166513. entropy->EOBRUN++; /* count an EOB */
  166514. entropy->BE += BR; /* concat my correction bits to older ones */
  166515. /* We force out the EOB if we risk either:
  166516. * 1. overflow of the EOB counter;
  166517. * 2. overflow of the correction bit buffer during the next MCU.
  166518. */
  166519. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166520. emit_eobrun(entropy);
  166521. }
  166522. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166523. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166524. /* Update restart-interval state too */
  166525. if (cinfo->restart_interval) {
  166526. if (entropy->restarts_to_go == 0) {
  166527. entropy->restarts_to_go = cinfo->restart_interval;
  166528. entropy->next_restart_num++;
  166529. entropy->next_restart_num &= 7;
  166530. }
  166531. entropy->restarts_to_go--;
  166532. }
  166533. return TRUE;
  166534. }
  166535. /*
  166536. * Finish up at the end of a Huffman-compressed progressive scan.
  166537. */
  166538. METHODDEF(void)
  166539. finish_pass_phuff (j_compress_ptr cinfo)
  166540. {
  166541. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166542. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166543. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166544. /* Flush out any buffered data */
  166545. emit_eobrun(entropy);
  166546. flush_bits_p(entropy);
  166547. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166548. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166549. }
  166550. /*
  166551. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166552. */
  166553. METHODDEF(void)
  166554. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166555. {
  166556. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166557. boolean is_DC_band;
  166558. int ci, tbl;
  166559. jpeg_component_info * compptr;
  166560. JHUFF_TBL **htblptr;
  166561. boolean did[NUM_HUFF_TBLS];
  166562. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166563. emit_eobrun(entropy);
  166564. is_DC_band = (cinfo->Ss == 0);
  166565. /* It's important not to apply jpeg_gen_optimal_table more than once
  166566. * per table, because it clobbers the input frequency counts!
  166567. */
  166568. MEMZERO(did, SIZEOF(did));
  166569. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166570. compptr = cinfo->cur_comp_info[ci];
  166571. if (is_DC_band) {
  166572. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166573. continue;
  166574. tbl = compptr->dc_tbl_no;
  166575. } else {
  166576. tbl = compptr->ac_tbl_no;
  166577. }
  166578. if (! did[tbl]) {
  166579. if (is_DC_band)
  166580. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166581. else
  166582. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166583. if (*htblptr == NULL)
  166584. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166585. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166586. did[tbl] = TRUE;
  166587. }
  166588. }
  166589. }
  166590. /*
  166591. * Module initialization routine for progressive Huffman entropy encoding.
  166592. */
  166593. GLOBAL(void)
  166594. jinit_phuff_encoder (j_compress_ptr cinfo)
  166595. {
  166596. phuff_entropy_ptr entropy;
  166597. int i;
  166598. entropy = (phuff_entropy_ptr)
  166599. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166600. SIZEOF(phuff_entropy_encoder));
  166601. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166602. entropy->pub.start_pass = start_pass_phuff;
  166603. /* Mark tables unallocated */
  166604. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166605. entropy->derived_tbls[i] = NULL;
  166606. entropy->count_ptrs[i] = NULL;
  166607. }
  166608. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166609. }
  166610. #endif /* C_PROGRESSIVE_SUPPORTED */
  166611. /*** End of inlined file: jcphuff.c ***/
  166612. /*** Start of inlined file: jcprepct.c ***/
  166613. #define JPEG_INTERNALS
  166614. /* At present, jcsample.c can request context rows only for smoothing.
  166615. * In the future, we might also need context rows for CCIR601 sampling
  166616. * or other more-complex downsampling procedures. The code to support
  166617. * context rows should be compiled only if needed.
  166618. */
  166619. #ifdef INPUT_SMOOTHING_SUPPORTED
  166620. #define CONTEXT_ROWS_SUPPORTED
  166621. #endif
  166622. /*
  166623. * For the simple (no-context-row) case, we just need to buffer one
  166624. * row group's worth of pixels for the downsampling step. At the bottom of
  166625. * the image, we pad to a full row group by replicating the last pixel row.
  166626. * The downsampler's last output row is then replicated if needed to pad
  166627. * out to a full iMCU row.
  166628. *
  166629. * When providing context rows, we must buffer three row groups' worth of
  166630. * pixels. Three row groups are physically allocated, but the row pointer
  166631. * arrays are made five row groups high, with the extra pointers above and
  166632. * below "wrapping around" to point to the last and first real row groups.
  166633. * This allows the downsampler to access the proper context rows.
  166634. * At the top and bottom of the image, we create dummy context rows by
  166635. * copying the first or last real pixel row. This copying could be avoided
  166636. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166637. * trouble on the compression side.
  166638. */
  166639. /* Private buffer controller object */
  166640. typedef struct {
  166641. struct jpeg_c_prep_controller pub; /* public fields */
  166642. /* Downsampling input buffer. This buffer holds color-converted data
  166643. * until we have enough to do a downsample step.
  166644. */
  166645. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166646. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166647. int next_buf_row; /* index of next row to store in color_buf */
  166648. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166649. int this_row_group; /* starting row index of group to process */
  166650. int next_buf_stop; /* downsample when we reach this index */
  166651. #endif
  166652. } my_prep_controller;
  166653. typedef my_prep_controller * my_prep_ptr;
  166654. /*
  166655. * Initialize for a processing pass.
  166656. */
  166657. METHODDEF(void)
  166658. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166659. {
  166660. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166661. if (pass_mode != JBUF_PASS_THRU)
  166662. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166663. /* Initialize total-height counter for detecting bottom of image */
  166664. prep->rows_to_go = cinfo->image_height;
  166665. /* Mark the conversion buffer empty */
  166666. prep->next_buf_row = 0;
  166667. #ifdef CONTEXT_ROWS_SUPPORTED
  166668. /* Preset additional state variables for context mode.
  166669. * These aren't used in non-context mode, so we needn't test which mode.
  166670. */
  166671. prep->this_row_group = 0;
  166672. /* Set next_buf_stop to stop after two row groups have been read in. */
  166673. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166674. #endif
  166675. }
  166676. /*
  166677. * Expand an image vertically from height input_rows to height output_rows,
  166678. * by duplicating the bottom row.
  166679. */
  166680. LOCAL(void)
  166681. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166682. int input_rows, int output_rows)
  166683. {
  166684. register int row;
  166685. for (row = input_rows; row < output_rows; row++) {
  166686. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166687. 1, num_cols);
  166688. }
  166689. }
  166690. /*
  166691. * Process some data in the simple no-context case.
  166692. *
  166693. * Preprocessor output data is counted in "row groups". A row group
  166694. * is defined to be v_samp_factor sample rows of each component.
  166695. * Downsampling will produce this much data from each max_v_samp_factor
  166696. * input rows.
  166697. */
  166698. METHODDEF(void)
  166699. pre_process_data (j_compress_ptr cinfo,
  166700. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166701. JDIMENSION in_rows_avail,
  166702. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166703. JDIMENSION out_row_groups_avail)
  166704. {
  166705. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166706. int numrows, ci;
  166707. JDIMENSION inrows;
  166708. jpeg_component_info * compptr;
  166709. while (*in_row_ctr < in_rows_avail &&
  166710. *out_row_group_ctr < out_row_groups_avail) {
  166711. /* Do color conversion to fill the conversion buffer. */
  166712. inrows = in_rows_avail - *in_row_ctr;
  166713. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166714. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166715. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166716. prep->color_buf,
  166717. (JDIMENSION) prep->next_buf_row,
  166718. numrows);
  166719. *in_row_ctr += numrows;
  166720. prep->next_buf_row += numrows;
  166721. prep->rows_to_go -= numrows;
  166722. /* If at bottom of image, pad to fill the conversion buffer. */
  166723. if (prep->rows_to_go == 0 &&
  166724. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166725. for (ci = 0; ci < cinfo->num_components; ci++) {
  166726. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166727. prep->next_buf_row, cinfo->max_v_samp_factor);
  166728. }
  166729. prep->next_buf_row = cinfo->max_v_samp_factor;
  166730. }
  166731. /* If we've filled the conversion buffer, empty it. */
  166732. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166733. (*cinfo->downsample->downsample) (cinfo,
  166734. prep->color_buf, (JDIMENSION) 0,
  166735. output_buf, *out_row_group_ctr);
  166736. prep->next_buf_row = 0;
  166737. (*out_row_group_ctr)++;
  166738. }
  166739. /* If at bottom of image, pad the output to a full iMCU height.
  166740. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166741. */
  166742. if (prep->rows_to_go == 0 &&
  166743. *out_row_group_ctr < out_row_groups_avail) {
  166744. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166745. ci++, compptr++) {
  166746. expand_bottom_edge(output_buf[ci],
  166747. compptr->width_in_blocks * DCTSIZE,
  166748. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166749. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166750. }
  166751. *out_row_group_ctr = out_row_groups_avail;
  166752. break; /* can exit outer loop without test */
  166753. }
  166754. }
  166755. }
  166756. #ifdef CONTEXT_ROWS_SUPPORTED
  166757. /*
  166758. * Process some data in the context case.
  166759. */
  166760. METHODDEF(void)
  166761. pre_process_context (j_compress_ptr cinfo,
  166762. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166763. JDIMENSION in_rows_avail,
  166764. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166765. JDIMENSION out_row_groups_avail)
  166766. {
  166767. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166768. int numrows, ci;
  166769. int buf_height = cinfo->max_v_samp_factor * 3;
  166770. JDIMENSION inrows;
  166771. while (*out_row_group_ctr < out_row_groups_avail) {
  166772. if (*in_row_ctr < in_rows_avail) {
  166773. /* Do color conversion to fill the conversion buffer. */
  166774. inrows = in_rows_avail - *in_row_ctr;
  166775. numrows = prep->next_buf_stop - prep->next_buf_row;
  166776. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166777. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166778. prep->color_buf,
  166779. (JDIMENSION) prep->next_buf_row,
  166780. numrows);
  166781. /* Pad at top of image, if first time through */
  166782. if (prep->rows_to_go == cinfo->image_height) {
  166783. for (ci = 0; ci < cinfo->num_components; ci++) {
  166784. int row;
  166785. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166786. jcopy_sample_rows(prep->color_buf[ci], 0,
  166787. prep->color_buf[ci], -row,
  166788. 1, cinfo->image_width);
  166789. }
  166790. }
  166791. }
  166792. *in_row_ctr += numrows;
  166793. prep->next_buf_row += numrows;
  166794. prep->rows_to_go -= numrows;
  166795. } else {
  166796. /* Return for more data, unless we are at the bottom of the image. */
  166797. if (prep->rows_to_go != 0)
  166798. break;
  166799. /* When at bottom of image, pad to fill the conversion buffer. */
  166800. if (prep->next_buf_row < prep->next_buf_stop) {
  166801. for (ci = 0; ci < cinfo->num_components; ci++) {
  166802. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166803. prep->next_buf_row, prep->next_buf_stop);
  166804. }
  166805. prep->next_buf_row = prep->next_buf_stop;
  166806. }
  166807. }
  166808. /* If we've gotten enough data, downsample a row group. */
  166809. if (prep->next_buf_row == prep->next_buf_stop) {
  166810. (*cinfo->downsample->downsample) (cinfo,
  166811. prep->color_buf,
  166812. (JDIMENSION) prep->this_row_group,
  166813. output_buf, *out_row_group_ctr);
  166814. (*out_row_group_ctr)++;
  166815. /* Advance pointers with wraparound as necessary. */
  166816. prep->this_row_group += cinfo->max_v_samp_factor;
  166817. if (prep->this_row_group >= buf_height)
  166818. prep->this_row_group = 0;
  166819. if (prep->next_buf_row >= buf_height)
  166820. prep->next_buf_row = 0;
  166821. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166822. }
  166823. }
  166824. }
  166825. /*
  166826. * Create the wrapped-around downsampling input buffer needed for context mode.
  166827. */
  166828. LOCAL(void)
  166829. create_context_buffer (j_compress_ptr cinfo)
  166830. {
  166831. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166832. int rgroup_height = cinfo->max_v_samp_factor;
  166833. int ci, i;
  166834. jpeg_component_info * compptr;
  166835. JSAMPARRAY true_buffer, fake_buffer;
  166836. /* Grab enough space for fake row pointers for all the components;
  166837. * we need five row groups' worth of pointers for each component.
  166838. */
  166839. fake_buffer = (JSAMPARRAY)
  166840. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166841. (cinfo->num_components * 5 * rgroup_height) *
  166842. SIZEOF(JSAMPROW));
  166843. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166844. ci++, compptr++) {
  166845. /* Allocate the actual buffer space (3 row groups) for this component.
  166846. * We make the buffer wide enough to allow the downsampler to edge-expand
  166847. * horizontally within the buffer, if it so chooses.
  166848. */
  166849. true_buffer = (*cinfo->mem->alloc_sarray)
  166850. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166851. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166852. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166853. (JDIMENSION) (3 * rgroup_height));
  166854. /* Copy true buffer row pointers into the middle of the fake row array */
  166855. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166856. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166857. /* Fill in the above and below wraparound pointers */
  166858. for (i = 0; i < rgroup_height; i++) {
  166859. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166860. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166861. }
  166862. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166863. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166864. }
  166865. }
  166866. #endif /* CONTEXT_ROWS_SUPPORTED */
  166867. /*
  166868. * Initialize preprocessing controller.
  166869. */
  166870. GLOBAL(void)
  166871. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166872. {
  166873. my_prep_ptr prep;
  166874. int ci;
  166875. jpeg_component_info * compptr;
  166876. if (need_full_buffer) /* safety check */
  166877. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166878. prep = (my_prep_ptr)
  166879. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166880. SIZEOF(my_prep_controller));
  166881. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166882. prep->pub.start_pass = start_pass_prep;
  166883. /* Allocate the color conversion buffer.
  166884. * We make the buffer wide enough to allow the downsampler to edge-expand
  166885. * horizontally within the buffer, if it so chooses.
  166886. */
  166887. if (cinfo->downsample->need_context_rows) {
  166888. /* Set up to provide context rows */
  166889. #ifdef CONTEXT_ROWS_SUPPORTED
  166890. prep->pub.pre_process_data = pre_process_context;
  166891. create_context_buffer(cinfo);
  166892. #else
  166893. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166894. #endif
  166895. } else {
  166896. /* No context, just make it tall enough for one row group */
  166897. prep->pub.pre_process_data = pre_process_data;
  166898. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166899. ci++, compptr++) {
  166900. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166901. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166902. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166903. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166904. (JDIMENSION) cinfo->max_v_samp_factor);
  166905. }
  166906. }
  166907. }
  166908. /*** End of inlined file: jcprepct.c ***/
  166909. /*** Start of inlined file: jcsample.c ***/
  166910. #define JPEG_INTERNALS
  166911. /* Pointer to routine to downsample a single component */
  166912. typedef JMETHOD(void, downsample1_ptr,
  166913. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166914. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166915. /* Private subobject */
  166916. typedef struct {
  166917. struct jpeg_downsampler pub; /* public fields */
  166918. /* Downsampling method pointers, one per component */
  166919. downsample1_ptr methods[MAX_COMPONENTS];
  166920. } my_downsampler;
  166921. typedef my_downsampler * my_downsample_ptr;
  166922. /*
  166923. * Initialize for a downsampling pass.
  166924. */
  166925. METHODDEF(void)
  166926. start_pass_downsample (j_compress_ptr)
  166927. {
  166928. /* no work for now */
  166929. }
  166930. /*
  166931. * Expand a component horizontally from width input_cols to width output_cols,
  166932. * by duplicating the rightmost samples.
  166933. */
  166934. LOCAL(void)
  166935. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166936. JDIMENSION input_cols, JDIMENSION output_cols)
  166937. {
  166938. register JSAMPROW ptr;
  166939. register JSAMPLE pixval;
  166940. register int count;
  166941. int row;
  166942. int numcols = (int) (output_cols - input_cols);
  166943. if (numcols > 0) {
  166944. for (row = 0; row < num_rows; row++) {
  166945. ptr = image_data[row] + input_cols;
  166946. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166947. for (count = numcols; count > 0; count--)
  166948. *ptr++ = pixval;
  166949. }
  166950. }
  166951. }
  166952. /*
  166953. * Do downsampling for a whole row group (all components).
  166954. *
  166955. * In this version we simply downsample each component independently.
  166956. */
  166957. METHODDEF(void)
  166958. sep_downsample (j_compress_ptr cinfo,
  166959. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166960. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166961. {
  166962. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166963. int ci;
  166964. jpeg_component_info * compptr;
  166965. JSAMPARRAY in_ptr, out_ptr;
  166966. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166967. ci++, compptr++) {
  166968. in_ptr = input_buf[ci] + in_row_index;
  166969. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166970. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166971. }
  166972. }
  166973. /*
  166974. * Downsample pixel values of a single component.
  166975. * One row group is processed per call.
  166976. * This version handles arbitrary integral sampling ratios, without smoothing.
  166977. * Note that this version is not actually used for customary sampling ratios.
  166978. */
  166979. METHODDEF(void)
  166980. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166981. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166982. {
  166983. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166984. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166985. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166986. JSAMPROW inptr, outptr;
  166987. INT32 outvalue;
  166988. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166989. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166990. numpix = h_expand * v_expand;
  166991. numpix2 = numpix/2;
  166992. /* Expand input data enough to let all the output samples be generated
  166993. * by the standard loop. Special-casing padded output would be more
  166994. * efficient.
  166995. */
  166996. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166997. cinfo->image_width, output_cols * h_expand);
  166998. inrow = 0;
  166999. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167000. outptr = output_data[outrow];
  167001. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167002. outcol++, outcol_h += h_expand) {
  167003. outvalue = 0;
  167004. for (v = 0; v < v_expand; v++) {
  167005. inptr = input_data[inrow+v] + outcol_h;
  167006. for (h = 0; h < h_expand; h++) {
  167007. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167008. }
  167009. }
  167010. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167011. }
  167012. inrow += v_expand;
  167013. }
  167014. }
  167015. /*
  167016. * Downsample pixel values of a single component.
  167017. * This version handles the special case of a full-size component,
  167018. * without smoothing.
  167019. */
  167020. METHODDEF(void)
  167021. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167022. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167023. {
  167024. /* Copy the data */
  167025. jcopy_sample_rows(input_data, 0, output_data, 0,
  167026. cinfo->max_v_samp_factor, cinfo->image_width);
  167027. /* Edge-expand */
  167028. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167029. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167030. }
  167031. /*
  167032. * Downsample pixel values of a single component.
  167033. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167034. * without smoothing.
  167035. *
  167036. * A note about the "bias" calculations: when rounding fractional values to
  167037. * integer, we do not want to always round 0.5 up to the next integer.
  167038. * If we did that, we'd introduce a noticeable bias towards larger values.
  167039. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167040. * alternate pixel locations (a simple ordered dither pattern).
  167041. */
  167042. METHODDEF(void)
  167043. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167044. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167045. {
  167046. int outrow;
  167047. JDIMENSION outcol;
  167048. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167049. register JSAMPROW inptr, outptr;
  167050. register int bias;
  167051. /* Expand input data enough to let all the output samples be generated
  167052. * by the standard loop. Special-casing padded output would be more
  167053. * efficient.
  167054. */
  167055. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167056. cinfo->image_width, output_cols * 2);
  167057. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167058. outptr = output_data[outrow];
  167059. inptr = input_data[outrow];
  167060. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167061. for (outcol = 0; outcol < output_cols; outcol++) {
  167062. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167063. + bias) >> 1);
  167064. bias ^= 1; /* 0=>1, 1=>0 */
  167065. inptr += 2;
  167066. }
  167067. }
  167068. }
  167069. /*
  167070. * Downsample pixel values of a single component.
  167071. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167072. * without smoothing.
  167073. */
  167074. METHODDEF(void)
  167075. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167076. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167077. {
  167078. int inrow, outrow;
  167079. JDIMENSION outcol;
  167080. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167081. register JSAMPROW inptr0, inptr1, outptr;
  167082. register int bias;
  167083. /* Expand input data enough to let all the output samples be generated
  167084. * by the standard loop. Special-casing padded output would be more
  167085. * efficient.
  167086. */
  167087. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167088. cinfo->image_width, output_cols * 2);
  167089. inrow = 0;
  167090. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167091. outptr = output_data[outrow];
  167092. inptr0 = input_data[inrow];
  167093. inptr1 = input_data[inrow+1];
  167094. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167095. for (outcol = 0; outcol < output_cols; outcol++) {
  167096. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167097. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167098. + bias) >> 2);
  167099. bias ^= 3; /* 1=>2, 2=>1 */
  167100. inptr0 += 2; inptr1 += 2;
  167101. }
  167102. inrow += 2;
  167103. }
  167104. }
  167105. #ifdef INPUT_SMOOTHING_SUPPORTED
  167106. /*
  167107. * Downsample pixel values of a single component.
  167108. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167109. * with smoothing. One row of context is required.
  167110. */
  167111. METHODDEF(void)
  167112. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167113. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167114. {
  167115. int inrow, outrow;
  167116. JDIMENSION colctr;
  167117. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167118. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167119. INT32 membersum, neighsum, memberscale, neighscale;
  167120. /* Expand input data enough to let all the output samples be generated
  167121. * by the standard loop. Special-casing padded output would be more
  167122. * efficient.
  167123. */
  167124. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167125. cinfo->image_width, output_cols * 2);
  167126. /* We don't bother to form the individual "smoothed" input pixel values;
  167127. * we can directly compute the output which is the average of the four
  167128. * smoothed values. Each of the four member pixels contributes a fraction
  167129. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167130. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167131. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167132. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167133. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167134. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167135. * factors are scaled by 2^16 = 65536.
  167136. * Also recall that SF = smoothing_factor / 1024.
  167137. */
  167138. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167139. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167140. inrow = 0;
  167141. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167142. outptr = output_data[outrow];
  167143. inptr0 = input_data[inrow];
  167144. inptr1 = input_data[inrow+1];
  167145. above_ptr = input_data[inrow-1];
  167146. below_ptr = input_data[inrow+2];
  167147. /* Special case for first column: pretend column -1 is same as column 0 */
  167148. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167149. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167150. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167151. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167152. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167153. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167154. neighsum += neighsum;
  167155. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167156. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167157. membersum = membersum * memberscale + neighsum * neighscale;
  167158. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167159. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167160. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167161. /* sum of pixels directly mapped to this output element */
  167162. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167163. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167164. /* sum of edge-neighbor pixels */
  167165. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167166. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167167. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167168. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167169. /* The edge-neighbors count twice as much as corner-neighbors */
  167170. neighsum += neighsum;
  167171. /* Add in the corner-neighbors */
  167172. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167173. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167174. /* form final output scaled up by 2^16 */
  167175. membersum = membersum * memberscale + neighsum * neighscale;
  167176. /* round, descale and output it */
  167177. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167178. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167179. }
  167180. /* Special case for last column */
  167181. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167182. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167183. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167184. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167185. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167186. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167187. neighsum += neighsum;
  167188. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167189. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167190. membersum = membersum * memberscale + neighsum * neighscale;
  167191. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167192. inrow += 2;
  167193. }
  167194. }
  167195. /*
  167196. * Downsample pixel values of a single component.
  167197. * This version handles the special case of a full-size component,
  167198. * with smoothing. One row of context is required.
  167199. */
  167200. METHODDEF(void)
  167201. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167202. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167203. {
  167204. int outrow;
  167205. JDIMENSION colctr;
  167206. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167207. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167208. INT32 membersum, neighsum, memberscale, neighscale;
  167209. int colsum, lastcolsum, nextcolsum;
  167210. /* Expand input data enough to let all the output samples be generated
  167211. * by the standard loop. Special-casing padded output would be more
  167212. * efficient.
  167213. */
  167214. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167215. cinfo->image_width, output_cols);
  167216. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167217. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167218. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167219. * Also recall that SF = smoothing_factor / 1024.
  167220. */
  167221. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167222. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167223. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167224. outptr = output_data[outrow];
  167225. inptr = input_data[outrow];
  167226. above_ptr = input_data[outrow-1];
  167227. below_ptr = input_data[outrow+1];
  167228. /* Special case for first column */
  167229. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167230. GETJSAMPLE(*inptr);
  167231. membersum = GETJSAMPLE(*inptr++);
  167232. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167233. GETJSAMPLE(*inptr);
  167234. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167235. membersum = membersum * memberscale + neighsum * neighscale;
  167236. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167237. lastcolsum = colsum; colsum = nextcolsum;
  167238. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167239. membersum = GETJSAMPLE(*inptr++);
  167240. above_ptr++; below_ptr++;
  167241. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167242. GETJSAMPLE(*inptr);
  167243. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167244. membersum = membersum * memberscale + neighsum * neighscale;
  167245. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167246. lastcolsum = colsum; colsum = nextcolsum;
  167247. }
  167248. /* Special case for last column */
  167249. membersum = GETJSAMPLE(*inptr);
  167250. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167251. membersum = membersum * memberscale + neighsum * neighscale;
  167252. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167253. }
  167254. }
  167255. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167256. /*
  167257. * Module initialization routine for downsampling.
  167258. * Note that we must select a routine for each component.
  167259. */
  167260. GLOBAL(void)
  167261. jinit_downsampler (j_compress_ptr cinfo)
  167262. {
  167263. my_downsample_ptr downsample;
  167264. int ci;
  167265. jpeg_component_info * compptr;
  167266. boolean smoothok = TRUE;
  167267. downsample = (my_downsample_ptr)
  167268. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167269. SIZEOF(my_downsampler));
  167270. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167271. downsample->pub.start_pass = start_pass_downsample;
  167272. downsample->pub.downsample = sep_downsample;
  167273. downsample->pub.need_context_rows = FALSE;
  167274. if (cinfo->CCIR601_sampling)
  167275. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167276. /* Verify we can handle the sampling factors, and set up method pointers */
  167277. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167278. ci++, compptr++) {
  167279. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167280. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167281. #ifdef INPUT_SMOOTHING_SUPPORTED
  167282. if (cinfo->smoothing_factor) {
  167283. downsample->methods[ci] = fullsize_smooth_downsample;
  167284. downsample->pub.need_context_rows = TRUE;
  167285. } else
  167286. #endif
  167287. downsample->methods[ci] = fullsize_downsample;
  167288. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167289. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167290. smoothok = FALSE;
  167291. downsample->methods[ci] = h2v1_downsample;
  167292. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167293. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167294. #ifdef INPUT_SMOOTHING_SUPPORTED
  167295. if (cinfo->smoothing_factor) {
  167296. downsample->methods[ci] = h2v2_smooth_downsample;
  167297. downsample->pub.need_context_rows = TRUE;
  167298. } else
  167299. #endif
  167300. downsample->methods[ci] = h2v2_downsample;
  167301. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167302. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167303. smoothok = FALSE;
  167304. downsample->methods[ci] = int_downsample;
  167305. } else
  167306. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167307. }
  167308. #ifdef INPUT_SMOOTHING_SUPPORTED
  167309. if (cinfo->smoothing_factor && !smoothok)
  167310. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167311. #endif
  167312. }
  167313. /*** End of inlined file: jcsample.c ***/
  167314. /*** Start of inlined file: jctrans.c ***/
  167315. #define JPEG_INTERNALS
  167316. /* Forward declarations */
  167317. LOCAL(void) transencode_master_selection
  167318. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167319. LOCAL(void) transencode_coef_controller
  167320. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167321. /*
  167322. * Compression initialization for writing raw-coefficient data.
  167323. * Before calling this, all parameters and a data destination must be set up.
  167324. * Call jpeg_finish_compress() to actually write the data.
  167325. *
  167326. * The number of passed virtual arrays must match cinfo->num_components.
  167327. * Note that the virtual arrays need not be filled or even realized at
  167328. * the time write_coefficients is called; indeed, if the virtual arrays
  167329. * were requested from this compression object's memory manager, they
  167330. * typically will be realized during this routine and filled afterwards.
  167331. */
  167332. GLOBAL(void)
  167333. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167334. {
  167335. if (cinfo->global_state != CSTATE_START)
  167336. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167337. /* Mark all tables to be written */
  167338. jpeg_suppress_tables(cinfo, FALSE);
  167339. /* (Re)initialize error mgr and destination modules */
  167340. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167341. (*cinfo->dest->init_destination) (cinfo);
  167342. /* Perform master selection of active modules */
  167343. transencode_master_selection(cinfo, coef_arrays);
  167344. /* Wait for jpeg_finish_compress() call */
  167345. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167346. cinfo->global_state = CSTATE_WRCOEFS;
  167347. }
  167348. /*
  167349. * Initialize the compression object with default parameters,
  167350. * then copy from the source object all parameters needed for lossless
  167351. * transcoding. Parameters that can be varied without loss (such as
  167352. * scan script and Huffman optimization) are left in their default states.
  167353. */
  167354. GLOBAL(void)
  167355. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167356. j_compress_ptr dstinfo)
  167357. {
  167358. JQUANT_TBL ** qtblptr;
  167359. jpeg_component_info *incomp, *outcomp;
  167360. JQUANT_TBL *c_quant, *slot_quant;
  167361. int tblno, ci, coefi;
  167362. /* Safety check to ensure start_compress not called yet. */
  167363. if (dstinfo->global_state != CSTATE_START)
  167364. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167365. /* Copy fundamental image dimensions */
  167366. dstinfo->image_width = srcinfo->image_width;
  167367. dstinfo->image_height = srcinfo->image_height;
  167368. dstinfo->input_components = srcinfo->num_components;
  167369. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167370. /* Initialize all parameters to default values */
  167371. jpeg_set_defaults(dstinfo);
  167372. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167373. * Fix it to get the right header markers for the image colorspace.
  167374. */
  167375. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167376. dstinfo->data_precision = srcinfo->data_precision;
  167377. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167378. /* Copy the source's quantization tables. */
  167379. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167380. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167381. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167382. if (*qtblptr == NULL)
  167383. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167384. MEMCOPY((*qtblptr)->quantval,
  167385. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167386. SIZEOF((*qtblptr)->quantval));
  167387. (*qtblptr)->sent_table = FALSE;
  167388. }
  167389. }
  167390. /* Copy the source's per-component info.
  167391. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167392. */
  167393. dstinfo->num_components = srcinfo->num_components;
  167394. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167395. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167396. MAX_COMPONENTS);
  167397. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167398. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167399. outcomp->component_id = incomp->component_id;
  167400. outcomp->h_samp_factor = incomp->h_samp_factor;
  167401. outcomp->v_samp_factor = incomp->v_samp_factor;
  167402. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167403. /* Make sure saved quantization table for component matches the qtable
  167404. * slot. If not, the input file re-used this qtable slot.
  167405. * IJG encoder currently cannot duplicate this.
  167406. */
  167407. tblno = outcomp->quant_tbl_no;
  167408. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167409. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167410. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167411. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167412. c_quant = incomp->quant_table;
  167413. if (c_quant != NULL) {
  167414. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167415. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167416. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167417. }
  167418. }
  167419. /* Note: we do not copy the source's Huffman table assignments;
  167420. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167421. */
  167422. }
  167423. /* Also copy JFIF version and resolution information, if available.
  167424. * Strictly speaking this isn't "critical" info, but it's nearly
  167425. * always appropriate to copy it if available. In particular,
  167426. * if the application chooses to copy JFIF 1.02 extension markers from
  167427. * the source file, we need to copy the version to make sure we don't
  167428. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167429. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167430. */
  167431. if (srcinfo->saw_JFIF_marker) {
  167432. if (srcinfo->JFIF_major_version == 1) {
  167433. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167434. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167435. }
  167436. dstinfo->density_unit = srcinfo->density_unit;
  167437. dstinfo->X_density = srcinfo->X_density;
  167438. dstinfo->Y_density = srcinfo->Y_density;
  167439. }
  167440. }
  167441. /*
  167442. * Master selection of compression modules for transcoding.
  167443. * This substitutes for jcinit.c's initialization of the full compressor.
  167444. */
  167445. LOCAL(void)
  167446. transencode_master_selection (j_compress_ptr cinfo,
  167447. jvirt_barray_ptr * coef_arrays)
  167448. {
  167449. /* Although we don't actually use input_components for transcoding,
  167450. * jcmaster.c's initial_setup will complain if input_components is 0.
  167451. */
  167452. cinfo->input_components = 1;
  167453. /* Initialize master control (includes parameter checking/processing) */
  167454. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167455. /* Entropy encoding: either Huffman or arithmetic coding. */
  167456. if (cinfo->arith_code) {
  167457. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167458. } else {
  167459. if (cinfo->progressive_mode) {
  167460. #ifdef C_PROGRESSIVE_SUPPORTED
  167461. jinit_phuff_encoder(cinfo);
  167462. #else
  167463. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167464. #endif
  167465. } else
  167466. jinit_huff_encoder(cinfo);
  167467. }
  167468. /* We need a special coefficient buffer controller. */
  167469. transencode_coef_controller(cinfo, coef_arrays);
  167470. jinit_marker_writer(cinfo);
  167471. /* We can now tell the memory manager to allocate virtual arrays. */
  167472. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167473. /* Write the datastream header (SOI, JFIF) immediately.
  167474. * Frame and scan headers are postponed till later.
  167475. * This lets application insert special markers after the SOI.
  167476. */
  167477. (*cinfo->marker->write_file_header) (cinfo);
  167478. }
  167479. /*
  167480. * The rest of this file is a special implementation of the coefficient
  167481. * buffer controller. This is similar to jccoefct.c, but it handles only
  167482. * output from presupplied virtual arrays. Furthermore, we generate any
  167483. * dummy padding blocks on-the-fly rather than expecting them to be present
  167484. * in the arrays.
  167485. */
  167486. /* Private buffer controller object */
  167487. typedef struct {
  167488. struct jpeg_c_coef_controller pub; /* public fields */
  167489. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167490. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167491. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167492. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167493. /* Virtual block array for each component. */
  167494. jvirt_barray_ptr * whole_image;
  167495. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167496. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167497. } my_coef_controller2;
  167498. typedef my_coef_controller2 * my_coef_ptr2;
  167499. LOCAL(void)
  167500. start_iMCU_row2 (j_compress_ptr cinfo)
  167501. /* Reset within-iMCU-row counters for a new row */
  167502. {
  167503. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167504. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167505. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167506. * But at the bottom of the image, process only what's left.
  167507. */
  167508. if (cinfo->comps_in_scan > 1) {
  167509. coef->MCU_rows_per_iMCU_row = 1;
  167510. } else {
  167511. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167512. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167513. else
  167514. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167515. }
  167516. coef->mcu_ctr = 0;
  167517. coef->MCU_vert_offset = 0;
  167518. }
  167519. /*
  167520. * Initialize for a processing pass.
  167521. */
  167522. METHODDEF(void)
  167523. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167524. {
  167525. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167526. if (pass_mode != JBUF_CRANK_DEST)
  167527. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167528. coef->iMCU_row_num = 0;
  167529. start_iMCU_row2(cinfo);
  167530. }
  167531. /*
  167532. * Process some data.
  167533. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167534. * per call, ie, v_samp_factor block rows for each component in the scan.
  167535. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167536. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167537. *
  167538. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167539. */
  167540. METHODDEF(boolean)
  167541. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167542. {
  167543. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167544. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167545. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167546. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167547. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167548. JDIMENSION start_col;
  167549. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167550. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167551. JBLOCKROW buffer_ptr;
  167552. jpeg_component_info *compptr;
  167553. /* Align the virtual buffers for the components used in this scan. */
  167554. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167555. compptr = cinfo->cur_comp_info[ci];
  167556. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167557. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167558. coef->iMCU_row_num * compptr->v_samp_factor,
  167559. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167560. }
  167561. /* Loop to process one whole iMCU row */
  167562. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167563. yoffset++) {
  167564. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167565. MCU_col_num++) {
  167566. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167567. blkn = 0; /* index of current DCT block within MCU */
  167568. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167569. compptr = cinfo->cur_comp_info[ci];
  167570. start_col = MCU_col_num * compptr->MCU_width;
  167571. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167572. : compptr->last_col_width;
  167573. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167574. if (coef->iMCU_row_num < last_iMCU_row ||
  167575. yindex+yoffset < compptr->last_row_height) {
  167576. /* Fill in pointers to real blocks in this row */
  167577. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167578. for (xindex = 0; xindex < blockcnt; xindex++)
  167579. MCU_buffer[blkn++] = buffer_ptr++;
  167580. } else {
  167581. /* At bottom of image, need a whole row of dummy blocks */
  167582. xindex = 0;
  167583. }
  167584. /* Fill in any dummy blocks needed in this row.
  167585. * Dummy blocks are filled in the same way as in jccoefct.c:
  167586. * all zeroes in the AC entries, DC entries equal to previous
  167587. * block's DC value. The init routine has already zeroed the
  167588. * AC entries, so we need only set the DC entries correctly.
  167589. */
  167590. for (; xindex < compptr->MCU_width; xindex++) {
  167591. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167592. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167593. blkn++;
  167594. }
  167595. }
  167596. }
  167597. /* Try to write the MCU. */
  167598. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167599. /* Suspension forced; update state counters and exit */
  167600. coef->MCU_vert_offset = yoffset;
  167601. coef->mcu_ctr = MCU_col_num;
  167602. return FALSE;
  167603. }
  167604. }
  167605. /* Completed an MCU row, but perhaps not an iMCU row */
  167606. coef->mcu_ctr = 0;
  167607. }
  167608. /* Completed the iMCU row, advance counters for next one */
  167609. coef->iMCU_row_num++;
  167610. start_iMCU_row2(cinfo);
  167611. return TRUE;
  167612. }
  167613. /*
  167614. * Initialize coefficient buffer controller.
  167615. *
  167616. * Each passed coefficient array must be the right size for that
  167617. * coefficient: width_in_blocks wide and height_in_blocks high,
  167618. * with unitheight at least v_samp_factor.
  167619. */
  167620. LOCAL(void)
  167621. transencode_coef_controller (j_compress_ptr cinfo,
  167622. jvirt_barray_ptr * coef_arrays)
  167623. {
  167624. my_coef_ptr2 coef;
  167625. JBLOCKROW buffer;
  167626. int i;
  167627. coef = (my_coef_ptr2)
  167628. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167629. SIZEOF(my_coef_controller2));
  167630. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167631. coef->pub.start_pass = start_pass_coef2;
  167632. coef->pub.compress_data = compress_output2;
  167633. /* Save pointer to virtual arrays */
  167634. coef->whole_image = coef_arrays;
  167635. /* Allocate and pre-zero space for dummy DCT blocks. */
  167636. buffer = (JBLOCKROW)
  167637. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167638. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167639. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167640. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167641. coef->dummy_buffer[i] = buffer + i;
  167642. }
  167643. }
  167644. /*** End of inlined file: jctrans.c ***/
  167645. /*** Start of inlined file: jdapistd.c ***/
  167646. #define JPEG_INTERNALS
  167647. /* Forward declarations */
  167648. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167649. /*
  167650. * Decompression initialization.
  167651. * jpeg_read_header must be completed before calling this.
  167652. *
  167653. * If a multipass operating mode was selected, this will do all but the
  167654. * last pass, and thus may take a great deal of time.
  167655. *
  167656. * Returns FALSE if suspended. The return value need be inspected only if
  167657. * a suspending data source is used.
  167658. */
  167659. GLOBAL(boolean)
  167660. jpeg_start_decompress (j_decompress_ptr cinfo)
  167661. {
  167662. if (cinfo->global_state == DSTATE_READY) {
  167663. /* First call: initialize master control, select active modules */
  167664. jinit_master_decompress(cinfo);
  167665. if (cinfo->buffered_image) {
  167666. /* No more work here; expecting jpeg_start_output next */
  167667. cinfo->global_state = DSTATE_BUFIMAGE;
  167668. return TRUE;
  167669. }
  167670. cinfo->global_state = DSTATE_PRELOAD;
  167671. }
  167672. if (cinfo->global_state == DSTATE_PRELOAD) {
  167673. /* If file has multiple scans, absorb them all into the coef buffer */
  167674. if (cinfo->inputctl->has_multiple_scans) {
  167675. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167676. for (;;) {
  167677. int retcode;
  167678. /* Call progress monitor hook if present */
  167679. if (cinfo->progress != NULL)
  167680. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167681. /* Absorb some more input */
  167682. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167683. if (retcode == JPEG_SUSPENDED)
  167684. return FALSE;
  167685. if (retcode == JPEG_REACHED_EOI)
  167686. break;
  167687. /* Advance progress counter if appropriate */
  167688. if (cinfo->progress != NULL &&
  167689. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167690. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167691. /* jdmaster underestimated number of scans; ratchet up one scan */
  167692. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167693. }
  167694. }
  167695. }
  167696. #else
  167697. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167698. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167699. }
  167700. cinfo->output_scan_number = cinfo->input_scan_number;
  167701. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167702. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167703. /* Perform any dummy output passes, and set up for the final pass */
  167704. return output_pass_setup(cinfo);
  167705. }
  167706. /*
  167707. * Set up for an output pass, and perform any dummy pass(es) needed.
  167708. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167709. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167710. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167711. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167712. */
  167713. LOCAL(boolean)
  167714. output_pass_setup (j_decompress_ptr cinfo)
  167715. {
  167716. if (cinfo->global_state != DSTATE_PRESCAN) {
  167717. /* First call: do pass setup */
  167718. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167719. cinfo->output_scanline = 0;
  167720. cinfo->global_state = DSTATE_PRESCAN;
  167721. }
  167722. /* Loop over any required dummy passes */
  167723. while (cinfo->master->is_dummy_pass) {
  167724. #ifdef QUANT_2PASS_SUPPORTED
  167725. /* Crank through the dummy pass */
  167726. while (cinfo->output_scanline < cinfo->output_height) {
  167727. JDIMENSION last_scanline;
  167728. /* Call progress monitor hook if present */
  167729. if (cinfo->progress != NULL) {
  167730. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167731. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167732. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167733. }
  167734. /* Process some data */
  167735. last_scanline = cinfo->output_scanline;
  167736. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167737. &cinfo->output_scanline, (JDIMENSION) 0);
  167738. if (cinfo->output_scanline == last_scanline)
  167739. return FALSE; /* No progress made, must suspend */
  167740. }
  167741. /* Finish up dummy pass, and set up for another one */
  167742. (*cinfo->master->finish_output_pass) (cinfo);
  167743. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167744. cinfo->output_scanline = 0;
  167745. #else
  167746. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167747. #endif /* QUANT_2PASS_SUPPORTED */
  167748. }
  167749. /* Ready for application to drive output pass through
  167750. * jpeg_read_scanlines or jpeg_read_raw_data.
  167751. */
  167752. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167753. return TRUE;
  167754. }
  167755. /*
  167756. * Read some scanlines of data from the JPEG decompressor.
  167757. *
  167758. * The return value will be the number of lines actually read.
  167759. * This may be less than the number requested in several cases,
  167760. * including bottom of image, data source suspension, and operating
  167761. * modes that emit multiple scanlines at a time.
  167762. *
  167763. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167764. * this likely signals an application programmer error. However,
  167765. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167766. */
  167767. GLOBAL(JDIMENSION)
  167768. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167769. JDIMENSION max_lines)
  167770. {
  167771. JDIMENSION row_ctr;
  167772. if (cinfo->global_state != DSTATE_SCANNING)
  167773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167774. if (cinfo->output_scanline >= cinfo->output_height) {
  167775. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167776. return 0;
  167777. }
  167778. /* Call progress monitor hook if present */
  167779. if (cinfo->progress != NULL) {
  167780. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167781. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167782. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167783. }
  167784. /* Process some data */
  167785. row_ctr = 0;
  167786. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167787. cinfo->output_scanline += row_ctr;
  167788. return row_ctr;
  167789. }
  167790. /*
  167791. * Alternate entry point to read raw data.
  167792. * Processes exactly one iMCU row per call, unless suspended.
  167793. */
  167794. GLOBAL(JDIMENSION)
  167795. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167796. JDIMENSION max_lines)
  167797. {
  167798. JDIMENSION lines_per_iMCU_row;
  167799. if (cinfo->global_state != DSTATE_RAW_OK)
  167800. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167801. if (cinfo->output_scanline >= cinfo->output_height) {
  167802. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167803. return 0;
  167804. }
  167805. /* Call progress monitor hook if present */
  167806. if (cinfo->progress != NULL) {
  167807. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167808. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167809. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167810. }
  167811. /* Verify that at least one iMCU row can be returned. */
  167812. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167813. if (max_lines < lines_per_iMCU_row)
  167814. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167815. /* Decompress directly into user's buffer. */
  167816. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167817. return 0; /* suspension forced, can do nothing more */
  167818. /* OK, we processed one iMCU row. */
  167819. cinfo->output_scanline += lines_per_iMCU_row;
  167820. return lines_per_iMCU_row;
  167821. }
  167822. /* Additional entry points for buffered-image mode. */
  167823. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167824. /*
  167825. * Initialize for an output pass in buffered-image mode.
  167826. */
  167827. GLOBAL(boolean)
  167828. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167829. {
  167830. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167831. cinfo->global_state != DSTATE_PRESCAN)
  167832. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167833. /* Limit scan number to valid range */
  167834. if (scan_number <= 0)
  167835. scan_number = 1;
  167836. if (cinfo->inputctl->eoi_reached &&
  167837. scan_number > cinfo->input_scan_number)
  167838. scan_number = cinfo->input_scan_number;
  167839. cinfo->output_scan_number = scan_number;
  167840. /* Perform any dummy output passes, and set up for the real pass */
  167841. return output_pass_setup(cinfo);
  167842. }
  167843. /*
  167844. * Finish up after an output pass in buffered-image mode.
  167845. *
  167846. * Returns FALSE if suspended. The return value need be inspected only if
  167847. * a suspending data source is used.
  167848. */
  167849. GLOBAL(boolean)
  167850. jpeg_finish_output (j_decompress_ptr cinfo)
  167851. {
  167852. if ((cinfo->global_state == DSTATE_SCANNING ||
  167853. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167854. /* Terminate this pass. */
  167855. /* We do not require the whole pass to have been completed. */
  167856. (*cinfo->master->finish_output_pass) (cinfo);
  167857. cinfo->global_state = DSTATE_BUFPOST;
  167858. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167859. /* BUFPOST = repeat call after a suspension, anything else is error */
  167860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167861. }
  167862. /* Read markers looking for SOS or EOI */
  167863. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167864. ! cinfo->inputctl->eoi_reached) {
  167865. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167866. return FALSE; /* Suspend, come back later */
  167867. }
  167868. cinfo->global_state = DSTATE_BUFIMAGE;
  167869. return TRUE;
  167870. }
  167871. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167872. /*** End of inlined file: jdapistd.c ***/
  167873. /*** Start of inlined file: jdapimin.c ***/
  167874. #define JPEG_INTERNALS
  167875. /*
  167876. * Initialization of a JPEG decompression object.
  167877. * The error manager must already be set up (in case memory manager fails).
  167878. */
  167879. GLOBAL(void)
  167880. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167881. {
  167882. int i;
  167883. /* Guard against version mismatches between library and caller. */
  167884. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167885. if (version != JPEG_LIB_VERSION)
  167886. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167887. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167888. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167889. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167890. /* For debugging purposes, we zero the whole master structure.
  167891. * But the application has already set the err pointer, and may have set
  167892. * client_data, so we have to save and restore those fields.
  167893. * Note: if application hasn't set client_data, tools like Purify may
  167894. * complain here.
  167895. */
  167896. {
  167897. struct jpeg_error_mgr * err = cinfo->err;
  167898. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167899. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167900. cinfo->err = err;
  167901. cinfo->client_data = client_data;
  167902. }
  167903. cinfo->is_decompressor = TRUE;
  167904. /* Initialize a memory manager instance for this object */
  167905. jinit_memory_mgr((j_common_ptr) cinfo);
  167906. /* Zero out pointers to permanent structures. */
  167907. cinfo->progress = NULL;
  167908. cinfo->src = NULL;
  167909. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167910. cinfo->quant_tbl_ptrs[i] = NULL;
  167911. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167912. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167913. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167914. }
  167915. /* Initialize marker processor so application can override methods
  167916. * for COM, APPn markers before calling jpeg_read_header.
  167917. */
  167918. cinfo->marker_list = NULL;
  167919. jinit_marker_reader(cinfo);
  167920. /* And initialize the overall input controller. */
  167921. jinit_input_controller(cinfo);
  167922. /* OK, I'm ready */
  167923. cinfo->global_state = DSTATE_START;
  167924. }
  167925. /*
  167926. * Destruction of a JPEG decompression object
  167927. */
  167928. GLOBAL(void)
  167929. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167930. {
  167931. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167932. }
  167933. /*
  167934. * Abort processing of a JPEG decompression operation,
  167935. * but don't destroy the object itself.
  167936. */
  167937. GLOBAL(void)
  167938. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167939. {
  167940. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167941. }
  167942. /*
  167943. * Set default decompression parameters.
  167944. */
  167945. LOCAL(void)
  167946. default_decompress_parms (j_decompress_ptr cinfo)
  167947. {
  167948. /* Guess the input colorspace, and set output colorspace accordingly. */
  167949. /* (Wish JPEG committee had provided a real way to specify this...) */
  167950. /* Note application may override our guesses. */
  167951. switch (cinfo->num_components) {
  167952. case 1:
  167953. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167954. cinfo->out_color_space = JCS_GRAYSCALE;
  167955. break;
  167956. case 3:
  167957. if (cinfo->saw_JFIF_marker) {
  167958. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167959. } else if (cinfo->saw_Adobe_marker) {
  167960. switch (cinfo->Adobe_transform) {
  167961. case 0:
  167962. cinfo->jpeg_color_space = JCS_RGB;
  167963. break;
  167964. case 1:
  167965. cinfo->jpeg_color_space = JCS_YCbCr;
  167966. break;
  167967. default:
  167968. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167969. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167970. break;
  167971. }
  167972. } else {
  167973. /* Saw no special markers, try to guess from the component IDs */
  167974. int cid0 = cinfo->comp_info[0].component_id;
  167975. int cid1 = cinfo->comp_info[1].component_id;
  167976. int cid2 = cinfo->comp_info[2].component_id;
  167977. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167978. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167979. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167980. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167981. else {
  167982. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167983. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167984. }
  167985. }
  167986. /* Always guess RGB is proper output colorspace. */
  167987. cinfo->out_color_space = JCS_RGB;
  167988. break;
  167989. case 4:
  167990. if (cinfo->saw_Adobe_marker) {
  167991. switch (cinfo->Adobe_transform) {
  167992. case 0:
  167993. cinfo->jpeg_color_space = JCS_CMYK;
  167994. break;
  167995. case 2:
  167996. cinfo->jpeg_color_space = JCS_YCCK;
  167997. break;
  167998. default:
  167999. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168000. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168001. break;
  168002. }
  168003. } else {
  168004. /* No special markers, assume straight CMYK. */
  168005. cinfo->jpeg_color_space = JCS_CMYK;
  168006. }
  168007. cinfo->out_color_space = JCS_CMYK;
  168008. break;
  168009. default:
  168010. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168011. cinfo->out_color_space = JCS_UNKNOWN;
  168012. break;
  168013. }
  168014. /* Set defaults for other decompression parameters. */
  168015. cinfo->scale_num = 1; /* 1:1 scaling */
  168016. cinfo->scale_denom = 1;
  168017. cinfo->output_gamma = 1.0;
  168018. cinfo->buffered_image = FALSE;
  168019. cinfo->raw_data_out = FALSE;
  168020. cinfo->dct_method = JDCT_DEFAULT;
  168021. cinfo->do_fancy_upsampling = TRUE;
  168022. cinfo->do_block_smoothing = TRUE;
  168023. cinfo->quantize_colors = FALSE;
  168024. /* We set these in case application only sets quantize_colors. */
  168025. cinfo->dither_mode = JDITHER_FS;
  168026. #ifdef QUANT_2PASS_SUPPORTED
  168027. cinfo->two_pass_quantize = TRUE;
  168028. #else
  168029. cinfo->two_pass_quantize = FALSE;
  168030. #endif
  168031. cinfo->desired_number_of_colors = 256;
  168032. cinfo->colormap = NULL;
  168033. /* Initialize for no mode change in buffered-image mode. */
  168034. cinfo->enable_1pass_quant = FALSE;
  168035. cinfo->enable_external_quant = FALSE;
  168036. cinfo->enable_2pass_quant = FALSE;
  168037. }
  168038. /*
  168039. * Decompression startup: read start of JPEG datastream to see what's there.
  168040. * Need only initialize JPEG object and supply a data source before calling.
  168041. *
  168042. * This routine will read as far as the first SOS marker (ie, actual start of
  168043. * compressed data), and will save all tables and parameters in the JPEG
  168044. * object. It will also initialize the decompression parameters to default
  168045. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168046. * adjust the decompression parameters and then call jpeg_start_decompress.
  168047. * (Or, if the application only wanted to determine the image parameters,
  168048. * the data need not be decompressed. In that case, call jpeg_abort or
  168049. * jpeg_destroy to release any temporary space.)
  168050. * If an abbreviated (tables only) datastream is presented, the routine will
  168051. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168052. * re-use the JPEG object to read the abbreviated image datastream(s).
  168053. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168054. * The JPEG_SUSPENDED return code only occurs if the data source module
  168055. * requests suspension of the decompressor. In this case the application
  168056. * should load more source data and then re-call jpeg_read_header to resume
  168057. * processing.
  168058. * If a non-suspending data source is used and require_image is TRUE, then the
  168059. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168060. *
  168061. * This routine is now just a front end to jpeg_consume_input, with some
  168062. * extra error checking.
  168063. */
  168064. GLOBAL(int)
  168065. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168066. {
  168067. int retcode;
  168068. if (cinfo->global_state != DSTATE_START &&
  168069. cinfo->global_state != DSTATE_INHEADER)
  168070. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168071. retcode = jpeg_consume_input(cinfo);
  168072. switch (retcode) {
  168073. case JPEG_REACHED_SOS:
  168074. retcode = JPEG_HEADER_OK;
  168075. break;
  168076. case JPEG_REACHED_EOI:
  168077. if (require_image) /* Complain if application wanted an image */
  168078. ERREXIT(cinfo, JERR_NO_IMAGE);
  168079. /* Reset to start state; it would be safer to require the application to
  168080. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168081. * A side effect is to free any temporary memory (there shouldn't be any).
  168082. */
  168083. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168084. retcode = JPEG_HEADER_TABLES_ONLY;
  168085. break;
  168086. case JPEG_SUSPENDED:
  168087. /* no work */
  168088. break;
  168089. }
  168090. return retcode;
  168091. }
  168092. /*
  168093. * Consume data in advance of what the decompressor requires.
  168094. * This can be called at any time once the decompressor object has
  168095. * been created and a data source has been set up.
  168096. *
  168097. * This routine is essentially a state machine that handles a couple
  168098. * of critical state-transition actions, namely initial setup and
  168099. * transition from header scanning to ready-for-start_decompress.
  168100. * All the actual input is done via the input controller's consume_input
  168101. * method.
  168102. */
  168103. GLOBAL(int)
  168104. jpeg_consume_input (j_decompress_ptr cinfo)
  168105. {
  168106. int retcode = JPEG_SUSPENDED;
  168107. /* NB: every possible DSTATE value should be listed in this switch */
  168108. switch (cinfo->global_state) {
  168109. case DSTATE_START:
  168110. /* Start-of-datastream actions: reset appropriate modules */
  168111. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168112. /* Initialize application's data source module */
  168113. (*cinfo->src->init_source) (cinfo);
  168114. cinfo->global_state = DSTATE_INHEADER;
  168115. /*FALLTHROUGH*/
  168116. case DSTATE_INHEADER:
  168117. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168118. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168119. /* Set up default parameters based on header data */
  168120. default_decompress_parms(cinfo);
  168121. /* Set global state: ready for start_decompress */
  168122. cinfo->global_state = DSTATE_READY;
  168123. }
  168124. break;
  168125. case DSTATE_READY:
  168126. /* Can't advance past first SOS until start_decompress is called */
  168127. retcode = JPEG_REACHED_SOS;
  168128. break;
  168129. case DSTATE_PRELOAD:
  168130. case DSTATE_PRESCAN:
  168131. case DSTATE_SCANNING:
  168132. case DSTATE_RAW_OK:
  168133. case DSTATE_BUFIMAGE:
  168134. case DSTATE_BUFPOST:
  168135. case DSTATE_STOPPING:
  168136. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168137. break;
  168138. default:
  168139. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168140. }
  168141. return retcode;
  168142. }
  168143. /*
  168144. * Have we finished reading the input file?
  168145. */
  168146. GLOBAL(boolean)
  168147. jpeg_input_complete (j_decompress_ptr cinfo)
  168148. {
  168149. /* Check for valid jpeg object */
  168150. if (cinfo->global_state < DSTATE_START ||
  168151. cinfo->global_state > DSTATE_STOPPING)
  168152. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168153. return cinfo->inputctl->eoi_reached;
  168154. }
  168155. /*
  168156. * Is there more than one scan?
  168157. */
  168158. GLOBAL(boolean)
  168159. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168160. {
  168161. /* Only valid after jpeg_read_header completes */
  168162. if (cinfo->global_state < DSTATE_READY ||
  168163. cinfo->global_state > DSTATE_STOPPING)
  168164. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168165. return cinfo->inputctl->has_multiple_scans;
  168166. }
  168167. /*
  168168. * Finish JPEG decompression.
  168169. *
  168170. * This will normally just verify the file trailer and release temp storage.
  168171. *
  168172. * Returns FALSE if suspended. The return value need be inspected only if
  168173. * a suspending data source is used.
  168174. */
  168175. GLOBAL(boolean)
  168176. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168177. {
  168178. if ((cinfo->global_state == DSTATE_SCANNING ||
  168179. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168180. /* Terminate final pass of non-buffered mode */
  168181. if (cinfo->output_scanline < cinfo->output_height)
  168182. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168183. (*cinfo->master->finish_output_pass) (cinfo);
  168184. cinfo->global_state = DSTATE_STOPPING;
  168185. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168186. /* Finishing after a buffered-image operation */
  168187. cinfo->global_state = DSTATE_STOPPING;
  168188. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168189. /* STOPPING = repeat call after a suspension, anything else is error */
  168190. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168191. }
  168192. /* Read until EOI */
  168193. while (! cinfo->inputctl->eoi_reached) {
  168194. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168195. return FALSE; /* Suspend, come back later */
  168196. }
  168197. /* Do final cleanup */
  168198. (*cinfo->src->term_source) (cinfo);
  168199. /* We can use jpeg_abort to release memory and reset global_state */
  168200. jpeg_abort((j_common_ptr) cinfo);
  168201. return TRUE;
  168202. }
  168203. /*** End of inlined file: jdapimin.c ***/
  168204. /*** Start of inlined file: jdatasrc.c ***/
  168205. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168206. /*** Start of inlined file: jerror.h ***/
  168207. /*
  168208. * To define the enum list of message codes, include this file without
  168209. * defining macro JMESSAGE. To create a message string table, include it
  168210. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168211. */
  168212. #ifndef JMESSAGE
  168213. #ifndef JERROR_H
  168214. /* First time through, define the enum list */
  168215. #define JMAKE_ENUM_LIST
  168216. #else
  168217. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168218. #define JMESSAGE(code,string)
  168219. #endif /* JERROR_H */
  168220. #endif /* JMESSAGE */
  168221. #ifdef JMAKE_ENUM_LIST
  168222. typedef enum {
  168223. #define JMESSAGE(code,string) code ,
  168224. #endif /* JMAKE_ENUM_LIST */
  168225. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168226. /* For maintenance convenience, list is alphabetical by message code name */
  168227. JMESSAGE(JERR_ARITH_NOTIMPL,
  168228. "Sorry, there are legal restrictions on arithmetic coding")
  168229. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168230. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168231. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168232. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168233. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168234. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168235. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168236. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168237. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168238. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168239. JMESSAGE(JERR_BAD_LIB_VERSION,
  168240. "Wrong JPEG library version: library is %d, caller expects %d")
  168241. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168242. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168243. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168244. JMESSAGE(JERR_BAD_PROGRESSION,
  168245. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168246. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168247. "Invalid progressive parameters at scan script entry %d")
  168248. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168249. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168250. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168251. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168252. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168253. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168254. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168255. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168256. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168257. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168258. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168259. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168260. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168261. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168262. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168263. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168264. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168265. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168266. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168267. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168268. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168269. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168270. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168271. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168272. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168273. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168274. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168275. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168276. "Cannot transcode due to multiple use of quantization table %d")
  168277. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168278. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168279. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168280. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168281. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168282. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168283. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168284. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168285. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168286. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168287. JMESSAGE(JERR_QUANT_COMPONENTS,
  168288. "Cannot quantize more than %d color components")
  168289. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168290. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168291. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168292. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168293. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168294. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168295. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168296. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168297. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168298. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168299. JMESSAGE(JERR_TFILE_WRITE,
  168300. "Write failed on temporary file --- out of disk space?")
  168301. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168302. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168303. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168304. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168305. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168306. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168307. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168308. JMESSAGE(JMSG_VERSION, JVERSION)
  168309. JMESSAGE(JTRC_16BIT_TABLES,
  168310. "Caution: quantization tables are too coarse for baseline JPEG")
  168311. JMESSAGE(JTRC_ADOBE,
  168312. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168313. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168314. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168315. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168316. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168317. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168318. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168319. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168320. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168321. JMESSAGE(JTRC_EOI, "End Of Image")
  168322. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168323. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168324. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168325. "Warning: thumbnail image size does not match data length %u")
  168326. JMESSAGE(JTRC_JFIF_EXTENSION,
  168327. "JFIF extension marker: type 0x%02x, length %u")
  168328. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168329. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168330. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168331. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168332. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168333. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168334. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168335. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168336. JMESSAGE(JTRC_RST, "RST%d")
  168337. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168338. "Smoothing not supported with nonstandard sampling ratios")
  168339. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168340. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168341. JMESSAGE(JTRC_SOI, "Start of Image")
  168342. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168343. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168344. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168345. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168346. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168347. JMESSAGE(JTRC_THUMB_JPEG,
  168348. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168349. JMESSAGE(JTRC_THUMB_PALETTE,
  168350. "JFIF extension marker: palette thumbnail image, length %u")
  168351. JMESSAGE(JTRC_THUMB_RGB,
  168352. "JFIF extension marker: RGB thumbnail image, length %u")
  168353. JMESSAGE(JTRC_UNKNOWN_IDS,
  168354. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168355. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168356. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168357. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168358. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168359. "Inconsistent progression sequence for component %d coefficient %d")
  168360. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168361. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168362. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168363. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168364. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168365. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168366. JMESSAGE(JWRN_MUST_RESYNC,
  168367. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168368. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168369. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168370. #ifdef JMAKE_ENUM_LIST
  168371. JMSG_LASTMSGCODE
  168372. } J_MESSAGE_CODE;
  168373. #undef JMAKE_ENUM_LIST
  168374. #endif /* JMAKE_ENUM_LIST */
  168375. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168376. #undef JMESSAGE
  168377. #ifndef JERROR_H
  168378. #define JERROR_H
  168379. /* Macros to simplify using the error and trace message stuff */
  168380. /* The first parameter is either type of cinfo pointer */
  168381. /* Fatal errors (print message and exit) */
  168382. #define ERREXIT(cinfo,code) \
  168383. ((cinfo)->err->msg_code = (code), \
  168384. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168385. #define ERREXIT1(cinfo,code,p1) \
  168386. ((cinfo)->err->msg_code = (code), \
  168387. (cinfo)->err->msg_parm.i[0] = (p1), \
  168388. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168389. #define ERREXIT2(cinfo,code,p1,p2) \
  168390. ((cinfo)->err->msg_code = (code), \
  168391. (cinfo)->err->msg_parm.i[0] = (p1), \
  168392. (cinfo)->err->msg_parm.i[1] = (p2), \
  168393. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168394. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168395. ((cinfo)->err->msg_code = (code), \
  168396. (cinfo)->err->msg_parm.i[0] = (p1), \
  168397. (cinfo)->err->msg_parm.i[1] = (p2), \
  168398. (cinfo)->err->msg_parm.i[2] = (p3), \
  168399. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168400. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168401. ((cinfo)->err->msg_code = (code), \
  168402. (cinfo)->err->msg_parm.i[0] = (p1), \
  168403. (cinfo)->err->msg_parm.i[1] = (p2), \
  168404. (cinfo)->err->msg_parm.i[2] = (p3), \
  168405. (cinfo)->err->msg_parm.i[3] = (p4), \
  168406. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168407. #define ERREXITS(cinfo,code,str) \
  168408. ((cinfo)->err->msg_code = (code), \
  168409. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168410. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168411. #define MAKESTMT(stuff) do { stuff } while (0)
  168412. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168413. #define WARNMS(cinfo,code) \
  168414. ((cinfo)->err->msg_code = (code), \
  168415. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168416. #define WARNMS1(cinfo,code,p1) \
  168417. ((cinfo)->err->msg_code = (code), \
  168418. (cinfo)->err->msg_parm.i[0] = (p1), \
  168419. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168420. #define WARNMS2(cinfo,code,p1,p2) \
  168421. ((cinfo)->err->msg_code = (code), \
  168422. (cinfo)->err->msg_parm.i[0] = (p1), \
  168423. (cinfo)->err->msg_parm.i[1] = (p2), \
  168424. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168425. /* Informational/debugging messages */
  168426. #define TRACEMS(cinfo,lvl,code) \
  168427. ((cinfo)->err->msg_code = (code), \
  168428. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168429. #define TRACEMS1(cinfo,lvl,code,p1) \
  168430. ((cinfo)->err->msg_code = (code), \
  168431. (cinfo)->err->msg_parm.i[0] = (p1), \
  168432. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168433. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168434. ((cinfo)->err->msg_code = (code), \
  168435. (cinfo)->err->msg_parm.i[0] = (p1), \
  168436. (cinfo)->err->msg_parm.i[1] = (p2), \
  168437. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168438. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168439. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168440. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168441. (cinfo)->err->msg_code = (code); \
  168442. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168443. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168444. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168445. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168446. (cinfo)->err->msg_code = (code); \
  168447. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168448. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168449. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168450. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168451. _mp[4] = (p5); \
  168452. (cinfo)->err->msg_code = (code); \
  168453. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168454. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168455. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168456. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168457. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168458. (cinfo)->err->msg_code = (code); \
  168459. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168460. #define TRACEMSS(cinfo,lvl,code,str) \
  168461. ((cinfo)->err->msg_code = (code), \
  168462. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168463. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168464. #endif /* JERROR_H */
  168465. /*** End of inlined file: jerror.h ***/
  168466. /* Expanded data source object for stdio input */
  168467. typedef struct {
  168468. struct jpeg_source_mgr pub; /* public fields */
  168469. FILE * infile; /* source stream */
  168470. JOCTET * buffer; /* start of buffer */
  168471. boolean start_of_file; /* have we gotten any data yet? */
  168472. } my_source_mgr;
  168473. typedef my_source_mgr * my_src_ptr;
  168474. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168475. /*
  168476. * Initialize source --- called by jpeg_read_header
  168477. * before any data is actually read.
  168478. */
  168479. METHODDEF(void)
  168480. init_source (j_decompress_ptr cinfo)
  168481. {
  168482. my_src_ptr src = (my_src_ptr) cinfo->src;
  168483. /* We reset the empty-input-file flag for each image,
  168484. * but we don't clear the input buffer.
  168485. * This is correct behavior for reading a series of images from one source.
  168486. */
  168487. src->start_of_file = TRUE;
  168488. }
  168489. /*
  168490. * Fill the input buffer --- called whenever buffer is emptied.
  168491. *
  168492. * In typical applications, this should read fresh data into the buffer
  168493. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168494. * reset the pointer & count to the start of the buffer, and return TRUE
  168495. * indicating that the buffer has been reloaded. It is not necessary to
  168496. * fill the buffer entirely, only to obtain at least one more byte.
  168497. *
  168498. * There is no such thing as an EOF return. If the end of the file has been
  168499. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168500. * the buffer. In most cases, generating a warning message and inserting a
  168501. * fake EOI marker is the best course of action --- this will allow the
  168502. * decompressor to output however much of the image is there. However,
  168503. * the resulting error message is misleading if the real problem is an empty
  168504. * input file, so we handle that case specially.
  168505. *
  168506. * In applications that need to be able to suspend compression due to input
  168507. * not being available yet, a FALSE return indicates that no more data can be
  168508. * obtained right now, but more may be forthcoming later. In this situation,
  168509. * the decompressor will return to its caller (with an indication of the
  168510. * number of scanlines it has read, if any). The application should resume
  168511. * decompression after it has loaded more data into the input buffer. Note
  168512. * that there are substantial restrictions on the use of suspension --- see
  168513. * the documentation.
  168514. *
  168515. * When suspending, the decompressor will back up to a convenient restart point
  168516. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168517. * indicate where the restart point will be if the current call returns FALSE.
  168518. * Data beyond this point must be rescanned after resumption, so move it to
  168519. * the front of the buffer rather than discarding it.
  168520. */
  168521. METHODDEF(boolean)
  168522. fill_input_buffer (j_decompress_ptr cinfo)
  168523. {
  168524. my_src_ptr src = (my_src_ptr) cinfo->src;
  168525. size_t nbytes;
  168526. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168527. if (nbytes <= 0) {
  168528. if (src->start_of_file) /* Treat empty input file as fatal error */
  168529. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168530. WARNMS(cinfo, JWRN_JPEG_EOF);
  168531. /* Insert a fake EOI marker */
  168532. src->buffer[0] = (JOCTET) 0xFF;
  168533. src->buffer[1] = (JOCTET) JPEG_EOI;
  168534. nbytes = 2;
  168535. }
  168536. src->pub.next_input_byte = src->buffer;
  168537. src->pub.bytes_in_buffer = nbytes;
  168538. src->start_of_file = FALSE;
  168539. return TRUE;
  168540. }
  168541. /*
  168542. * Skip data --- used to skip over a potentially large amount of
  168543. * uninteresting data (such as an APPn marker).
  168544. *
  168545. * Writers of suspendable-input applications must note that skip_input_data
  168546. * is not granted the right to give a suspension return. If the skip extends
  168547. * beyond the data currently in the buffer, the buffer can be marked empty so
  168548. * that the next read will cause a fill_input_buffer call that can suspend.
  168549. * Arranging for additional bytes to be discarded before reloading the input
  168550. * buffer is the application writer's problem.
  168551. */
  168552. METHODDEF(void)
  168553. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168554. {
  168555. my_src_ptr src = (my_src_ptr) cinfo->src;
  168556. /* Just a dumb implementation for now. Could use fseek() except
  168557. * it doesn't work on pipes. Not clear that being smart is worth
  168558. * any trouble anyway --- large skips are infrequent.
  168559. */
  168560. if (num_bytes > 0) {
  168561. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168562. num_bytes -= (long) src->pub.bytes_in_buffer;
  168563. (void) fill_input_buffer(cinfo);
  168564. /* note we assume that fill_input_buffer will never return FALSE,
  168565. * so suspension need not be handled.
  168566. */
  168567. }
  168568. src->pub.next_input_byte += (size_t) num_bytes;
  168569. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168570. }
  168571. }
  168572. /*
  168573. * An additional method that can be provided by data source modules is the
  168574. * resync_to_restart method for error recovery in the presence of RST markers.
  168575. * For the moment, this source module just uses the default resync method
  168576. * provided by the JPEG library. That method assumes that no backtracking
  168577. * is possible.
  168578. */
  168579. /*
  168580. * Terminate source --- called by jpeg_finish_decompress
  168581. * after all data has been read. Often a no-op.
  168582. *
  168583. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168584. * application must deal with any cleanup that should happen even
  168585. * for error exit.
  168586. */
  168587. METHODDEF(void)
  168588. term_source (j_decompress_ptr)
  168589. {
  168590. /* no work necessary here */
  168591. }
  168592. /*
  168593. * Prepare for input from a stdio stream.
  168594. * The caller must have already opened the stream, and is responsible
  168595. * for closing it after finishing decompression.
  168596. */
  168597. GLOBAL(void)
  168598. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168599. {
  168600. my_src_ptr src;
  168601. /* The source object and input buffer are made permanent so that a series
  168602. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168603. * only before the first one. (If we discarded the buffer at the end of
  168604. * one image, we'd likely lose the start of the next one.)
  168605. * This makes it unsafe to use this manager and a different source
  168606. * manager serially with the same JPEG object. Caveat programmer.
  168607. */
  168608. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168609. cinfo->src = (struct jpeg_source_mgr *)
  168610. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168611. SIZEOF(my_source_mgr));
  168612. src = (my_src_ptr) cinfo->src;
  168613. src->buffer = (JOCTET *)
  168614. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168615. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168616. }
  168617. src = (my_src_ptr) cinfo->src;
  168618. src->pub.init_source = init_source;
  168619. src->pub.fill_input_buffer = fill_input_buffer;
  168620. src->pub.skip_input_data = skip_input_data;
  168621. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168622. src->pub.term_source = term_source;
  168623. src->infile = infile;
  168624. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168625. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168626. }
  168627. /*** End of inlined file: jdatasrc.c ***/
  168628. /*** Start of inlined file: jdcoefct.c ***/
  168629. #define JPEG_INTERNALS
  168630. /* Block smoothing is only applicable for progressive JPEG, so: */
  168631. #ifndef D_PROGRESSIVE_SUPPORTED
  168632. #undef BLOCK_SMOOTHING_SUPPORTED
  168633. #endif
  168634. /* Private buffer controller object */
  168635. typedef struct {
  168636. struct jpeg_d_coef_controller pub; /* public fields */
  168637. /* These variables keep track of the current location of the input side. */
  168638. /* cinfo->input_iMCU_row is also used for this. */
  168639. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168640. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168641. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168642. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168643. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168644. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168645. * and let the entropy decoder write into that workspace each time.
  168646. * (On 80x86, the workspace is FAR even though it's not really very big;
  168647. * this is to keep the module interfaces unchanged when a large coefficient
  168648. * buffer is necessary.)
  168649. * In multi-pass modes, this array points to the current MCU's blocks
  168650. * within the virtual arrays; it is used only by the input side.
  168651. */
  168652. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168653. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168654. /* In multi-pass modes, we need a virtual block array for each component. */
  168655. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168656. #endif
  168657. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168658. /* When doing block smoothing, we latch coefficient Al values here */
  168659. int * coef_bits_latch;
  168660. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168661. #endif
  168662. } my_coef_controller3;
  168663. typedef my_coef_controller3 * my_coef_ptr3;
  168664. /* Forward declarations */
  168665. METHODDEF(int) decompress_onepass
  168666. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168667. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168668. METHODDEF(int) decompress_data
  168669. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168670. #endif
  168671. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168672. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168673. METHODDEF(int) decompress_smooth_data
  168674. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168675. #endif
  168676. LOCAL(void)
  168677. start_iMCU_row3 (j_decompress_ptr cinfo)
  168678. /* Reset within-iMCU-row counters for a new row (input side) */
  168679. {
  168680. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168681. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168682. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168683. * But at the bottom of the image, process only what's left.
  168684. */
  168685. if (cinfo->comps_in_scan > 1) {
  168686. coef->MCU_rows_per_iMCU_row = 1;
  168687. } else {
  168688. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168689. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168690. else
  168691. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168692. }
  168693. coef->MCU_ctr = 0;
  168694. coef->MCU_vert_offset = 0;
  168695. }
  168696. /*
  168697. * Initialize for an input processing pass.
  168698. */
  168699. METHODDEF(void)
  168700. start_input_pass (j_decompress_ptr cinfo)
  168701. {
  168702. cinfo->input_iMCU_row = 0;
  168703. start_iMCU_row3(cinfo);
  168704. }
  168705. /*
  168706. * Initialize for an output processing pass.
  168707. */
  168708. METHODDEF(void)
  168709. start_output_pass (j_decompress_ptr cinfo)
  168710. {
  168711. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168712. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168713. /* If multipass, check to see whether to use block smoothing on this pass */
  168714. if (coef->pub.coef_arrays != NULL) {
  168715. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168716. coef->pub.decompress_data = decompress_smooth_data;
  168717. else
  168718. coef->pub.decompress_data = decompress_data;
  168719. }
  168720. #endif
  168721. cinfo->output_iMCU_row = 0;
  168722. }
  168723. /*
  168724. * Decompress and return some data in the single-pass case.
  168725. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168726. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168727. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168728. *
  168729. * NB: output_buf contains a plane for each component in image,
  168730. * which we index according to the component's SOF position.
  168731. */
  168732. METHODDEF(int)
  168733. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168734. {
  168735. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168736. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168737. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168738. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168739. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168740. JSAMPARRAY output_ptr;
  168741. JDIMENSION start_col, output_col;
  168742. jpeg_component_info *compptr;
  168743. inverse_DCT_method_ptr inverse_DCT;
  168744. /* Loop to process as much as one whole iMCU row */
  168745. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168746. yoffset++) {
  168747. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168748. MCU_col_num++) {
  168749. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168750. jzero_far((void FAR *) coef->MCU_buffer[0],
  168751. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168752. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168753. /* Suspension forced; update state counters and exit */
  168754. coef->MCU_vert_offset = yoffset;
  168755. coef->MCU_ctr = MCU_col_num;
  168756. return JPEG_SUSPENDED;
  168757. }
  168758. /* Determine where data should go in output_buf and do the IDCT thing.
  168759. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168760. * incremented past them!). Note the inner loop relies on having
  168761. * allocated the MCU_buffer[] blocks sequentially.
  168762. */
  168763. blkn = 0; /* index of current DCT block within MCU */
  168764. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168765. compptr = cinfo->cur_comp_info[ci];
  168766. /* Don't bother to IDCT an uninteresting component. */
  168767. if (! compptr->component_needed) {
  168768. blkn += compptr->MCU_blocks;
  168769. continue;
  168770. }
  168771. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168772. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168773. : compptr->last_col_width;
  168774. output_ptr = output_buf[compptr->component_index] +
  168775. yoffset * compptr->DCT_scaled_size;
  168776. start_col = MCU_col_num * compptr->MCU_sample_width;
  168777. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168778. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168779. yoffset+yindex < compptr->last_row_height) {
  168780. output_col = start_col;
  168781. for (xindex = 0; xindex < useful_width; xindex++) {
  168782. (*inverse_DCT) (cinfo, compptr,
  168783. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168784. output_ptr, output_col);
  168785. output_col += compptr->DCT_scaled_size;
  168786. }
  168787. }
  168788. blkn += compptr->MCU_width;
  168789. output_ptr += compptr->DCT_scaled_size;
  168790. }
  168791. }
  168792. }
  168793. /* Completed an MCU row, but perhaps not an iMCU row */
  168794. coef->MCU_ctr = 0;
  168795. }
  168796. /* Completed the iMCU row, advance counters for next one */
  168797. cinfo->output_iMCU_row++;
  168798. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168799. start_iMCU_row3(cinfo);
  168800. return JPEG_ROW_COMPLETED;
  168801. }
  168802. /* Completed the scan */
  168803. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168804. return JPEG_SCAN_COMPLETED;
  168805. }
  168806. /*
  168807. * Dummy consume-input routine for single-pass operation.
  168808. */
  168809. METHODDEF(int)
  168810. dummy_consume_data (j_decompress_ptr)
  168811. {
  168812. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168813. }
  168814. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168815. /*
  168816. * Consume input data and store it in the full-image coefficient buffer.
  168817. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168818. * ie, v_samp_factor block rows for each component in the scan.
  168819. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168820. */
  168821. METHODDEF(int)
  168822. consume_data (j_decompress_ptr cinfo)
  168823. {
  168824. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168825. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168826. int blkn, ci, xindex, yindex, yoffset;
  168827. JDIMENSION start_col;
  168828. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168829. JBLOCKROW buffer_ptr;
  168830. jpeg_component_info *compptr;
  168831. /* Align the virtual buffers for the components used in this scan. */
  168832. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168833. compptr = cinfo->cur_comp_info[ci];
  168834. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168835. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168836. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168837. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168838. /* Note: entropy decoder expects buffer to be zeroed,
  168839. * but this is handled automatically by the memory manager
  168840. * because we requested a pre-zeroed array.
  168841. */
  168842. }
  168843. /* Loop to process one whole iMCU row */
  168844. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168845. yoffset++) {
  168846. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168847. MCU_col_num++) {
  168848. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168849. blkn = 0; /* index of current DCT block within MCU */
  168850. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168851. compptr = cinfo->cur_comp_info[ci];
  168852. start_col = MCU_col_num * compptr->MCU_width;
  168853. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168854. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168855. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168856. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168857. }
  168858. }
  168859. }
  168860. /* Try to fetch the MCU. */
  168861. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168862. /* Suspension forced; update state counters and exit */
  168863. coef->MCU_vert_offset = yoffset;
  168864. coef->MCU_ctr = MCU_col_num;
  168865. return JPEG_SUSPENDED;
  168866. }
  168867. }
  168868. /* Completed an MCU row, but perhaps not an iMCU row */
  168869. coef->MCU_ctr = 0;
  168870. }
  168871. /* Completed the iMCU row, advance counters for next one */
  168872. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168873. start_iMCU_row3(cinfo);
  168874. return JPEG_ROW_COMPLETED;
  168875. }
  168876. /* Completed the scan */
  168877. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168878. return JPEG_SCAN_COMPLETED;
  168879. }
  168880. /*
  168881. * Decompress and return some data in the multi-pass case.
  168882. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168883. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168884. *
  168885. * NB: output_buf contains a plane for each component in image.
  168886. */
  168887. METHODDEF(int)
  168888. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168889. {
  168890. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168891. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168892. JDIMENSION block_num;
  168893. int ci, block_row, block_rows;
  168894. JBLOCKARRAY buffer;
  168895. JBLOCKROW buffer_ptr;
  168896. JSAMPARRAY output_ptr;
  168897. JDIMENSION output_col;
  168898. jpeg_component_info *compptr;
  168899. inverse_DCT_method_ptr inverse_DCT;
  168900. /* Force some input to be done if we are getting ahead of the input. */
  168901. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168902. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168903. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168904. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168905. return JPEG_SUSPENDED;
  168906. }
  168907. /* OK, output from the virtual arrays. */
  168908. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168909. ci++, compptr++) {
  168910. /* Don't bother to IDCT an uninteresting component. */
  168911. if (! compptr->component_needed)
  168912. continue;
  168913. /* Align the virtual buffer for this component. */
  168914. buffer = (*cinfo->mem->access_virt_barray)
  168915. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168916. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168917. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168918. /* Count non-dummy DCT block rows in this iMCU row. */
  168919. if (cinfo->output_iMCU_row < last_iMCU_row)
  168920. block_rows = compptr->v_samp_factor;
  168921. else {
  168922. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168923. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168924. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168925. }
  168926. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168927. output_ptr = output_buf[ci];
  168928. /* Loop over all DCT blocks to be processed. */
  168929. for (block_row = 0; block_row < block_rows; block_row++) {
  168930. buffer_ptr = buffer[block_row];
  168931. output_col = 0;
  168932. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168933. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168934. output_ptr, output_col);
  168935. buffer_ptr++;
  168936. output_col += compptr->DCT_scaled_size;
  168937. }
  168938. output_ptr += compptr->DCT_scaled_size;
  168939. }
  168940. }
  168941. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168942. return JPEG_ROW_COMPLETED;
  168943. return JPEG_SCAN_COMPLETED;
  168944. }
  168945. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168946. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168947. /*
  168948. * This code applies interblock smoothing as described by section K.8
  168949. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168950. * the DC values of a DCT block and its 8 neighboring blocks.
  168951. * We apply smoothing only for progressive JPEG decoding, and only if
  168952. * the coefficients it can estimate are not yet known to full precision.
  168953. */
  168954. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168955. #define Q01_POS 1
  168956. #define Q10_POS 8
  168957. #define Q20_POS 16
  168958. #define Q11_POS 9
  168959. #define Q02_POS 2
  168960. /*
  168961. * Determine whether block smoothing is applicable and safe.
  168962. * We also latch the current states of the coef_bits[] entries for the
  168963. * AC coefficients; otherwise, if the input side of the decompressor
  168964. * advances into a new scan, we might think the coefficients are known
  168965. * more accurately than they really are.
  168966. */
  168967. LOCAL(boolean)
  168968. smoothing_ok (j_decompress_ptr cinfo)
  168969. {
  168970. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168971. boolean smoothing_useful = FALSE;
  168972. int ci, coefi;
  168973. jpeg_component_info *compptr;
  168974. JQUANT_TBL * qtable;
  168975. int * coef_bits;
  168976. int * coef_bits_latch;
  168977. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168978. return FALSE;
  168979. /* Allocate latch area if not already done */
  168980. if (coef->coef_bits_latch == NULL)
  168981. coef->coef_bits_latch = (int *)
  168982. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168983. cinfo->num_components *
  168984. (SAVED_COEFS * SIZEOF(int)));
  168985. coef_bits_latch = coef->coef_bits_latch;
  168986. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168987. ci++, compptr++) {
  168988. /* All components' quantization values must already be latched. */
  168989. if ((qtable = compptr->quant_table) == NULL)
  168990. return FALSE;
  168991. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168992. if (qtable->quantval[0] == 0 ||
  168993. qtable->quantval[Q01_POS] == 0 ||
  168994. qtable->quantval[Q10_POS] == 0 ||
  168995. qtable->quantval[Q20_POS] == 0 ||
  168996. qtable->quantval[Q11_POS] == 0 ||
  168997. qtable->quantval[Q02_POS] == 0)
  168998. return FALSE;
  168999. /* DC values must be at least partly known for all components. */
  169000. coef_bits = cinfo->coef_bits[ci];
  169001. if (coef_bits[0] < 0)
  169002. return FALSE;
  169003. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169004. for (coefi = 1; coefi <= 5; coefi++) {
  169005. coef_bits_latch[coefi] = coef_bits[coefi];
  169006. if (coef_bits[coefi] != 0)
  169007. smoothing_useful = TRUE;
  169008. }
  169009. coef_bits_latch += SAVED_COEFS;
  169010. }
  169011. return smoothing_useful;
  169012. }
  169013. /*
  169014. * Variant of decompress_data for use when doing block smoothing.
  169015. */
  169016. METHODDEF(int)
  169017. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169018. {
  169019. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169020. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169021. JDIMENSION block_num, last_block_column;
  169022. int ci, block_row, block_rows, access_rows;
  169023. JBLOCKARRAY buffer;
  169024. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169025. JSAMPARRAY output_ptr;
  169026. JDIMENSION output_col;
  169027. jpeg_component_info *compptr;
  169028. inverse_DCT_method_ptr inverse_DCT;
  169029. boolean first_row, last_row;
  169030. JBLOCK workspace;
  169031. int *coef_bits;
  169032. JQUANT_TBL *quanttbl;
  169033. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169034. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169035. int Al, pred;
  169036. /* Force some input to be done if we are getting ahead of the input. */
  169037. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169038. ! cinfo->inputctl->eoi_reached) {
  169039. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169040. /* If input is working on current scan, we ordinarily want it to
  169041. * have completed the current row. But if input scan is DC,
  169042. * we want it to keep one row ahead so that next block row's DC
  169043. * values are up to date.
  169044. */
  169045. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169046. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169047. break;
  169048. }
  169049. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169050. return JPEG_SUSPENDED;
  169051. }
  169052. /* OK, output from the virtual arrays. */
  169053. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169054. ci++, compptr++) {
  169055. /* Don't bother to IDCT an uninteresting component. */
  169056. if (! compptr->component_needed)
  169057. continue;
  169058. /* Count non-dummy DCT block rows in this iMCU row. */
  169059. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169060. block_rows = compptr->v_samp_factor;
  169061. access_rows = block_rows * 2; /* this and next iMCU row */
  169062. last_row = FALSE;
  169063. } else {
  169064. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169065. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169066. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169067. access_rows = block_rows; /* this iMCU row only */
  169068. last_row = TRUE;
  169069. }
  169070. /* Align the virtual buffer for this component. */
  169071. if (cinfo->output_iMCU_row > 0) {
  169072. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169073. buffer = (*cinfo->mem->access_virt_barray)
  169074. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169075. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169076. (JDIMENSION) access_rows, FALSE);
  169077. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169078. first_row = FALSE;
  169079. } else {
  169080. buffer = (*cinfo->mem->access_virt_barray)
  169081. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169082. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169083. first_row = TRUE;
  169084. }
  169085. /* Fetch component-dependent info */
  169086. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169087. quanttbl = compptr->quant_table;
  169088. Q00 = quanttbl->quantval[0];
  169089. Q01 = quanttbl->quantval[Q01_POS];
  169090. Q10 = quanttbl->quantval[Q10_POS];
  169091. Q20 = quanttbl->quantval[Q20_POS];
  169092. Q11 = quanttbl->quantval[Q11_POS];
  169093. Q02 = quanttbl->quantval[Q02_POS];
  169094. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169095. output_ptr = output_buf[ci];
  169096. /* Loop over all DCT blocks to be processed. */
  169097. for (block_row = 0; block_row < block_rows; block_row++) {
  169098. buffer_ptr = buffer[block_row];
  169099. if (first_row && block_row == 0)
  169100. prev_block_row = buffer_ptr;
  169101. else
  169102. prev_block_row = buffer[block_row-1];
  169103. if (last_row && block_row == block_rows-1)
  169104. next_block_row = buffer_ptr;
  169105. else
  169106. next_block_row = buffer[block_row+1];
  169107. /* We fetch the surrounding DC values using a sliding-register approach.
  169108. * Initialize all nine here so as to do the right thing on narrow pics.
  169109. */
  169110. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169111. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169112. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169113. output_col = 0;
  169114. last_block_column = compptr->width_in_blocks - 1;
  169115. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169116. /* Fetch current DCT block into workspace so we can modify it. */
  169117. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169118. /* Update DC values */
  169119. if (block_num < last_block_column) {
  169120. DC3 = (int) prev_block_row[1][0];
  169121. DC6 = (int) buffer_ptr[1][0];
  169122. DC9 = (int) next_block_row[1][0];
  169123. }
  169124. /* Compute coefficient estimates per K.8.
  169125. * An estimate is applied only if coefficient is still zero,
  169126. * and is not known to be fully accurate.
  169127. */
  169128. /* AC01 */
  169129. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169130. num = 36 * Q00 * (DC4 - DC6);
  169131. if (num >= 0) {
  169132. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169133. if (Al > 0 && pred >= (1<<Al))
  169134. pred = (1<<Al)-1;
  169135. } else {
  169136. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169137. if (Al > 0 && pred >= (1<<Al))
  169138. pred = (1<<Al)-1;
  169139. pred = -pred;
  169140. }
  169141. workspace[1] = (JCOEF) pred;
  169142. }
  169143. /* AC10 */
  169144. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169145. num = 36 * Q00 * (DC2 - DC8);
  169146. if (num >= 0) {
  169147. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169148. if (Al > 0 && pred >= (1<<Al))
  169149. pred = (1<<Al)-1;
  169150. } else {
  169151. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169152. if (Al > 0 && pred >= (1<<Al))
  169153. pred = (1<<Al)-1;
  169154. pred = -pred;
  169155. }
  169156. workspace[8] = (JCOEF) pred;
  169157. }
  169158. /* AC20 */
  169159. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169160. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169161. if (num >= 0) {
  169162. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169163. if (Al > 0 && pred >= (1<<Al))
  169164. pred = (1<<Al)-1;
  169165. } else {
  169166. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169167. if (Al > 0 && pred >= (1<<Al))
  169168. pred = (1<<Al)-1;
  169169. pred = -pred;
  169170. }
  169171. workspace[16] = (JCOEF) pred;
  169172. }
  169173. /* AC11 */
  169174. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169175. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169176. if (num >= 0) {
  169177. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169178. if (Al > 0 && pred >= (1<<Al))
  169179. pred = (1<<Al)-1;
  169180. } else {
  169181. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169182. if (Al > 0 && pred >= (1<<Al))
  169183. pred = (1<<Al)-1;
  169184. pred = -pred;
  169185. }
  169186. workspace[9] = (JCOEF) pred;
  169187. }
  169188. /* AC02 */
  169189. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169190. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169191. if (num >= 0) {
  169192. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169193. if (Al > 0 && pred >= (1<<Al))
  169194. pred = (1<<Al)-1;
  169195. } else {
  169196. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169197. if (Al > 0 && pred >= (1<<Al))
  169198. pred = (1<<Al)-1;
  169199. pred = -pred;
  169200. }
  169201. workspace[2] = (JCOEF) pred;
  169202. }
  169203. /* OK, do the IDCT */
  169204. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169205. output_ptr, output_col);
  169206. /* Advance for next column */
  169207. DC1 = DC2; DC2 = DC3;
  169208. DC4 = DC5; DC5 = DC6;
  169209. DC7 = DC8; DC8 = DC9;
  169210. buffer_ptr++, prev_block_row++, next_block_row++;
  169211. output_col += compptr->DCT_scaled_size;
  169212. }
  169213. output_ptr += compptr->DCT_scaled_size;
  169214. }
  169215. }
  169216. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169217. return JPEG_ROW_COMPLETED;
  169218. return JPEG_SCAN_COMPLETED;
  169219. }
  169220. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169221. /*
  169222. * Initialize coefficient buffer controller.
  169223. */
  169224. GLOBAL(void)
  169225. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169226. {
  169227. my_coef_ptr3 coef;
  169228. coef = (my_coef_ptr3)
  169229. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169230. SIZEOF(my_coef_controller3));
  169231. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169232. coef->pub.start_input_pass = start_input_pass;
  169233. coef->pub.start_output_pass = start_output_pass;
  169234. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169235. coef->coef_bits_latch = NULL;
  169236. #endif
  169237. /* Create the coefficient buffer. */
  169238. if (need_full_buffer) {
  169239. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169240. /* Allocate a full-image virtual array for each component, */
  169241. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169242. /* Note we ask for a pre-zeroed array. */
  169243. int ci, access_rows;
  169244. jpeg_component_info *compptr;
  169245. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169246. ci++, compptr++) {
  169247. access_rows = compptr->v_samp_factor;
  169248. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169249. /* If block smoothing could be used, need a bigger window */
  169250. if (cinfo->progressive_mode)
  169251. access_rows *= 3;
  169252. #endif
  169253. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169254. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169255. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169256. (long) compptr->h_samp_factor),
  169257. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169258. (long) compptr->v_samp_factor),
  169259. (JDIMENSION) access_rows);
  169260. }
  169261. coef->pub.consume_data = consume_data;
  169262. coef->pub.decompress_data = decompress_data;
  169263. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169264. #else
  169265. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169266. #endif
  169267. } else {
  169268. /* We only need a single-MCU buffer. */
  169269. JBLOCKROW buffer;
  169270. int i;
  169271. buffer = (JBLOCKROW)
  169272. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169273. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169274. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169275. coef->MCU_buffer[i] = buffer + i;
  169276. }
  169277. coef->pub.consume_data = dummy_consume_data;
  169278. coef->pub.decompress_data = decompress_onepass;
  169279. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169280. }
  169281. }
  169282. /*** End of inlined file: jdcoefct.c ***/
  169283. #undef FIX
  169284. /*** Start of inlined file: jdcolor.c ***/
  169285. #define JPEG_INTERNALS
  169286. /* Private subobject */
  169287. typedef struct {
  169288. struct jpeg_color_deconverter pub; /* public fields */
  169289. /* Private state for YCC->RGB conversion */
  169290. int * Cr_r_tab; /* => table for Cr to R conversion */
  169291. int * Cb_b_tab; /* => table for Cb to B conversion */
  169292. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169293. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169294. } my_color_deconverter2;
  169295. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169296. /**************** YCbCr -> RGB conversion: most common case **************/
  169297. /*
  169298. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169299. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169300. * The conversion equations to be implemented are therefore
  169301. * R = Y + 1.40200 * Cr
  169302. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169303. * B = Y + 1.77200 * Cb
  169304. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169305. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169306. *
  169307. * To avoid floating-point arithmetic, we represent the fractional constants
  169308. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169309. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169310. * Notice that Y, being an integral input, does not contribute any fraction
  169311. * so it need not participate in the rounding.
  169312. *
  169313. * For even more speed, we avoid doing any multiplications in the inner loop
  169314. * by precalculating the constants times Cb and Cr for all possible values.
  169315. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169316. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169317. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169318. * colorspace anyway.
  169319. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169320. * values for the G calculation are left scaled up, since we must add them
  169321. * together before rounding.
  169322. */
  169323. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169324. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169325. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169326. /*
  169327. * Initialize tables for YCC->RGB colorspace conversion.
  169328. */
  169329. LOCAL(void)
  169330. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169331. {
  169332. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169333. int i;
  169334. INT32 x;
  169335. SHIFT_TEMPS
  169336. cconvert->Cr_r_tab = (int *)
  169337. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169338. (MAXJSAMPLE+1) * SIZEOF(int));
  169339. cconvert->Cb_b_tab = (int *)
  169340. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169341. (MAXJSAMPLE+1) * SIZEOF(int));
  169342. cconvert->Cr_g_tab = (INT32 *)
  169343. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169344. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169345. cconvert->Cb_g_tab = (INT32 *)
  169346. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169347. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169348. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169349. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169350. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169351. /* Cr=>R value is nearest int to 1.40200 * x */
  169352. cconvert->Cr_r_tab[i] = (int)
  169353. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169354. /* Cb=>B value is nearest int to 1.77200 * x */
  169355. cconvert->Cb_b_tab[i] = (int)
  169356. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169357. /* Cr=>G value is scaled-up -0.71414 * x */
  169358. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169359. /* Cb=>G value is scaled-up -0.34414 * x */
  169360. /* We also add in ONE_HALF so that need not do it in inner loop */
  169361. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169362. }
  169363. }
  169364. /*
  169365. * Convert some rows of samples to the output colorspace.
  169366. *
  169367. * Note that we change from noninterleaved, one-plane-per-component format
  169368. * to interleaved-pixel format. The output buffer is therefore three times
  169369. * as wide as the input buffer.
  169370. * A starting row offset is provided only for the input buffer. The caller
  169371. * can easily adjust the passed output_buf value to accommodate any row
  169372. * offset required on that side.
  169373. */
  169374. METHODDEF(void)
  169375. ycc_rgb_convert (j_decompress_ptr cinfo,
  169376. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169377. JSAMPARRAY output_buf, int num_rows)
  169378. {
  169379. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169380. register int y, cb, cr;
  169381. register JSAMPROW outptr;
  169382. register JSAMPROW inptr0, inptr1, inptr2;
  169383. register JDIMENSION col;
  169384. JDIMENSION num_cols = cinfo->output_width;
  169385. /* copy these pointers into registers if possible */
  169386. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169387. register int * Crrtab = cconvert->Cr_r_tab;
  169388. register int * Cbbtab = cconvert->Cb_b_tab;
  169389. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169390. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169391. SHIFT_TEMPS
  169392. while (--num_rows >= 0) {
  169393. inptr0 = input_buf[0][input_row];
  169394. inptr1 = input_buf[1][input_row];
  169395. inptr2 = input_buf[2][input_row];
  169396. input_row++;
  169397. outptr = *output_buf++;
  169398. for (col = 0; col < num_cols; col++) {
  169399. y = GETJSAMPLE(inptr0[col]);
  169400. cb = GETJSAMPLE(inptr1[col]);
  169401. cr = GETJSAMPLE(inptr2[col]);
  169402. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169403. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169404. outptr[RGB_GREEN] = range_limit[y +
  169405. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169406. SCALEBITS))];
  169407. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169408. outptr += RGB_PIXELSIZE;
  169409. }
  169410. }
  169411. }
  169412. /**************** Cases other than YCbCr -> RGB **************/
  169413. /*
  169414. * Color conversion for no colorspace change: just copy the data,
  169415. * converting from separate-planes to interleaved representation.
  169416. */
  169417. METHODDEF(void)
  169418. null_convert2 (j_decompress_ptr cinfo,
  169419. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169420. JSAMPARRAY output_buf, int num_rows)
  169421. {
  169422. register JSAMPROW inptr, outptr;
  169423. register JDIMENSION count;
  169424. register int num_components = cinfo->num_components;
  169425. JDIMENSION num_cols = cinfo->output_width;
  169426. int ci;
  169427. while (--num_rows >= 0) {
  169428. for (ci = 0; ci < num_components; ci++) {
  169429. inptr = input_buf[ci][input_row];
  169430. outptr = output_buf[0] + ci;
  169431. for (count = num_cols; count > 0; count--) {
  169432. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169433. outptr += num_components;
  169434. }
  169435. }
  169436. input_row++;
  169437. output_buf++;
  169438. }
  169439. }
  169440. /*
  169441. * Color conversion for grayscale: just copy the data.
  169442. * This also works for YCbCr -> grayscale conversion, in which
  169443. * we just copy the Y (luminance) component and ignore chrominance.
  169444. */
  169445. METHODDEF(void)
  169446. grayscale_convert2 (j_decompress_ptr cinfo,
  169447. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169448. JSAMPARRAY output_buf, int num_rows)
  169449. {
  169450. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169451. num_rows, cinfo->output_width);
  169452. }
  169453. /*
  169454. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169455. * This is provided to support applications that don't want to cope
  169456. * with grayscale as a separate case.
  169457. */
  169458. METHODDEF(void)
  169459. gray_rgb_convert (j_decompress_ptr cinfo,
  169460. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169461. JSAMPARRAY output_buf, int num_rows)
  169462. {
  169463. register JSAMPROW inptr, outptr;
  169464. register JDIMENSION col;
  169465. JDIMENSION num_cols = cinfo->output_width;
  169466. while (--num_rows >= 0) {
  169467. inptr = input_buf[0][input_row++];
  169468. outptr = *output_buf++;
  169469. for (col = 0; col < num_cols; col++) {
  169470. /* We can dispense with GETJSAMPLE() here */
  169471. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169472. outptr += RGB_PIXELSIZE;
  169473. }
  169474. }
  169475. }
  169476. /*
  169477. * Adobe-style YCCK->CMYK conversion.
  169478. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169479. * conversion as above, while passing K (black) unchanged.
  169480. * We assume build_ycc_rgb_table has been called.
  169481. */
  169482. METHODDEF(void)
  169483. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169484. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169485. JSAMPARRAY output_buf, int num_rows)
  169486. {
  169487. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169488. register int y, cb, cr;
  169489. register JSAMPROW outptr;
  169490. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169491. register JDIMENSION col;
  169492. JDIMENSION num_cols = cinfo->output_width;
  169493. /* copy these pointers into registers if possible */
  169494. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169495. register int * Crrtab = cconvert->Cr_r_tab;
  169496. register int * Cbbtab = cconvert->Cb_b_tab;
  169497. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169498. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169499. SHIFT_TEMPS
  169500. while (--num_rows >= 0) {
  169501. inptr0 = input_buf[0][input_row];
  169502. inptr1 = input_buf[1][input_row];
  169503. inptr2 = input_buf[2][input_row];
  169504. inptr3 = input_buf[3][input_row];
  169505. input_row++;
  169506. outptr = *output_buf++;
  169507. for (col = 0; col < num_cols; col++) {
  169508. y = GETJSAMPLE(inptr0[col]);
  169509. cb = GETJSAMPLE(inptr1[col]);
  169510. cr = GETJSAMPLE(inptr2[col]);
  169511. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169512. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169513. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169514. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169515. SCALEBITS)))];
  169516. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169517. /* K passes through unchanged */
  169518. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169519. outptr += 4;
  169520. }
  169521. }
  169522. }
  169523. /*
  169524. * Empty method for start_pass.
  169525. */
  169526. METHODDEF(void)
  169527. start_pass_dcolor (j_decompress_ptr)
  169528. {
  169529. /* no work needed */
  169530. }
  169531. /*
  169532. * Module initialization routine for output colorspace conversion.
  169533. */
  169534. GLOBAL(void)
  169535. jinit_color_deconverter (j_decompress_ptr cinfo)
  169536. {
  169537. my_cconvert_ptr2 cconvert;
  169538. int ci;
  169539. cconvert = (my_cconvert_ptr2)
  169540. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169541. SIZEOF(my_color_deconverter2));
  169542. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169543. cconvert->pub.start_pass = start_pass_dcolor;
  169544. /* Make sure num_components agrees with jpeg_color_space */
  169545. switch (cinfo->jpeg_color_space) {
  169546. case JCS_GRAYSCALE:
  169547. if (cinfo->num_components != 1)
  169548. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169549. break;
  169550. case JCS_RGB:
  169551. case JCS_YCbCr:
  169552. if (cinfo->num_components != 3)
  169553. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169554. break;
  169555. case JCS_CMYK:
  169556. case JCS_YCCK:
  169557. if (cinfo->num_components != 4)
  169558. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169559. break;
  169560. default: /* JCS_UNKNOWN can be anything */
  169561. if (cinfo->num_components < 1)
  169562. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169563. break;
  169564. }
  169565. /* Set out_color_components and conversion method based on requested space.
  169566. * Also clear the component_needed flags for any unused components,
  169567. * so that earlier pipeline stages can avoid useless computation.
  169568. */
  169569. switch (cinfo->out_color_space) {
  169570. case JCS_GRAYSCALE:
  169571. cinfo->out_color_components = 1;
  169572. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169573. cinfo->jpeg_color_space == JCS_YCbCr) {
  169574. cconvert->pub.color_convert = grayscale_convert2;
  169575. /* For color->grayscale conversion, only the Y (0) component is needed */
  169576. for (ci = 1; ci < cinfo->num_components; ci++)
  169577. cinfo->comp_info[ci].component_needed = FALSE;
  169578. } else
  169579. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169580. break;
  169581. case JCS_RGB:
  169582. cinfo->out_color_components = RGB_PIXELSIZE;
  169583. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169584. cconvert->pub.color_convert = ycc_rgb_convert;
  169585. build_ycc_rgb_table(cinfo);
  169586. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169587. cconvert->pub.color_convert = gray_rgb_convert;
  169588. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169589. cconvert->pub.color_convert = null_convert2;
  169590. } else
  169591. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169592. break;
  169593. case JCS_CMYK:
  169594. cinfo->out_color_components = 4;
  169595. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169596. cconvert->pub.color_convert = ycck_cmyk_convert;
  169597. build_ycc_rgb_table(cinfo);
  169598. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169599. cconvert->pub.color_convert = null_convert2;
  169600. } else
  169601. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169602. break;
  169603. default:
  169604. /* Permit null conversion to same output space */
  169605. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169606. cinfo->out_color_components = cinfo->num_components;
  169607. cconvert->pub.color_convert = null_convert2;
  169608. } else /* unsupported non-null conversion */
  169609. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169610. break;
  169611. }
  169612. if (cinfo->quantize_colors)
  169613. cinfo->output_components = 1; /* single colormapped output component */
  169614. else
  169615. cinfo->output_components = cinfo->out_color_components;
  169616. }
  169617. /*** End of inlined file: jdcolor.c ***/
  169618. #undef FIX
  169619. /*** Start of inlined file: jddctmgr.c ***/
  169620. #define JPEG_INTERNALS
  169621. /*
  169622. * The decompressor input side (jdinput.c) saves away the appropriate
  169623. * quantization table for each component at the start of the first scan
  169624. * involving that component. (This is necessary in order to correctly
  169625. * decode files that reuse Q-table slots.)
  169626. * When we are ready to make an output pass, the saved Q-table is converted
  169627. * to a multiplier table that will actually be used by the IDCT routine.
  169628. * The multiplier table contents are IDCT-method-dependent. To support
  169629. * application changes in IDCT method between scans, we can remake the
  169630. * multiplier tables if necessary.
  169631. * In buffered-image mode, the first output pass may occur before any data
  169632. * has been seen for some components, and thus before their Q-tables have
  169633. * been saved away. To handle this case, multiplier tables are preset
  169634. * to zeroes; the result of the IDCT will be a neutral gray level.
  169635. */
  169636. /* Private subobject for this module */
  169637. typedef struct {
  169638. struct jpeg_inverse_dct pub; /* public fields */
  169639. /* This array contains the IDCT method code that each multiplier table
  169640. * is currently set up for, or -1 if it's not yet set up.
  169641. * The actual multiplier tables are pointed to by dct_table in the
  169642. * per-component comp_info structures.
  169643. */
  169644. int cur_method[MAX_COMPONENTS];
  169645. } my_idct_controller;
  169646. typedef my_idct_controller * my_idct_ptr;
  169647. /* Allocated multiplier tables: big enough for any supported variant */
  169648. typedef union {
  169649. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169650. #ifdef DCT_IFAST_SUPPORTED
  169651. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169652. #endif
  169653. #ifdef DCT_FLOAT_SUPPORTED
  169654. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169655. #endif
  169656. } multiplier_table;
  169657. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169658. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169659. */
  169660. #ifdef DCT_ISLOW_SUPPORTED
  169661. #define PROVIDE_ISLOW_TABLES
  169662. #else
  169663. #ifdef IDCT_SCALING_SUPPORTED
  169664. #define PROVIDE_ISLOW_TABLES
  169665. #endif
  169666. #endif
  169667. /*
  169668. * Prepare for an output pass.
  169669. * Here we select the proper IDCT routine for each component and build
  169670. * a matching multiplier table.
  169671. */
  169672. METHODDEF(void)
  169673. start_pass (j_decompress_ptr cinfo)
  169674. {
  169675. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169676. int ci, i;
  169677. jpeg_component_info *compptr;
  169678. int method = 0;
  169679. inverse_DCT_method_ptr method_ptr = NULL;
  169680. JQUANT_TBL * qtbl;
  169681. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169682. ci++, compptr++) {
  169683. /* Select the proper IDCT routine for this component's scaling */
  169684. switch (compptr->DCT_scaled_size) {
  169685. #ifdef IDCT_SCALING_SUPPORTED
  169686. case 1:
  169687. method_ptr = jpeg_idct_1x1;
  169688. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169689. break;
  169690. case 2:
  169691. method_ptr = jpeg_idct_2x2;
  169692. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169693. break;
  169694. case 4:
  169695. method_ptr = jpeg_idct_4x4;
  169696. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169697. break;
  169698. #endif
  169699. case DCTSIZE:
  169700. switch (cinfo->dct_method) {
  169701. #ifdef DCT_ISLOW_SUPPORTED
  169702. case JDCT_ISLOW:
  169703. method_ptr = jpeg_idct_islow;
  169704. method = JDCT_ISLOW;
  169705. break;
  169706. #endif
  169707. #ifdef DCT_IFAST_SUPPORTED
  169708. case JDCT_IFAST:
  169709. method_ptr = jpeg_idct_ifast;
  169710. method = JDCT_IFAST;
  169711. break;
  169712. #endif
  169713. #ifdef DCT_FLOAT_SUPPORTED
  169714. case JDCT_FLOAT:
  169715. method_ptr = jpeg_idct_float;
  169716. method = JDCT_FLOAT;
  169717. break;
  169718. #endif
  169719. default:
  169720. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169721. break;
  169722. }
  169723. break;
  169724. default:
  169725. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169726. break;
  169727. }
  169728. idct->pub.inverse_DCT[ci] = method_ptr;
  169729. /* Create multiplier table from quant table.
  169730. * However, we can skip this if the component is uninteresting
  169731. * or if we already built the table. Also, if no quant table
  169732. * has yet been saved for the component, we leave the
  169733. * multiplier table all-zero; we'll be reading zeroes from the
  169734. * coefficient controller's buffer anyway.
  169735. */
  169736. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169737. continue;
  169738. qtbl = compptr->quant_table;
  169739. if (qtbl == NULL) /* happens if no data yet for component */
  169740. continue;
  169741. idct->cur_method[ci] = method;
  169742. switch (method) {
  169743. #ifdef PROVIDE_ISLOW_TABLES
  169744. case JDCT_ISLOW:
  169745. {
  169746. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169747. * coefficients, but are stored as ints to ensure access efficiency.
  169748. */
  169749. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169750. for (i = 0; i < DCTSIZE2; i++) {
  169751. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169752. }
  169753. }
  169754. break;
  169755. #endif
  169756. #ifdef DCT_IFAST_SUPPORTED
  169757. case JDCT_IFAST:
  169758. {
  169759. /* For AA&N IDCT method, multipliers are equal to quantization
  169760. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169761. * scalefactor[0] = 1
  169762. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169763. * For integer operation, the multiplier table is to be scaled by
  169764. * IFAST_SCALE_BITS.
  169765. */
  169766. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169767. #define CONST_BITS 14
  169768. static const INT16 aanscales[DCTSIZE2] = {
  169769. /* precomputed values scaled up by 14 bits */
  169770. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169771. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169772. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169773. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169774. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169775. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169776. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169777. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169778. };
  169779. SHIFT_TEMPS
  169780. for (i = 0; i < DCTSIZE2; i++) {
  169781. ifmtbl[i] = (IFAST_MULT_TYPE)
  169782. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169783. (INT32) aanscales[i]),
  169784. CONST_BITS-IFAST_SCALE_BITS);
  169785. }
  169786. }
  169787. break;
  169788. #endif
  169789. #ifdef DCT_FLOAT_SUPPORTED
  169790. case JDCT_FLOAT:
  169791. {
  169792. /* For float AA&N IDCT method, multipliers are equal to quantization
  169793. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169794. * scalefactor[0] = 1
  169795. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169796. */
  169797. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169798. int row, col;
  169799. static const double aanscalefactor[DCTSIZE] = {
  169800. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169801. 1.0, 0.785694958, 0.541196100, 0.275899379
  169802. };
  169803. i = 0;
  169804. for (row = 0; row < DCTSIZE; row++) {
  169805. for (col = 0; col < DCTSIZE; col++) {
  169806. fmtbl[i] = (FLOAT_MULT_TYPE)
  169807. ((double) qtbl->quantval[i] *
  169808. aanscalefactor[row] * aanscalefactor[col]);
  169809. i++;
  169810. }
  169811. }
  169812. }
  169813. break;
  169814. #endif
  169815. default:
  169816. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169817. break;
  169818. }
  169819. }
  169820. }
  169821. /*
  169822. * Initialize IDCT manager.
  169823. */
  169824. GLOBAL(void)
  169825. jinit_inverse_dct (j_decompress_ptr cinfo)
  169826. {
  169827. my_idct_ptr idct;
  169828. int ci;
  169829. jpeg_component_info *compptr;
  169830. idct = (my_idct_ptr)
  169831. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169832. SIZEOF(my_idct_controller));
  169833. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169834. idct->pub.start_pass = start_pass;
  169835. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169836. ci++, compptr++) {
  169837. /* Allocate and pre-zero a multiplier table for each component */
  169838. compptr->dct_table =
  169839. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169840. SIZEOF(multiplier_table));
  169841. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169842. /* Mark multiplier table not yet set up for any method */
  169843. idct->cur_method[ci] = -1;
  169844. }
  169845. }
  169846. /*** End of inlined file: jddctmgr.c ***/
  169847. #undef CONST_BITS
  169848. #undef ASSIGN_STATE
  169849. /*** Start of inlined file: jdhuff.c ***/
  169850. #define JPEG_INTERNALS
  169851. /*** Start of inlined file: jdhuff.h ***/
  169852. /* Short forms of external names for systems with brain-damaged linkers. */
  169853. #ifndef __jdhuff_h__
  169854. #define __jdhuff_h__
  169855. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169856. #define jpeg_make_d_derived_tbl jMkDDerived
  169857. #define jpeg_fill_bit_buffer jFilBitBuf
  169858. #define jpeg_huff_decode jHufDecode
  169859. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169860. /* Derived data constructed for each Huffman table */
  169861. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169862. typedef struct {
  169863. /* Basic tables: (element [0] of each array is unused) */
  169864. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169865. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169866. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169867. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169868. * the smallest code of length k; so given a code of length k, the
  169869. * corresponding symbol is huffval[code + valoffset[k]]
  169870. */
  169871. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169872. JHUFF_TBL *pub;
  169873. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169874. * the input data stream. If the next Huffman code is no more
  169875. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169876. * the corresponding symbol directly from these tables.
  169877. */
  169878. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169879. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169880. } d_derived_tbl;
  169881. /* Expand a Huffman table definition into the derived format */
  169882. EXTERN(void) jpeg_make_d_derived_tbl
  169883. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169884. d_derived_tbl ** pdtbl));
  169885. /*
  169886. * Fetching the next N bits from the input stream is a time-critical operation
  169887. * for the Huffman decoders. We implement it with a combination of inline
  169888. * macros and out-of-line subroutines. Note that N (the number of bits
  169889. * demanded at one time) never exceeds 15 for JPEG use.
  169890. *
  169891. * We read source bytes into get_buffer and dole out bits as needed.
  169892. * If get_buffer already contains enough bits, they are fetched in-line
  169893. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169894. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169895. * as full as possible (not just to the number of bits needed; this
  169896. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169897. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169898. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169899. * at least the requested number of bits --- dummy zeroes are inserted if
  169900. * necessary.
  169901. */
  169902. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169903. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169904. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169905. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169906. * appropriately should be a win. Unfortunately we can't define the size
  169907. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169908. * because not all machines measure sizeof in 8-bit bytes.
  169909. */
  169910. typedef struct { /* Bitreading state saved across MCUs */
  169911. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169912. int bits_left; /* # of unused bits in it */
  169913. } bitread_perm_state;
  169914. typedef struct { /* Bitreading working state within an MCU */
  169915. /* Current data source location */
  169916. /* We need a copy, rather than munging the original, in case of suspension */
  169917. const JOCTET * next_input_byte; /* => next byte to read from source */
  169918. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169919. /* Bit input buffer --- note these values are kept in register variables,
  169920. * not in this struct, inside the inner loops.
  169921. */
  169922. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169923. int bits_left; /* # of unused bits in it */
  169924. /* Pointer needed by jpeg_fill_bit_buffer. */
  169925. j_decompress_ptr cinfo; /* back link to decompress master record */
  169926. } bitread_working_state;
  169927. /* Macros to declare and load/save bitread local variables. */
  169928. #define BITREAD_STATE_VARS \
  169929. register bit_buf_type get_buffer; \
  169930. register int bits_left; \
  169931. bitread_working_state br_state
  169932. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169933. br_state.cinfo = cinfop; \
  169934. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169935. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169936. get_buffer = permstate.get_buffer; \
  169937. bits_left = permstate.bits_left;
  169938. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169939. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169940. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169941. permstate.get_buffer = get_buffer; \
  169942. permstate.bits_left = bits_left
  169943. /*
  169944. * These macros provide the in-line portion of bit fetching.
  169945. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169946. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169947. * The variables get_buffer and bits_left are assumed to be locals,
  169948. * but the state struct might not be (jpeg_huff_decode needs this).
  169949. * CHECK_BIT_BUFFER(state,n,action);
  169950. * Ensure there are N bits in get_buffer; if suspend, take action.
  169951. * val = GET_BITS(n);
  169952. * Fetch next N bits.
  169953. * val = PEEK_BITS(n);
  169954. * Fetch next N bits without removing them from the buffer.
  169955. * DROP_BITS(n);
  169956. * Discard next N bits.
  169957. * The value N should be a simple variable, not an expression, because it
  169958. * is evaluated multiple times.
  169959. */
  169960. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169961. { if (bits_left < (nbits)) { \
  169962. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169963. { action; } \
  169964. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169965. #define GET_BITS(nbits) \
  169966. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169967. #define PEEK_BITS(nbits) \
  169968. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169969. #define DROP_BITS(nbits) \
  169970. (bits_left -= (nbits))
  169971. /* Load up the bit buffer to a depth of at least nbits */
  169972. EXTERN(boolean) jpeg_fill_bit_buffer
  169973. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169974. register int bits_left, int nbits));
  169975. /*
  169976. * Code for extracting next Huffman-coded symbol from input bit stream.
  169977. * Again, this is time-critical and we make the main paths be macros.
  169978. *
  169979. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169980. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169981. * or fewer bits long. The few overlength codes are handled with a loop,
  169982. * which need not be inline code.
  169983. *
  169984. * Notes about the HUFF_DECODE macro:
  169985. * 1. Near the end of the data segment, we may fail to get enough bits
  169986. * for a lookahead. In that case, we do it the hard way.
  169987. * 2. If the lookahead table contains no entry, the next code must be
  169988. * more than HUFF_LOOKAHEAD bits long.
  169989. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169990. */
  169991. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169992. { register int nb, look; \
  169993. if (bits_left < HUFF_LOOKAHEAD) { \
  169994. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169995. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169996. if (bits_left < HUFF_LOOKAHEAD) { \
  169997. nb = 1; goto slowlabel; \
  169998. } \
  169999. } \
  170000. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170001. if ((nb = htbl->look_nbits[look]) != 0) { \
  170002. DROP_BITS(nb); \
  170003. result = htbl->look_sym[look]; \
  170004. } else { \
  170005. nb = HUFF_LOOKAHEAD+1; \
  170006. slowlabel: \
  170007. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170008. { failaction; } \
  170009. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170010. } \
  170011. }
  170012. /* Out-of-line case for Huffman code fetching */
  170013. EXTERN(int) jpeg_huff_decode
  170014. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170015. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170016. #endif
  170017. /*** End of inlined file: jdhuff.h ***/
  170018. /* Declarations shared with jdphuff.c */
  170019. /*
  170020. * Expanded entropy decoder object for Huffman decoding.
  170021. *
  170022. * The savable_state subrecord contains fields that change within an MCU,
  170023. * but must not be updated permanently until we complete the MCU.
  170024. */
  170025. typedef struct {
  170026. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170027. } savable_state2;
  170028. /* This macro is to work around compilers with missing or broken
  170029. * structure assignment. You'll need to fix this code if you have
  170030. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170031. */
  170032. #ifndef NO_STRUCT_ASSIGN
  170033. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170034. #else
  170035. #if MAX_COMPS_IN_SCAN == 4
  170036. #define ASSIGN_STATE(dest,src) \
  170037. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170038. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170039. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170040. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170041. #endif
  170042. #endif
  170043. typedef struct {
  170044. struct jpeg_entropy_decoder pub; /* public fields */
  170045. /* These fields are loaded into local variables at start of each MCU.
  170046. * In case of suspension, we exit WITHOUT updating them.
  170047. */
  170048. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170049. savable_state2 saved; /* Other state at start of MCU */
  170050. /* These fields are NOT loaded into local working state. */
  170051. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170052. /* Pointers to derived tables (these workspaces have image lifespan) */
  170053. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170054. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170055. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170056. /* Pointers to derived tables to be used for each block within an MCU */
  170057. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170058. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170059. /* Whether we care about the DC and AC coefficient values for each block */
  170060. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170061. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170062. } huff_entropy_decoder2;
  170063. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170064. /*
  170065. * Initialize for a Huffman-compressed scan.
  170066. */
  170067. METHODDEF(void)
  170068. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170069. {
  170070. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170071. int ci, blkn, dctbl, actbl;
  170072. jpeg_component_info * compptr;
  170073. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170074. * This ought to be an error condition, but we make it a warning because
  170075. * there are some baseline files out there with all zeroes in these bytes.
  170076. */
  170077. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170078. cinfo->Ah != 0 || cinfo->Al != 0)
  170079. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170080. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170081. compptr = cinfo->cur_comp_info[ci];
  170082. dctbl = compptr->dc_tbl_no;
  170083. actbl = compptr->ac_tbl_no;
  170084. /* Compute derived values for Huffman tables */
  170085. /* We may do this more than once for a table, but it's not expensive */
  170086. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170087. & entropy->dc_derived_tbls[dctbl]);
  170088. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170089. & entropy->ac_derived_tbls[actbl]);
  170090. /* Initialize DC predictions to 0 */
  170091. entropy->saved.last_dc_val[ci] = 0;
  170092. }
  170093. /* Precalculate decoding info for each block in an MCU of this scan */
  170094. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170095. ci = cinfo->MCU_membership[blkn];
  170096. compptr = cinfo->cur_comp_info[ci];
  170097. /* Precalculate which table to use for each block */
  170098. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170099. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170100. /* Decide whether we really care about the coefficient values */
  170101. if (compptr->component_needed) {
  170102. entropy->dc_needed[blkn] = TRUE;
  170103. /* we don't need the ACs if producing a 1/8th-size image */
  170104. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170105. } else {
  170106. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170107. }
  170108. }
  170109. /* Initialize bitread state variables */
  170110. entropy->bitstate.bits_left = 0;
  170111. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170112. entropy->pub.insufficient_data = FALSE;
  170113. /* Initialize restart counter */
  170114. entropy->restarts_to_go = cinfo->restart_interval;
  170115. }
  170116. /*
  170117. * Compute the derived values for a Huffman table.
  170118. * This routine also performs some validation checks on the table.
  170119. *
  170120. * Note this is also used by jdphuff.c.
  170121. */
  170122. GLOBAL(void)
  170123. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170124. d_derived_tbl ** pdtbl)
  170125. {
  170126. JHUFF_TBL *htbl;
  170127. d_derived_tbl *dtbl;
  170128. int p, i, l, si, numsymbols;
  170129. int lookbits, ctr;
  170130. char huffsize[257];
  170131. unsigned int huffcode[257];
  170132. unsigned int code;
  170133. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170134. * paralleling the order of the symbols themselves in htbl->huffval[].
  170135. */
  170136. /* Find the input Huffman table */
  170137. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170138. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170139. htbl =
  170140. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170141. if (htbl == NULL)
  170142. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170143. /* Allocate a workspace if we haven't already done so. */
  170144. if (*pdtbl == NULL)
  170145. *pdtbl = (d_derived_tbl *)
  170146. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170147. SIZEOF(d_derived_tbl));
  170148. dtbl = *pdtbl;
  170149. dtbl->pub = htbl; /* fill in back link */
  170150. /* Figure C.1: make table of Huffman code length for each symbol */
  170151. p = 0;
  170152. for (l = 1; l <= 16; l++) {
  170153. i = (int) htbl->bits[l];
  170154. if (i < 0 || p + i > 256) /* protect against table overrun */
  170155. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170156. while (i--)
  170157. huffsize[p++] = (char) l;
  170158. }
  170159. huffsize[p] = 0;
  170160. numsymbols = p;
  170161. /* Figure C.2: generate the codes themselves */
  170162. /* We also validate that the counts represent a legal Huffman code tree. */
  170163. code = 0;
  170164. si = huffsize[0];
  170165. p = 0;
  170166. while (huffsize[p]) {
  170167. while (((int) huffsize[p]) == si) {
  170168. huffcode[p++] = code;
  170169. code++;
  170170. }
  170171. /* code is now 1 more than the last code used for codelength si; but
  170172. * it must still fit in si bits, since no code is allowed to be all ones.
  170173. */
  170174. if (((INT32) code) >= (((INT32) 1) << si))
  170175. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170176. code <<= 1;
  170177. si++;
  170178. }
  170179. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170180. p = 0;
  170181. for (l = 1; l <= 16; l++) {
  170182. if (htbl->bits[l]) {
  170183. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170184. * minus the minimum code of length l
  170185. */
  170186. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170187. p += htbl->bits[l];
  170188. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170189. } else {
  170190. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170191. }
  170192. }
  170193. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170194. /* Compute lookahead tables to speed up decoding.
  170195. * First we set all the table entries to 0, indicating "too long";
  170196. * then we iterate through the Huffman codes that are short enough and
  170197. * fill in all the entries that correspond to bit sequences starting
  170198. * with that code.
  170199. */
  170200. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170201. p = 0;
  170202. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170203. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170204. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170205. /* Generate left-justified code followed by all possible bit sequences */
  170206. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170207. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170208. dtbl->look_nbits[lookbits] = l;
  170209. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170210. lookbits++;
  170211. }
  170212. }
  170213. }
  170214. /* Validate symbols as being reasonable.
  170215. * For AC tables, we make no check, but accept all byte values 0..255.
  170216. * For DC tables, we require the symbols to be in range 0..15.
  170217. * (Tighter bounds could be applied depending on the data depth and mode,
  170218. * but this is sufficient to ensure safe decoding.)
  170219. */
  170220. if (isDC) {
  170221. for (i = 0; i < numsymbols; i++) {
  170222. int sym = htbl->huffval[i];
  170223. if (sym < 0 || sym > 15)
  170224. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170225. }
  170226. }
  170227. }
  170228. /*
  170229. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170230. * See jdhuff.h for info about usage.
  170231. * Note: current values of get_buffer and bits_left are passed as parameters,
  170232. * but are returned in the corresponding fields of the state struct.
  170233. *
  170234. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170235. * of get_buffer to be used. (On machines with wider words, an even larger
  170236. * buffer could be used.) However, on some machines 32-bit shifts are
  170237. * quite slow and take time proportional to the number of places shifted.
  170238. * (This is true with most PC compilers, for instance.) In this case it may
  170239. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170240. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170241. */
  170242. #ifdef SLOW_SHIFT_32
  170243. #define MIN_GET_BITS 15 /* minimum allowable value */
  170244. #else
  170245. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170246. #endif
  170247. GLOBAL(boolean)
  170248. jpeg_fill_bit_buffer (bitread_working_state * state,
  170249. register bit_buf_type get_buffer, register int bits_left,
  170250. int nbits)
  170251. /* Load up the bit buffer to a depth of at least nbits */
  170252. {
  170253. /* Copy heavily used state fields into locals (hopefully registers) */
  170254. register const JOCTET * next_input_byte = state->next_input_byte;
  170255. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170256. j_decompress_ptr cinfo = state->cinfo;
  170257. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170258. /* (It is assumed that no request will be for more than that many bits.) */
  170259. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170260. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170261. while (bits_left < MIN_GET_BITS) {
  170262. register int c;
  170263. /* Attempt to read a byte */
  170264. if (bytes_in_buffer == 0) {
  170265. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170266. return FALSE;
  170267. next_input_byte = cinfo->src->next_input_byte;
  170268. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170269. }
  170270. bytes_in_buffer--;
  170271. c = GETJOCTET(*next_input_byte++);
  170272. /* If it's 0xFF, check and discard stuffed zero byte */
  170273. if (c == 0xFF) {
  170274. /* Loop here to discard any padding FF's on terminating marker,
  170275. * so that we can save a valid unread_marker value. NOTE: we will
  170276. * accept multiple FF's followed by a 0 as meaning a single FF data
  170277. * byte. This data pattern is not valid according to the standard.
  170278. */
  170279. do {
  170280. if (bytes_in_buffer == 0) {
  170281. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170282. return FALSE;
  170283. next_input_byte = cinfo->src->next_input_byte;
  170284. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170285. }
  170286. bytes_in_buffer--;
  170287. c = GETJOCTET(*next_input_byte++);
  170288. } while (c == 0xFF);
  170289. if (c == 0) {
  170290. /* Found FF/00, which represents an FF data byte */
  170291. c = 0xFF;
  170292. } else {
  170293. /* Oops, it's actually a marker indicating end of compressed data.
  170294. * Save the marker code for later use.
  170295. * Fine point: it might appear that we should save the marker into
  170296. * bitread working state, not straight into permanent state. But
  170297. * once we have hit a marker, we cannot need to suspend within the
  170298. * current MCU, because we will read no more bytes from the data
  170299. * source. So it is OK to update permanent state right away.
  170300. */
  170301. cinfo->unread_marker = c;
  170302. /* See if we need to insert some fake zero bits. */
  170303. goto no_more_bytes;
  170304. }
  170305. }
  170306. /* OK, load c into get_buffer */
  170307. get_buffer = (get_buffer << 8) | c;
  170308. bits_left += 8;
  170309. } /* end while */
  170310. } else {
  170311. no_more_bytes:
  170312. /* We get here if we've read the marker that terminates the compressed
  170313. * data segment. There should be enough bits in the buffer register
  170314. * to satisfy the request; if so, no problem.
  170315. */
  170316. if (nbits > bits_left) {
  170317. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170318. * the data stream, so that we can produce some kind of image.
  170319. * We use a nonvolatile flag to ensure that only one warning message
  170320. * appears per data segment.
  170321. */
  170322. if (! cinfo->entropy->insufficient_data) {
  170323. WARNMS(cinfo, JWRN_HIT_MARKER);
  170324. cinfo->entropy->insufficient_data = TRUE;
  170325. }
  170326. /* Fill the buffer with zero bits */
  170327. get_buffer <<= MIN_GET_BITS - bits_left;
  170328. bits_left = MIN_GET_BITS;
  170329. }
  170330. }
  170331. /* Unload the local registers */
  170332. state->next_input_byte = next_input_byte;
  170333. state->bytes_in_buffer = bytes_in_buffer;
  170334. state->get_buffer = get_buffer;
  170335. state->bits_left = bits_left;
  170336. return TRUE;
  170337. }
  170338. /*
  170339. * Out-of-line code for Huffman code decoding.
  170340. * See jdhuff.h for info about usage.
  170341. */
  170342. GLOBAL(int)
  170343. jpeg_huff_decode (bitread_working_state * state,
  170344. register bit_buf_type get_buffer, register int bits_left,
  170345. d_derived_tbl * htbl, int min_bits)
  170346. {
  170347. register int l = min_bits;
  170348. register INT32 code;
  170349. /* HUFF_DECODE has determined that the code is at least min_bits */
  170350. /* bits long, so fetch that many bits in one swoop. */
  170351. CHECK_BIT_BUFFER(*state, l, return -1);
  170352. code = GET_BITS(l);
  170353. /* Collect the rest of the Huffman code one bit at a time. */
  170354. /* This is per Figure F.16 in the JPEG spec. */
  170355. while (code > htbl->maxcode[l]) {
  170356. code <<= 1;
  170357. CHECK_BIT_BUFFER(*state, 1, return -1);
  170358. code |= GET_BITS(1);
  170359. l++;
  170360. }
  170361. /* Unload the local registers */
  170362. state->get_buffer = get_buffer;
  170363. state->bits_left = bits_left;
  170364. /* With garbage input we may reach the sentinel value l = 17. */
  170365. if (l > 16) {
  170366. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170367. return 0; /* fake a zero as the safest result */
  170368. }
  170369. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170370. }
  170371. /*
  170372. * Check for a restart marker & resynchronize decoder.
  170373. * Returns FALSE if must suspend.
  170374. */
  170375. LOCAL(boolean)
  170376. process_restart (j_decompress_ptr cinfo)
  170377. {
  170378. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170379. int ci;
  170380. /* Throw away any unused bits remaining in bit buffer; */
  170381. /* include any full bytes in next_marker's count of discarded bytes */
  170382. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170383. entropy->bitstate.bits_left = 0;
  170384. /* Advance past the RSTn marker */
  170385. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170386. return FALSE;
  170387. /* Re-initialize DC predictions to 0 */
  170388. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170389. entropy->saved.last_dc_val[ci] = 0;
  170390. /* Reset restart counter */
  170391. entropy->restarts_to_go = cinfo->restart_interval;
  170392. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170393. * against a marker. In that case we will end up treating the next data
  170394. * segment as empty, and we can avoid producing bogus output pixels by
  170395. * leaving the flag set.
  170396. */
  170397. if (cinfo->unread_marker == 0)
  170398. entropy->pub.insufficient_data = FALSE;
  170399. return TRUE;
  170400. }
  170401. /*
  170402. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170403. * The coefficients are reordered from zigzag order into natural array order,
  170404. * but are not dequantized.
  170405. *
  170406. * The i'th block of the MCU is stored into the block pointed to by
  170407. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170408. * (Wholesale zeroing is usually a little faster than retail...)
  170409. *
  170410. * Returns FALSE if data source requested suspension. In that case no
  170411. * changes have been made to permanent state. (Exception: some output
  170412. * coefficients may already have been assigned. This is harmless for
  170413. * this module, since we'll just re-assign them on the next call.)
  170414. */
  170415. METHODDEF(boolean)
  170416. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170417. {
  170418. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170419. int blkn;
  170420. BITREAD_STATE_VARS;
  170421. savable_state2 state;
  170422. /* Process restart marker if needed; may have to suspend */
  170423. if (cinfo->restart_interval) {
  170424. if (entropy->restarts_to_go == 0)
  170425. if (! process_restart(cinfo))
  170426. return FALSE;
  170427. }
  170428. /* If we've run out of data, just leave the MCU set to zeroes.
  170429. * This way, we return uniform gray for the remainder of the segment.
  170430. */
  170431. if (! entropy->pub.insufficient_data) {
  170432. /* Load up working state */
  170433. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170434. ASSIGN_STATE(state, entropy->saved);
  170435. /* Outer loop handles each block in the MCU */
  170436. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170437. JBLOCKROW block = MCU_data[blkn];
  170438. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170439. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170440. register int s, k, r;
  170441. /* Decode a single block's worth of coefficients */
  170442. /* Section F.2.2.1: decode the DC coefficient difference */
  170443. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170444. if (s) {
  170445. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170446. r = GET_BITS(s);
  170447. s = HUFF_EXTEND(r, s);
  170448. }
  170449. if (entropy->dc_needed[blkn]) {
  170450. /* Convert DC difference to actual value, update last_dc_val */
  170451. int ci = cinfo->MCU_membership[blkn];
  170452. s += state.last_dc_val[ci];
  170453. state.last_dc_val[ci] = s;
  170454. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170455. (*block)[0] = (JCOEF) s;
  170456. }
  170457. if (entropy->ac_needed[blkn]) {
  170458. /* Section F.2.2.2: decode the AC coefficients */
  170459. /* Since zeroes are skipped, output area must be cleared beforehand */
  170460. for (k = 1; k < DCTSIZE2; k++) {
  170461. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170462. r = s >> 4;
  170463. s &= 15;
  170464. if (s) {
  170465. k += r;
  170466. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170467. r = GET_BITS(s);
  170468. s = HUFF_EXTEND(r, s);
  170469. /* Output coefficient in natural (dezigzagged) order.
  170470. * Note: the extra entries in jpeg_natural_order[] will save us
  170471. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170472. */
  170473. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170474. } else {
  170475. if (r != 15)
  170476. break;
  170477. k += 15;
  170478. }
  170479. }
  170480. } else {
  170481. /* Section F.2.2.2: decode the AC coefficients */
  170482. /* In this path we just discard the values */
  170483. for (k = 1; k < DCTSIZE2; k++) {
  170484. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170485. r = s >> 4;
  170486. s &= 15;
  170487. if (s) {
  170488. k += r;
  170489. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170490. DROP_BITS(s);
  170491. } else {
  170492. if (r != 15)
  170493. break;
  170494. k += 15;
  170495. }
  170496. }
  170497. }
  170498. }
  170499. /* Completed MCU, so update state */
  170500. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170501. ASSIGN_STATE(entropy->saved, state);
  170502. }
  170503. /* Account for restart interval (no-op if not using restarts) */
  170504. entropy->restarts_to_go--;
  170505. return TRUE;
  170506. }
  170507. /*
  170508. * Module initialization routine for Huffman entropy decoding.
  170509. */
  170510. GLOBAL(void)
  170511. jinit_huff_decoder (j_decompress_ptr cinfo)
  170512. {
  170513. huff_entropy_ptr2 entropy;
  170514. int i;
  170515. entropy = (huff_entropy_ptr2)
  170516. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170517. SIZEOF(huff_entropy_decoder2));
  170518. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170519. entropy->pub.start_pass = start_pass_huff_decoder;
  170520. entropy->pub.decode_mcu = decode_mcu;
  170521. /* Mark tables unallocated */
  170522. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170523. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170524. }
  170525. }
  170526. /*** End of inlined file: jdhuff.c ***/
  170527. /*** Start of inlined file: jdinput.c ***/
  170528. #define JPEG_INTERNALS
  170529. /* Private state */
  170530. typedef struct {
  170531. struct jpeg_input_controller pub; /* public fields */
  170532. boolean inheaders; /* TRUE until first SOS is reached */
  170533. } my_input_controller;
  170534. typedef my_input_controller * my_inputctl_ptr;
  170535. /* Forward declarations */
  170536. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170537. /*
  170538. * Routines to calculate various quantities related to the size of the image.
  170539. */
  170540. LOCAL(void)
  170541. initial_setup2 (j_decompress_ptr cinfo)
  170542. /* Called once, when first SOS marker is reached */
  170543. {
  170544. int ci;
  170545. jpeg_component_info *compptr;
  170546. /* Make sure image isn't bigger than I can handle */
  170547. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170548. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170549. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170550. /* For now, precision must match compiled-in value... */
  170551. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170552. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170553. /* Check that number of components won't exceed internal array sizes */
  170554. if (cinfo->num_components > MAX_COMPONENTS)
  170555. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170556. MAX_COMPONENTS);
  170557. /* Compute maximum sampling factors; check factor validity */
  170558. cinfo->max_h_samp_factor = 1;
  170559. cinfo->max_v_samp_factor = 1;
  170560. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170561. ci++, compptr++) {
  170562. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170563. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170564. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170565. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170566. compptr->h_samp_factor);
  170567. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170568. compptr->v_samp_factor);
  170569. }
  170570. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170571. * In the full decompressor, this will be overridden by jdmaster.c;
  170572. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170573. */
  170574. cinfo->min_DCT_scaled_size = DCTSIZE;
  170575. /* Compute dimensions of components */
  170576. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170577. ci++, compptr++) {
  170578. compptr->DCT_scaled_size = DCTSIZE;
  170579. /* Size in DCT blocks */
  170580. compptr->width_in_blocks = (JDIMENSION)
  170581. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170582. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170583. compptr->height_in_blocks = (JDIMENSION)
  170584. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170585. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170586. /* downsampled_width and downsampled_height will also be overridden by
  170587. * jdmaster.c if we are doing full decompression. The transcoder library
  170588. * doesn't use these values, but the calling application might.
  170589. */
  170590. /* Size in samples */
  170591. compptr->downsampled_width = (JDIMENSION)
  170592. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170593. (long) cinfo->max_h_samp_factor);
  170594. compptr->downsampled_height = (JDIMENSION)
  170595. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170596. (long) cinfo->max_v_samp_factor);
  170597. /* Mark component needed, until color conversion says otherwise */
  170598. compptr->component_needed = TRUE;
  170599. /* Mark no quantization table yet saved for component */
  170600. compptr->quant_table = NULL;
  170601. }
  170602. /* Compute number of fully interleaved MCU rows. */
  170603. cinfo->total_iMCU_rows = (JDIMENSION)
  170604. jdiv_round_up((long) cinfo->image_height,
  170605. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170606. /* Decide whether file contains multiple scans */
  170607. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170608. cinfo->inputctl->has_multiple_scans = TRUE;
  170609. else
  170610. cinfo->inputctl->has_multiple_scans = FALSE;
  170611. }
  170612. LOCAL(void)
  170613. per_scan_setup2 (j_decompress_ptr cinfo)
  170614. /* Do computations that are needed before processing a JPEG scan */
  170615. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170616. {
  170617. int ci, mcublks, tmp;
  170618. jpeg_component_info *compptr;
  170619. if (cinfo->comps_in_scan == 1) {
  170620. /* Noninterleaved (single-component) scan */
  170621. compptr = cinfo->cur_comp_info[0];
  170622. /* Overall image size in MCUs */
  170623. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170624. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170625. /* For noninterleaved scan, always one block per MCU */
  170626. compptr->MCU_width = 1;
  170627. compptr->MCU_height = 1;
  170628. compptr->MCU_blocks = 1;
  170629. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170630. compptr->last_col_width = 1;
  170631. /* For noninterleaved scans, it is convenient to define last_row_height
  170632. * as the number of block rows present in the last iMCU row.
  170633. */
  170634. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170635. if (tmp == 0) tmp = compptr->v_samp_factor;
  170636. compptr->last_row_height = tmp;
  170637. /* Prepare array describing MCU composition */
  170638. cinfo->blocks_in_MCU = 1;
  170639. cinfo->MCU_membership[0] = 0;
  170640. } else {
  170641. /* Interleaved (multi-component) scan */
  170642. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170643. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170644. MAX_COMPS_IN_SCAN);
  170645. /* Overall image size in MCUs */
  170646. cinfo->MCUs_per_row = (JDIMENSION)
  170647. jdiv_round_up((long) cinfo->image_width,
  170648. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170649. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170650. jdiv_round_up((long) cinfo->image_height,
  170651. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170652. cinfo->blocks_in_MCU = 0;
  170653. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170654. compptr = cinfo->cur_comp_info[ci];
  170655. /* Sampling factors give # of blocks of component in each MCU */
  170656. compptr->MCU_width = compptr->h_samp_factor;
  170657. compptr->MCU_height = compptr->v_samp_factor;
  170658. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170659. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170660. /* Figure number of non-dummy blocks in last MCU column & row */
  170661. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170662. if (tmp == 0) tmp = compptr->MCU_width;
  170663. compptr->last_col_width = tmp;
  170664. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170665. if (tmp == 0) tmp = compptr->MCU_height;
  170666. compptr->last_row_height = tmp;
  170667. /* Prepare array describing MCU composition */
  170668. mcublks = compptr->MCU_blocks;
  170669. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170670. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170671. while (mcublks-- > 0) {
  170672. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170673. }
  170674. }
  170675. }
  170676. }
  170677. /*
  170678. * Save away a copy of the Q-table referenced by each component present
  170679. * in the current scan, unless already saved during a prior scan.
  170680. *
  170681. * In a multiple-scan JPEG file, the encoder could assign different components
  170682. * the same Q-table slot number, but change table definitions between scans
  170683. * so that each component uses a different Q-table. (The IJG encoder is not
  170684. * currently capable of doing this, but other encoders might.) Since we want
  170685. * to be able to dequantize all the components at the end of the file, this
  170686. * means that we have to save away the table actually used for each component.
  170687. * We do this by copying the table at the start of the first scan containing
  170688. * the component.
  170689. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170690. * slot between scans of a component using that slot. If the encoder does so
  170691. * anyway, this decoder will simply use the Q-table values that were current
  170692. * at the start of the first scan for the component.
  170693. *
  170694. * The decompressor output side looks only at the saved quant tables,
  170695. * not at the current Q-table slots.
  170696. */
  170697. LOCAL(void)
  170698. latch_quant_tables (j_decompress_ptr cinfo)
  170699. {
  170700. int ci, qtblno;
  170701. jpeg_component_info *compptr;
  170702. JQUANT_TBL * qtbl;
  170703. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170704. compptr = cinfo->cur_comp_info[ci];
  170705. /* No work if we already saved Q-table for this component */
  170706. if (compptr->quant_table != NULL)
  170707. continue;
  170708. /* Make sure specified quantization table is present */
  170709. qtblno = compptr->quant_tbl_no;
  170710. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170711. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170712. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170713. /* OK, save away the quantization table */
  170714. qtbl = (JQUANT_TBL *)
  170715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170716. SIZEOF(JQUANT_TBL));
  170717. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170718. compptr->quant_table = qtbl;
  170719. }
  170720. }
  170721. /*
  170722. * Initialize the input modules to read a scan of compressed data.
  170723. * The first call to this is done by jdmaster.c after initializing
  170724. * the entire decompressor (during jpeg_start_decompress).
  170725. * Subsequent calls come from consume_markers, below.
  170726. */
  170727. METHODDEF(void)
  170728. start_input_pass2 (j_decompress_ptr cinfo)
  170729. {
  170730. per_scan_setup2(cinfo);
  170731. latch_quant_tables(cinfo);
  170732. (*cinfo->entropy->start_pass) (cinfo);
  170733. (*cinfo->coef->start_input_pass) (cinfo);
  170734. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170735. }
  170736. /*
  170737. * Finish up after inputting a compressed-data scan.
  170738. * This is called by the coefficient controller after it's read all
  170739. * the expected data of the scan.
  170740. */
  170741. METHODDEF(void)
  170742. finish_input_pass (j_decompress_ptr cinfo)
  170743. {
  170744. cinfo->inputctl->consume_input = consume_markers;
  170745. }
  170746. /*
  170747. * Read JPEG markers before, between, or after compressed-data scans.
  170748. * Change state as necessary when a new scan is reached.
  170749. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170750. *
  170751. * The consume_input method pointer points either here or to the
  170752. * coefficient controller's consume_data routine, depending on whether
  170753. * we are reading a compressed data segment or inter-segment markers.
  170754. */
  170755. METHODDEF(int)
  170756. consume_markers (j_decompress_ptr cinfo)
  170757. {
  170758. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170759. int val;
  170760. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170761. return JPEG_REACHED_EOI;
  170762. val = (*cinfo->marker->read_markers) (cinfo);
  170763. switch (val) {
  170764. case JPEG_REACHED_SOS: /* Found SOS */
  170765. if (inputctl->inheaders) { /* 1st SOS */
  170766. initial_setup2(cinfo);
  170767. inputctl->inheaders = FALSE;
  170768. /* Note: start_input_pass must be called by jdmaster.c
  170769. * before any more input can be consumed. jdapimin.c is
  170770. * responsible for enforcing this sequencing.
  170771. */
  170772. } else { /* 2nd or later SOS marker */
  170773. if (! inputctl->pub.has_multiple_scans)
  170774. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170775. start_input_pass2(cinfo);
  170776. }
  170777. break;
  170778. case JPEG_REACHED_EOI: /* Found EOI */
  170779. inputctl->pub.eoi_reached = TRUE;
  170780. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170781. if (cinfo->marker->saw_SOF)
  170782. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170783. } else {
  170784. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170785. * if user set output_scan_number larger than number of scans.
  170786. */
  170787. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170788. cinfo->output_scan_number = cinfo->input_scan_number;
  170789. }
  170790. break;
  170791. case JPEG_SUSPENDED:
  170792. break;
  170793. }
  170794. return val;
  170795. }
  170796. /*
  170797. * Reset state to begin a fresh datastream.
  170798. */
  170799. METHODDEF(void)
  170800. reset_input_controller (j_decompress_ptr cinfo)
  170801. {
  170802. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170803. inputctl->pub.consume_input = consume_markers;
  170804. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170805. inputctl->pub.eoi_reached = FALSE;
  170806. inputctl->inheaders = TRUE;
  170807. /* Reset other modules */
  170808. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170809. (*cinfo->marker->reset_marker_reader) (cinfo);
  170810. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170811. cinfo->coef_bits = NULL;
  170812. }
  170813. /*
  170814. * Initialize the input controller module.
  170815. * This is called only once, when the decompression object is created.
  170816. */
  170817. GLOBAL(void)
  170818. jinit_input_controller (j_decompress_ptr cinfo)
  170819. {
  170820. my_inputctl_ptr inputctl;
  170821. /* Create subobject in permanent pool */
  170822. inputctl = (my_inputctl_ptr)
  170823. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170824. SIZEOF(my_input_controller));
  170825. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170826. /* Initialize method pointers */
  170827. inputctl->pub.consume_input = consume_markers;
  170828. inputctl->pub.reset_input_controller = reset_input_controller;
  170829. inputctl->pub.start_input_pass = start_input_pass2;
  170830. inputctl->pub.finish_input_pass = finish_input_pass;
  170831. /* Initialize state: can't use reset_input_controller since we don't
  170832. * want to try to reset other modules yet.
  170833. */
  170834. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170835. inputctl->pub.eoi_reached = FALSE;
  170836. inputctl->inheaders = TRUE;
  170837. }
  170838. /*** End of inlined file: jdinput.c ***/
  170839. /*** Start of inlined file: jdmainct.c ***/
  170840. #define JPEG_INTERNALS
  170841. /*
  170842. * In the current system design, the main buffer need never be a full-image
  170843. * buffer; any full-height buffers will be found inside the coefficient or
  170844. * postprocessing controllers. Nonetheless, the main controller is not
  170845. * trivial. Its responsibility is to provide context rows for upsampling/
  170846. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170847. *
  170848. * Postprocessor input data is counted in "row groups". A row group
  170849. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170850. * sample rows of each component. (We require DCT_scaled_size values to be
  170851. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170852. * values will likely be powers of two, so we actually have the stronger
  170853. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170854. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170855. * row group (times any additional scale factor that the upsampler is
  170856. * applying).
  170857. *
  170858. * The coefficient controller will deliver data to us one iMCU row at a time;
  170859. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170860. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170861. * to one row of MCUs when the image is fully interleaved.) Note that the
  170862. * number of sample rows varies across components, but the number of row
  170863. * groups does not. Some garbage sample rows may be included in the last iMCU
  170864. * row at the bottom of the image.
  170865. *
  170866. * Depending on the vertical scaling algorithm used, the upsampler may need
  170867. * access to the sample row(s) above and below its current input row group.
  170868. * The upsampler is required to set need_context_rows TRUE at global selection
  170869. * time if so. When need_context_rows is FALSE, this controller can simply
  170870. * obtain one iMCU row at a time from the coefficient controller and dole it
  170871. * out as row groups to the postprocessor.
  170872. *
  170873. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170874. * passed to postprocessing contains at least one row group's worth of samples
  170875. * above and below the row group(s) being processed. Note that the context
  170876. * rows "above" the first passed row group appear at negative row offsets in
  170877. * the passed buffer. At the top and bottom of the image, the required
  170878. * context rows are manufactured by duplicating the first or last real sample
  170879. * row; this avoids having special cases in the upsampling inner loops.
  170880. *
  170881. * The amount of context is fixed at one row group just because that's a
  170882. * convenient number for this controller to work with. The existing
  170883. * upsamplers really only need one sample row of context. An upsampler
  170884. * supporting arbitrary output rescaling might wish for more than one row
  170885. * group of context when shrinking the image; tough, we don't handle that.
  170886. * (This is justified by the assumption that downsizing will be handled mostly
  170887. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170888. * the upsample step needn't be much less than one.)
  170889. *
  170890. * To provide the desired context, we have to retain the last two row groups
  170891. * of one iMCU row while reading in the next iMCU row. (The last row group
  170892. * can't be processed until we have another row group for its below-context,
  170893. * and so we have to save the next-to-last group too for its above-context.)
  170894. * We could do this most simply by copying data around in our buffer, but
  170895. * that'd be very slow. We can avoid copying any data by creating a rather
  170896. * strange pointer structure. Here's how it works. We allocate a workspace
  170897. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170898. * of row groups per iMCU row). We create two sets of redundant pointers to
  170899. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170900. * pointer lists look like this:
  170901. * M+1 M-1
  170902. * master pointer --> 0 master pointer --> 0
  170903. * 1 1
  170904. * ... ...
  170905. * M-3 M-3
  170906. * M-2 M
  170907. * M-1 M+1
  170908. * M M-2
  170909. * M+1 M-1
  170910. * 0 0
  170911. * We read alternate iMCU rows using each master pointer; thus the last two
  170912. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170913. * The pointer lists are set up so that the required context rows appear to
  170914. * be adjacent to the proper places when we pass the pointer lists to the
  170915. * upsampler.
  170916. *
  170917. * The above pictures describe the normal state of the pointer lists.
  170918. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170919. * the first or last sample row as necessary (this is cheaper than copying
  170920. * sample rows around).
  170921. *
  170922. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170923. * situation each iMCU row provides only one row group so the buffering logic
  170924. * must be different (eg, we must read two iMCU rows before we can emit the
  170925. * first row group). For now, we simply do not support providing context
  170926. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170927. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170928. * want it quick and dirty, so a context-free upsampler is sufficient.
  170929. */
  170930. /* Private buffer controller object */
  170931. typedef struct {
  170932. struct jpeg_d_main_controller pub; /* public fields */
  170933. /* Pointer to allocated workspace (M or M+2 row groups). */
  170934. JSAMPARRAY buffer[MAX_COMPONENTS];
  170935. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170936. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170937. /* Remaining fields are only used in the context case. */
  170938. /* These are the master pointers to the funny-order pointer lists. */
  170939. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170940. int whichptr; /* indicates which pointer set is now in use */
  170941. int context_state; /* process_data state machine status */
  170942. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170943. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170944. } my_main_controller4;
  170945. typedef my_main_controller4 * my_main_ptr4;
  170946. /* context_state values: */
  170947. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170948. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170949. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170950. /* Forward declarations */
  170951. METHODDEF(void) process_data_simple_main2
  170952. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170953. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170954. METHODDEF(void) process_data_context_main
  170955. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170956. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170957. #ifdef QUANT_2PASS_SUPPORTED
  170958. METHODDEF(void) process_data_crank_post
  170959. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170960. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170961. #endif
  170962. LOCAL(void)
  170963. alloc_funny_pointers (j_decompress_ptr cinfo)
  170964. /* Allocate space for the funny pointer lists.
  170965. * This is done only once, not once per pass.
  170966. */
  170967. {
  170968. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170969. int ci, rgroup;
  170970. int M = cinfo->min_DCT_scaled_size;
  170971. jpeg_component_info *compptr;
  170972. JSAMPARRAY xbuf;
  170973. /* Get top-level space for component array pointers.
  170974. * We alloc both arrays with one call to save a few cycles.
  170975. */
  170976. main_->xbuffer[0] = (JSAMPIMAGE)
  170977. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170978. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170979. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170980. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170981. ci++, compptr++) {
  170982. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170983. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170984. /* Get space for pointer lists --- M+4 row groups in each list.
  170985. * We alloc both pointer lists with one call to save a few cycles.
  170986. */
  170987. xbuf = (JSAMPARRAY)
  170988. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170989. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170990. xbuf += rgroup; /* want one row group at negative offsets */
  170991. main_->xbuffer[0][ci] = xbuf;
  170992. xbuf += rgroup * (M + 4);
  170993. main_->xbuffer[1][ci] = xbuf;
  170994. }
  170995. }
  170996. LOCAL(void)
  170997. make_funny_pointers (j_decompress_ptr cinfo)
  170998. /* Create the funny pointer lists discussed in the comments above.
  170999. * The actual workspace is already allocated (in main->buffer),
  171000. * and the space for the pointer lists is allocated too.
  171001. * This routine just fills in the curiously ordered lists.
  171002. * This will be repeated at the beginning of each pass.
  171003. */
  171004. {
  171005. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171006. int ci, i, rgroup;
  171007. int M = cinfo->min_DCT_scaled_size;
  171008. jpeg_component_info *compptr;
  171009. JSAMPARRAY buf, xbuf0, xbuf1;
  171010. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171011. ci++, compptr++) {
  171012. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171013. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171014. xbuf0 = main_->xbuffer[0][ci];
  171015. xbuf1 = main_->xbuffer[1][ci];
  171016. /* First copy the workspace pointers as-is */
  171017. buf = main_->buffer[ci];
  171018. for (i = 0; i < rgroup * (M + 2); i++) {
  171019. xbuf0[i] = xbuf1[i] = buf[i];
  171020. }
  171021. /* In the second list, put the last four row groups in swapped order */
  171022. for (i = 0; i < rgroup * 2; i++) {
  171023. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171024. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171025. }
  171026. /* The wraparound pointers at top and bottom will be filled later
  171027. * (see set_wraparound_pointers, below). Initially we want the "above"
  171028. * pointers to duplicate the first actual data line. This only needs
  171029. * to happen in xbuffer[0].
  171030. */
  171031. for (i = 0; i < rgroup; i++) {
  171032. xbuf0[i - rgroup] = xbuf0[0];
  171033. }
  171034. }
  171035. }
  171036. LOCAL(void)
  171037. set_wraparound_pointers (j_decompress_ptr cinfo)
  171038. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171039. * This changes the pointer list state from top-of-image to the normal state.
  171040. */
  171041. {
  171042. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171043. int ci, i, rgroup;
  171044. int M = cinfo->min_DCT_scaled_size;
  171045. jpeg_component_info *compptr;
  171046. JSAMPARRAY xbuf0, xbuf1;
  171047. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171048. ci++, compptr++) {
  171049. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171050. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171051. xbuf0 = main_->xbuffer[0][ci];
  171052. xbuf1 = main_->xbuffer[1][ci];
  171053. for (i = 0; i < rgroup; i++) {
  171054. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171055. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171056. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171057. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171058. }
  171059. }
  171060. }
  171061. LOCAL(void)
  171062. set_bottom_pointers (j_decompress_ptr cinfo)
  171063. /* Change the pointer lists to duplicate the last sample row at the bottom
  171064. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171065. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171066. */
  171067. {
  171068. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171069. int ci, i, rgroup, iMCUheight, rows_left;
  171070. jpeg_component_info *compptr;
  171071. JSAMPARRAY xbuf;
  171072. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171073. ci++, compptr++) {
  171074. /* Count sample rows in one iMCU row and in one row group */
  171075. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171076. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171077. /* Count nondummy sample rows remaining for this component */
  171078. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171079. if (rows_left == 0) rows_left = iMCUheight;
  171080. /* Count nondummy row groups. Should get same answer for each component,
  171081. * so we need only do it once.
  171082. */
  171083. if (ci == 0) {
  171084. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171085. }
  171086. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171087. * last partial rowgroup and ensures at least one full rowgroup of context.
  171088. */
  171089. xbuf = main_->xbuffer[main_->whichptr][ci];
  171090. for (i = 0; i < rgroup * 2; i++) {
  171091. xbuf[rows_left + i] = xbuf[rows_left-1];
  171092. }
  171093. }
  171094. }
  171095. /*
  171096. * Initialize for a processing pass.
  171097. */
  171098. METHODDEF(void)
  171099. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171100. {
  171101. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171102. switch (pass_mode) {
  171103. case JBUF_PASS_THRU:
  171104. if (cinfo->upsample->need_context_rows) {
  171105. main_->pub.process_data = process_data_context_main;
  171106. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171107. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171108. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171109. main_->iMCU_row_ctr = 0;
  171110. } else {
  171111. /* Simple case with no context needed */
  171112. main_->pub.process_data = process_data_simple_main2;
  171113. }
  171114. main_->buffer_full = FALSE; /* Mark buffer empty */
  171115. main_->rowgroup_ctr = 0;
  171116. break;
  171117. #ifdef QUANT_2PASS_SUPPORTED
  171118. case JBUF_CRANK_DEST:
  171119. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171120. main_->pub.process_data = process_data_crank_post;
  171121. break;
  171122. #endif
  171123. default:
  171124. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171125. break;
  171126. }
  171127. }
  171128. /*
  171129. * Process some data.
  171130. * This handles the simple case where no context is required.
  171131. */
  171132. METHODDEF(void)
  171133. process_data_simple_main2 (j_decompress_ptr cinfo,
  171134. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171135. JDIMENSION out_rows_avail)
  171136. {
  171137. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171138. JDIMENSION rowgroups_avail;
  171139. /* Read input data if we haven't filled the main buffer yet */
  171140. if (! main_->buffer_full) {
  171141. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171142. return; /* suspension forced, can do nothing more */
  171143. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171144. }
  171145. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171146. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171147. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171148. * to the postprocessor. The postprocessor has to check for bottom
  171149. * of image anyway (at row resolution), so no point in us doing it too.
  171150. */
  171151. /* Feed the postprocessor */
  171152. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171153. &main_->rowgroup_ctr, rowgroups_avail,
  171154. output_buf, out_row_ctr, out_rows_avail);
  171155. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171156. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171157. main_->buffer_full = FALSE;
  171158. main_->rowgroup_ctr = 0;
  171159. }
  171160. }
  171161. /*
  171162. * Process some data.
  171163. * This handles the case where context rows must be provided.
  171164. */
  171165. METHODDEF(void)
  171166. process_data_context_main (j_decompress_ptr cinfo,
  171167. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171168. JDIMENSION out_rows_avail)
  171169. {
  171170. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171171. /* Read input data if we haven't filled the main buffer yet */
  171172. if (! main_->buffer_full) {
  171173. if (! (*cinfo->coef->decompress_data) (cinfo,
  171174. main_->xbuffer[main_->whichptr]))
  171175. return; /* suspension forced, can do nothing more */
  171176. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171177. main_->iMCU_row_ctr++; /* count rows received */
  171178. }
  171179. /* Postprocessor typically will not swallow all the input data it is handed
  171180. * in one call (due to filling the output buffer first). Must be prepared
  171181. * to exit and restart. This switch lets us keep track of how far we got.
  171182. * Note that each case falls through to the next on successful completion.
  171183. */
  171184. switch (main_->context_state) {
  171185. case CTX_POSTPONED_ROW:
  171186. /* Call postprocessor using previously set pointers for postponed row */
  171187. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171188. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171189. output_buf, out_row_ctr, out_rows_avail);
  171190. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171191. return; /* Need to suspend */
  171192. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171193. if (*out_row_ctr >= out_rows_avail)
  171194. return; /* Postprocessor exactly filled output buf */
  171195. /*FALLTHROUGH*/
  171196. case CTX_PREPARE_FOR_IMCU:
  171197. /* Prepare to process first M-1 row groups of this iMCU row */
  171198. main_->rowgroup_ctr = 0;
  171199. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171200. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171201. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171202. */
  171203. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171204. set_bottom_pointers(cinfo);
  171205. main_->context_state = CTX_PROCESS_IMCU;
  171206. /*FALLTHROUGH*/
  171207. case CTX_PROCESS_IMCU:
  171208. /* Call postprocessor using previously set pointers */
  171209. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171210. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171211. output_buf, out_row_ctr, out_rows_avail);
  171212. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171213. return; /* Need to suspend */
  171214. /* After the first iMCU, change wraparound pointers to normal state */
  171215. if (main_->iMCU_row_ctr == 1)
  171216. set_wraparound_pointers(cinfo);
  171217. /* Prepare to load new iMCU row using other xbuffer list */
  171218. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171219. main_->buffer_full = FALSE;
  171220. /* Still need to process last row group of this iMCU row, */
  171221. /* which is saved at index M+1 of the other xbuffer */
  171222. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171223. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171224. main_->context_state = CTX_POSTPONED_ROW;
  171225. }
  171226. }
  171227. /*
  171228. * Process some data.
  171229. * Final pass of two-pass quantization: just call the postprocessor.
  171230. * Source data will be the postprocessor controller's internal buffer.
  171231. */
  171232. #ifdef QUANT_2PASS_SUPPORTED
  171233. METHODDEF(void)
  171234. process_data_crank_post (j_decompress_ptr cinfo,
  171235. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171236. JDIMENSION out_rows_avail)
  171237. {
  171238. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171239. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171240. output_buf, out_row_ctr, out_rows_avail);
  171241. }
  171242. #endif /* QUANT_2PASS_SUPPORTED */
  171243. /*
  171244. * Initialize main buffer controller.
  171245. */
  171246. GLOBAL(void)
  171247. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171248. {
  171249. my_main_ptr4 main_;
  171250. int ci, rgroup, ngroups;
  171251. jpeg_component_info *compptr;
  171252. main_ = (my_main_ptr4)
  171253. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171254. SIZEOF(my_main_controller4));
  171255. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171256. main_->pub.start_pass = start_pass_main2;
  171257. if (need_full_buffer) /* shouldn't happen */
  171258. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171259. /* Allocate the workspace.
  171260. * ngroups is the number of row groups we need.
  171261. */
  171262. if (cinfo->upsample->need_context_rows) {
  171263. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171264. ERREXIT(cinfo, JERR_NOTIMPL);
  171265. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171266. ngroups = cinfo->min_DCT_scaled_size + 2;
  171267. } else {
  171268. ngroups = cinfo->min_DCT_scaled_size;
  171269. }
  171270. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171271. ci++, compptr++) {
  171272. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171273. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171274. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171275. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171276. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171277. (JDIMENSION) (rgroup * ngroups));
  171278. }
  171279. }
  171280. /*** End of inlined file: jdmainct.c ***/
  171281. /*** Start of inlined file: jdmarker.c ***/
  171282. #define JPEG_INTERNALS
  171283. /* Private state */
  171284. typedef struct {
  171285. struct jpeg_marker_reader pub; /* public fields */
  171286. /* Application-overridable marker processing methods */
  171287. jpeg_marker_parser_method process_COM;
  171288. jpeg_marker_parser_method process_APPn[16];
  171289. /* Limit on marker data length to save for each marker type */
  171290. unsigned int length_limit_COM;
  171291. unsigned int length_limit_APPn[16];
  171292. /* Status of COM/APPn marker saving */
  171293. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171294. unsigned int bytes_read; /* data bytes read so far in marker */
  171295. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171296. } my_marker_reader;
  171297. typedef my_marker_reader * my_marker_ptr2;
  171298. /*
  171299. * Macros for fetching data from the data source module.
  171300. *
  171301. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171302. * the current restart point; we update them only when we have reached a
  171303. * suitable place to restart if a suspension occurs.
  171304. */
  171305. /* Declare and initialize local copies of input pointer/count */
  171306. #define INPUT_VARS(cinfo) \
  171307. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171308. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171309. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171310. /* Unload the local copies --- do this only at a restart boundary */
  171311. #define INPUT_SYNC(cinfo) \
  171312. ( datasrc->next_input_byte = next_input_byte, \
  171313. datasrc->bytes_in_buffer = bytes_in_buffer )
  171314. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171315. #define INPUT_RELOAD(cinfo) \
  171316. ( next_input_byte = datasrc->next_input_byte, \
  171317. bytes_in_buffer = datasrc->bytes_in_buffer )
  171318. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171319. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171320. * but we must reload the local copies after a successful fill.
  171321. */
  171322. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171323. if (bytes_in_buffer == 0) { \
  171324. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171325. { action; } \
  171326. INPUT_RELOAD(cinfo); \
  171327. }
  171328. /* Read a byte into variable V.
  171329. * If must suspend, take the specified action (typically "return FALSE").
  171330. */
  171331. #define INPUT_BYTE(cinfo,V,action) \
  171332. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171333. bytes_in_buffer--; \
  171334. V = GETJOCTET(*next_input_byte++); )
  171335. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171336. * V should be declared unsigned int or perhaps INT32.
  171337. */
  171338. #define INPUT_2BYTES(cinfo,V,action) \
  171339. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171340. bytes_in_buffer--; \
  171341. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171342. MAKE_BYTE_AVAIL(cinfo,action); \
  171343. bytes_in_buffer--; \
  171344. V += GETJOCTET(*next_input_byte++); )
  171345. /*
  171346. * Routines to process JPEG markers.
  171347. *
  171348. * Entry condition: JPEG marker itself has been read and its code saved
  171349. * in cinfo->unread_marker; input restart point is just after the marker.
  171350. *
  171351. * Exit: if return TRUE, have read and processed any parameters, and have
  171352. * updated the restart point to point after the parameters.
  171353. * If return FALSE, was forced to suspend before reaching end of
  171354. * marker parameters; restart point has not been moved. Same routine
  171355. * will be called again after application supplies more input data.
  171356. *
  171357. * This approach to suspension assumes that all of a marker's parameters
  171358. * can fit into a single input bufferload. This should hold for "normal"
  171359. * markers. Some COM/APPn markers might have large parameter segments
  171360. * that might not fit. If we are simply dropping such a marker, we use
  171361. * skip_input_data to get past it, and thereby put the problem on the
  171362. * source manager's shoulders. If we are saving the marker's contents
  171363. * into memory, we use a slightly different convention: when forced to
  171364. * suspend, the marker processor updates the restart point to the end of
  171365. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171366. * On resumption, cinfo->unread_marker still contains the marker code,
  171367. * but the data source will point to the next chunk of marker data.
  171368. * The marker processor must retain internal state to deal with this.
  171369. *
  171370. * Note that we don't bother to avoid duplicate trace messages if a
  171371. * suspension occurs within marker parameters. Other side effects
  171372. * require more care.
  171373. */
  171374. LOCAL(boolean)
  171375. get_soi (j_decompress_ptr cinfo)
  171376. /* Process an SOI marker */
  171377. {
  171378. int i;
  171379. TRACEMS(cinfo, 1, JTRC_SOI);
  171380. if (cinfo->marker->saw_SOI)
  171381. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171382. /* Reset all parameters that are defined to be reset by SOI */
  171383. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171384. cinfo->arith_dc_L[i] = 0;
  171385. cinfo->arith_dc_U[i] = 1;
  171386. cinfo->arith_ac_K[i] = 5;
  171387. }
  171388. cinfo->restart_interval = 0;
  171389. /* Set initial assumptions for colorspace etc */
  171390. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171391. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171392. cinfo->saw_JFIF_marker = FALSE;
  171393. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171394. cinfo->JFIF_minor_version = 1;
  171395. cinfo->density_unit = 0;
  171396. cinfo->X_density = 1;
  171397. cinfo->Y_density = 1;
  171398. cinfo->saw_Adobe_marker = FALSE;
  171399. cinfo->Adobe_transform = 0;
  171400. cinfo->marker->saw_SOI = TRUE;
  171401. return TRUE;
  171402. }
  171403. LOCAL(boolean)
  171404. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171405. /* Process a SOFn marker */
  171406. {
  171407. INT32 length;
  171408. int c, ci;
  171409. jpeg_component_info * compptr;
  171410. INPUT_VARS(cinfo);
  171411. cinfo->progressive_mode = is_prog;
  171412. cinfo->arith_code = is_arith;
  171413. INPUT_2BYTES(cinfo, length, return FALSE);
  171414. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171415. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171416. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171417. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171418. length -= 8;
  171419. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171420. (int) cinfo->image_width, (int) cinfo->image_height,
  171421. cinfo->num_components);
  171422. if (cinfo->marker->saw_SOF)
  171423. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171424. /* We don't support files in which the image height is initially specified */
  171425. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171426. /* might as well have a general sanity check. */
  171427. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171428. || cinfo->num_components <= 0)
  171429. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171430. if (length != (cinfo->num_components * 3))
  171431. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171432. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171433. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171434. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171435. cinfo->num_components * SIZEOF(jpeg_component_info));
  171436. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171437. ci++, compptr++) {
  171438. compptr->component_index = ci;
  171439. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171440. INPUT_BYTE(cinfo, c, return FALSE);
  171441. compptr->h_samp_factor = (c >> 4) & 15;
  171442. compptr->v_samp_factor = (c ) & 15;
  171443. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171444. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171445. compptr->component_id, compptr->h_samp_factor,
  171446. compptr->v_samp_factor, compptr->quant_tbl_no);
  171447. }
  171448. cinfo->marker->saw_SOF = TRUE;
  171449. INPUT_SYNC(cinfo);
  171450. return TRUE;
  171451. }
  171452. LOCAL(boolean)
  171453. get_sos (j_decompress_ptr cinfo)
  171454. /* Process a SOS marker */
  171455. {
  171456. INT32 length;
  171457. int i, ci, n, c, cc;
  171458. jpeg_component_info * compptr;
  171459. INPUT_VARS(cinfo);
  171460. if (! cinfo->marker->saw_SOF)
  171461. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171462. INPUT_2BYTES(cinfo, length, return FALSE);
  171463. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171464. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171465. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171466. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171467. cinfo->comps_in_scan = n;
  171468. /* Collect the component-spec parameters */
  171469. for (i = 0; i < n; i++) {
  171470. INPUT_BYTE(cinfo, cc, return FALSE);
  171471. INPUT_BYTE(cinfo, c, return FALSE);
  171472. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171473. ci++, compptr++) {
  171474. if (cc == compptr->component_id)
  171475. goto id_found;
  171476. }
  171477. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171478. id_found:
  171479. cinfo->cur_comp_info[i] = compptr;
  171480. compptr->dc_tbl_no = (c >> 4) & 15;
  171481. compptr->ac_tbl_no = (c ) & 15;
  171482. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171483. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171484. }
  171485. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171486. INPUT_BYTE(cinfo, c, return FALSE);
  171487. cinfo->Ss = c;
  171488. INPUT_BYTE(cinfo, c, return FALSE);
  171489. cinfo->Se = c;
  171490. INPUT_BYTE(cinfo, c, return FALSE);
  171491. cinfo->Ah = (c >> 4) & 15;
  171492. cinfo->Al = (c ) & 15;
  171493. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171494. cinfo->Ah, cinfo->Al);
  171495. /* Prepare to scan data & restart markers */
  171496. cinfo->marker->next_restart_num = 0;
  171497. /* Count another SOS marker */
  171498. cinfo->input_scan_number++;
  171499. INPUT_SYNC(cinfo);
  171500. return TRUE;
  171501. }
  171502. #ifdef D_ARITH_CODING_SUPPORTED
  171503. LOCAL(boolean)
  171504. get_dac (j_decompress_ptr cinfo)
  171505. /* Process a DAC marker */
  171506. {
  171507. INT32 length;
  171508. int index, val;
  171509. INPUT_VARS(cinfo);
  171510. INPUT_2BYTES(cinfo, length, return FALSE);
  171511. length -= 2;
  171512. while (length > 0) {
  171513. INPUT_BYTE(cinfo, index, return FALSE);
  171514. INPUT_BYTE(cinfo, val, return FALSE);
  171515. length -= 2;
  171516. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171517. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171518. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171519. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171520. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171521. } else { /* define DC table */
  171522. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171523. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171524. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171525. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171526. }
  171527. }
  171528. if (length != 0)
  171529. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171530. INPUT_SYNC(cinfo);
  171531. return TRUE;
  171532. }
  171533. #else /* ! D_ARITH_CODING_SUPPORTED */
  171534. #define get_dac(cinfo) skip_variable(cinfo)
  171535. #endif /* D_ARITH_CODING_SUPPORTED */
  171536. LOCAL(boolean)
  171537. get_dht (j_decompress_ptr cinfo)
  171538. /* Process a DHT marker */
  171539. {
  171540. INT32 length;
  171541. UINT8 bits[17];
  171542. UINT8 huffval[256];
  171543. int i, index, count;
  171544. JHUFF_TBL **htblptr;
  171545. INPUT_VARS(cinfo);
  171546. INPUT_2BYTES(cinfo, length, return FALSE);
  171547. length -= 2;
  171548. while (length > 16) {
  171549. INPUT_BYTE(cinfo, index, return FALSE);
  171550. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171551. bits[0] = 0;
  171552. count = 0;
  171553. for (i = 1; i <= 16; i++) {
  171554. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171555. count += bits[i];
  171556. }
  171557. length -= 1 + 16;
  171558. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171559. bits[1], bits[2], bits[3], bits[4],
  171560. bits[5], bits[6], bits[7], bits[8]);
  171561. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171562. bits[9], bits[10], bits[11], bits[12],
  171563. bits[13], bits[14], bits[15], bits[16]);
  171564. /* Here we just do minimal validation of the counts to avoid walking
  171565. * off the end of our table space. jdhuff.c will check more carefully.
  171566. */
  171567. if (count > 256 || ((INT32) count) > length)
  171568. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171569. for (i = 0; i < count; i++)
  171570. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171571. length -= count;
  171572. if (index & 0x10) { /* AC table definition */
  171573. index -= 0x10;
  171574. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171575. } else { /* DC table definition */
  171576. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171577. }
  171578. if (index < 0 || index >= NUM_HUFF_TBLS)
  171579. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171580. if (*htblptr == NULL)
  171581. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171582. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171583. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171584. }
  171585. if (length != 0)
  171586. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171587. INPUT_SYNC(cinfo);
  171588. return TRUE;
  171589. }
  171590. LOCAL(boolean)
  171591. get_dqt (j_decompress_ptr cinfo)
  171592. /* Process a DQT marker */
  171593. {
  171594. INT32 length;
  171595. int n, i, prec;
  171596. unsigned int tmp;
  171597. JQUANT_TBL *quant_ptr;
  171598. INPUT_VARS(cinfo);
  171599. INPUT_2BYTES(cinfo, length, return FALSE);
  171600. length -= 2;
  171601. while (length > 0) {
  171602. INPUT_BYTE(cinfo, n, return FALSE);
  171603. prec = n >> 4;
  171604. n &= 0x0F;
  171605. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171606. if (n >= NUM_QUANT_TBLS)
  171607. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171608. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171609. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171610. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171611. for (i = 0; i < DCTSIZE2; i++) {
  171612. if (prec)
  171613. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171614. else
  171615. INPUT_BYTE(cinfo, tmp, return FALSE);
  171616. /* We convert the zigzag-order table to natural array order. */
  171617. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171618. }
  171619. if (cinfo->err->trace_level >= 2) {
  171620. for (i = 0; i < DCTSIZE2; i += 8) {
  171621. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171622. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171623. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171624. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171625. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171626. }
  171627. }
  171628. length -= DCTSIZE2+1;
  171629. if (prec) length -= DCTSIZE2;
  171630. }
  171631. if (length != 0)
  171632. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171633. INPUT_SYNC(cinfo);
  171634. return TRUE;
  171635. }
  171636. LOCAL(boolean)
  171637. get_dri (j_decompress_ptr cinfo)
  171638. /* Process a DRI marker */
  171639. {
  171640. INT32 length;
  171641. unsigned int tmp;
  171642. INPUT_VARS(cinfo);
  171643. INPUT_2BYTES(cinfo, length, return FALSE);
  171644. if (length != 4)
  171645. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171646. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171647. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171648. cinfo->restart_interval = tmp;
  171649. INPUT_SYNC(cinfo);
  171650. return TRUE;
  171651. }
  171652. /*
  171653. * Routines for processing APPn and COM markers.
  171654. * These are either saved in memory or discarded, per application request.
  171655. * APP0 and APP14 are specially checked to see if they are
  171656. * JFIF and Adobe markers, respectively.
  171657. */
  171658. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171659. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171660. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171661. LOCAL(void)
  171662. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171663. unsigned int datalen, INT32 remaining)
  171664. /* Examine first few bytes from an APP0.
  171665. * Take appropriate action if it is a JFIF marker.
  171666. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171667. */
  171668. {
  171669. INT32 totallen = (INT32) datalen + remaining;
  171670. if (datalen >= APP0_DATA_LEN &&
  171671. GETJOCTET(data[0]) == 0x4A &&
  171672. GETJOCTET(data[1]) == 0x46 &&
  171673. GETJOCTET(data[2]) == 0x49 &&
  171674. GETJOCTET(data[3]) == 0x46 &&
  171675. GETJOCTET(data[4]) == 0) {
  171676. /* Found JFIF APP0 marker: save info */
  171677. cinfo->saw_JFIF_marker = TRUE;
  171678. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171679. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171680. cinfo->density_unit = GETJOCTET(data[7]);
  171681. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171682. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171683. /* Check version.
  171684. * Major version must be 1, anything else signals an incompatible change.
  171685. * (We used to treat this as an error, but now it's a nonfatal warning,
  171686. * because some bozo at Hijaak couldn't read the spec.)
  171687. * Minor version should be 0..2, but process anyway if newer.
  171688. */
  171689. if (cinfo->JFIF_major_version != 1)
  171690. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171691. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171692. /* Generate trace messages */
  171693. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171694. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171695. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171696. /* Validate thumbnail dimensions and issue appropriate messages */
  171697. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171698. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171699. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171700. totallen -= APP0_DATA_LEN;
  171701. if (totallen !=
  171702. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171703. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171704. } else if (datalen >= 6 &&
  171705. GETJOCTET(data[0]) == 0x4A &&
  171706. GETJOCTET(data[1]) == 0x46 &&
  171707. GETJOCTET(data[2]) == 0x58 &&
  171708. GETJOCTET(data[3]) == 0x58 &&
  171709. GETJOCTET(data[4]) == 0) {
  171710. /* Found JFIF "JFXX" extension APP0 marker */
  171711. /* The library doesn't actually do anything with these,
  171712. * but we try to produce a helpful trace message.
  171713. */
  171714. switch (GETJOCTET(data[5])) {
  171715. case 0x10:
  171716. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171717. break;
  171718. case 0x11:
  171719. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171720. break;
  171721. case 0x13:
  171722. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171723. break;
  171724. default:
  171725. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171726. GETJOCTET(data[5]), (int) totallen);
  171727. break;
  171728. }
  171729. } else {
  171730. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171731. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171732. }
  171733. }
  171734. LOCAL(void)
  171735. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171736. unsigned int datalen, INT32 remaining)
  171737. /* Examine first few bytes from an APP14.
  171738. * Take appropriate action if it is an Adobe marker.
  171739. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171740. */
  171741. {
  171742. unsigned int version, flags0, flags1, transform;
  171743. if (datalen >= APP14_DATA_LEN &&
  171744. GETJOCTET(data[0]) == 0x41 &&
  171745. GETJOCTET(data[1]) == 0x64 &&
  171746. GETJOCTET(data[2]) == 0x6F &&
  171747. GETJOCTET(data[3]) == 0x62 &&
  171748. GETJOCTET(data[4]) == 0x65) {
  171749. /* Found Adobe APP14 marker */
  171750. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171751. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171752. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171753. transform = GETJOCTET(data[11]);
  171754. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171755. cinfo->saw_Adobe_marker = TRUE;
  171756. cinfo->Adobe_transform = (UINT8) transform;
  171757. } else {
  171758. /* Start of APP14 does not match "Adobe", or too short */
  171759. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171760. }
  171761. }
  171762. METHODDEF(boolean)
  171763. get_interesting_appn (j_decompress_ptr cinfo)
  171764. /* Process an APP0 or APP14 marker without saving it */
  171765. {
  171766. INT32 length;
  171767. JOCTET b[APPN_DATA_LEN];
  171768. unsigned int i, numtoread;
  171769. INPUT_VARS(cinfo);
  171770. INPUT_2BYTES(cinfo, length, return FALSE);
  171771. length -= 2;
  171772. /* get the interesting part of the marker data */
  171773. if (length >= APPN_DATA_LEN)
  171774. numtoread = APPN_DATA_LEN;
  171775. else if (length > 0)
  171776. numtoread = (unsigned int) length;
  171777. else
  171778. numtoread = 0;
  171779. for (i = 0; i < numtoread; i++)
  171780. INPUT_BYTE(cinfo, b[i], return FALSE);
  171781. length -= numtoread;
  171782. /* process it */
  171783. switch (cinfo->unread_marker) {
  171784. case M_APP0:
  171785. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171786. break;
  171787. case M_APP14:
  171788. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171789. break;
  171790. default:
  171791. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171792. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171793. break;
  171794. }
  171795. /* skip any remaining data -- could be lots */
  171796. INPUT_SYNC(cinfo);
  171797. if (length > 0)
  171798. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171799. return TRUE;
  171800. }
  171801. #ifdef SAVE_MARKERS_SUPPORTED
  171802. METHODDEF(boolean)
  171803. save_marker (j_decompress_ptr cinfo)
  171804. /* Save an APPn or COM marker into the marker list */
  171805. {
  171806. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171807. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171808. unsigned int bytes_read, data_length;
  171809. JOCTET FAR * data;
  171810. INT32 length = 0;
  171811. INPUT_VARS(cinfo);
  171812. if (cur_marker == NULL) {
  171813. /* begin reading a marker */
  171814. INPUT_2BYTES(cinfo, length, return FALSE);
  171815. length -= 2;
  171816. if (length >= 0) { /* watch out for bogus length word */
  171817. /* figure out how much we want to save */
  171818. unsigned int limit;
  171819. if (cinfo->unread_marker == (int) M_COM)
  171820. limit = marker->length_limit_COM;
  171821. else
  171822. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171823. if ((unsigned int) length < limit)
  171824. limit = (unsigned int) length;
  171825. /* allocate and initialize the marker item */
  171826. cur_marker = (jpeg_saved_marker_ptr)
  171827. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171828. SIZEOF(struct jpeg_marker_struct) + limit);
  171829. cur_marker->next = NULL;
  171830. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171831. cur_marker->original_length = (unsigned int) length;
  171832. cur_marker->data_length = limit;
  171833. /* data area is just beyond the jpeg_marker_struct */
  171834. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171835. marker->cur_marker = cur_marker;
  171836. marker->bytes_read = 0;
  171837. bytes_read = 0;
  171838. data_length = limit;
  171839. } else {
  171840. /* deal with bogus length word */
  171841. bytes_read = data_length = 0;
  171842. data = NULL;
  171843. }
  171844. } else {
  171845. /* resume reading a marker */
  171846. bytes_read = marker->bytes_read;
  171847. data_length = cur_marker->data_length;
  171848. data = cur_marker->data + bytes_read;
  171849. }
  171850. while (bytes_read < data_length) {
  171851. INPUT_SYNC(cinfo); /* move the restart point to here */
  171852. marker->bytes_read = bytes_read;
  171853. /* If there's not at least one byte in buffer, suspend */
  171854. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171855. /* Copy bytes with reasonable rapidity */
  171856. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171857. *data++ = *next_input_byte++;
  171858. bytes_in_buffer--;
  171859. bytes_read++;
  171860. }
  171861. }
  171862. /* Done reading what we want to read */
  171863. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171864. /* Add new marker to end of list */
  171865. if (cinfo->marker_list == NULL) {
  171866. cinfo->marker_list = cur_marker;
  171867. } else {
  171868. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171869. while (prev->next != NULL)
  171870. prev = prev->next;
  171871. prev->next = cur_marker;
  171872. }
  171873. /* Reset pointer & calc remaining data length */
  171874. data = cur_marker->data;
  171875. length = cur_marker->original_length - data_length;
  171876. }
  171877. /* Reset to initial state for next marker */
  171878. marker->cur_marker = NULL;
  171879. /* Process the marker if interesting; else just make a generic trace msg */
  171880. switch (cinfo->unread_marker) {
  171881. case M_APP0:
  171882. examine_app0(cinfo, data, data_length, length);
  171883. break;
  171884. case M_APP14:
  171885. examine_app14(cinfo, data, data_length, length);
  171886. break;
  171887. default:
  171888. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171889. (int) (data_length + length));
  171890. break;
  171891. }
  171892. /* skip any remaining data -- could be lots */
  171893. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171894. if (length > 0)
  171895. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171896. return TRUE;
  171897. }
  171898. #endif /* SAVE_MARKERS_SUPPORTED */
  171899. METHODDEF(boolean)
  171900. skip_variable (j_decompress_ptr cinfo)
  171901. /* Skip over an unknown or uninteresting variable-length marker */
  171902. {
  171903. INT32 length;
  171904. INPUT_VARS(cinfo);
  171905. INPUT_2BYTES(cinfo, length, return FALSE);
  171906. length -= 2;
  171907. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171908. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171909. if (length > 0)
  171910. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171911. return TRUE;
  171912. }
  171913. /*
  171914. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171915. * Returns FALSE if had to suspend before reaching a marker;
  171916. * in that case cinfo->unread_marker is unchanged.
  171917. *
  171918. * Note that the result might not be a valid marker code,
  171919. * but it will never be 0 or FF.
  171920. */
  171921. LOCAL(boolean)
  171922. next_marker (j_decompress_ptr cinfo)
  171923. {
  171924. int c;
  171925. INPUT_VARS(cinfo);
  171926. for (;;) {
  171927. INPUT_BYTE(cinfo, c, return FALSE);
  171928. /* Skip any non-FF bytes.
  171929. * This may look a bit inefficient, but it will not occur in a valid file.
  171930. * We sync after each discarded byte so that a suspending data source
  171931. * can discard the byte from its buffer.
  171932. */
  171933. while (c != 0xFF) {
  171934. cinfo->marker->discarded_bytes++;
  171935. INPUT_SYNC(cinfo);
  171936. INPUT_BYTE(cinfo, c, return FALSE);
  171937. }
  171938. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171939. * pad bytes, so don't count them in discarded_bytes. We assume there
  171940. * will not be so many consecutive FF bytes as to overflow a suspending
  171941. * data source's input buffer.
  171942. */
  171943. do {
  171944. INPUT_BYTE(cinfo, c, return FALSE);
  171945. } while (c == 0xFF);
  171946. if (c != 0)
  171947. break; /* found a valid marker, exit loop */
  171948. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171949. * Discard it and loop back to try again.
  171950. */
  171951. cinfo->marker->discarded_bytes += 2;
  171952. INPUT_SYNC(cinfo);
  171953. }
  171954. if (cinfo->marker->discarded_bytes != 0) {
  171955. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171956. cinfo->marker->discarded_bytes = 0;
  171957. }
  171958. cinfo->unread_marker = c;
  171959. INPUT_SYNC(cinfo);
  171960. return TRUE;
  171961. }
  171962. LOCAL(boolean)
  171963. first_marker (j_decompress_ptr cinfo)
  171964. /* Like next_marker, but used to obtain the initial SOI marker. */
  171965. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171966. * we might well scan an entire input file before realizing it ain't JPEG.
  171967. * If an application wants to process non-JFIF files, it must seek to the
  171968. * SOI before calling the JPEG library.
  171969. */
  171970. {
  171971. int c, c2;
  171972. INPUT_VARS(cinfo);
  171973. INPUT_BYTE(cinfo, c, return FALSE);
  171974. INPUT_BYTE(cinfo, c2, return FALSE);
  171975. if (c != 0xFF || c2 != (int) M_SOI)
  171976. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171977. cinfo->unread_marker = c2;
  171978. INPUT_SYNC(cinfo);
  171979. return TRUE;
  171980. }
  171981. /*
  171982. * Read markers until SOS or EOI.
  171983. *
  171984. * Returns same codes as are defined for jpeg_consume_input:
  171985. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171986. */
  171987. METHODDEF(int)
  171988. read_markers (j_decompress_ptr cinfo)
  171989. {
  171990. /* Outer loop repeats once for each marker. */
  171991. for (;;) {
  171992. /* Collect the marker proper, unless we already did. */
  171993. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171994. if (cinfo->unread_marker == 0) {
  171995. if (! cinfo->marker->saw_SOI) {
  171996. if (! first_marker(cinfo))
  171997. return JPEG_SUSPENDED;
  171998. } else {
  171999. if (! next_marker(cinfo))
  172000. return JPEG_SUSPENDED;
  172001. }
  172002. }
  172003. /* At this point cinfo->unread_marker contains the marker code and the
  172004. * input point is just past the marker proper, but before any parameters.
  172005. * A suspension will cause us to return with this state still true.
  172006. */
  172007. switch (cinfo->unread_marker) {
  172008. case M_SOI:
  172009. if (! get_soi(cinfo))
  172010. return JPEG_SUSPENDED;
  172011. break;
  172012. case M_SOF0: /* Baseline */
  172013. case M_SOF1: /* Extended sequential, Huffman */
  172014. if (! get_sof(cinfo, FALSE, FALSE))
  172015. return JPEG_SUSPENDED;
  172016. break;
  172017. case M_SOF2: /* Progressive, Huffman */
  172018. if (! get_sof(cinfo, TRUE, FALSE))
  172019. return JPEG_SUSPENDED;
  172020. break;
  172021. case M_SOF9: /* Extended sequential, arithmetic */
  172022. if (! get_sof(cinfo, FALSE, TRUE))
  172023. return JPEG_SUSPENDED;
  172024. break;
  172025. case M_SOF10: /* Progressive, arithmetic */
  172026. if (! get_sof(cinfo, TRUE, TRUE))
  172027. return JPEG_SUSPENDED;
  172028. break;
  172029. /* Currently unsupported SOFn types */
  172030. case M_SOF3: /* Lossless, Huffman */
  172031. case M_SOF5: /* Differential sequential, Huffman */
  172032. case M_SOF6: /* Differential progressive, Huffman */
  172033. case M_SOF7: /* Differential lossless, Huffman */
  172034. case M_JPG: /* Reserved for JPEG extensions */
  172035. case M_SOF11: /* Lossless, arithmetic */
  172036. case M_SOF13: /* Differential sequential, arithmetic */
  172037. case M_SOF14: /* Differential progressive, arithmetic */
  172038. case M_SOF15: /* Differential lossless, arithmetic */
  172039. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172040. break;
  172041. case M_SOS:
  172042. if (! get_sos(cinfo))
  172043. return JPEG_SUSPENDED;
  172044. cinfo->unread_marker = 0; /* processed the marker */
  172045. return JPEG_REACHED_SOS;
  172046. case M_EOI:
  172047. TRACEMS(cinfo, 1, JTRC_EOI);
  172048. cinfo->unread_marker = 0; /* processed the marker */
  172049. return JPEG_REACHED_EOI;
  172050. case M_DAC:
  172051. if (! get_dac(cinfo))
  172052. return JPEG_SUSPENDED;
  172053. break;
  172054. case M_DHT:
  172055. if (! get_dht(cinfo))
  172056. return JPEG_SUSPENDED;
  172057. break;
  172058. case M_DQT:
  172059. if (! get_dqt(cinfo))
  172060. return JPEG_SUSPENDED;
  172061. break;
  172062. case M_DRI:
  172063. if (! get_dri(cinfo))
  172064. return JPEG_SUSPENDED;
  172065. break;
  172066. case M_APP0:
  172067. case M_APP1:
  172068. case M_APP2:
  172069. case M_APP3:
  172070. case M_APP4:
  172071. case M_APP5:
  172072. case M_APP6:
  172073. case M_APP7:
  172074. case M_APP8:
  172075. case M_APP9:
  172076. case M_APP10:
  172077. case M_APP11:
  172078. case M_APP12:
  172079. case M_APP13:
  172080. case M_APP14:
  172081. case M_APP15:
  172082. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172083. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172084. return JPEG_SUSPENDED;
  172085. break;
  172086. case M_COM:
  172087. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172088. return JPEG_SUSPENDED;
  172089. break;
  172090. case M_RST0: /* these are all parameterless */
  172091. case M_RST1:
  172092. case M_RST2:
  172093. case M_RST3:
  172094. case M_RST4:
  172095. case M_RST5:
  172096. case M_RST6:
  172097. case M_RST7:
  172098. case M_TEM:
  172099. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172100. break;
  172101. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172102. if (! skip_variable(cinfo))
  172103. return JPEG_SUSPENDED;
  172104. break;
  172105. default: /* must be DHP, EXP, JPGn, or RESn */
  172106. /* For now, we treat the reserved markers as fatal errors since they are
  172107. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172108. * Once the JPEG 3 version-number marker is well defined, this code
  172109. * ought to change!
  172110. */
  172111. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172112. break;
  172113. }
  172114. /* Successfully processed marker, so reset state variable */
  172115. cinfo->unread_marker = 0;
  172116. } /* end loop */
  172117. }
  172118. /*
  172119. * Read a restart marker, which is expected to appear next in the datastream;
  172120. * if the marker is not there, take appropriate recovery action.
  172121. * Returns FALSE if suspension is required.
  172122. *
  172123. * This is called by the entropy decoder after it has read an appropriate
  172124. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172125. * has already read a marker from the data source. Under normal conditions
  172126. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172127. * it holds a marker which the decoder will be unable to read past.
  172128. */
  172129. METHODDEF(boolean)
  172130. read_restart_marker (j_decompress_ptr cinfo)
  172131. {
  172132. /* Obtain a marker unless we already did. */
  172133. /* Note that next_marker will complain if it skips any data. */
  172134. if (cinfo->unread_marker == 0) {
  172135. if (! next_marker(cinfo))
  172136. return FALSE;
  172137. }
  172138. if (cinfo->unread_marker ==
  172139. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172140. /* Normal case --- swallow the marker and let entropy decoder continue */
  172141. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172142. cinfo->unread_marker = 0;
  172143. } else {
  172144. /* Uh-oh, the restart markers have been messed up. */
  172145. /* Let the data source manager determine how to resync. */
  172146. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172147. cinfo->marker->next_restart_num))
  172148. return FALSE;
  172149. }
  172150. /* Update next-restart state */
  172151. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172152. return TRUE;
  172153. }
  172154. /*
  172155. * This is the default resync_to_restart method for data source managers
  172156. * to use if they don't have any better approach. Some data source managers
  172157. * may be able to back up, or may have additional knowledge about the data
  172158. * which permits a more intelligent recovery strategy; such managers would
  172159. * presumably supply their own resync method.
  172160. *
  172161. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172162. * the restart marker it was expecting. (This code is *not* used unless
  172163. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172164. * the marker code actually found (might be anything, except 0 or FF).
  172165. * The desired restart marker number (0..7) is passed as a parameter.
  172166. * This routine is supposed to apply whatever error recovery strategy seems
  172167. * appropriate in order to position the input stream to the next data segment.
  172168. * Note that cinfo->unread_marker is treated as a marker appearing before
  172169. * the current data-source input point; usually it should be reset to zero
  172170. * before returning.
  172171. * Returns FALSE if suspension is required.
  172172. *
  172173. * This implementation is substantially constrained by wanting to treat the
  172174. * input as a data stream; this means we can't back up. Therefore, we have
  172175. * only the following actions to work with:
  172176. * 1. Simply discard the marker and let the entropy decoder resume at next
  172177. * byte of file.
  172178. * 2. Read forward until we find another marker, discarding intervening
  172179. * data. (In theory we could look ahead within the current bufferload,
  172180. * without having to discard data if we don't find the desired marker.
  172181. * This idea is not implemented here, in part because it makes behavior
  172182. * dependent on buffer size and chance buffer-boundary positions.)
  172183. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172184. * This will cause the entropy decoder to process an empty data segment,
  172185. * inserting dummy zeroes, and then we will reprocess the marker.
  172186. *
  172187. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172188. * appropriate if the found marker is a future restart marker (indicating
  172189. * that we have missed the desired restart marker, probably because it got
  172190. * corrupted).
  172191. * We apply #2 or #3 if the found marker is a restart marker no more than
  172192. * two counts behind or ahead of the expected one. We also apply #2 if the
  172193. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172194. * If the found marker is a restart marker more than 2 counts away, we do #1
  172195. * (too much risk that the marker is erroneous; with luck we will be able to
  172196. * resync at some future point).
  172197. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172198. * overrunning the end of a scan. An implementation limited to single-scan
  172199. * files might find it better to apply #2 for markers other than EOI, since
  172200. * any other marker would have to be bogus data in that case.
  172201. */
  172202. GLOBAL(boolean)
  172203. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172204. {
  172205. int marker = cinfo->unread_marker;
  172206. int action = 1;
  172207. /* Always put up a warning. */
  172208. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172209. /* Outer loop handles repeated decision after scanning forward. */
  172210. for (;;) {
  172211. if (marker < (int) M_SOF0)
  172212. action = 2; /* invalid marker */
  172213. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172214. action = 3; /* valid non-restart marker */
  172215. else {
  172216. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172217. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172218. action = 3; /* one of the next two expected restarts */
  172219. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172220. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172221. action = 2; /* a prior restart, so advance */
  172222. else
  172223. action = 1; /* desired restart or too far away */
  172224. }
  172225. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172226. switch (action) {
  172227. case 1:
  172228. /* Discard marker and let entropy decoder resume processing. */
  172229. cinfo->unread_marker = 0;
  172230. return TRUE;
  172231. case 2:
  172232. /* Scan to the next marker, and repeat the decision loop. */
  172233. if (! next_marker(cinfo))
  172234. return FALSE;
  172235. marker = cinfo->unread_marker;
  172236. break;
  172237. case 3:
  172238. /* Return without advancing past this marker. */
  172239. /* Entropy decoder will be forced to process an empty segment. */
  172240. return TRUE;
  172241. }
  172242. } /* end loop */
  172243. }
  172244. /*
  172245. * Reset marker processing state to begin a fresh datastream.
  172246. */
  172247. METHODDEF(void)
  172248. reset_marker_reader (j_decompress_ptr cinfo)
  172249. {
  172250. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172251. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172252. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172253. cinfo->unread_marker = 0; /* no pending marker */
  172254. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172255. marker->pub.saw_SOF = FALSE;
  172256. marker->pub.discarded_bytes = 0;
  172257. marker->cur_marker = NULL;
  172258. }
  172259. /*
  172260. * Initialize the marker reader module.
  172261. * This is called only once, when the decompression object is created.
  172262. */
  172263. GLOBAL(void)
  172264. jinit_marker_reader (j_decompress_ptr cinfo)
  172265. {
  172266. my_marker_ptr2 marker;
  172267. int i;
  172268. /* Create subobject in permanent pool */
  172269. marker = (my_marker_ptr2)
  172270. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172271. SIZEOF(my_marker_reader));
  172272. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172273. /* Initialize public method pointers */
  172274. marker->pub.reset_marker_reader = reset_marker_reader;
  172275. marker->pub.read_markers = read_markers;
  172276. marker->pub.read_restart_marker = read_restart_marker;
  172277. /* Initialize COM/APPn processing.
  172278. * By default, we examine and then discard APP0 and APP14,
  172279. * but simply discard COM and all other APPn.
  172280. */
  172281. marker->process_COM = skip_variable;
  172282. marker->length_limit_COM = 0;
  172283. for (i = 0; i < 16; i++) {
  172284. marker->process_APPn[i] = skip_variable;
  172285. marker->length_limit_APPn[i] = 0;
  172286. }
  172287. marker->process_APPn[0] = get_interesting_appn;
  172288. marker->process_APPn[14] = get_interesting_appn;
  172289. /* Reset marker processing state */
  172290. reset_marker_reader(cinfo);
  172291. }
  172292. /*
  172293. * Control saving of COM and APPn markers into marker_list.
  172294. */
  172295. #ifdef SAVE_MARKERS_SUPPORTED
  172296. GLOBAL(void)
  172297. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172298. unsigned int length_limit)
  172299. {
  172300. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172301. long maxlength;
  172302. jpeg_marker_parser_method processor;
  172303. /* Length limit mustn't be larger than what we can allocate
  172304. * (should only be a concern in a 16-bit environment).
  172305. */
  172306. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172307. if (((long) length_limit) > maxlength)
  172308. length_limit = (unsigned int) maxlength;
  172309. /* Choose processor routine to use.
  172310. * APP0/APP14 have special requirements.
  172311. */
  172312. if (length_limit) {
  172313. processor = save_marker;
  172314. /* If saving APP0/APP14, save at least enough for our internal use. */
  172315. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172316. length_limit = APP0_DATA_LEN;
  172317. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172318. length_limit = APP14_DATA_LEN;
  172319. } else {
  172320. processor = skip_variable;
  172321. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172322. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172323. processor = get_interesting_appn;
  172324. }
  172325. if (marker_code == (int) M_COM) {
  172326. marker->process_COM = processor;
  172327. marker->length_limit_COM = length_limit;
  172328. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172329. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172330. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172331. } else
  172332. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172333. }
  172334. #endif /* SAVE_MARKERS_SUPPORTED */
  172335. /*
  172336. * Install a special processing method for COM or APPn markers.
  172337. */
  172338. GLOBAL(void)
  172339. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172340. jpeg_marker_parser_method routine)
  172341. {
  172342. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172343. if (marker_code == (int) M_COM)
  172344. marker->process_COM = routine;
  172345. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172346. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172347. else
  172348. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172349. }
  172350. /*** End of inlined file: jdmarker.c ***/
  172351. /*** Start of inlined file: jdmaster.c ***/
  172352. #define JPEG_INTERNALS
  172353. /* Private state */
  172354. typedef struct {
  172355. struct jpeg_decomp_master pub; /* public fields */
  172356. int pass_number; /* # of passes completed */
  172357. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172358. /* Saved references to initialized quantizer modules,
  172359. * in case we need to switch modes.
  172360. */
  172361. struct jpeg_color_quantizer * quantizer_1pass;
  172362. struct jpeg_color_quantizer * quantizer_2pass;
  172363. } my_decomp_master;
  172364. typedef my_decomp_master * my_master_ptr6;
  172365. /*
  172366. * Determine whether merged upsample/color conversion should be used.
  172367. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172368. */
  172369. LOCAL(boolean)
  172370. use_merged_upsample (j_decompress_ptr cinfo)
  172371. {
  172372. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172373. /* Merging is the equivalent of plain box-filter upsampling */
  172374. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172375. return FALSE;
  172376. /* jdmerge.c only supports YCC=>RGB color conversion */
  172377. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172378. cinfo->out_color_space != JCS_RGB ||
  172379. cinfo->out_color_components != RGB_PIXELSIZE)
  172380. return FALSE;
  172381. /* and it only handles 2h1v or 2h2v sampling ratios */
  172382. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172383. cinfo->comp_info[1].h_samp_factor != 1 ||
  172384. cinfo->comp_info[2].h_samp_factor != 1 ||
  172385. cinfo->comp_info[0].v_samp_factor > 2 ||
  172386. cinfo->comp_info[1].v_samp_factor != 1 ||
  172387. cinfo->comp_info[2].v_samp_factor != 1)
  172388. return FALSE;
  172389. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172390. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172391. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172392. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172393. return FALSE;
  172394. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172395. return TRUE; /* by golly, it'll work... */
  172396. #else
  172397. return FALSE;
  172398. #endif
  172399. }
  172400. /*
  172401. * Compute output image dimensions and related values.
  172402. * NOTE: this is exported for possible use by application.
  172403. * Hence it mustn't do anything that can't be done twice.
  172404. * Also note that it may be called before the master module is initialized!
  172405. */
  172406. GLOBAL(void)
  172407. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172408. /* Do computations that are needed before master selection phase */
  172409. {
  172410. #ifdef IDCT_SCALING_SUPPORTED
  172411. int ci;
  172412. jpeg_component_info *compptr;
  172413. #endif
  172414. /* Prevent application from calling me at wrong times */
  172415. if (cinfo->global_state != DSTATE_READY)
  172416. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172417. #ifdef IDCT_SCALING_SUPPORTED
  172418. /* Compute actual output image dimensions and DCT scaling choices. */
  172419. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172420. /* Provide 1/8 scaling */
  172421. cinfo->output_width = (JDIMENSION)
  172422. jdiv_round_up((long) cinfo->image_width, 8L);
  172423. cinfo->output_height = (JDIMENSION)
  172424. jdiv_round_up((long) cinfo->image_height, 8L);
  172425. cinfo->min_DCT_scaled_size = 1;
  172426. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172427. /* Provide 1/4 scaling */
  172428. cinfo->output_width = (JDIMENSION)
  172429. jdiv_round_up((long) cinfo->image_width, 4L);
  172430. cinfo->output_height = (JDIMENSION)
  172431. jdiv_round_up((long) cinfo->image_height, 4L);
  172432. cinfo->min_DCT_scaled_size = 2;
  172433. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172434. /* Provide 1/2 scaling */
  172435. cinfo->output_width = (JDIMENSION)
  172436. jdiv_round_up((long) cinfo->image_width, 2L);
  172437. cinfo->output_height = (JDIMENSION)
  172438. jdiv_round_up((long) cinfo->image_height, 2L);
  172439. cinfo->min_DCT_scaled_size = 4;
  172440. } else {
  172441. /* Provide 1/1 scaling */
  172442. cinfo->output_width = cinfo->image_width;
  172443. cinfo->output_height = cinfo->image_height;
  172444. cinfo->min_DCT_scaled_size = DCTSIZE;
  172445. }
  172446. /* In selecting the actual DCT scaling for each component, we try to
  172447. * scale up the chroma components via IDCT scaling rather than upsampling.
  172448. * This saves time if the upsampler gets to use 1:1 scaling.
  172449. * Note this code assumes that the supported DCT scalings are powers of 2.
  172450. */
  172451. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172452. ci++, compptr++) {
  172453. int ssize = cinfo->min_DCT_scaled_size;
  172454. while (ssize < DCTSIZE &&
  172455. (compptr->h_samp_factor * ssize * 2 <=
  172456. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172457. (compptr->v_samp_factor * ssize * 2 <=
  172458. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172459. ssize = ssize * 2;
  172460. }
  172461. compptr->DCT_scaled_size = ssize;
  172462. }
  172463. /* Recompute downsampled dimensions of components;
  172464. * application needs to know these if using raw downsampled data.
  172465. */
  172466. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172467. ci++, compptr++) {
  172468. /* Size in samples, after IDCT scaling */
  172469. compptr->downsampled_width = (JDIMENSION)
  172470. jdiv_round_up((long) cinfo->image_width *
  172471. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172472. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172473. compptr->downsampled_height = (JDIMENSION)
  172474. jdiv_round_up((long) cinfo->image_height *
  172475. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172476. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172477. }
  172478. #else /* !IDCT_SCALING_SUPPORTED */
  172479. /* Hardwire it to "no scaling" */
  172480. cinfo->output_width = cinfo->image_width;
  172481. cinfo->output_height = cinfo->image_height;
  172482. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172483. * and has computed unscaled downsampled_width and downsampled_height.
  172484. */
  172485. #endif /* IDCT_SCALING_SUPPORTED */
  172486. /* Report number of components in selected colorspace. */
  172487. /* Probably this should be in the color conversion module... */
  172488. switch (cinfo->out_color_space) {
  172489. case JCS_GRAYSCALE:
  172490. cinfo->out_color_components = 1;
  172491. break;
  172492. case JCS_RGB:
  172493. #if RGB_PIXELSIZE != 3
  172494. cinfo->out_color_components = RGB_PIXELSIZE;
  172495. break;
  172496. #endif /* else share code with YCbCr */
  172497. case JCS_YCbCr:
  172498. cinfo->out_color_components = 3;
  172499. break;
  172500. case JCS_CMYK:
  172501. case JCS_YCCK:
  172502. cinfo->out_color_components = 4;
  172503. break;
  172504. default: /* else must be same colorspace as in file */
  172505. cinfo->out_color_components = cinfo->num_components;
  172506. break;
  172507. }
  172508. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172509. cinfo->out_color_components);
  172510. /* See if upsampler will want to emit more than one row at a time */
  172511. if (use_merged_upsample(cinfo))
  172512. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172513. else
  172514. cinfo->rec_outbuf_height = 1;
  172515. }
  172516. /*
  172517. * Several decompression processes need to range-limit values to the range
  172518. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172519. * due to noise introduced by quantization, roundoff error, etc. These
  172520. * processes are inner loops and need to be as fast as possible. On most
  172521. * machines, particularly CPUs with pipelines or instruction prefetch,
  172522. * a (subscript-check-less) C table lookup
  172523. * x = sample_range_limit[x];
  172524. * is faster than explicit tests
  172525. * if (x < 0) x = 0;
  172526. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172527. * These processes all use a common table prepared by the routine below.
  172528. *
  172529. * For most steps we can mathematically guarantee that the initial value
  172530. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172531. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172532. * limiting step (just after the IDCT), a wildly out-of-range value is
  172533. * possible if the input data is corrupt. To avoid any chance of indexing
  172534. * off the end of memory and getting a bad-pointer trap, we perform the
  172535. * post-IDCT limiting thus:
  172536. * x = range_limit[x & MASK];
  172537. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172538. * samples. Under normal circumstances this is more than enough range and
  172539. * a correct output will be generated; with bogus input data the mask will
  172540. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172541. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172542. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172543. * So the post-IDCT limiting table ends up looking like this:
  172544. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172545. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172546. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172547. * 0,1,...,CENTERJSAMPLE-1
  172548. * Negative inputs select values from the upper half of the table after
  172549. * masking.
  172550. *
  172551. * We can save some space by overlapping the start of the post-IDCT table
  172552. * with the simpler range limiting table. The post-IDCT table begins at
  172553. * sample_range_limit + CENTERJSAMPLE.
  172554. *
  172555. * Note that the table is allocated in near data space on PCs; it's small
  172556. * enough and used often enough to justify this.
  172557. */
  172558. LOCAL(void)
  172559. prepare_range_limit_table (j_decompress_ptr cinfo)
  172560. /* Allocate and fill in the sample_range_limit table */
  172561. {
  172562. JSAMPLE * table;
  172563. int i;
  172564. table = (JSAMPLE *)
  172565. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172566. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172567. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172568. cinfo->sample_range_limit = table;
  172569. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172570. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172571. /* Main part of "simple" table: limit[x] = x */
  172572. for (i = 0; i <= MAXJSAMPLE; i++)
  172573. table[i] = (JSAMPLE) i;
  172574. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172575. /* End of simple table, rest of first half of post-IDCT table */
  172576. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172577. table[i] = MAXJSAMPLE;
  172578. /* Second half of post-IDCT table */
  172579. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172580. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172581. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172582. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172583. }
  172584. /*
  172585. * Master selection of decompression modules.
  172586. * This is done once at jpeg_start_decompress time. We determine
  172587. * which modules will be used and give them appropriate initialization calls.
  172588. * We also initialize the decompressor input side to begin consuming data.
  172589. *
  172590. * Since jpeg_read_header has finished, we know what is in the SOF
  172591. * and (first) SOS markers. We also have all the application parameter
  172592. * settings.
  172593. */
  172594. LOCAL(void)
  172595. master_selection (j_decompress_ptr cinfo)
  172596. {
  172597. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172598. boolean use_c_buffer;
  172599. long samplesperrow;
  172600. JDIMENSION jd_samplesperrow;
  172601. /* Initialize dimensions and other stuff */
  172602. jpeg_calc_output_dimensions(cinfo);
  172603. prepare_range_limit_table(cinfo);
  172604. /* Width of an output scanline must be representable as JDIMENSION. */
  172605. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172606. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172607. if ((long) jd_samplesperrow != samplesperrow)
  172608. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172609. /* Initialize my private state */
  172610. master->pass_number = 0;
  172611. master->using_merged_upsample = use_merged_upsample(cinfo);
  172612. /* Color quantizer selection */
  172613. master->quantizer_1pass = NULL;
  172614. master->quantizer_2pass = NULL;
  172615. /* No mode changes if not using buffered-image mode. */
  172616. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172617. cinfo->enable_1pass_quant = FALSE;
  172618. cinfo->enable_external_quant = FALSE;
  172619. cinfo->enable_2pass_quant = FALSE;
  172620. }
  172621. if (cinfo->quantize_colors) {
  172622. if (cinfo->raw_data_out)
  172623. ERREXIT(cinfo, JERR_NOTIMPL);
  172624. /* 2-pass quantizer only works in 3-component color space. */
  172625. if (cinfo->out_color_components != 3) {
  172626. cinfo->enable_1pass_quant = TRUE;
  172627. cinfo->enable_external_quant = FALSE;
  172628. cinfo->enable_2pass_quant = FALSE;
  172629. cinfo->colormap = NULL;
  172630. } else if (cinfo->colormap != NULL) {
  172631. cinfo->enable_external_quant = TRUE;
  172632. } else if (cinfo->two_pass_quantize) {
  172633. cinfo->enable_2pass_quant = TRUE;
  172634. } else {
  172635. cinfo->enable_1pass_quant = TRUE;
  172636. }
  172637. if (cinfo->enable_1pass_quant) {
  172638. #ifdef QUANT_1PASS_SUPPORTED
  172639. jinit_1pass_quantizer(cinfo);
  172640. master->quantizer_1pass = cinfo->cquantize;
  172641. #else
  172642. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172643. #endif
  172644. }
  172645. /* We use the 2-pass code to map to external colormaps. */
  172646. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172647. #ifdef QUANT_2PASS_SUPPORTED
  172648. jinit_2pass_quantizer(cinfo);
  172649. master->quantizer_2pass = cinfo->cquantize;
  172650. #else
  172651. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172652. #endif
  172653. }
  172654. /* If both quantizers are initialized, the 2-pass one is left active;
  172655. * this is necessary for starting with quantization to an external map.
  172656. */
  172657. }
  172658. /* Post-processing: in particular, color conversion first */
  172659. if (! cinfo->raw_data_out) {
  172660. if (master->using_merged_upsample) {
  172661. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172662. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172663. #else
  172664. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172665. #endif
  172666. } else {
  172667. jinit_color_deconverter(cinfo);
  172668. jinit_upsampler(cinfo);
  172669. }
  172670. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172671. }
  172672. /* Inverse DCT */
  172673. jinit_inverse_dct(cinfo);
  172674. /* Entropy decoding: either Huffman or arithmetic coding. */
  172675. if (cinfo->arith_code) {
  172676. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172677. } else {
  172678. if (cinfo->progressive_mode) {
  172679. #ifdef D_PROGRESSIVE_SUPPORTED
  172680. jinit_phuff_decoder(cinfo);
  172681. #else
  172682. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172683. #endif
  172684. } else
  172685. jinit_huff_decoder(cinfo);
  172686. }
  172687. /* Initialize principal buffer controllers. */
  172688. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172689. jinit_d_coef_controller(cinfo, use_c_buffer);
  172690. if (! cinfo->raw_data_out)
  172691. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172692. /* We can now tell the memory manager to allocate virtual arrays. */
  172693. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172694. /* Initialize input side of decompressor to consume first scan. */
  172695. (*cinfo->inputctl->start_input_pass) (cinfo);
  172696. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172697. /* If jpeg_start_decompress will read the whole file, initialize
  172698. * progress monitoring appropriately. The input step is counted
  172699. * as one pass.
  172700. */
  172701. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172702. cinfo->inputctl->has_multiple_scans) {
  172703. int nscans;
  172704. /* Estimate number of scans to set pass_limit. */
  172705. if (cinfo->progressive_mode) {
  172706. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172707. nscans = 2 + 3 * cinfo->num_components;
  172708. } else {
  172709. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172710. nscans = cinfo->num_components;
  172711. }
  172712. cinfo->progress->pass_counter = 0L;
  172713. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172714. cinfo->progress->completed_passes = 0;
  172715. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172716. /* Count the input pass as done */
  172717. master->pass_number++;
  172718. }
  172719. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172720. }
  172721. /*
  172722. * Per-pass setup.
  172723. * This is called at the beginning of each output pass. We determine which
  172724. * modules will be active during this pass and give them appropriate
  172725. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172726. * is a "real" output pass or a dummy pass for color quantization.
  172727. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172728. */
  172729. METHODDEF(void)
  172730. prepare_for_output_pass (j_decompress_ptr cinfo)
  172731. {
  172732. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172733. if (master->pub.is_dummy_pass) {
  172734. #ifdef QUANT_2PASS_SUPPORTED
  172735. /* Final pass of 2-pass quantization */
  172736. master->pub.is_dummy_pass = FALSE;
  172737. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172738. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172739. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172740. #else
  172741. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172742. #endif /* QUANT_2PASS_SUPPORTED */
  172743. } else {
  172744. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172745. /* Select new quantization method */
  172746. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172747. cinfo->cquantize = master->quantizer_2pass;
  172748. master->pub.is_dummy_pass = TRUE;
  172749. } else if (cinfo->enable_1pass_quant) {
  172750. cinfo->cquantize = master->quantizer_1pass;
  172751. } else {
  172752. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172753. }
  172754. }
  172755. (*cinfo->idct->start_pass) (cinfo);
  172756. (*cinfo->coef->start_output_pass) (cinfo);
  172757. if (! cinfo->raw_data_out) {
  172758. if (! master->using_merged_upsample)
  172759. (*cinfo->cconvert->start_pass) (cinfo);
  172760. (*cinfo->upsample->start_pass) (cinfo);
  172761. if (cinfo->quantize_colors)
  172762. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172763. (*cinfo->post->start_pass) (cinfo,
  172764. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172765. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172766. }
  172767. }
  172768. /* Set up progress monitor's pass info if present */
  172769. if (cinfo->progress != NULL) {
  172770. cinfo->progress->completed_passes = master->pass_number;
  172771. cinfo->progress->total_passes = master->pass_number +
  172772. (master->pub.is_dummy_pass ? 2 : 1);
  172773. /* In buffered-image mode, we assume one more output pass if EOI not
  172774. * yet reached, but no more passes if EOI has been reached.
  172775. */
  172776. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172777. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172778. }
  172779. }
  172780. }
  172781. /*
  172782. * Finish up at end of an output pass.
  172783. */
  172784. METHODDEF(void)
  172785. finish_output_pass (j_decompress_ptr cinfo)
  172786. {
  172787. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172788. if (cinfo->quantize_colors)
  172789. (*cinfo->cquantize->finish_pass) (cinfo);
  172790. master->pass_number++;
  172791. }
  172792. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172793. /*
  172794. * Switch to a new external colormap between output passes.
  172795. */
  172796. GLOBAL(void)
  172797. jpeg_new_colormap (j_decompress_ptr cinfo)
  172798. {
  172799. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172800. /* Prevent application from calling me at wrong times */
  172801. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172802. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172803. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172804. cinfo->colormap != NULL) {
  172805. /* Select 2-pass quantizer for external colormap use */
  172806. cinfo->cquantize = master->quantizer_2pass;
  172807. /* Notify quantizer of colormap change */
  172808. (*cinfo->cquantize->new_color_map) (cinfo);
  172809. master->pub.is_dummy_pass = FALSE; /* just in case */
  172810. } else
  172811. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172812. }
  172813. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172814. /*
  172815. * Initialize master decompression control and select active modules.
  172816. * This is performed at the start of jpeg_start_decompress.
  172817. */
  172818. GLOBAL(void)
  172819. jinit_master_decompress (j_decompress_ptr cinfo)
  172820. {
  172821. my_master_ptr6 master;
  172822. master = (my_master_ptr6)
  172823. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172824. SIZEOF(my_decomp_master));
  172825. cinfo->master = (struct jpeg_decomp_master *) master;
  172826. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172827. master->pub.finish_output_pass = finish_output_pass;
  172828. master->pub.is_dummy_pass = FALSE;
  172829. master_selection(cinfo);
  172830. }
  172831. /*** End of inlined file: jdmaster.c ***/
  172832. #undef FIX
  172833. /*** Start of inlined file: jdmerge.c ***/
  172834. #define JPEG_INTERNALS
  172835. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172836. /* Private subobject */
  172837. typedef struct {
  172838. struct jpeg_upsampler pub; /* public fields */
  172839. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172840. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172841. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172842. JSAMPARRAY output_buf));
  172843. /* Private state for YCC->RGB conversion */
  172844. int * Cr_r_tab; /* => table for Cr to R conversion */
  172845. int * Cb_b_tab; /* => table for Cb to B conversion */
  172846. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172847. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172848. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172849. * We need a "spare" row buffer to hold the second output row if the
  172850. * application provides just a one-row buffer; we also use the spare
  172851. * to discard the dummy last row if the image height is odd.
  172852. */
  172853. JSAMPROW spare_row;
  172854. boolean spare_full; /* T if spare buffer is occupied */
  172855. JDIMENSION out_row_width; /* samples per output row */
  172856. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172857. } my_upsampler;
  172858. typedef my_upsampler * my_upsample_ptr;
  172859. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172860. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172861. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172862. /*
  172863. * Initialize tables for YCC->RGB colorspace conversion.
  172864. * This is taken directly from jdcolor.c; see that file for more info.
  172865. */
  172866. LOCAL(void)
  172867. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172868. {
  172869. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172870. int i;
  172871. INT32 x;
  172872. SHIFT_TEMPS
  172873. upsample->Cr_r_tab = (int *)
  172874. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172875. (MAXJSAMPLE+1) * SIZEOF(int));
  172876. upsample->Cb_b_tab = (int *)
  172877. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172878. (MAXJSAMPLE+1) * SIZEOF(int));
  172879. upsample->Cr_g_tab = (INT32 *)
  172880. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172881. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172882. upsample->Cb_g_tab = (INT32 *)
  172883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172884. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172885. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172886. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172887. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172888. /* Cr=>R value is nearest int to 1.40200 * x */
  172889. upsample->Cr_r_tab[i] = (int)
  172890. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172891. /* Cb=>B value is nearest int to 1.77200 * x */
  172892. upsample->Cb_b_tab[i] = (int)
  172893. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172894. /* Cr=>G value is scaled-up -0.71414 * x */
  172895. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172896. /* Cb=>G value is scaled-up -0.34414 * x */
  172897. /* We also add in ONE_HALF so that need not do it in inner loop */
  172898. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172899. }
  172900. }
  172901. /*
  172902. * Initialize for an upsampling pass.
  172903. */
  172904. METHODDEF(void)
  172905. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172906. {
  172907. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172908. /* Mark the spare buffer empty */
  172909. upsample->spare_full = FALSE;
  172910. /* Initialize total-height counter for detecting bottom of image */
  172911. upsample->rows_to_go = cinfo->output_height;
  172912. }
  172913. /*
  172914. * Control routine to do upsampling (and color conversion).
  172915. *
  172916. * The control routine just handles the row buffering considerations.
  172917. */
  172918. METHODDEF(void)
  172919. merged_2v_upsample (j_decompress_ptr cinfo,
  172920. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172921. JDIMENSION,
  172922. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172923. JDIMENSION out_rows_avail)
  172924. /* 2:1 vertical sampling case: may need a spare row. */
  172925. {
  172926. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172927. JSAMPROW work_ptrs[2];
  172928. JDIMENSION num_rows; /* number of rows returned to caller */
  172929. if (upsample->spare_full) {
  172930. /* If we have a spare row saved from a previous cycle, just return it. */
  172931. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172932. 1, upsample->out_row_width);
  172933. num_rows = 1;
  172934. upsample->spare_full = FALSE;
  172935. } else {
  172936. /* Figure number of rows to return to caller. */
  172937. num_rows = 2;
  172938. /* Not more than the distance to the end of the image. */
  172939. if (num_rows > upsample->rows_to_go)
  172940. num_rows = upsample->rows_to_go;
  172941. /* And not more than what the client can accept: */
  172942. out_rows_avail -= *out_row_ctr;
  172943. if (num_rows > out_rows_avail)
  172944. num_rows = out_rows_avail;
  172945. /* Create output pointer array for upsampler. */
  172946. work_ptrs[0] = output_buf[*out_row_ctr];
  172947. if (num_rows > 1) {
  172948. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172949. } else {
  172950. work_ptrs[1] = upsample->spare_row;
  172951. upsample->spare_full = TRUE;
  172952. }
  172953. /* Now do the upsampling. */
  172954. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172955. }
  172956. /* Adjust counts */
  172957. *out_row_ctr += num_rows;
  172958. upsample->rows_to_go -= num_rows;
  172959. /* When the buffer is emptied, declare this input row group consumed */
  172960. if (! upsample->spare_full)
  172961. (*in_row_group_ctr)++;
  172962. }
  172963. METHODDEF(void)
  172964. merged_1v_upsample (j_decompress_ptr cinfo,
  172965. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172966. JDIMENSION,
  172967. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172968. JDIMENSION)
  172969. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172970. {
  172971. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172972. /* Just do the upsampling. */
  172973. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172974. output_buf + *out_row_ctr);
  172975. /* Adjust counts */
  172976. (*out_row_ctr)++;
  172977. (*in_row_group_ctr)++;
  172978. }
  172979. /*
  172980. * These are the routines invoked by the control routines to do
  172981. * the actual upsampling/conversion. One row group is processed per call.
  172982. *
  172983. * Note: since we may be writing directly into application-supplied buffers,
  172984. * we have to be honest about the output width; we can't assume the buffer
  172985. * has been rounded up to an even width.
  172986. */
  172987. /*
  172988. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172989. */
  172990. METHODDEF(void)
  172991. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172992. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172993. JSAMPARRAY output_buf)
  172994. {
  172995. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172996. register int y, cred, cgreen, cblue;
  172997. int cb, cr;
  172998. register JSAMPROW outptr;
  172999. JSAMPROW inptr0, inptr1, inptr2;
  173000. JDIMENSION col;
  173001. /* copy these pointers into registers if possible */
  173002. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173003. int * Crrtab = upsample->Cr_r_tab;
  173004. int * Cbbtab = upsample->Cb_b_tab;
  173005. INT32 * Crgtab = upsample->Cr_g_tab;
  173006. INT32 * Cbgtab = upsample->Cb_g_tab;
  173007. SHIFT_TEMPS
  173008. inptr0 = input_buf[0][in_row_group_ctr];
  173009. inptr1 = input_buf[1][in_row_group_ctr];
  173010. inptr2 = input_buf[2][in_row_group_ctr];
  173011. outptr = output_buf[0];
  173012. /* Loop for each pair of output pixels */
  173013. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173014. /* Do the chroma part of the calculation */
  173015. cb = GETJSAMPLE(*inptr1++);
  173016. cr = GETJSAMPLE(*inptr2++);
  173017. cred = Crrtab[cr];
  173018. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173019. cblue = Cbbtab[cb];
  173020. /* Fetch 2 Y values and emit 2 pixels */
  173021. y = GETJSAMPLE(*inptr0++);
  173022. outptr[RGB_RED] = range_limit[y + cred];
  173023. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173024. outptr[RGB_BLUE] = range_limit[y + cblue];
  173025. outptr += RGB_PIXELSIZE;
  173026. y = GETJSAMPLE(*inptr0++);
  173027. outptr[RGB_RED] = range_limit[y + cred];
  173028. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173029. outptr[RGB_BLUE] = range_limit[y + cblue];
  173030. outptr += RGB_PIXELSIZE;
  173031. }
  173032. /* If image width is odd, do the last output column separately */
  173033. if (cinfo->output_width & 1) {
  173034. cb = GETJSAMPLE(*inptr1);
  173035. cr = GETJSAMPLE(*inptr2);
  173036. cred = Crrtab[cr];
  173037. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173038. cblue = Cbbtab[cb];
  173039. y = GETJSAMPLE(*inptr0);
  173040. outptr[RGB_RED] = range_limit[y + cred];
  173041. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173042. outptr[RGB_BLUE] = range_limit[y + cblue];
  173043. }
  173044. }
  173045. /*
  173046. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173047. */
  173048. METHODDEF(void)
  173049. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173050. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173051. JSAMPARRAY output_buf)
  173052. {
  173053. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173054. register int y, cred, cgreen, cblue;
  173055. int cb, cr;
  173056. register JSAMPROW outptr0, outptr1;
  173057. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173058. JDIMENSION col;
  173059. /* copy these pointers into registers if possible */
  173060. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173061. int * Crrtab = upsample->Cr_r_tab;
  173062. int * Cbbtab = upsample->Cb_b_tab;
  173063. INT32 * Crgtab = upsample->Cr_g_tab;
  173064. INT32 * Cbgtab = upsample->Cb_g_tab;
  173065. SHIFT_TEMPS
  173066. inptr00 = input_buf[0][in_row_group_ctr*2];
  173067. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173068. inptr1 = input_buf[1][in_row_group_ctr];
  173069. inptr2 = input_buf[2][in_row_group_ctr];
  173070. outptr0 = output_buf[0];
  173071. outptr1 = output_buf[1];
  173072. /* Loop for each group of output pixels */
  173073. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173074. /* Do the chroma part of the calculation */
  173075. cb = GETJSAMPLE(*inptr1++);
  173076. cr = GETJSAMPLE(*inptr2++);
  173077. cred = Crrtab[cr];
  173078. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173079. cblue = Cbbtab[cb];
  173080. /* Fetch 4 Y values and emit 4 pixels */
  173081. y = GETJSAMPLE(*inptr00++);
  173082. outptr0[RGB_RED] = range_limit[y + cred];
  173083. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173084. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173085. outptr0 += RGB_PIXELSIZE;
  173086. y = GETJSAMPLE(*inptr00++);
  173087. outptr0[RGB_RED] = range_limit[y + cred];
  173088. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173089. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173090. outptr0 += RGB_PIXELSIZE;
  173091. y = GETJSAMPLE(*inptr01++);
  173092. outptr1[RGB_RED] = range_limit[y + cred];
  173093. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173094. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173095. outptr1 += RGB_PIXELSIZE;
  173096. y = GETJSAMPLE(*inptr01++);
  173097. outptr1[RGB_RED] = range_limit[y + cred];
  173098. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173099. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173100. outptr1 += RGB_PIXELSIZE;
  173101. }
  173102. /* If image width is odd, do the last output column separately */
  173103. if (cinfo->output_width & 1) {
  173104. cb = GETJSAMPLE(*inptr1);
  173105. cr = GETJSAMPLE(*inptr2);
  173106. cred = Crrtab[cr];
  173107. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173108. cblue = Cbbtab[cb];
  173109. y = GETJSAMPLE(*inptr00);
  173110. outptr0[RGB_RED] = range_limit[y + cred];
  173111. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173112. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173113. y = GETJSAMPLE(*inptr01);
  173114. outptr1[RGB_RED] = range_limit[y + cred];
  173115. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173116. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173117. }
  173118. }
  173119. /*
  173120. * Module initialization routine for merged upsampling/color conversion.
  173121. *
  173122. * NB: this is called under the conditions determined by use_merged_upsample()
  173123. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173124. * of this module; no safety checks are made here.
  173125. */
  173126. GLOBAL(void)
  173127. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173128. {
  173129. my_upsample_ptr upsample;
  173130. upsample = (my_upsample_ptr)
  173131. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173132. SIZEOF(my_upsampler));
  173133. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173134. upsample->pub.start_pass = start_pass_merged_upsample;
  173135. upsample->pub.need_context_rows = FALSE;
  173136. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173137. if (cinfo->max_v_samp_factor == 2) {
  173138. upsample->pub.upsample = merged_2v_upsample;
  173139. upsample->upmethod = h2v2_merged_upsample;
  173140. /* Allocate a spare row buffer */
  173141. upsample->spare_row = (JSAMPROW)
  173142. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173143. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173144. } else {
  173145. upsample->pub.upsample = merged_1v_upsample;
  173146. upsample->upmethod = h2v1_merged_upsample;
  173147. /* No spare row needed */
  173148. upsample->spare_row = NULL;
  173149. }
  173150. build_ycc_rgb_table2(cinfo);
  173151. }
  173152. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173153. /*** End of inlined file: jdmerge.c ***/
  173154. #undef ASSIGN_STATE
  173155. /*** Start of inlined file: jdphuff.c ***/
  173156. #define JPEG_INTERNALS
  173157. #ifdef D_PROGRESSIVE_SUPPORTED
  173158. /*
  173159. * Expanded entropy decoder object for progressive Huffman decoding.
  173160. *
  173161. * The savable_state subrecord contains fields that change within an MCU,
  173162. * but must not be updated permanently until we complete the MCU.
  173163. */
  173164. typedef struct {
  173165. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173166. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173167. } savable_state3;
  173168. /* This macro is to work around compilers with missing or broken
  173169. * structure assignment. You'll need to fix this code if you have
  173170. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173171. */
  173172. #ifndef NO_STRUCT_ASSIGN
  173173. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173174. #else
  173175. #if MAX_COMPS_IN_SCAN == 4
  173176. #define ASSIGN_STATE(dest,src) \
  173177. ((dest).EOBRUN = (src).EOBRUN, \
  173178. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173179. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173180. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173181. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173182. #endif
  173183. #endif
  173184. typedef struct {
  173185. struct jpeg_entropy_decoder pub; /* public fields */
  173186. /* These fields are loaded into local variables at start of each MCU.
  173187. * In case of suspension, we exit WITHOUT updating them.
  173188. */
  173189. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173190. savable_state3 saved; /* Other state at start of MCU */
  173191. /* These fields are NOT loaded into local working state. */
  173192. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173193. /* Pointers to derived tables (these workspaces have image lifespan) */
  173194. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173195. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173196. } phuff_entropy_decoder;
  173197. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173198. /* Forward declarations */
  173199. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173200. JBLOCKROW *MCU_data));
  173201. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173202. JBLOCKROW *MCU_data));
  173203. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173204. JBLOCKROW *MCU_data));
  173205. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173206. JBLOCKROW *MCU_data));
  173207. /*
  173208. * Initialize for a Huffman-compressed scan.
  173209. */
  173210. METHODDEF(void)
  173211. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173212. {
  173213. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173214. boolean is_DC_band, bad;
  173215. int ci, coefi, tbl;
  173216. int *coef_bit_ptr;
  173217. jpeg_component_info * compptr;
  173218. is_DC_band = (cinfo->Ss == 0);
  173219. /* Validate scan parameters */
  173220. bad = FALSE;
  173221. if (is_DC_band) {
  173222. if (cinfo->Se != 0)
  173223. bad = TRUE;
  173224. } else {
  173225. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173226. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173227. bad = TRUE;
  173228. /* AC scans may have only one component */
  173229. if (cinfo->comps_in_scan != 1)
  173230. bad = TRUE;
  173231. }
  173232. if (cinfo->Ah != 0) {
  173233. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173234. if (cinfo->Al != cinfo->Ah-1)
  173235. bad = TRUE;
  173236. }
  173237. if (cinfo->Al > 13) /* need not check for < 0 */
  173238. bad = TRUE;
  173239. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173240. * but the spec doesn't say so, and we try to be liberal about what we
  173241. * accept. Note: large Al values could result in out-of-range DC
  173242. * coefficients during early scans, leading to bizarre displays due to
  173243. * overflows in the IDCT math. But we won't crash.
  173244. */
  173245. if (bad)
  173246. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173247. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173248. /* Update progression status, and verify that scan order is legal.
  173249. * Note that inter-scan inconsistencies are treated as warnings
  173250. * not fatal errors ... not clear if this is right way to behave.
  173251. */
  173252. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173253. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173254. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173255. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173256. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173257. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173258. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173259. if (cinfo->Ah != expected)
  173260. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173261. coef_bit_ptr[coefi] = cinfo->Al;
  173262. }
  173263. }
  173264. /* Select MCU decoding routine */
  173265. if (cinfo->Ah == 0) {
  173266. if (is_DC_band)
  173267. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173268. else
  173269. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173270. } else {
  173271. if (is_DC_band)
  173272. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173273. else
  173274. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173275. }
  173276. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173277. compptr = cinfo->cur_comp_info[ci];
  173278. /* Make sure requested tables are present, and compute derived tables.
  173279. * We may build same derived table more than once, but it's not expensive.
  173280. */
  173281. if (is_DC_band) {
  173282. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173283. tbl = compptr->dc_tbl_no;
  173284. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173285. & entropy->derived_tbls[tbl]);
  173286. }
  173287. } else {
  173288. tbl = compptr->ac_tbl_no;
  173289. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173290. & entropy->derived_tbls[tbl]);
  173291. /* remember the single active table */
  173292. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173293. }
  173294. /* Initialize DC predictions to 0 */
  173295. entropy->saved.last_dc_val[ci] = 0;
  173296. }
  173297. /* Initialize bitread state variables */
  173298. entropy->bitstate.bits_left = 0;
  173299. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173300. entropy->pub.insufficient_data = FALSE;
  173301. /* Initialize private state variables */
  173302. entropy->saved.EOBRUN = 0;
  173303. /* Initialize restart counter */
  173304. entropy->restarts_to_go = cinfo->restart_interval;
  173305. }
  173306. /*
  173307. * Check for a restart marker & resynchronize decoder.
  173308. * Returns FALSE if must suspend.
  173309. */
  173310. LOCAL(boolean)
  173311. process_restartp (j_decompress_ptr cinfo)
  173312. {
  173313. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173314. int ci;
  173315. /* Throw away any unused bits remaining in bit buffer; */
  173316. /* include any full bytes in next_marker's count of discarded bytes */
  173317. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173318. entropy->bitstate.bits_left = 0;
  173319. /* Advance past the RSTn marker */
  173320. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173321. return FALSE;
  173322. /* Re-initialize DC predictions to 0 */
  173323. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173324. entropy->saved.last_dc_val[ci] = 0;
  173325. /* Re-init EOB run count, too */
  173326. entropy->saved.EOBRUN = 0;
  173327. /* Reset restart counter */
  173328. entropy->restarts_to_go = cinfo->restart_interval;
  173329. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173330. * against a marker. In that case we will end up treating the next data
  173331. * segment as empty, and we can avoid producing bogus output pixels by
  173332. * leaving the flag set.
  173333. */
  173334. if (cinfo->unread_marker == 0)
  173335. entropy->pub.insufficient_data = FALSE;
  173336. return TRUE;
  173337. }
  173338. /*
  173339. * Huffman MCU decoding.
  173340. * Each of these routines decodes and returns one MCU's worth of
  173341. * Huffman-compressed coefficients.
  173342. * The coefficients are reordered from zigzag order into natural array order,
  173343. * but are not dequantized.
  173344. *
  173345. * The i'th block of the MCU is stored into the block pointed to by
  173346. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173347. *
  173348. * We return FALSE if data source requested suspension. In that case no
  173349. * changes have been made to permanent state. (Exception: some output
  173350. * coefficients may already have been assigned. This is harmless for
  173351. * spectral selection, since we'll just re-assign them on the next call.
  173352. * Successive approximation AC refinement has to be more careful, however.)
  173353. */
  173354. /*
  173355. * MCU decoding for DC initial scan (either spectral selection,
  173356. * or first pass of successive approximation).
  173357. */
  173358. METHODDEF(boolean)
  173359. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173360. {
  173361. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173362. int Al = cinfo->Al;
  173363. register int s, r;
  173364. int blkn, ci;
  173365. JBLOCKROW block;
  173366. BITREAD_STATE_VARS;
  173367. savable_state3 state;
  173368. d_derived_tbl * tbl;
  173369. jpeg_component_info * compptr;
  173370. /* Process restart marker if needed; may have to suspend */
  173371. if (cinfo->restart_interval) {
  173372. if (entropy->restarts_to_go == 0)
  173373. if (! process_restartp(cinfo))
  173374. return FALSE;
  173375. }
  173376. /* If we've run out of data, just leave the MCU set to zeroes.
  173377. * This way, we return uniform gray for the remainder of the segment.
  173378. */
  173379. if (! entropy->pub.insufficient_data) {
  173380. /* Load up working state */
  173381. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173382. ASSIGN_STATE(state, entropy->saved);
  173383. /* Outer loop handles each block in the MCU */
  173384. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173385. block = MCU_data[blkn];
  173386. ci = cinfo->MCU_membership[blkn];
  173387. compptr = cinfo->cur_comp_info[ci];
  173388. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173389. /* Decode a single block's worth of coefficients */
  173390. /* Section F.2.2.1: decode the DC coefficient difference */
  173391. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173392. if (s) {
  173393. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173394. r = GET_BITS(s);
  173395. s = HUFF_EXTEND(r, s);
  173396. }
  173397. /* Convert DC difference to actual value, update last_dc_val */
  173398. s += state.last_dc_val[ci];
  173399. state.last_dc_val[ci] = s;
  173400. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173401. (*block)[0] = (JCOEF) (s << Al);
  173402. }
  173403. /* Completed MCU, so update state */
  173404. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173405. ASSIGN_STATE(entropy->saved, state);
  173406. }
  173407. /* Account for restart interval (no-op if not using restarts) */
  173408. entropy->restarts_to_go--;
  173409. return TRUE;
  173410. }
  173411. /*
  173412. * MCU decoding for AC initial scan (either spectral selection,
  173413. * or first pass of successive approximation).
  173414. */
  173415. METHODDEF(boolean)
  173416. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173417. {
  173418. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173419. int Se = cinfo->Se;
  173420. int Al = cinfo->Al;
  173421. register int s, k, r;
  173422. unsigned int EOBRUN;
  173423. JBLOCKROW block;
  173424. BITREAD_STATE_VARS;
  173425. d_derived_tbl * tbl;
  173426. /* Process restart marker if needed; may have to suspend */
  173427. if (cinfo->restart_interval) {
  173428. if (entropy->restarts_to_go == 0)
  173429. if (! process_restartp(cinfo))
  173430. return FALSE;
  173431. }
  173432. /* If we've run out of data, just leave the MCU set to zeroes.
  173433. * This way, we return uniform gray for the remainder of the segment.
  173434. */
  173435. if (! entropy->pub.insufficient_data) {
  173436. /* Load up working state.
  173437. * We can avoid loading/saving bitread state if in an EOB run.
  173438. */
  173439. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173440. /* There is always only one block per MCU */
  173441. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173442. EOBRUN--; /* ...process it now (we do nothing) */
  173443. else {
  173444. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173445. block = MCU_data[0];
  173446. tbl = entropy->ac_derived_tbl;
  173447. for (k = cinfo->Ss; k <= Se; k++) {
  173448. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173449. r = s >> 4;
  173450. s &= 15;
  173451. if (s) {
  173452. k += r;
  173453. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173454. r = GET_BITS(s);
  173455. s = HUFF_EXTEND(r, s);
  173456. /* Scale and output coefficient in natural (dezigzagged) order */
  173457. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173458. } else {
  173459. if (r == 15) { /* ZRL */
  173460. k += 15; /* skip 15 zeroes in band */
  173461. } else { /* EOBr, run length is 2^r + appended bits */
  173462. EOBRUN = 1 << r;
  173463. if (r) { /* EOBr, r > 0 */
  173464. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173465. r = GET_BITS(r);
  173466. EOBRUN += r;
  173467. }
  173468. EOBRUN--; /* this band is processed at this moment */
  173469. break; /* force end-of-band */
  173470. }
  173471. }
  173472. }
  173473. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173474. }
  173475. /* Completed MCU, so update state */
  173476. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173477. }
  173478. /* Account for restart interval (no-op if not using restarts) */
  173479. entropy->restarts_to_go--;
  173480. return TRUE;
  173481. }
  173482. /*
  173483. * MCU decoding for DC successive approximation refinement scan.
  173484. * Note: we assume such scans can be multi-component, although the spec
  173485. * is not very clear on the point.
  173486. */
  173487. METHODDEF(boolean)
  173488. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173489. {
  173490. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173491. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173492. int blkn;
  173493. JBLOCKROW block;
  173494. BITREAD_STATE_VARS;
  173495. /* Process restart marker if needed; may have to suspend */
  173496. if (cinfo->restart_interval) {
  173497. if (entropy->restarts_to_go == 0)
  173498. if (! process_restartp(cinfo))
  173499. return FALSE;
  173500. }
  173501. /* Not worth the cycles to check insufficient_data here,
  173502. * since we will not change the data anyway if we read zeroes.
  173503. */
  173504. /* Load up working state */
  173505. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173506. /* Outer loop handles each block in the MCU */
  173507. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173508. block = MCU_data[blkn];
  173509. /* Encoded data is simply the next bit of the two's-complement DC value */
  173510. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173511. if (GET_BITS(1))
  173512. (*block)[0] |= p1;
  173513. /* Note: since we use |=, repeating the assignment later is safe */
  173514. }
  173515. /* Completed MCU, so update state */
  173516. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173517. /* Account for restart interval (no-op if not using restarts) */
  173518. entropy->restarts_to_go--;
  173519. return TRUE;
  173520. }
  173521. /*
  173522. * MCU decoding for AC successive approximation refinement scan.
  173523. */
  173524. METHODDEF(boolean)
  173525. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173526. {
  173527. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173528. int Se = cinfo->Se;
  173529. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173530. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173531. register int s, k, r;
  173532. unsigned int EOBRUN;
  173533. JBLOCKROW block;
  173534. JCOEFPTR thiscoef;
  173535. BITREAD_STATE_VARS;
  173536. d_derived_tbl * tbl;
  173537. int num_newnz;
  173538. int newnz_pos[DCTSIZE2];
  173539. /* Process restart marker if needed; may have to suspend */
  173540. if (cinfo->restart_interval) {
  173541. if (entropy->restarts_to_go == 0)
  173542. if (! process_restartp(cinfo))
  173543. return FALSE;
  173544. }
  173545. /* If we've run out of data, don't modify the MCU.
  173546. */
  173547. if (! entropy->pub.insufficient_data) {
  173548. /* Load up working state */
  173549. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173550. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173551. /* There is always only one block per MCU */
  173552. block = MCU_data[0];
  173553. tbl = entropy->ac_derived_tbl;
  173554. /* If we are forced to suspend, we must undo the assignments to any newly
  173555. * nonzero coefficients in the block, because otherwise we'd get confused
  173556. * next time about which coefficients were already nonzero.
  173557. * But we need not undo addition of bits to already-nonzero coefficients;
  173558. * instead, we can test the current bit to see if we already did it.
  173559. */
  173560. num_newnz = 0;
  173561. /* initialize coefficient loop counter to start of band */
  173562. k = cinfo->Ss;
  173563. if (EOBRUN == 0) {
  173564. for (; k <= Se; k++) {
  173565. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173566. r = s >> 4;
  173567. s &= 15;
  173568. if (s) {
  173569. if (s != 1) /* size of new coef should always be 1 */
  173570. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173571. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173572. if (GET_BITS(1))
  173573. s = p1; /* newly nonzero coef is positive */
  173574. else
  173575. s = m1; /* newly nonzero coef is negative */
  173576. } else {
  173577. if (r != 15) {
  173578. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173579. if (r) {
  173580. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173581. r = GET_BITS(r);
  173582. EOBRUN += r;
  173583. }
  173584. break; /* rest of block is handled by EOB logic */
  173585. }
  173586. /* note s = 0 for processing ZRL */
  173587. }
  173588. /* Advance over already-nonzero coefs and r still-zero coefs,
  173589. * appending correction bits to the nonzeroes. A correction bit is 1
  173590. * if the absolute value of the coefficient must be increased.
  173591. */
  173592. do {
  173593. thiscoef = *block + jpeg_natural_order[k];
  173594. if (*thiscoef != 0) {
  173595. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173596. if (GET_BITS(1)) {
  173597. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173598. if (*thiscoef >= 0)
  173599. *thiscoef += p1;
  173600. else
  173601. *thiscoef += m1;
  173602. }
  173603. }
  173604. } else {
  173605. if (--r < 0)
  173606. break; /* reached target zero coefficient */
  173607. }
  173608. k++;
  173609. } while (k <= Se);
  173610. if (s) {
  173611. int pos = jpeg_natural_order[k];
  173612. /* Output newly nonzero coefficient */
  173613. (*block)[pos] = (JCOEF) s;
  173614. /* Remember its position in case we have to suspend */
  173615. newnz_pos[num_newnz++] = pos;
  173616. }
  173617. }
  173618. }
  173619. if (EOBRUN > 0) {
  173620. /* Scan any remaining coefficient positions after the end-of-band
  173621. * (the last newly nonzero coefficient, if any). Append a correction
  173622. * bit to each already-nonzero coefficient. A correction bit is 1
  173623. * if the absolute value of the coefficient must be increased.
  173624. */
  173625. for (; k <= Se; k++) {
  173626. thiscoef = *block + jpeg_natural_order[k];
  173627. if (*thiscoef != 0) {
  173628. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173629. if (GET_BITS(1)) {
  173630. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173631. if (*thiscoef >= 0)
  173632. *thiscoef += p1;
  173633. else
  173634. *thiscoef += m1;
  173635. }
  173636. }
  173637. }
  173638. }
  173639. /* Count one block completed in EOB run */
  173640. EOBRUN--;
  173641. }
  173642. /* Completed MCU, so update state */
  173643. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173644. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173645. }
  173646. /* Account for restart interval (no-op if not using restarts) */
  173647. entropy->restarts_to_go--;
  173648. return TRUE;
  173649. undoit:
  173650. /* Re-zero any output coefficients that we made newly nonzero */
  173651. while (num_newnz > 0)
  173652. (*block)[newnz_pos[--num_newnz]] = 0;
  173653. return FALSE;
  173654. }
  173655. /*
  173656. * Module initialization routine for progressive Huffman entropy decoding.
  173657. */
  173658. GLOBAL(void)
  173659. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173660. {
  173661. phuff_entropy_ptr2 entropy;
  173662. int *coef_bit_ptr;
  173663. int ci, i;
  173664. entropy = (phuff_entropy_ptr2)
  173665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173666. SIZEOF(phuff_entropy_decoder));
  173667. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173668. entropy->pub.start_pass = start_pass_phuff_decoder;
  173669. /* Mark derived tables unallocated */
  173670. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173671. entropy->derived_tbls[i] = NULL;
  173672. }
  173673. /* Create progression status table */
  173674. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173675. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173676. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173677. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173678. for (ci = 0; ci < cinfo->num_components; ci++)
  173679. for (i = 0; i < DCTSIZE2; i++)
  173680. *coef_bit_ptr++ = -1;
  173681. }
  173682. #endif /* D_PROGRESSIVE_SUPPORTED */
  173683. /*** End of inlined file: jdphuff.c ***/
  173684. /*** Start of inlined file: jdpostct.c ***/
  173685. #define JPEG_INTERNALS
  173686. /* Private buffer controller object */
  173687. typedef struct {
  173688. struct jpeg_d_post_controller pub; /* public fields */
  173689. /* Color quantization source buffer: this holds output data from
  173690. * the upsample/color conversion step to be passed to the quantizer.
  173691. * For two-pass color quantization, we need a full-image buffer;
  173692. * for one-pass operation, a strip buffer is sufficient.
  173693. */
  173694. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173695. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173696. JDIMENSION strip_height; /* buffer size in rows */
  173697. /* for two-pass mode only: */
  173698. JDIMENSION starting_row; /* row # of first row in current strip */
  173699. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173700. } my_post_controller;
  173701. typedef my_post_controller * my_post_ptr;
  173702. /* Forward declarations */
  173703. METHODDEF(void) post_process_1pass
  173704. JPP((j_decompress_ptr cinfo,
  173705. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173706. JDIMENSION in_row_groups_avail,
  173707. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173708. JDIMENSION out_rows_avail));
  173709. #ifdef QUANT_2PASS_SUPPORTED
  173710. METHODDEF(void) post_process_prepass
  173711. JPP((j_decompress_ptr cinfo,
  173712. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173713. JDIMENSION in_row_groups_avail,
  173714. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173715. JDIMENSION out_rows_avail));
  173716. METHODDEF(void) post_process_2pass
  173717. JPP((j_decompress_ptr cinfo,
  173718. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173719. JDIMENSION in_row_groups_avail,
  173720. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173721. JDIMENSION out_rows_avail));
  173722. #endif
  173723. /*
  173724. * Initialize for a processing pass.
  173725. */
  173726. METHODDEF(void)
  173727. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173728. {
  173729. my_post_ptr post = (my_post_ptr) cinfo->post;
  173730. switch (pass_mode) {
  173731. case JBUF_PASS_THRU:
  173732. if (cinfo->quantize_colors) {
  173733. /* Single-pass processing with color quantization. */
  173734. post->pub.post_process_data = post_process_1pass;
  173735. /* We could be doing buffered-image output before starting a 2-pass
  173736. * color quantization; in that case, jinit_d_post_controller did not
  173737. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173738. */
  173739. if (post->buffer == NULL) {
  173740. post->buffer = (*cinfo->mem->access_virt_sarray)
  173741. ((j_common_ptr) cinfo, post->whole_image,
  173742. (JDIMENSION) 0, post->strip_height, TRUE);
  173743. }
  173744. } else {
  173745. /* For single-pass processing without color quantization,
  173746. * I have no work to do; just call the upsampler directly.
  173747. */
  173748. post->pub.post_process_data = cinfo->upsample->upsample;
  173749. }
  173750. break;
  173751. #ifdef QUANT_2PASS_SUPPORTED
  173752. case JBUF_SAVE_AND_PASS:
  173753. /* First pass of 2-pass quantization */
  173754. if (post->whole_image == NULL)
  173755. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173756. post->pub.post_process_data = post_process_prepass;
  173757. break;
  173758. case JBUF_CRANK_DEST:
  173759. /* Second pass of 2-pass quantization */
  173760. if (post->whole_image == NULL)
  173761. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173762. post->pub.post_process_data = post_process_2pass;
  173763. break;
  173764. #endif /* QUANT_2PASS_SUPPORTED */
  173765. default:
  173766. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173767. break;
  173768. }
  173769. post->starting_row = post->next_row = 0;
  173770. }
  173771. /*
  173772. * Process some data in the one-pass (strip buffer) case.
  173773. * This is used for color precision reduction as well as one-pass quantization.
  173774. */
  173775. METHODDEF(void)
  173776. post_process_1pass (j_decompress_ptr cinfo,
  173777. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173778. JDIMENSION in_row_groups_avail,
  173779. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173780. JDIMENSION out_rows_avail)
  173781. {
  173782. my_post_ptr post = (my_post_ptr) cinfo->post;
  173783. JDIMENSION num_rows, max_rows;
  173784. /* Fill the buffer, but not more than what we can dump out in one go. */
  173785. /* Note we rely on the upsampler to detect bottom of image. */
  173786. max_rows = out_rows_avail - *out_row_ctr;
  173787. if (max_rows > post->strip_height)
  173788. max_rows = post->strip_height;
  173789. num_rows = 0;
  173790. (*cinfo->upsample->upsample) (cinfo,
  173791. input_buf, in_row_group_ctr, in_row_groups_avail,
  173792. post->buffer, &num_rows, max_rows);
  173793. /* Quantize and emit data. */
  173794. (*cinfo->cquantize->color_quantize) (cinfo,
  173795. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173796. *out_row_ctr += num_rows;
  173797. }
  173798. #ifdef QUANT_2PASS_SUPPORTED
  173799. /*
  173800. * Process some data in the first pass of 2-pass quantization.
  173801. */
  173802. METHODDEF(void)
  173803. post_process_prepass (j_decompress_ptr cinfo,
  173804. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173805. JDIMENSION in_row_groups_avail,
  173806. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173807. JDIMENSION)
  173808. {
  173809. my_post_ptr post = (my_post_ptr) cinfo->post;
  173810. JDIMENSION old_next_row, num_rows;
  173811. /* Reposition virtual buffer if at start of strip. */
  173812. if (post->next_row == 0) {
  173813. post->buffer = (*cinfo->mem->access_virt_sarray)
  173814. ((j_common_ptr) cinfo, post->whole_image,
  173815. post->starting_row, post->strip_height, TRUE);
  173816. }
  173817. /* Upsample some data (up to a strip height's worth). */
  173818. old_next_row = post->next_row;
  173819. (*cinfo->upsample->upsample) (cinfo,
  173820. input_buf, in_row_group_ctr, in_row_groups_avail,
  173821. post->buffer, &post->next_row, post->strip_height);
  173822. /* Allow quantizer to scan new data. No data is emitted, */
  173823. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173824. if (post->next_row > old_next_row) {
  173825. num_rows = post->next_row - old_next_row;
  173826. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173827. (JSAMPARRAY) NULL, (int) num_rows);
  173828. *out_row_ctr += num_rows;
  173829. }
  173830. /* Advance if we filled the strip. */
  173831. if (post->next_row >= post->strip_height) {
  173832. post->starting_row += post->strip_height;
  173833. post->next_row = 0;
  173834. }
  173835. }
  173836. /*
  173837. * Process some data in the second pass of 2-pass quantization.
  173838. */
  173839. METHODDEF(void)
  173840. post_process_2pass (j_decompress_ptr cinfo,
  173841. JSAMPIMAGE, JDIMENSION *,
  173842. JDIMENSION,
  173843. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173844. JDIMENSION out_rows_avail)
  173845. {
  173846. my_post_ptr post = (my_post_ptr) cinfo->post;
  173847. JDIMENSION num_rows, max_rows;
  173848. /* Reposition virtual buffer if at start of strip. */
  173849. if (post->next_row == 0) {
  173850. post->buffer = (*cinfo->mem->access_virt_sarray)
  173851. ((j_common_ptr) cinfo, post->whole_image,
  173852. post->starting_row, post->strip_height, FALSE);
  173853. }
  173854. /* Determine number of rows to emit. */
  173855. num_rows = post->strip_height - post->next_row; /* available in strip */
  173856. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173857. if (num_rows > max_rows)
  173858. num_rows = max_rows;
  173859. /* We have to check bottom of image here, can't depend on upsampler. */
  173860. max_rows = cinfo->output_height - post->starting_row;
  173861. if (num_rows > max_rows)
  173862. num_rows = max_rows;
  173863. /* Quantize and emit data. */
  173864. (*cinfo->cquantize->color_quantize) (cinfo,
  173865. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173866. (int) num_rows);
  173867. *out_row_ctr += num_rows;
  173868. /* Advance if we filled the strip. */
  173869. post->next_row += num_rows;
  173870. if (post->next_row >= post->strip_height) {
  173871. post->starting_row += post->strip_height;
  173872. post->next_row = 0;
  173873. }
  173874. }
  173875. #endif /* QUANT_2PASS_SUPPORTED */
  173876. /*
  173877. * Initialize postprocessing controller.
  173878. */
  173879. GLOBAL(void)
  173880. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173881. {
  173882. my_post_ptr post;
  173883. post = (my_post_ptr)
  173884. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173885. SIZEOF(my_post_controller));
  173886. cinfo->post = (struct jpeg_d_post_controller *) post;
  173887. post->pub.start_pass = start_pass_dpost;
  173888. post->whole_image = NULL; /* flag for no virtual arrays */
  173889. post->buffer = NULL; /* flag for no strip buffer */
  173890. /* Create the quantization buffer, if needed */
  173891. if (cinfo->quantize_colors) {
  173892. /* The buffer strip height is max_v_samp_factor, which is typically
  173893. * an efficient number of rows for upsampling to return.
  173894. * (In the presence of output rescaling, we might want to be smarter?)
  173895. */
  173896. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173897. if (need_full_buffer) {
  173898. /* Two-pass color quantization: need full-image storage. */
  173899. /* We round up the number of rows to a multiple of the strip height. */
  173900. #ifdef QUANT_2PASS_SUPPORTED
  173901. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173902. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173903. cinfo->output_width * cinfo->out_color_components,
  173904. (JDIMENSION) jround_up((long) cinfo->output_height,
  173905. (long) post->strip_height),
  173906. post->strip_height);
  173907. #else
  173908. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173909. #endif /* QUANT_2PASS_SUPPORTED */
  173910. } else {
  173911. /* One-pass color quantization: just make a strip buffer. */
  173912. post->buffer = (*cinfo->mem->alloc_sarray)
  173913. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173914. cinfo->output_width * cinfo->out_color_components,
  173915. post->strip_height);
  173916. }
  173917. }
  173918. }
  173919. /*** End of inlined file: jdpostct.c ***/
  173920. #undef FIX
  173921. /*** Start of inlined file: jdsample.c ***/
  173922. #define JPEG_INTERNALS
  173923. /* Pointer to routine to upsample a single component */
  173924. typedef JMETHOD(void, upsample1_ptr,
  173925. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173926. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173927. /* Private subobject */
  173928. typedef struct {
  173929. struct jpeg_upsampler pub; /* public fields */
  173930. /* Color conversion buffer. When using separate upsampling and color
  173931. * conversion steps, this buffer holds one upsampled row group until it
  173932. * has been color converted and output.
  173933. * Note: we do not allocate any storage for component(s) which are full-size,
  173934. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173935. * simply set to point to the input data array, thereby avoiding copying.
  173936. */
  173937. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173938. /* Per-component upsampling method pointers */
  173939. upsample1_ptr methods[MAX_COMPONENTS];
  173940. int next_row_out; /* counts rows emitted from color_buf */
  173941. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173942. /* Height of an input row group for each component. */
  173943. int rowgroup_height[MAX_COMPONENTS];
  173944. /* These arrays save pixel expansion factors so that int_expand need not
  173945. * recompute them each time. They are unused for other upsampling methods.
  173946. */
  173947. UINT8 h_expand[MAX_COMPONENTS];
  173948. UINT8 v_expand[MAX_COMPONENTS];
  173949. } my_upsampler2;
  173950. typedef my_upsampler2 * my_upsample_ptr2;
  173951. /*
  173952. * Initialize for an upsampling pass.
  173953. */
  173954. METHODDEF(void)
  173955. start_pass_upsample (j_decompress_ptr cinfo)
  173956. {
  173957. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173958. /* Mark the conversion buffer empty */
  173959. upsample->next_row_out = cinfo->max_v_samp_factor;
  173960. /* Initialize total-height counter for detecting bottom of image */
  173961. upsample->rows_to_go = cinfo->output_height;
  173962. }
  173963. /*
  173964. * Control routine to do upsampling (and color conversion).
  173965. *
  173966. * In this version we upsample each component independently.
  173967. * We upsample one row group into the conversion buffer, then apply
  173968. * color conversion a row at a time.
  173969. */
  173970. METHODDEF(void)
  173971. sep_upsample (j_decompress_ptr cinfo,
  173972. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173973. JDIMENSION,
  173974. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173975. JDIMENSION out_rows_avail)
  173976. {
  173977. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173978. int ci;
  173979. jpeg_component_info * compptr;
  173980. JDIMENSION num_rows;
  173981. /* Fill the conversion buffer, if it's empty */
  173982. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173983. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173984. ci++, compptr++) {
  173985. /* Invoke per-component upsample method. Notice we pass a POINTER
  173986. * to color_buf[ci], so that fullsize_upsample can change it.
  173987. */
  173988. (*upsample->methods[ci]) (cinfo, compptr,
  173989. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173990. upsample->color_buf + ci);
  173991. }
  173992. upsample->next_row_out = 0;
  173993. }
  173994. /* Color-convert and emit rows */
  173995. /* How many we have in the buffer: */
  173996. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173997. /* Not more than the distance to the end of the image. Need this test
  173998. * in case the image height is not a multiple of max_v_samp_factor:
  173999. */
  174000. if (num_rows > upsample->rows_to_go)
  174001. num_rows = upsample->rows_to_go;
  174002. /* And not more than what the client can accept: */
  174003. out_rows_avail -= *out_row_ctr;
  174004. if (num_rows > out_rows_avail)
  174005. num_rows = out_rows_avail;
  174006. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174007. (JDIMENSION) upsample->next_row_out,
  174008. output_buf + *out_row_ctr,
  174009. (int) num_rows);
  174010. /* Adjust counts */
  174011. *out_row_ctr += num_rows;
  174012. upsample->rows_to_go -= num_rows;
  174013. upsample->next_row_out += num_rows;
  174014. /* When the buffer is emptied, declare this input row group consumed */
  174015. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174016. (*in_row_group_ctr)++;
  174017. }
  174018. /*
  174019. * These are the routines invoked by sep_upsample to upsample pixel values
  174020. * of a single component. One row group is processed per call.
  174021. */
  174022. /*
  174023. * For full-size components, we just make color_buf[ci] point at the
  174024. * input buffer, and thus avoid copying any data. Note that this is
  174025. * safe only because sep_upsample doesn't declare the input row group
  174026. * "consumed" until we are done color converting and emitting it.
  174027. */
  174028. METHODDEF(void)
  174029. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174030. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174031. {
  174032. *output_data_ptr = input_data;
  174033. }
  174034. /*
  174035. * This is a no-op version used for "uninteresting" components.
  174036. * These components will not be referenced by color conversion.
  174037. */
  174038. METHODDEF(void)
  174039. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174040. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174041. {
  174042. *output_data_ptr = NULL; /* safety check */
  174043. }
  174044. /*
  174045. * This version handles any integral sampling ratios.
  174046. * This is not used for typical JPEG files, so it need not be fast.
  174047. * Nor, for that matter, is it particularly accurate: the algorithm is
  174048. * simple replication of the input pixel onto the corresponding output
  174049. * pixels. The hi-falutin sampling literature refers to this as a
  174050. * "box filter". A box filter tends to introduce visible artifacts,
  174051. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174052. * you would be well advised to improve this code.
  174053. */
  174054. METHODDEF(void)
  174055. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174056. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174057. {
  174058. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174059. JSAMPARRAY output_data = *output_data_ptr;
  174060. register JSAMPROW inptr, outptr;
  174061. register JSAMPLE invalue;
  174062. register int h;
  174063. JSAMPROW outend;
  174064. int h_expand, v_expand;
  174065. int inrow, outrow;
  174066. h_expand = upsample->h_expand[compptr->component_index];
  174067. v_expand = upsample->v_expand[compptr->component_index];
  174068. inrow = outrow = 0;
  174069. while (outrow < cinfo->max_v_samp_factor) {
  174070. /* Generate one output row with proper horizontal expansion */
  174071. inptr = input_data[inrow];
  174072. outptr = output_data[outrow];
  174073. outend = outptr + cinfo->output_width;
  174074. while (outptr < outend) {
  174075. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174076. for (h = h_expand; h > 0; h--) {
  174077. *outptr++ = invalue;
  174078. }
  174079. }
  174080. /* Generate any additional output rows by duplicating the first one */
  174081. if (v_expand > 1) {
  174082. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174083. v_expand-1, cinfo->output_width);
  174084. }
  174085. inrow++;
  174086. outrow += v_expand;
  174087. }
  174088. }
  174089. /*
  174090. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174091. * It's still a box filter.
  174092. */
  174093. METHODDEF(void)
  174094. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174095. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174096. {
  174097. JSAMPARRAY output_data = *output_data_ptr;
  174098. register JSAMPROW inptr, outptr;
  174099. register JSAMPLE invalue;
  174100. JSAMPROW outend;
  174101. int inrow;
  174102. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174103. inptr = input_data[inrow];
  174104. outptr = output_data[inrow];
  174105. outend = outptr + cinfo->output_width;
  174106. while (outptr < outend) {
  174107. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174108. *outptr++ = invalue;
  174109. *outptr++ = invalue;
  174110. }
  174111. }
  174112. }
  174113. /*
  174114. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174115. * It's still a box filter.
  174116. */
  174117. METHODDEF(void)
  174118. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174119. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174120. {
  174121. JSAMPARRAY output_data = *output_data_ptr;
  174122. register JSAMPROW inptr, outptr;
  174123. register JSAMPLE invalue;
  174124. JSAMPROW outend;
  174125. int inrow, outrow;
  174126. inrow = outrow = 0;
  174127. while (outrow < cinfo->max_v_samp_factor) {
  174128. inptr = input_data[inrow];
  174129. outptr = output_data[outrow];
  174130. outend = outptr + cinfo->output_width;
  174131. while (outptr < outend) {
  174132. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174133. *outptr++ = invalue;
  174134. *outptr++ = invalue;
  174135. }
  174136. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174137. 1, cinfo->output_width);
  174138. inrow++;
  174139. outrow += 2;
  174140. }
  174141. }
  174142. /*
  174143. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174144. *
  174145. * The upsampling algorithm is linear interpolation between pixel centers,
  174146. * also known as a "triangle filter". This is a good compromise between
  174147. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174148. * of the way between input pixel centers.
  174149. *
  174150. * A note about the "bias" calculations: when rounding fractional values to
  174151. * integer, we do not want to always round 0.5 up to the next integer.
  174152. * If we did that, we'd introduce a noticeable bias towards larger values.
  174153. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174154. * alternate pixel locations (a simple ordered dither pattern).
  174155. */
  174156. METHODDEF(void)
  174157. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174158. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174159. {
  174160. JSAMPARRAY output_data = *output_data_ptr;
  174161. register JSAMPROW inptr, outptr;
  174162. register int invalue;
  174163. register JDIMENSION colctr;
  174164. int inrow;
  174165. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174166. inptr = input_data[inrow];
  174167. outptr = output_data[inrow];
  174168. /* Special case for first column */
  174169. invalue = GETJSAMPLE(*inptr++);
  174170. *outptr++ = (JSAMPLE) invalue;
  174171. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174172. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174173. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174174. invalue = GETJSAMPLE(*inptr++) * 3;
  174175. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174176. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174177. }
  174178. /* Special case for last column */
  174179. invalue = GETJSAMPLE(*inptr);
  174180. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174181. *outptr++ = (JSAMPLE) invalue;
  174182. }
  174183. }
  174184. /*
  174185. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174186. * Again a triangle filter; see comments for h2v1 case, above.
  174187. *
  174188. * It is OK for us to reference the adjacent input rows because we demanded
  174189. * context from the main buffer controller (see initialization code).
  174190. */
  174191. METHODDEF(void)
  174192. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174193. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174194. {
  174195. JSAMPARRAY output_data = *output_data_ptr;
  174196. register JSAMPROW inptr0, inptr1, outptr;
  174197. #if BITS_IN_JSAMPLE == 8
  174198. register int thiscolsum, lastcolsum, nextcolsum;
  174199. #else
  174200. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174201. #endif
  174202. register JDIMENSION colctr;
  174203. int inrow, outrow, v;
  174204. inrow = outrow = 0;
  174205. while (outrow < cinfo->max_v_samp_factor) {
  174206. for (v = 0; v < 2; v++) {
  174207. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174208. inptr0 = input_data[inrow];
  174209. if (v == 0) /* next nearest is row above */
  174210. inptr1 = input_data[inrow-1];
  174211. else /* next nearest is row below */
  174212. inptr1 = input_data[inrow+1];
  174213. outptr = output_data[outrow++];
  174214. /* Special case for first column */
  174215. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174216. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174217. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174218. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174219. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174220. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174221. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174222. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174223. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174224. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174225. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174226. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174227. }
  174228. /* Special case for last column */
  174229. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174230. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174231. }
  174232. inrow++;
  174233. }
  174234. }
  174235. /*
  174236. * Module initialization routine for upsampling.
  174237. */
  174238. GLOBAL(void)
  174239. jinit_upsampler (j_decompress_ptr cinfo)
  174240. {
  174241. my_upsample_ptr2 upsample;
  174242. int ci;
  174243. jpeg_component_info * compptr;
  174244. boolean need_buffer, do_fancy;
  174245. int h_in_group, v_in_group, h_out_group, v_out_group;
  174246. upsample = (my_upsample_ptr2)
  174247. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174248. SIZEOF(my_upsampler2));
  174249. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174250. upsample->pub.start_pass = start_pass_upsample;
  174251. upsample->pub.upsample = sep_upsample;
  174252. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174253. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174254. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174255. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174256. * so don't ask for it.
  174257. */
  174258. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174259. /* Verify we can handle the sampling factors, select per-component methods,
  174260. * and create storage as needed.
  174261. */
  174262. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174263. ci++, compptr++) {
  174264. /* Compute size of an "input group" after IDCT scaling. This many samples
  174265. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174266. */
  174267. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174268. cinfo->min_DCT_scaled_size;
  174269. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174270. cinfo->min_DCT_scaled_size;
  174271. h_out_group = cinfo->max_h_samp_factor;
  174272. v_out_group = cinfo->max_v_samp_factor;
  174273. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174274. need_buffer = TRUE;
  174275. if (! compptr->component_needed) {
  174276. /* Don't bother to upsample an uninteresting component. */
  174277. upsample->methods[ci] = noop_upsample;
  174278. need_buffer = FALSE;
  174279. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174280. /* Fullsize components can be processed without any work. */
  174281. upsample->methods[ci] = fullsize_upsample;
  174282. need_buffer = FALSE;
  174283. } else if (h_in_group * 2 == h_out_group &&
  174284. v_in_group == v_out_group) {
  174285. /* Special cases for 2h1v upsampling */
  174286. if (do_fancy && compptr->downsampled_width > 2)
  174287. upsample->methods[ci] = h2v1_fancy_upsample;
  174288. else
  174289. upsample->methods[ci] = h2v1_upsample;
  174290. } else if (h_in_group * 2 == h_out_group &&
  174291. v_in_group * 2 == v_out_group) {
  174292. /* Special cases for 2h2v upsampling */
  174293. if (do_fancy && compptr->downsampled_width > 2) {
  174294. upsample->methods[ci] = h2v2_fancy_upsample;
  174295. upsample->pub.need_context_rows = TRUE;
  174296. } else
  174297. upsample->methods[ci] = h2v2_upsample;
  174298. } else if ((h_out_group % h_in_group) == 0 &&
  174299. (v_out_group % v_in_group) == 0) {
  174300. /* Generic integral-factors upsampling method */
  174301. upsample->methods[ci] = int_upsample;
  174302. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174303. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174304. } else
  174305. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174306. if (need_buffer) {
  174307. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174308. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174309. (JDIMENSION) jround_up((long) cinfo->output_width,
  174310. (long) cinfo->max_h_samp_factor),
  174311. (JDIMENSION) cinfo->max_v_samp_factor);
  174312. }
  174313. }
  174314. }
  174315. /*** End of inlined file: jdsample.c ***/
  174316. /*** Start of inlined file: jdtrans.c ***/
  174317. #define JPEG_INTERNALS
  174318. /* Forward declarations */
  174319. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174320. /*
  174321. * Read the coefficient arrays from a JPEG file.
  174322. * jpeg_read_header must be completed before calling this.
  174323. *
  174324. * The entire image is read into a set of virtual coefficient-block arrays,
  174325. * one per component. The return value is a pointer to the array of
  174326. * virtual-array descriptors. These can be manipulated directly via the
  174327. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174328. * To release the memory occupied by the virtual arrays, call
  174329. * jpeg_finish_decompress() when done with the data.
  174330. *
  174331. * An alternative usage is to simply obtain access to the coefficient arrays
  174332. * during a buffered-image-mode decompression operation. This is allowed
  174333. * after any jpeg_finish_output() call. The arrays can be accessed until
  174334. * jpeg_finish_decompress() is called. (Note that any call to the library
  174335. * may reposition the arrays, so don't rely on access_virt_barray() results
  174336. * to stay valid across library calls.)
  174337. *
  174338. * Returns NULL if suspended. This case need be checked only if
  174339. * a suspending data source is used.
  174340. */
  174341. GLOBAL(jvirt_barray_ptr *)
  174342. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174343. {
  174344. if (cinfo->global_state == DSTATE_READY) {
  174345. /* First call: initialize active modules */
  174346. transdecode_master_selection(cinfo);
  174347. cinfo->global_state = DSTATE_RDCOEFS;
  174348. }
  174349. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174350. /* Absorb whole file into the coef buffer */
  174351. for (;;) {
  174352. int retcode;
  174353. /* Call progress monitor hook if present */
  174354. if (cinfo->progress != NULL)
  174355. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174356. /* Absorb some more input */
  174357. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174358. if (retcode == JPEG_SUSPENDED)
  174359. return NULL;
  174360. if (retcode == JPEG_REACHED_EOI)
  174361. break;
  174362. /* Advance progress counter if appropriate */
  174363. if (cinfo->progress != NULL &&
  174364. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174365. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174366. /* startup underestimated number of scans; ratchet up one scan */
  174367. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174368. }
  174369. }
  174370. }
  174371. /* Set state so that jpeg_finish_decompress does the right thing */
  174372. cinfo->global_state = DSTATE_STOPPING;
  174373. }
  174374. /* At this point we should be in state DSTATE_STOPPING if being used
  174375. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174376. * to the coefficients during a full buffered-image-mode decompression.
  174377. */
  174378. if ((cinfo->global_state == DSTATE_STOPPING ||
  174379. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174380. return cinfo->coef->coef_arrays;
  174381. }
  174382. /* Oops, improper usage */
  174383. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174384. return NULL; /* keep compiler happy */
  174385. }
  174386. /*
  174387. * Master selection of decompression modules for transcoding.
  174388. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174389. */
  174390. LOCAL(void)
  174391. transdecode_master_selection (j_decompress_ptr cinfo)
  174392. {
  174393. /* This is effectively a buffered-image operation. */
  174394. cinfo->buffered_image = TRUE;
  174395. /* Entropy decoding: either Huffman or arithmetic coding. */
  174396. if (cinfo->arith_code) {
  174397. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174398. } else {
  174399. if (cinfo->progressive_mode) {
  174400. #ifdef D_PROGRESSIVE_SUPPORTED
  174401. jinit_phuff_decoder(cinfo);
  174402. #else
  174403. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174404. #endif
  174405. } else
  174406. jinit_huff_decoder(cinfo);
  174407. }
  174408. /* Always get a full-image coefficient buffer. */
  174409. jinit_d_coef_controller(cinfo, TRUE);
  174410. /* We can now tell the memory manager to allocate virtual arrays. */
  174411. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174412. /* Initialize input side of decompressor to consume first scan. */
  174413. (*cinfo->inputctl->start_input_pass) (cinfo);
  174414. /* Initialize progress monitoring. */
  174415. if (cinfo->progress != NULL) {
  174416. int nscans;
  174417. /* Estimate number of scans to set pass_limit. */
  174418. if (cinfo->progressive_mode) {
  174419. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174420. nscans = 2 + 3 * cinfo->num_components;
  174421. } else if (cinfo->inputctl->has_multiple_scans) {
  174422. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174423. nscans = cinfo->num_components;
  174424. } else {
  174425. nscans = 1;
  174426. }
  174427. cinfo->progress->pass_counter = 0L;
  174428. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174429. cinfo->progress->completed_passes = 0;
  174430. cinfo->progress->total_passes = 1;
  174431. }
  174432. }
  174433. /*** End of inlined file: jdtrans.c ***/
  174434. /*** Start of inlined file: jfdctflt.c ***/
  174435. #define JPEG_INTERNALS
  174436. #ifdef DCT_FLOAT_SUPPORTED
  174437. /*
  174438. * This module is specialized to the case DCTSIZE = 8.
  174439. */
  174440. #if DCTSIZE != 8
  174441. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174442. #endif
  174443. /*
  174444. * Perform the forward DCT on one block of samples.
  174445. */
  174446. GLOBAL(void)
  174447. jpeg_fdct_float (FAST_FLOAT * data)
  174448. {
  174449. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174450. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174451. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174452. FAST_FLOAT *dataptr;
  174453. int ctr;
  174454. /* Pass 1: process rows. */
  174455. dataptr = data;
  174456. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174457. tmp0 = dataptr[0] + dataptr[7];
  174458. tmp7 = dataptr[0] - dataptr[7];
  174459. tmp1 = dataptr[1] + dataptr[6];
  174460. tmp6 = dataptr[1] - dataptr[6];
  174461. tmp2 = dataptr[2] + dataptr[5];
  174462. tmp5 = dataptr[2] - dataptr[5];
  174463. tmp3 = dataptr[3] + dataptr[4];
  174464. tmp4 = dataptr[3] - dataptr[4];
  174465. /* Even part */
  174466. tmp10 = tmp0 + tmp3; /* phase 2 */
  174467. tmp13 = tmp0 - tmp3;
  174468. tmp11 = tmp1 + tmp2;
  174469. tmp12 = tmp1 - tmp2;
  174470. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174471. dataptr[4] = tmp10 - tmp11;
  174472. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174473. dataptr[2] = tmp13 + z1; /* phase 5 */
  174474. dataptr[6] = tmp13 - z1;
  174475. /* Odd part */
  174476. tmp10 = tmp4 + tmp5; /* phase 2 */
  174477. tmp11 = tmp5 + tmp6;
  174478. tmp12 = tmp6 + tmp7;
  174479. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174480. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174481. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174482. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174483. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174484. z11 = tmp7 + z3; /* phase 5 */
  174485. z13 = tmp7 - z3;
  174486. dataptr[5] = z13 + z2; /* phase 6 */
  174487. dataptr[3] = z13 - z2;
  174488. dataptr[1] = z11 + z4;
  174489. dataptr[7] = z11 - z4;
  174490. dataptr += DCTSIZE; /* advance pointer to next row */
  174491. }
  174492. /* Pass 2: process columns. */
  174493. dataptr = data;
  174494. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174495. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174496. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174497. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174498. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174499. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174500. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174501. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174502. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174503. /* Even part */
  174504. tmp10 = tmp0 + tmp3; /* phase 2 */
  174505. tmp13 = tmp0 - tmp3;
  174506. tmp11 = tmp1 + tmp2;
  174507. tmp12 = tmp1 - tmp2;
  174508. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174509. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174510. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174511. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174512. dataptr[DCTSIZE*6] = tmp13 - z1;
  174513. /* Odd part */
  174514. tmp10 = tmp4 + tmp5; /* phase 2 */
  174515. tmp11 = tmp5 + tmp6;
  174516. tmp12 = tmp6 + tmp7;
  174517. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174518. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174519. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174520. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174521. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174522. z11 = tmp7 + z3; /* phase 5 */
  174523. z13 = tmp7 - z3;
  174524. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174525. dataptr[DCTSIZE*3] = z13 - z2;
  174526. dataptr[DCTSIZE*1] = z11 + z4;
  174527. dataptr[DCTSIZE*7] = z11 - z4;
  174528. dataptr++; /* advance pointer to next column */
  174529. }
  174530. }
  174531. #endif /* DCT_FLOAT_SUPPORTED */
  174532. /*** End of inlined file: jfdctflt.c ***/
  174533. /*** Start of inlined file: jfdctint.c ***/
  174534. #define JPEG_INTERNALS
  174535. #ifdef DCT_ISLOW_SUPPORTED
  174536. /*
  174537. * This module is specialized to the case DCTSIZE = 8.
  174538. */
  174539. #if DCTSIZE != 8
  174540. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174541. #endif
  174542. /*
  174543. * The poop on this scaling stuff is as follows:
  174544. *
  174545. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174546. * larger than the true DCT outputs. The final outputs are therefore
  174547. * a factor of N larger than desired; since N=8 this can be cured by
  174548. * a simple right shift at the end of the algorithm. The advantage of
  174549. * this arrangement is that we save two multiplications per 1-D DCT,
  174550. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174551. * In the IJG code, this factor of 8 is removed by the quantization step
  174552. * (in jcdctmgr.c), NOT in this module.
  174553. *
  174554. * We have to do addition and subtraction of the integer inputs, which
  174555. * is no problem, and multiplication by fractional constants, which is
  174556. * a problem to do in integer arithmetic. We multiply all the constants
  174557. * by CONST_SCALE and convert them to integer constants (thus retaining
  174558. * CONST_BITS bits of precision in the constants). After doing a
  174559. * multiplication we have to divide the product by CONST_SCALE, with proper
  174560. * rounding, to produce the correct output. This division can be done
  174561. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174562. * as long as possible so that partial sums can be added together with
  174563. * full fractional precision.
  174564. *
  174565. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174566. * they are represented to better-than-integral precision. These outputs
  174567. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174568. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174569. * array is INT32 anyway.)
  174570. *
  174571. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174572. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174573. * shows that the values given below are the most effective.
  174574. */
  174575. #if BITS_IN_JSAMPLE == 8
  174576. #define CONST_BITS 13
  174577. #define PASS1_BITS 2
  174578. #else
  174579. #define CONST_BITS 13
  174580. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174581. #endif
  174582. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174583. * causing a lot of useless floating-point operations at run time.
  174584. * To get around this we use the following pre-calculated constants.
  174585. * If you change CONST_BITS you may want to add appropriate values.
  174586. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174587. */
  174588. #if CONST_BITS == 13
  174589. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174590. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174591. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174592. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174593. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174594. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174595. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174596. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174597. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174598. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174599. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174600. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174601. #else
  174602. #define FIX_0_298631336 FIX(0.298631336)
  174603. #define FIX_0_390180644 FIX(0.390180644)
  174604. #define FIX_0_541196100 FIX(0.541196100)
  174605. #define FIX_0_765366865 FIX(0.765366865)
  174606. #define FIX_0_899976223 FIX(0.899976223)
  174607. #define FIX_1_175875602 FIX(1.175875602)
  174608. #define FIX_1_501321110 FIX(1.501321110)
  174609. #define FIX_1_847759065 FIX(1.847759065)
  174610. #define FIX_1_961570560 FIX(1.961570560)
  174611. #define FIX_2_053119869 FIX(2.053119869)
  174612. #define FIX_2_562915447 FIX(2.562915447)
  174613. #define FIX_3_072711026 FIX(3.072711026)
  174614. #endif
  174615. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174616. * For 8-bit samples with the recommended scaling, all the variable
  174617. * and constant values involved are no more than 16 bits wide, so a
  174618. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174619. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174620. */
  174621. #if BITS_IN_JSAMPLE == 8
  174622. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174623. #else
  174624. #define MULTIPLY(var,const) ((var) * (const))
  174625. #endif
  174626. /*
  174627. * Perform the forward DCT on one block of samples.
  174628. */
  174629. GLOBAL(void)
  174630. jpeg_fdct_islow (DCTELEM * data)
  174631. {
  174632. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174633. INT32 tmp10, tmp11, tmp12, tmp13;
  174634. INT32 z1, z2, z3, z4, z5;
  174635. DCTELEM *dataptr;
  174636. int ctr;
  174637. SHIFT_TEMPS
  174638. /* Pass 1: process rows. */
  174639. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174640. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174641. dataptr = data;
  174642. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174643. tmp0 = dataptr[0] + dataptr[7];
  174644. tmp7 = dataptr[0] - dataptr[7];
  174645. tmp1 = dataptr[1] + dataptr[6];
  174646. tmp6 = dataptr[1] - dataptr[6];
  174647. tmp2 = dataptr[2] + dataptr[5];
  174648. tmp5 = dataptr[2] - dataptr[5];
  174649. tmp3 = dataptr[3] + dataptr[4];
  174650. tmp4 = dataptr[3] - dataptr[4];
  174651. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174652. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174653. */
  174654. tmp10 = tmp0 + tmp3;
  174655. tmp13 = tmp0 - tmp3;
  174656. tmp11 = tmp1 + tmp2;
  174657. tmp12 = tmp1 - tmp2;
  174658. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174659. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174660. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174661. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174662. CONST_BITS-PASS1_BITS);
  174663. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174664. CONST_BITS-PASS1_BITS);
  174665. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174666. * cK represents cos(K*pi/16).
  174667. * i0..i3 in the paper are tmp4..tmp7 here.
  174668. */
  174669. z1 = tmp4 + tmp7;
  174670. z2 = tmp5 + tmp6;
  174671. z3 = tmp4 + tmp6;
  174672. z4 = tmp5 + tmp7;
  174673. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174674. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174675. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174676. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174677. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174678. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174679. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174680. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174681. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174682. z3 += z5;
  174683. z4 += z5;
  174684. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174685. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174686. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174687. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174688. dataptr += DCTSIZE; /* advance pointer to next row */
  174689. }
  174690. /* Pass 2: process columns.
  174691. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174692. * by an overall factor of 8.
  174693. */
  174694. dataptr = data;
  174695. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174696. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174697. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174698. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174699. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174700. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174701. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174702. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174703. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174704. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174705. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174706. */
  174707. tmp10 = tmp0 + tmp3;
  174708. tmp13 = tmp0 - tmp3;
  174709. tmp11 = tmp1 + tmp2;
  174710. tmp12 = tmp1 - tmp2;
  174711. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174712. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174713. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174714. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174715. CONST_BITS+PASS1_BITS);
  174716. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174717. CONST_BITS+PASS1_BITS);
  174718. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174719. * cK represents cos(K*pi/16).
  174720. * i0..i3 in the paper are tmp4..tmp7 here.
  174721. */
  174722. z1 = tmp4 + tmp7;
  174723. z2 = tmp5 + tmp6;
  174724. z3 = tmp4 + tmp6;
  174725. z4 = tmp5 + tmp7;
  174726. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174727. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174728. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174729. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174730. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174731. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174732. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174733. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174734. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174735. z3 += z5;
  174736. z4 += z5;
  174737. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174738. CONST_BITS+PASS1_BITS);
  174739. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174740. CONST_BITS+PASS1_BITS);
  174741. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174742. CONST_BITS+PASS1_BITS);
  174743. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174744. CONST_BITS+PASS1_BITS);
  174745. dataptr++; /* advance pointer to next column */
  174746. }
  174747. }
  174748. #endif /* DCT_ISLOW_SUPPORTED */
  174749. /*** End of inlined file: jfdctint.c ***/
  174750. #undef CONST_BITS
  174751. #undef MULTIPLY
  174752. #undef FIX_0_541196100
  174753. /*** Start of inlined file: jfdctfst.c ***/
  174754. #define JPEG_INTERNALS
  174755. #ifdef DCT_IFAST_SUPPORTED
  174756. /*
  174757. * This module is specialized to the case DCTSIZE = 8.
  174758. */
  174759. #if DCTSIZE != 8
  174760. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174761. #endif
  174762. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174763. * see jfdctint.c for more details. However, we choose to descale
  174764. * (right shift) multiplication products as soon as they are formed,
  174765. * rather than carrying additional fractional bits into subsequent additions.
  174766. * This compromises accuracy slightly, but it lets us save a few shifts.
  174767. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174768. * everywhere except in the multiplications proper; this saves a good deal
  174769. * of work on 16-bit-int machines.
  174770. *
  174771. * Again to save a few shifts, the intermediate results between pass 1 and
  174772. * pass 2 are not upscaled, but are represented only to integral precision.
  174773. *
  174774. * A final compromise is to represent the multiplicative constants to only
  174775. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174776. * machines, and may also reduce the cost of multiplication (since there
  174777. * are fewer one-bits in the constants).
  174778. */
  174779. #define CONST_BITS 8
  174780. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174781. * causing a lot of useless floating-point operations at run time.
  174782. * To get around this we use the following pre-calculated constants.
  174783. * If you change CONST_BITS you may want to add appropriate values.
  174784. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174785. */
  174786. #if CONST_BITS == 8
  174787. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174788. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174789. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174790. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174791. #else
  174792. #define FIX_0_382683433 FIX(0.382683433)
  174793. #define FIX_0_541196100 FIX(0.541196100)
  174794. #define FIX_0_707106781 FIX(0.707106781)
  174795. #define FIX_1_306562965 FIX(1.306562965)
  174796. #endif
  174797. /* We can gain a little more speed, with a further compromise in accuracy,
  174798. * by omitting the addition in a descaling shift. This yields an incorrectly
  174799. * rounded result half the time...
  174800. */
  174801. #ifndef USE_ACCURATE_ROUNDING
  174802. #undef DESCALE
  174803. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174804. #endif
  174805. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174806. * descale to yield a DCTELEM result.
  174807. */
  174808. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174809. /*
  174810. * Perform the forward DCT on one block of samples.
  174811. */
  174812. GLOBAL(void)
  174813. jpeg_fdct_ifast (DCTELEM * data)
  174814. {
  174815. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174816. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174817. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174818. DCTELEM *dataptr;
  174819. int ctr;
  174820. SHIFT_TEMPS
  174821. /* Pass 1: process rows. */
  174822. dataptr = data;
  174823. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174824. tmp0 = dataptr[0] + dataptr[7];
  174825. tmp7 = dataptr[0] - dataptr[7];
  174826. tmp1 = dataptr[1] + dataptr[6];
  174827. tmp6 = dataptr[1] - dataptr[6];
  174828. tmp2 = dataptr[2] + dataptr[5];
  174829. tmp5 = dataptr[2] - dataptr[5];
  174830. tmp3 = dataptr[3] + dataptr[4];
  174831. tmp4 = dataptr[3] - dataptr[4];
  174832. /* Even part */
  174833. tmp10 = tmp0 + tmp3; /* phase 2 */
  174834. tmp13 = tmp0 - tmp3;
  174835. tmp11 = tmp1 + tmp2;
  174836. tmp12 = tmp1 - tmp2;
  174837. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174838. dataptr[4] = tmp10 - tmp11;
  174839. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174840. dataptr[2] = tmp13 + z1; /* phase 5 */
  174841. dataptr[6] = tmp13 - z1;
  174842. /* Odd part */
  174843. tmp10 = tmp4 + tmp5; /* phase 2 */
  174844. tmp11 = tmp5 + tmp6;
  174845. tmp12 = tmp6 + tmp7;
  174846. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174847. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174848. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174849. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174850. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174851. z11 = tmp7 + z3; /* phase 5 */
  174852. z13 = tmp7 - z3;
  174853. dataptr[5] = z13 + z2; /* phase 6 */
  174854. dataptr[3] = z13 - z2;
  174855. dataptr[1] = z11 + z4;
  174856. dataptr[7] = z11 - z4;
  174857. dataptr += DCTSIZE; /* advance pointer to next row */
  174858. }
  174859. /* Pass 2: process columns. */
  174860. dataptr = data;
  174861. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174862. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174863. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174864. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174865. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174866. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174867. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174868. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174869. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174870. /* Even part */
  174871. tmp10 = tmp0 + tmp3; /* phase 2 */
  174872. tmp13 = tmp0 - tmp3;
  174873. tmp11 = tmp1 + tmp2;
  174874. tmp12 = tmp1 - tmp2;
  174875. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174876. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174877. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174878. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174879. dataptr[DCTSIZE*6] = tmp13 - z1;
  174880. /* Odd part */
  174881. tmp10 = tmp4 + tmp5; /* phase 2 */
  174882. tmp11 = tmp5 + tmp6;
  174883. tmp12 = tmp6 + tmp7;
  174884. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174885. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174886. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174887. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174888. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174889. z11 = tmp7 + z3; /* phase 5 */
  174890. z13 = tmp7 - z3;
  174891. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174892. dataptr[DCTSIZE*3] = z13 - z2;
  174893. dataptr[DCTSIZE*1] = z11 + z4;
  174894. dataptr[DCTSIZE*7] = z11 - z4;
  174895. dataptr++; /* advance pointer to next column */
  174896. }
  174897. }
  174898. #endif /* DCT_IFAST_SUPPORTED */
  174899. /*** End of inlined file: jfdctfst.c ***/
  174900. #undef FIX_0_541196100
  174901. /*** Start of inlined file: jidctflt.c ***/
  174902. #define JPEG_INTERNALS
  174903. #ifdef DCT_FLOAT_SUPPORTED
  174904. /*
  174905. * This module is specialized to the case DCTSIZE = 8.
  174906. */
  174907. #if DCTSIZE != 8
  174908. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174909. #endif
  174910. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174911. * entry; produce a float result.
  174912. */
  174913. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174914. /*
  174915. * Perform dequantization and inverse DCT on one block of coefficients.
  174916. */
  174917. GLOBAL(void)
  174918. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174919. JCOEFPTR coef_block,
  174920. JSAMPARRAY output_buf, JDIMENSION output_col)
  174921. {
  174922. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174923. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174924. FAST_FLOAT z5, z10, z11, z12, z13;
  174925. JCOEFPTR inptr;
  174926. FLOAT_MULT_TYPE * quantptr;
  174927. FAST_FLOAT * wsptr;
  174928. JSAMPROW outptr;
  174929. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174930. int ctr;
  174931. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174932. SHIFT_TEMPS
  174933. /* Pass 1: process columns from input, store into work array. */
  174934. inptr = coef_block;
  174935. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174936. wsptr = workspace;
  174937. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174938. /* Due to quantization, we will usually find that many of the input
  174939. * coefficients are zero, especially the AC terms. We can exploit this
  174940. * by short-circuiting the IDCT calculation for any column in which all
  174941. * the AC terms are zero. In that case each output is equal to the
  174942. * DC coefficient (with scale factor as needed).
  174943. * With typical images and quantization tables, half or more of the
  174944. * column DCT calculations can be simplified this way.
  174945. */
  174946. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174947. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174948. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174949. inptr[DCTSIZE*7] == 0) {
  174950. /* AC terms all zero */
  174951. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174952. wsptr[DCTSIZE*0] = dcval;
  174953. wsptr[DCTSIZE*1] = dcval;
  174954. wsptr[DCTSIZE*2] = dcval;
  174955. wsptr[DCTSIZE*3] = dcval;
  174956. wsptr[DCTSIZE*4] = dcval;
  174957. wsptr[DCTSIZE*5] = dcval;
  174958. wsptr[DCTSIZE*6] = dcval;
  174959. wsptr[DCTSIZE*7] = dcval;
  174960. inptr++; /* advance pointers to next column */
  174961. quantptr++;
  174962. wsptr++;
  174963. continue;
  174964. }
  174965. /* Even part */
  174966. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174967. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174968. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174969. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174970. tmp10 = tmp0 + tmp2; /* phase 3 */
  174971. tmp11 = tmp0 - tmp2;
  174972. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174973. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174974. tmp0 = tmp10 + tmp13; /* phase 2 */
  174975. tmp3 = tmp10 - tmp13;
  174976. tmp1 = tmp11 + tmp12;
  174977. tmp2 = tmp11 - tmp12;
  174978. /* Odd part */
  174979. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174980. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174981. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174982. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174983. z13 = tmp6 + tmp5; /* phase 6 */
  174984. z10 = tmp6 - tmp5;
  174985. z11 = tmp4 + tmp7;
  174986. z12 = tmp4 - tmp7;
  174987. tmp7 = z11 + z13; /* phase 5 */
  174988. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174989. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174990. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174991. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174992. tmp6 = tmp12 - tmp7; /* phase 2 */
  174993. tmp5 = tmp11 - tmp6;
  174994. tmp4 = tmp10 + tmp5;
  174995. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174996. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174997. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174998. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174999. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175000. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175001. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175002. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175003. inptr++; /* advance pointers to next column */
  175004. quantptr++;
  175005. wsptr++;
  175006. }
  175007. /* Pass 2: process rows from work array, store into output array. */
  175008. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175009. wsptr = workspace;
  175010. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175011. outptr = output_buf[ctr] + output_col;
  175012. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175013. * However, the column calculation has created many nonzero AC terms, so
  175014. * the simplification applies less often (typically 5% to 10% of the time).
  175015. * And testing floats for zero is relatively expensive, so we don't bother.
  175016. */
  175017. /* Even part */
  175018. tmp10 = wsptr[0] + wsptr[4];
  175019. tmp11 = wsptr[0] - wsptr[4];
  175020. tmp13 = wsptr[2] + wsptr[6];
  175021. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175022. tmp0 = tmp10 + tmp13;
  175023. tmp3 = tmp10 - tmp13;
  175024. tmp1 = tmp11 + tmp12;
  175025. tmp2 = tmp11 - tmp12;
  175026. /* Odd part */
  175027. z13 = wsptr[5] + wsptr[3];
  175028. z10 = wsptr[5] - wsptr[3];
  175029. z11 = wsptr[1] + wsptr[7];
  175030. z12 = wsptr[1] - wsptr[7];
  175031. tmp7 = z11 + z13;
  175032. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175033. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175034. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175035. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175036. tmp6 = tmp12 - tmp7;
  175037. tmp5 = tmp11 - tmp6;
  175038. tmp4 = tmp10 + tmp5;
  175039. /* Final output stage: scale down by a factor of 8 and range-limit */
  175040. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175041. & RANGE_MASK];
  175042. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175043. & RANGE_MASK];
  175044. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175045. & RANGE_MASK];
  175046. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175047. & RANGE_MASK];
  175048. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175049. & RANGE_MASK];
  175050. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175051. & RANGE_MASK];
  175052. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175053. & RANGE_MASK];
  175054. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175055. & RANGE_MASK];
  175056. wsptr += DCTSIZE; /* advance pointer to next row */
  175057. }
  175058. }
  175059. #endif /* DCT_FLOAT_SUPPORTED */
  175060. /*** End of inlined file: jidctflt.c ***/
  175061. #undef CONST_BITS
  175062. #undef FIX_1_847759065
  175063. #undef MULTIPLY
  175064. #undef DEQUANTIZE
  175065. #undef DESCALE
  175066. /*** Start of inlined file: jidctfst.c ***/
  175067. #define JPEG_INTERNALS
  175068. #ifdef DCT_IFAST_SUPPORTED
  175069. /*
  175070. * This module is specialized to the case DCTSIZE = 8.
  175071. */
  175072. #if DCTSIZE != 8
  175073. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175074. #endif
  175075. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175076. * see jidctint.c for more details. However, we choose to descale
  175077. * (right shift) multiplication products as soon as they are formed,
  175078. * rather than carrying additional fractional bits into subsequent additions.
  175079. * This compromises accuracy slightly, but it lets us save a few shifts.
  175080. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175081. * everywhere except in the multiplications proper; this saves a good deal
  175082. * of work on 16-bit-int machines.
  175083. *
  175084. * The dequantized coefficients are not integers because the AA&N scaling
  175085. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175086. * so that the first and second IDCT rounds have the same input scaling.
  175087. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175088. * avoid a descaling shift; this compromises accuracy rather drastically
  175089. * for small quantization table entries, but it saves a lot of shifts.
  175090. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175091. * so we use a much larger scaling factor to preserve accuracy.
  175092. *
  175093. * A final compromise is to represent the multiplicative constants to only
  175094. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175095. * machines, and may also reduce the cost of multiplication (since there
  175096. * are fewer one-bits in the constants).
  175097. */
  175098. #if BITS_IN_JSAMPLE == 8
  175099. #define CONST_BITS 8
  175100. #define PASS1_BITS 2
  175101. #else
  175102. #define CONST_BITS 8
  175103. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175104. #endif
  175105. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175106. * causing a lot of useless floating-point operations at run time.
  175107. * To get around this we use the following pre-calculated constants.
  175108. * If you change CONST_BITS you may want to add appropriate values.
  175109. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175110. */
  175111. #if CONST_BITS == 8
  175112. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175113. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175114. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175115. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175116. #else
  175117. #define FIX_1_082392200 FIX(1.082392200)
  175118. #define FIX_1_414213562 FIX(1.414213562)
  175119. #define FIX_1_847759065 FIX(1.847759065)
  175120. #define FIX_2_613125930 FIX(2.613125930)
  175121. #endif
  175122. /* We can gain a little more speed, with a further compromise in accuracy,
  175123. * by omitting the addition in a descaling shift. This yields an incorrectly
  175124. * rounded result half the time...
  175125. */
  175126. #ifndef USE_ACCURATE_ROUNDING
  175127. #undef DESCALE
  175128. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175129. #endif
  175130. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175131. * descale to yield a DCTELEM result.
  175132. */
  175133. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175134. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175135. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175136. * multiplication will do. For 12-bit data, the multiplier table is
  175137. * declared INT32, so a 32-bit multiply will be used.
  175138. */
  175139. #if BITS_IN_JSAMPLE == 8
  175140. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175141. #else
  175142. #define DEQUANTIZE(coef,quantval) \
  175143. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175144. #endif
  175145. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175146. * We assume that int right shift is unsigned if INT32 right shift is.
  175147. */
  175148. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175149. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175150. #if BITS_IN_JSAMPLE == 8
  175151. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175152. #else
  175153. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175154. #endif
  175155. #define IRIGHT_SHIFT(x,shft) \
  175156. ((ishift_temp = (x)) < 0 ? \
  175157. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175158. (ishift_temp >> (shft)))
  175159. #else
  175160. #define ISHIFT_TEMPS
  175161. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175162. #endif
  175163. #ifdef USE_ACCURATE_ROUNDING
  175164. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175165. #else
  175166. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175167. #endif
  175168. /*
  175169. * Perform dequantization and inverse DCT on one block of coefficients.
  175170. */
  175171. GLOBAL(void)
  175172. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175173. JCOEFPTR coef_block,
  175174. JSAMPARRAY output_buf, JDIMENSION output_col)
  175175. {
  175176. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175177. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175178. DCTELEM z5, z10, z11, z12, z13;
  175179. JCOEFPTR inptr;
  175180. IFAST_MULT_TYPE * quantptr;
  175181. int * wsptr;
  175182. JSAMPROW outptr;
  175183. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175184. int ctr;
  175185. int workspace[DCTSIZE2]; /* buffers data between passes */
  175186. SHIFT_TEMPS /* for DESCALE */
  175187. ISHIFT_TEMPS /* for IDESCALE */
  175188. /* Pass 1: process columns from input, store into work array. */
  175189. inptr = coef_block;
  175190. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175191. wsptr = workspace;
  175192. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175193. /* Due to quantization, we will usually find that many of the input
  175194. * coefficients are zero, especially the AC terms. We can exploit this
  175195. * by short-circuiting the IDCT calculation for any column in which all
  175196. * the AC terms are zero. In that case each output is equal to the
  175197. * DC coefficient (with scale factor as needed).
  175198. * With typical images and quantization tables, half or more of the
  175199. * column DCT calculations can be simplified this way.
  175200. */
  175201. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175202. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175203. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175204. inptr[DCTSIZE*7] == 0) {
  175205. /* AC terms all zero */
  175206. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175207. wsptr[DCTSIZE*0] = dcval;
  175208. wsptr[DCTSIZE*1] = dcval;
  175209. wsptr[DCTSIZE*2] = dcval;
  175210. wsptr[DCTSIZE*3] = dcval;
  175211. wsptr[DCTSIZE*4] = dcval;
  175212. wsptr[DCTSIZE*5] = dcval;
  175213. wsptr[DCTSIZE*6] = dcval;
  175214. wsptr[DCTSIZE*7] = dcval;
  175215. inptr++; /* advance pointers to next column */
  175216. quantptr++;
  175217. wsptr++;
  175218. continue;
  175219. }
  175220. /* Even part */
  175221. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175222. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175223. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175224. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175225. tmp10 = tmp0 + tmp2; /* phase 3 */
  175226. tmp11 = tmp0 - tmp2;
  175227. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175228. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175229. tmp0 = tmp10 + tmp13; /* phase 2 */
  175230. tmp3 = tmp10 - tmp13;
  175231. tmp1 = tmp11 + tmp12;
  175232. tmp2 = tmp11 - tmp12;
  175233. /* Odd part */
  175234. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175235. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175236. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175237. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175238. z13 = tmp6 + tmp5; /* phase 6 */
  175239. z10 = tmp6 - tmp5;
  175240. z11 = tmp4 + tmp7;
  175241. z12 = tmp4 - tmp7;
  175242. tmp7 = z11 + z13; /* phase 5 */
  175243. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175244. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175245. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175246. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175247. tmp6 = tmp12 - tmp7; /* phase 2 */
  175248. tmp5 = tmp11 - tmp6;
  175249. tmp4 = tmp10 + tmp5;
  175250. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175251. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175252. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175253. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175254. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175255. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175256. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175257. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175258. inptr++; /* advance pointers to next column */
  175259. quantptr++;
  175260. wsptr++;
  175261. }
  175262. /* Pass 2: process rows from work array, store into output array. */
  175263. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175264. /* and also undo the PASS1_BITS scaling. */
  175265. wsptr = workspace;
  175266. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175267. outptr = output_buf[ctr] + output_col;
  175268. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175269. * However, the column calculation has created many nonzero AC terms, so
  175270. * the simplification applies less often (typically 5% to 10% of the time).
  175271. * On machines with very fast multiplication, it's possible that the
  175272. * test takes more time than it's worth. In that case this section
  175273. * may be commented out.
  175274. */
  175275. #ifndef NO_ZERO_ROW_TEST
  175276. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175277. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175278. /* AC terms all zero */
  175279. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175280. & RANGE_MASK];
  175281. outptr[0] = dcval;
  175282. outptr[1] = dcval;
  175283. outptr[2] = dcval;
  175284. outptr[3] = dcval;
  175285. outptr[4] = dcval;
  175286. outptr[5] = dcval;
  175287. outptr[6] = dcval;
  175288. outptr[7] = dcval;
  175289. wsptr += DCTSIZE; /* advance pointer to next row */
  175290. continue;
  175291. }
  175292. #endif
  175293. /* Even part */
  175294. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175295. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175296. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175297. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175298. - tmp13;
  175299. tmp0 = tmp10 + tmp13;
  175300. tmp3 = tmp10 - tmp13;
  175301. tmp1 = tmp11 + tmp12;
  175302. tmp2 = tmp11 - tmp12;
  175303. /* Odd part */
  175304. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175305. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175306. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175307. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175308. tmp7 = z11 + z13; /* phase 5 */
  175309. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175310. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175311. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175312. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175313. tmp6 = tmp12 - tmp7; /* phase 2 */
  175314. tmp5 = tmp11 - tmp6;
  175315. tmp4 = tmp10 + tmp5;
  175316. /* Final output stage: scale down by a factor of 8 and range-limit */
  175317. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175318. & RANGE_MASK];
  175319. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175320. & RANGE_MASK];
  175321. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175322. & RANGE_MASK];
  175323. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175324. & RANGE_MASK];
  175325. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175326. & RANGE_MASK];
  175327. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175328. & RANGE_MASK];
  175329. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175330. & RANGE_MASK];
  175331. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175332. & RANGE_MASK];
  175333. wsptr += DCTSIZE; /* advance pointer to next row */
  175334. }
  175335. }
  175336. #endif /* DCT_IFAST_SUPPORTED */
  175337. /*** End of inlined file: jidctfst.c ***/
  175338. #undef CONST_BITS
  175339. #undef FIX_1_847759065
  175340. #undef MULTIPLY
  175341. #undef DEQUANTIZE
  175342. /*** Start of inlined file: jidctint.c ***/
  175343. #define JPEG_INTERNALS
  175344. #ifdef DCT_ISLOW_SUPPORTED
  175345. /*
  175346. * This module is specialized to the case DCTSIZE = 8.
  175347. */
  175348. #if DCTSIZE != 8
  175349. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175350. #endif
  175351. /*
  175352. * The poop on this scaling stuff is as follows:
  175353. *
  175354. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175355. * larger than the true IDCT outputs. The final outputs are therefore
  175356. * a factor of N larger than desired; since N=8 this can be cured by
  175357. * a simple right shift at the end of the algorithm. The advantage of
  175358. * this arrangement is that we save two multiplications per 1-D IDCT,
  175359. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175360. *
  175361. * We have to do addition and subtraction of the integer inputs, which
  175362. * is no problem, and multiplication by fractional constants, which is
  175363. * a problem to do in integer arithmetic. We multiply all the constants
  175364. * by CONST_SCALE and convert them to integer constants (thus retaining
  175365. * CONST_BITS bits of precision in the constants). After doing a
  175366. * multiplication we have to divide the product by CONST_SCALE, with proper
  175367. * rounding, to produce the correct output. This division can be done
  175368. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175369. * as long as possible so that partial sums can be added together with
  175370. * full fractional precision.
  175371. *
  175372. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175373. * they are represented to better-than-integral precision. These outputs
  175374. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175375. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175376. * intermediate INT32 array would be needed.)
  175377. *
  175378. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175379. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175380. * shows that the values given below are the most effective.
  175381. */
  175382. #if BITS_IN_JSAMPLE == 8
  175383. #define CONST_BITS 13
  175384. #define PASS1_BITS 2
  175385. #else
  175386. #define CONST_BITS 13
  175387. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175388. #endif
  175389. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175390. * causing a lot of useless floating-point operations at run time.
  175391. * To get around this we use the following pre-calculated constants.
  175392. * If you change CONST_BITS you may want to add appropriate values.
  175393. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175394. */
  175395. #if CONST_BITS == 13
  175396. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175397. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175398. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175399. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175400. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175401. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175402. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175403. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175404. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175405. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175406. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175407. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175408. #else
  175409. #define FIX_0_298631336 FIX(0.298631336)
  175410. #define FIX_0_390180644 FIX(0.390180644)
  175411. #define FIX_0_541196100 FIX(0.541196100)
  175412. #define FIX_0_765366865 FIX(0.765366865)
  175413. #define FIX_0_899976223 FIX(0.899976223)
  175414. #define FIX_1_175875602 FIX(1.175875602)
  175415. #define FIX_1_501321110 FIX(1.501321110)
  175416. #define FIX_1_847759065 FIX(1.847759065)
  175417. #define FIX_1_961570560 FIX(1.961570560)
  175418. #define FIX_2_053119869 FIX(2.053119869)
  175419. #define FIX_2_562915447 FIX(2.562915447)
  175420. #define FIX_3_072711026 FIX(3.072711026)
  175421. #endif
  175422. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175423. * For 8-bit samples with the recommended scaling, all the variable
  175424. * and constant values involved are no more than 16 bits wide, so a
  175425. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175426. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175427. */
  175428. #if BITS_IN_JSAMPLE == 8
  175429. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175430. #else
  175431. #define MULTIPLY(var,const) ((var) * (const))
  175432. #endif
  175433. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175434. * entry; produce an int result. In this module, both inputs and result
  175435. * are 16 bits or less, so either int or short multiply will work.
  175436. */
  175437. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175438. /*
  175439. * Perform dequantization and inverse DCT on one block of coefficients.
  175440. */
  175441. GLOBAL(void)
  175442. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175443. JCOEFPTR coef_block,
  175444. JSAMPARRAY output_buf, JDIMENSION output_col)
  175445. {
  175446. INT32 tmp0, tmp1, tmp2, tmp3;
  175447. INT32 tmp10, tmp11, tmp12, tmp13;
  175448. INT32 z1, z2, z3, z4, z5;
  175449. JCOEFPTR inptr;
  175450. ISLOW_MULT_TYPE * quantptr;
  175451. int * wsptr;
  175452. JSAMPROW outptr;
  175453. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175454. int ctr;
  175455. int workspace[DCTSIZE2]; /* buffers data between passes */
  175456. SHIFT_TEMPS
  175457. /* Pass 1: process columns from input, store into work array. */
  175458. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175459. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175460. inptr = coef_block;
  175461. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175462. wsptr = workspace;
  175463. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175464. /* Due to quantization, we will usually find that many of the input
  175465. * coefficients are zero, especially the AC terms. We can exploit this
  175466. * by short-circuiting the IDCT calculation for any column in which all
  175467. * the AC terms are zero. In that case each output is equal to the
  175468. * DC coefficient (with scale factor as needed).
  175469. * With typical images and quantization tables, half or more of the
  175470. * column DCT calculations can be simplified this way.
  175471. */
  175472. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175473. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175474. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175475. inptr[DCTSIZE*7] == 0) {
  175476. /* AC terms all zero */
  175477. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175478. wsptr[DCTSIZE*0] = dcval;
  175479. wsptr[DCTSIZE*1] = dcval;
  175480. wsptr[DCTSIZE*2] = dcval;
  175481. wsptr[DCTSIZE*3] = dcval;
  175482. wsptr[DCTSIZE*4] = dcval;
  175483. wsptr[DCTSIZE*5] = dcval;
  175484. wsptr[DCTSIZE*6] = dcval;
  175485. wsptr[DCTSIZE*7] = dcval;
  175486. inptr++; /* advance pointers to next column */
  175487. quantptr++;
  175488. wsptr++;
  175489. continue;
  175490. }
  175491. /* Even part: reverse the even part of the forward DCT. */
  175492. /* The rotator is sqrt(2)*c(-6). */
  175493. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175494. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175495. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175496. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175497. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175498. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175499. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175500. tmp0 = (z2 + z3) << CONST_BITS;
  175501. tmp1 = (z2 - z3) << CONST_BITS;
  175502. tmp10 = tmp0 + tmp3;
  175503. tmp13 = tmp0 - tmp3;
  175504. tmp11 = tmp1 + tmp2;
  175505. tmp12 = tmp1 - tmp2;
  175506. /* Odd part per figure 8; the matrix is unitary and hence its
  175507. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175508. */
  175509. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175510. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175511. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175512. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175513. z1 = tmp0 + tmp3;
  175514. z2 = tmp1 + tmp2;
  175515. z3 = tmp0 + tmp2;
  175516. z4 = tmp1 + tmp3;
  175517. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175518. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175519. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175520. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175521. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175522. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175523. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175524. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175525. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175526. z3 += z5;
  175527. z4 += z5;
  175528. tmp0 += z1 + z3;
  175529. tmp1 += z2 + z4;
  175530. tmp2 += z2 + z3;
  175531. tmp3 += z1 + z4;
  175532. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175533. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175534. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175535. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175536. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175537. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175538. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175539. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175540. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175541. inptr++; /* advance pointers to next column */
  175542. quantptr++;
  175543. wsptr++;
  175544. }
  175545. /* Pass 2: process rows from work array, store into output array. */
  175546. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175547. /* and also undo the PASS1_BITS scaling. */
  175548. wsptr = workspace;
  175549. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175550. outptr = output_buf[ctr] + output_col;
  175551. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175552. * However, the column calculation has created many nonzero AC terms, so
  175553. * the simplification applies less often (typically 5% to 10% of the time).
  175554. * On machines with very fast multiplication, it's possible that the
  175555. * test takes more time than it's worth. In that case this section
  175556. * may be commented out.
  175557. */
  175558. #ifndef NO_ZERO_ROW_TEST
  175559. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175560. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175561. /* AC terms all zero */
  175562. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175563. & RANGE_MASK];
  175564. outptr[0] = dcval;
  175565. outptr[1] = dcval;
  175566. outptr[2] = dcval;
  175567. outptr[3] = dcval;
  175568. outptr[4] = dcval;
  175569. outptr[5] = dcval;
  175570. outptr[6] = dcval;
  175571. outptr[7] = dcval;
  175572. wsptr += DCTSIZE; /* advance pointer to next row */
  175573. continue;
  175574. }
  175575. #endif
  175576. /* Even part: reverse the even part of the forward DCT. */
  175577. /* The rotator is sqrt(2)*c(-6). */
  175578. z2 = (INT32) wsptr[2];
  175579. z3 = (INT32) wsptr[6];
  175580. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175581. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175582. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175583. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175584. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175585. tmp10 = tmp0 + tmp3;
  175586. tmp13 = tmp0 - tmp3;
  175587. tmp11 = tmp1 + tmp2;
  175588. tmp12 = tmp1 - tmp2;
  175589. /* Odd part per figure 8; the matrix is unitary and hence its
  175590. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175591. */
  175592. tmp0 = (INT32) wsptr[7];
  175593. tmp1 = (INT32) wsptr[5];
  175594. tmp2 = (INT32) wsptr[3];
  175595. tmp3 = (INT32) wsptr[1];
  175596. z1 = tmp0 + tmp3;
  175597. z2 = tmp1 + tmp2;
  175598. z3 = tmp0 + tmp2;
  175599. z4 = tmp1 + tmp3;
  175600. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175601. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175602. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175603. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175604. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175605. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175606. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175607. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175608. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175609. z3 += z5;
  175610. z4 += z5;
  175611. tmp0 += z1 + z3;
  175612. tmp1 += z2 + z4;
  175613. tmp2 += z2 + z3;
  175614. tmp3 += z1 + z4;
  175615. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175616. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175617. CONST_BITS+PASS1_BITS+3)
  175618. & RANGE_MASK];
  175619. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175620. CONST_BITS+PASS1_BITS+3)
  175621. & RANGE_MASK];
  175622. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175623. CONST_BITS+PASS1_BITS+3)
  175624. & RANGE_MASK];
  175625. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175626. CONST_BITS+PASS1_BITS+3)
  175627. & RANGE_MASK];
  175628. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175629. CONST_BITS+PASS1_BITS+3)
  175630. & RANGE_MASK];
  175631. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175632. CONST_BITS+PASS1_BITS+3)
  175633. & RANGE_MASK];
  175634. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175635. CONST_BITS+PASS1_BITS+3)
  175636. & RANGE_MASK];
  175637. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175638. CONST_BITS+PASS1_BITS+3)
  175639. & RANGE_MASK];
  175640. wsptr += DCTSIZE; /* advance pointer to next row */
  175641. }
  175642. }
  175643. #endif /* DCT_ISLOW_SUPPORTED */
  175644. /*** End of inlined file: jidctint.c ***/
  175645. /*** Start of inlined file: jidctred.c ***/
  175646. #define JPEG_INTERNALS
  175647. #ifdef IDCT_SCALING_SUPPORTED
  175648. /*
  175649. * This module is specialized to the case DCTSIZE = 8.
  175650. */
  175651. #if DCTSIZE != 8
  175652. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175653. #endif
  175654. /* Scaling is the same as in jidctint.c. */
  175655. #if BITS_IN_JSAMPLE == 8
  175656. #define CONST_BITS 13
  175657. #define PASS1_BITS 2
  175658. #else
  175659. #define CONST_BITS 13
  175660. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175661. #endif
  175662. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175663. * causing a lot of useless floating-point operations at run time.
  175664. * To get around this we use the following pre-calculated constants.
  175665. * If you change CONST_BITS you may want to add appropriate values.
  175666. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175667. */
  175668. #if CONST_BITS == 13
  175669. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175670. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175671. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175672. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175673. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175674. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175675. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175676. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175677. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175678. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175679. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175680. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175681. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175682. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175683. #else
  175684. #define FIX_0_211164243 FIX(0.211164243)
  175685. #define FIX_0_509795579 FIX(0.509795579)
  175686. #define FIX_0_601344887 FIX(0.601344887)
  175687. #define FIX_0_720959822 FIX(0.720959822)
  175688. #define FIX_0_765366865 FIX(0.765366865)
  175689. #define FIX_0_850430095 FIX(0.850430095)
  175690. #define FIX_0_899976223 FIX(0.899976223)
  175691. #define FIX_1_061594337 FIX(1.061594337)
  175692. #define FIX_1_272758580 FIX(1.272758580)
  175693. #define FIX_1_451774981 FIX(1.451774981)
  175694. #define FIX_1_847759065 FIX(1.847759065)
  175695. #define FIX_2_172734803 FIX(2.172734803)
  175696. #define FIX_2_562915447 FIX(2.562915447)
  175697. #define FIX_3_624509785 FIX(3.624509785)
  175698. #endif
  175699. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175700. * For 8-bit samples with the recommended scaling, all the variable
  175701. * and constant values involved are no more than 16 bits wide, so a
  175702. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175703. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175704. */
  175705. #if BITS_IN_JSAMPLE == 8
  175706. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175707. #else
  175708. #define MULTIPLY(var,const) ((var) * (const))
  175709. #endif
  175710. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175711. * entry; produce an int result. In this module, both inputs and result
  175712. * are 16 bits or less, so either int or short multiply will work.
  175713. */
  175714. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175715. /*
  175716. * Perform dequantization and inverse DCT on one block of coefficients,
  175717. * producing a reduced-size 4x4 output block.
  175718. */
  175719. GLOBAL(void)
  175720. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175721. JCOEFPTR coef_block,
  175722. JSAMPARRAY output_buf, JDIMENSION output_col)
  175723. {
  175724. INT32 tmp0, tmp2, tmp10, tmp12;
  175725. INT32 z1, z2, z3, z4;
  175726. JCOEFPTR inptr;
  175727. ISLOW_MULT_TYPE * quantptr;
  175728. int * wsptr;
  175729. JSAMPROW outptr;
  175730. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175731. int ctr;
  175732. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175733. SHIFT_TEMPS
  175734. /* Pass 1: process columns from input, store into work array. */
  175735. inptr = coef_block;
  175736. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175737. wsptr = workspace;
  175738. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175739. /* Don't bother to process column 4, because second pass won't use it */
  175740. if (ctr == DCTSIZE-4)
  175741. continue;
  175742. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175743. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175744. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175745. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175746. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175747. wsptr[DCTSIZE*0] = dcval;
  175748. wsptr[DCTSIZE*1] = dcval;
  175749. wsptr[DCTSIZE*2] = dcval;
  175750. wsptr[DCTSIZE*3] = dcval;
  175751. continue;
  175752. }
  175753. /* Even part */
  175754. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175755. tmp0 <<= (CONST_BITS+1);
  175756. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175757. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175758. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175759. tmp10 = tmp0 + tmp2;
  175760. tmp12 = tmp0 - tmp2;
  175761. /* Odd part */
  175762. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175763. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175764. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175765. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175766. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175767. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175768. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175769. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175770. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175771. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175772. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175773. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175774. /* Final output stage */
  175775. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175776. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175777. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175778. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175779. }
  175780. /* Pass 2: process 4 rows from work array, store into output array. */
  175781. wsptr = workspace;
  175782. for (ctr = 0; ctr < 4; ctr++) {
  175783. outptr = output_buf[ctr] + output_col;
  175784. /* It's not clear whether a zero row test is worthwhile here ... */
  175785. #ifndef NO_ZERO_ROW_TEST
  175786. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175787. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175788. /* AC terms all zero */
  175789. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175790. & RANGE_MASK];
  175791. outptr[0] = dcval;
  175792. outptr[1] = dcval;
  175793. outptr[2] = dcval;
  175794. outptr[3] = dcval;
  175795. wsptr += DCTSIZE; /* advance pointer to next row */
  175796. continue;
  175797. }
  175798. #endif
  175799. /* Even part */
  175800. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175801. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175802. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175803. tmp10 = tmp0 + tmp2;
  175804. tmp12 = tmp0 - tmp2;
  175805. /* Odd part */
  175806. z1 = (INT32) wsptr[7];
  175807. z2 = (INT32) wsptr[5];
  175808. z3 = (INT32) wsptr[3];
  175809. z4 = (INT32) wsptr[1];
  175810. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175811. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175812. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175813. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175814. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175815. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175816. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175817. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175818. /* Final output stage */
  175819. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175820. CONST_BITS+PASS1_BITS+3+1)
  175821. & RANGE_MASK];
  175822. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175823. CONST_BITS+PASS1_BITS+3+1)
  175824. & RANGE_MASK];
  175825. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175826. CONST_BITS+PASS1_BITS+3+1)
  175827. & RANGE_MASK];
  175828. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175829. CONST_BITS+PASS1_BITS+3+1)
  175830. & RANGE_MASK];
  175831. wsptr += DCTSIZE; /* advance pointer to next row */
  175832. }
  175833. }
  175834. /*
  175835. * Perform dequantization and inverse DCT on one block of coefficients,
  175836. * producing a reduced-size 2x2 output block.
  175837. */
  175838. GLOBAL(void)
  175839. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175840. JCOEFPTR coef_block,
  175841. JSAMPARRAY output_buf, JDIMENSION output_col)
  175842. {
  175843. INT32 tmp0, tmp10, z1;
  175844. JCOEFPTR inptr;
  175845. ISLOW_MULT_TYPE * quantptr;
  175846. int * wsptr;
  175847. JSAMPROW outptr;
  175848. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175849. int ctr;
  175850. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175851. SHIFT_TEMPS
  175852. /* Pass 1: process columns from input, store into work array. */
  175853. inptr = coef_block;
  175854. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175855. wsptr = workspace;
  175856. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175857. /* Don't bother to process columns 2,4,6 */
  175858. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175859. continue;
  175860. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175861. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175862. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175863. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175864. wsptr[DCTSIZE*0] = dcval;
  175865. wsptr[DCTSIZE*1] = dcval;
  175866. continue;
  175867. }
  175868. /* Even part */
  175869. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175870. tmp10 = z1 << (CONST_BITS+2);
  175871. /* Odd part */
  175872. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175873. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175874. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175875. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175876. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175877. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175878. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175879. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175880. /* Final output stage */
  175881. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175882. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175883. }
  175884. /* Pass 2: process 2 rows from work array, store into output array. */
  175885. wsptr = workspace;
  175886. for (ctr = 0; ctr < 2; ctr++) {
  175887. outptr = output_buf[ctr] + output_col;
  175888. /* It's not clear whether a zero row test is worthwhile here ... */
  175889. #ifndef NO_ZERO_ROW_TEST
  175890. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175891. /* AC terms all zero */
  175892. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175893. & RANGE_MASK];
  175894. outptr[0] = dcval;
  175895. outptr[1] = dcval;
  175896. wsptr += DCTSIZE; /* advance pointer to next row */
  175897. continue;
  175898. }
  175899. #endif
  175900. /* Even part */
  175901. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175902. /* Odd part */
  175903. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175904. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175905. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175906. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175907. /* Final output stage */
  175908. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175909. CONST_BITS+PASS1_BITS+3+2)
  175910. & RANGE_MASK];
  175911. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175912. CONST_BITS+PASS1_BITS+3+2)
  175913. & RANGE_MASK];
  175914. wsptr += DCTSIZE; /* advance pointer to next row */
  175915. }
  175916. }
  175917. /*
  175918. * Perform dequantization and inverse DCT on one block of coefficients,
  175919. * producing a reduced-size 1x1 output block.
  175920. */
  175921. GLOBAL(void)
  175922. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175923. JCOEFPTR coef_block,
  175924. JSAMPARRAY output_buf, JDIMENSION output_col)
  175925. {
  175926. int dcval;
  175927. ISLOW_MULT_TYPE * quantptr;
  175928. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175929. SHIFT_TEMPS
  175930. /* We hardly need an inverse DCT routine for this: just take the
  175931. * average pixel value, which is one-eighth of the DC coefficient.
  175932. */
  175933. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175934. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175935. dcval = (int) DESCALE((INT32) dcval, 3);
  175936. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175937. }
  175938. #endif /* IDCT_SCALING_SUPPORTED */
  175939. /*** End of inlined file: jidctred.c ***/
  175940. /*** Start of inlined file: jmemmgr.c ***/
  175941. #define JPEG_INTERNALS
  175942. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175943. /*** Start of inlined file: jmemsys.h ***/
  175944. #ifndef __jmemsys_h__
  175945. #define __jmemsys_h__
  175946. /* Short forms of external names for systems with brain-damaged linkers. */
  175947. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175948. #define jpeg_get_small jGetSmall
  175949. #define jpeg_free_small jFreeSmall
  175950. #define jpeg_get_large jGetLarge
  175951. #define jpeg_free_large jFreeLarge
  175952. #define jpeg_mem_available jMemAvail
  175953. #define jpeg_open_backing_store jOpenBackStore
  175954. #define jpeg_mem_init jMemInit
  175955. #define jpeg_mem_term jMemTerm
  175956. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175957. /*
  175958. * These two functions are used to allocate and release small chunks of
  175959. * memory. (Typically the total amount requested through jpeg_get_small is
  175960. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175961. * Behavior should be the same as for the standard library functions malloc
  175962. * and free; in particular, jpeg_get_small must return NULL on failure.
  175963. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175964. * size of the object being freed, just in case it's needed.
  175965. * On an 80x86 machine using small-data memory model, these manage near heap.
  175966. */
  175967. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175968. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175969. size_t sizeofobject));
  175970. /*
  175971. * These two functions are used to allocate and release large chunks of
  175972. * memory (up to the total free space designated by jpeg_mem_available).
  175973. * The interface is the same as above, except that on an 80x86 machine,
  175974. * far pointers are used. On most other machines these are identical to
  175975. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175976. * in case a different allocation strategy is desirable for large chunks.
  175977. */
  175978. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175979. size_t sizeofobject));
  175980. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175981. size_t sizeofobject));
  175982. /*
  175983. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175984. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175985. * matter, but that case should never come into play). This macro is needed
  175986. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175987. * On those machines, we expect that jconfig.h will provide a proper value.
  175988. * On machines with 32-bit flat address spaces, any large constant may be used.
  175989. *
  175990. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175991. * size_t and will be a multiple of sizeof(align_type).
  175992. */
  175993. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175994. #define MAX_ALLOC_CHUNK 1000000000L
  175995. #endif
  175996. /*
  175997. * This routine computes the total space still available for allocation by
  175998. * jpeg_get_large. If more space than this is needed, backing store will be
  175999. * used. NOTE: any memory already allocated must not be counted.
  176000. *
  176001. * There is a minimum space requirement, corresponding to the minimum
  176002. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176003. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176004. * all working storage in memory, is also passed in case it is useful.
  176005. * Finally, the total space already allocated is passed. If no better
  176006. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176007. * is often a suitable calculation.
  176008. *
  176009. * It is OK for jpeg_mem_available to underestimate the space available
  176010. * (that'll just lead to more backing-store access than is really necessary).
  176011. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176012. * a slop factor from the true available space. 5% should be enough.
  176013. *
  176014. * On machines with lots of virtual memory, any large constant may be returned.
  176015. * Conversely, zero may be returned to always use the minimum amount of memory.
  176016. */
  176017. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176018. long min_bytes_needed,
  176019. long max_bytes_needed,
  176020. long already_allocated));
  176021. /*
  176022. * This structure holds whatever state is needed to access a single
  176023. * backing-store object. The read/write/close method pointers are called
  176024. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176025. * are private to the system-dependent backing store routines.
  176026. */
  176027. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176028. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176029. typedef unsigned short XMSH; /* type of extended-memory handles */
  176030. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176031. typedef union {
  176032. short file_handle; /* DOS file handle if it's a temp file */
  176033. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176034. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176035. } handle_union;
  176036. #endif /* USE_MSDOS_MEMMGR */
  176037. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176038. #include <Files.h>
  176039. #endif /* USE_MAC_MEMMGR */
  176040. //typedef struct backing_store_struct * backing_store_ptr;
  176041. typedef struct backing_store_struct {
  176042. /* Methods for reading/writing/closing this backing-store object */
  176043. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176044. struct backing_store_struct *info,
  176045. void FAR * buffer_address,
  176046. long file_offset, long byte_count));
  176047. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176048. struct backing_store_struct *info,
  176049. void FAR * buffer_address,
  176050. long file_offset, long byte_count));
  176051. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176052. struct backing_store_struct *info));
  176053. /* Private fields for system-dependent backing-store management */
  176054. #ifdef USE_MSDOS_MEMMGR
  176055. /* For the MS-DOS manager (jmemdos.c), we need: */
  176056. handle_union handle; /* reference to backing-store storage object */
  176057. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176058. #else
  176059. #ifdef USE_MAC_MEMMGR
  176060. /* For the Mac manager (jmemmac.c), we need: */
  176061. short temp_file; /* file reference number to temp file */
  176062. FSSpec tempSpec; /* the FSSpec for the temp file */
  176063. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176064. #else
  176065. /* For a typical implementation with temp files, we need: */
  176066. FILE * temp_file; /* stdio reference to temp file */
  176067. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176068. #endif
  176069. #endif
  176070. } backing_store_info;
  176071. /*
  176072. * Initial opening of a backing-store object. This must fill in the
  176073. * read/write/close pointers in the object. The read/write routines
  176074. * may take an error exit if the specified maximum file size is exceeded.
  176075. * (If jpeg_mem_available always returns a large value, this routine can
  176076. * just take an error exit.)
  176077. */
  176078. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176079. struct backing_store_struct *info,
  176080. long total_bytes_needed));
  176081. /*
  176082. * These routines take care of any system-dependent initialization and
  176083. * cleanup required. jpeg_mem_init will be called before anything is
  176084. * allocated (and, therefore, nothing in cinfo is of use except the error
  176085. * manager pointer). It should return a suitable default value for
  176086. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176087. * application. (Note that max_memory_to_use is only important if
  176088. * jpeg_mem_available chooses to consult it ... no one else will.)
  176089. * jpeg_mem_term may assume that all requested memory has been freed and that
  176090. * all opened backing-store objects have been closed.
  176091. */
  176092. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176093. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176094. #endif
  176095. /*** End of inlined file: jmemsys.h ***/
  176096. /* import the system-dependent declarations */
  176097. #ifndef NO_GETENV
  176098. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176099. extern char * getenv JPP((const char * name));
  176100. #endif
  176101. #endif
  176102. /*
  176103. * Some important notes:
  176104. * The allocation routines provided here must never return NULL.
  176105. * They should exit to error_exit if unsuccessful.
  176106. *
  176107. * It's not a good idea to try to merge the sarray and barray routines,
  176108. * even though they are textually almost the same, because samples are
  176109. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176110. * in machines where byte pointers have a different representation from
  176111. * word pointers, the resulting machine code could not be the same.
  176112. */
  176113. /*
  176114. * Many machines require storage alignment: longs must start on 4-byte
  176115. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176116. * always returns pointers that are multiples of the worst-case alignment
  176117. * requirement, and we had better do so too.
  176118. * There isn't any really portable way to determine the worst-case alignment
  176119. * requirement. This module assumes that the alignment requirement is
  176120. * multiples of sizeof(ALIGN_TYPE).
  176121. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176122. * workstations (where doubles really do need 8-byte alignment) and will work
  176123. * fine on nearly everything. If your machine has lesser alignment needs,
  176124. * you can save a few bytes by making ALIGN_TYPE smaller.
  176125. * The only place I know of where this will NOT work is certain Macintosh
  176126. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176127. * Doing 10-byte alignment is counterproductive because longwords won't be
  176128. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176129. * such a compiler.
  176130. */
  176131. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176132. #define ALIGN_TYPE double
  176133. #endif
  176134. /*
  176135. * We allocate objects from "pools", where each pool is gotten with a single
  176136. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176137. * overhead within a pool, except for alignment padding. Each pool has a
  176138. * header with a link to the next pool of the same class.
  176139. * Small and large pool headers are identical except that the latter's
  176140. * link pointer must be FAR on 80x86 machines.
  176141. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176142. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176143. * of the alignment requirement of ALIGN_TYPE.
  176144. */
  176145. typedef union small_pool_struct * small_pool_ptr;
  176146. typedef union small_pool_struct {
  176147. struct {
  176148. small_pool_ptr next; /* next in list of pools */
  176149. size_t bytes_used; /* how many bytes already used within pool */
  176150. size_t bytes_left; /* bytes still available in this pool */
  176151. } hdr;
  176152. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176153. } small_pool_hdr;
  176154. typedef union large_pool_struct FAR * large_pool_ptr;
  176155. typedef union large_pool_struct {
  176156. struct {
  176157. large_pool_ptr next; /* next in list of pools */
  176158. size_t bytes_used; /* how many bytes already used within pool */
  176159. size_t bytes_left; /* bytes still available in this pool */
  176160. } hdr;
  176161. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176162. } large_pool_hdr;
  176163. /*
  176164. * Here is the full definition of a memory manager object.
  176165. */
  176166. typedef struct {
  176167. struct jpeg_memory_mgr pub; /* public fields */
  176168. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176169. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176170. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176171. /* Since we only have one lifetime class of virtual arrays, only one
  176172. * linked list is necessary (for each datatype). Note that the virtual
  176173. * array control blocks being linked together are actually stored somewhere
  176174. * in the small-pool list.
  176175. */
  176176. jvirt_sarray_ptr virt_sarray_list;
  176177. jvirt_barray_ptr virt_barray_list;
  176178. /* This counts total space obtained from jpeg_get_small/large */
  176179. long total_space_allocated;
  176180. /* alloc_sarray and alloc_barray set this value for use by virtual
  176181. * array routines.
  176182. */
  176183. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176184. } my_memory_mgr;
  176185. typedef my_memory_mgr * my_mem_ptr;
  176186. /*
  176187. * The control blocks for virtual arrays.
  176188. * Note that these blocks are allocated in the "small" pool area.
  176189. * System-dependent info for the associated backing store (if any) is hidden
  176190. * inside the backing_store_info struct.
  176191. */
  176192. struct jvirt_sarray_control {
  176193. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176194. JDIMENSION rows_in_array; /* total virtual array height */
  176195. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176196. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176197. JDIMENSION rows_in_mem; /* height of memory buffer */
  176198. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176199. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176200. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176201. boolean pre_zero; /* pre-zero mode requested? */
  176202. boolean dirty; /* do current buffer contents need written? */
  176203. boolean b_s_open; /* is backing-store data valid? */
  176204. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176205. backing_store_info b_s_info; /* System-dependent control info */
  176206. };
  176207. struct jvirt_barray_control {
  176208. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176209. JDIMENSION rows_in_array; /* total virtual array height */
  176210. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176211. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176212. JDIMENSION rows_in_mem; /* height of memory buffer */
  176213. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176214. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176215. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176216. boolean pre_zero; /* pre-zero mode requested? */
  176217. boolean dirty; /* do current buffer contents need written? */
  176218. boolean b_s_open; /* is backing-store data valid? */
  176219. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176220. backing_store_info b_s_info; /* System-dependent control info */
  176221. };
  176222. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176223. LOCAL(void)
  176224. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176225. {
  176226. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176227. small_pool_ptr shdr_ptr;
  176228. large_pool_ptr lhdr_ptr;
  176229. /* Since this is only a debugging stub, we can cheat a little by using
  176230. * fprintf directly rather than going through the trace message code.
  176231. * This is helpful because message parm array can't handle longs.
  176232. */
  176233. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176234. pool_id, mem->total_space_allocated);
  176235. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176236. lhdr_ptr = lhdr_ptr->hdr.next) {
  176237. fprintf(stderr, " Large chunk used %ld\n",
  176238. (long) lhdr_ptr->hdr.bytes_used);
  176239. }
  176240. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176241. shdr_ptr = shdr_ptr->hdr.next) {
  176242. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176243. (long) shdr_ptr->hdr.bytes_used,
  176244. (long) shdr_ptr->hdr.bytes_left);
  176245. }
  176246. }
  176247. #endif /* MEM_STATS */
  176248. LOCAL(void)
  176249. out_of_memory (j_common_ptr cinfo, int which)
  176250. /* Report an out-of-memory error and stop execution */
  176251. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176252. {
  176253. #ifdef MEM_STATS
  176254. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176255. #endif
  176256. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176257. }
  176258. /*
  176259. * Allocation of "small" objects.
  176260. *
  176261. * For these, we use pooled storage. When a new pool must be created,
  176262. * we try to get enough space for the current request plus a "slop" factor,
  176263. * where the slop will be the amount of leftover space in the new pool.
  176264. * The speed vs. space tradeoff is largely determined by the slop values.
  176265. * A different slop value is provided for each pool class (lifetime),
  176266. * and we also distinguish the first pool of a class from later ones.
  176267. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176268. * machines, but may be too small if longs are 64 bits or more.
  176269. */
  176270. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176271. {
  176272. 1600, /* first PERMANENT pool */
  176273. 16000 /* first IMAGE pool */
  176274. };
  176275. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176276. {
  176277. 0, /* additional PERMANENT pools */
  176278. 5000 /* additional IMAGE pools */
  176279. };
  176280. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176281. METHODDEF(void *)
  176282. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176283. /* Allocate a "small" object */
  176284. {
  176285. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176286. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176287. char * data_ptr;
  176288. size_t odd_bytes, min_request, slop;
  176289. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176290. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176291. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176292. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176293. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176294. if (odd_bytes > 0)
  176295. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176296. /* See if space is available in any existing pool */
  176297. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176298. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176299. prev_hdr_ptr = NULL;
  176300. hdr_ptr = mem->small_list[pool_id];
  176301. while (hdr_ptr != NULL) {
  176302. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176303. break; /* found pool with enough space */
  176304. prev_hdr_ptr = hdr_ptr;
  176305. hdr_ptr = hdr_ptr->hdr.next;
  176306. }
  176307. /* Time to make a new pool? */
  176308. if (hdr_ptr == NULL) {
  176309. /* min_request is what we need now, slop is what will be leftover */
  176310. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176311. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176312. slop = first_pool_slop[pool_id];
  176313. else
  176314. slop = extra_pool_slop[pool_id];
  176315. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176316. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176317. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176318. /* Try to get space, if fail reduce slop and try again */
  176319. for (;;) {
  176320. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176321. if (hdr_ptr != NULL)
  176322. break;
  176323. slop /= 2;
  176324. if (slop < MIN_SLOP) /* give up when it gets real small */
  176325. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176326. }
  176327. mem->total_space_allocated += min_request + slop;
  176328. /* Success, initialize the new pool header and add to end of list */
  176329. hdr_ptr->hdr.next = NULL;
  176330. hdr_ptr->hdr.bytes_used = 0;
  176331. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176332. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176333. mem->small_list[pool_id] = hdr_ptr;
  176334. else
  176335. prev_hdr_ptr->hdr.next = hdr_ptr;
  176336. }
  176337. /* OK, allocate the object from the current pool */
  176338. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176339. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176340. hdr_ptr->hdr.bytes_used += sizeofobject;
  176341. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176342. return (void *) data_ptr;
  176343. }
  176344. /*
  176345. * Allocation of "large" objects.
  176346. *
  176347. * The external semantics of these are the same as "small" objects,
  176348. * except that FAR pointers are used on 80x86. However the pool
  176349. * management heuristics are quite different. We assume that each
  176350. * request is large enough that it may as well be passed directly to
  176351. * jpeg_get_large; the pool management just links everything together
  176352. * so that we can free it all on demand.
  176353. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176354. * structures. The routines that create these structures (see below)
  176355. * deliberately bunch rows together to ensure a large request size.
  176356. */
  176357. METHODDEF(void FAR *)
  176358. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176359. /* Allocate a "large" object */
  176360. {
  176361. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176362. large_pool_ptr hdr_ptr;
  176363. size_t odd_bytes;
  176364. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176365. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176366. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176367. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176368. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176369. if (odd_bytes > 0)
  176370. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176371. /* Always make a new pool */
  176372. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176373. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176374. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176375. SIZEOF(large_pool_hdr));
  176376. if (hdr_ptr == NULL)
  176377. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176378. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176379. /* Success, initialize the new pool header and add to list */
  176380. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176381. /* We maintain space counts in each pool header for statistical purposes,
  176382. * even though they are not needed for allocation.
  176383. */
  176384. hdr_ptr->hdr.bytes_used = sizeofobject;
  176385. hdr_ptr->hdr.bytes_left = 0;
  176386. mem->large_list[pool_id] = hdr_ptr;
  176387. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176388. }
  176389. /*
  176390. * Creation of 2-D sample arrays.
  176391. * The pointers are in near heap, the samples themselves in FAR heap.
  176392. *
  176393. * To minimize allocation overhead and to allow I/O of large contiguous
  176394. * blocks, we allocate the sample rows in groups of as many rows as possible
  176395. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176396. * NB: the virtual array control routines, later in this file, know about
  176397. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176398. * object so that it can be saved away if this sarray is the workspace for
  176399. * a virtual array.
  176400. */
  176401. METHODDEF(JSAMPARRAY)
  176402. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176403. JDIMENSION samplesperrow, JDIMENSION numrows)
  176404. /* Allocate a 2-D sample array */
  176405. {
  176406. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176407. JSAMPARRAY result;
  176408. JSAMPROW workspace;
  176409. JDIMENSION rowsperchunk, currow, i;
  176410. long ltemp;
  176411. /* Calculate max # of rows allowed in one allocation chunk */
  176412. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176413. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176414. if (ltemp <= 0)
  176415. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176416. if (ltemp < (long) numrows)
  176417. rowsperchunk = (JDIMENSION) ltemp;
  176418. else
  176419. rowsperchunk = numrows;
  176420. mem->last_rowsperchunk = rowsperchunk;
  176421. /* Get space for row pointers (small object) */
  176422. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176423. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176424. /* Get the rows themselves (large objects) */
  176425. currow = 0;
  176426. while (currow < numrows) {
  176427. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176428. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176429. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176430. * SIZEOF(JSAMPLE)));
  176431. for (i = rowsperchunk; i > 0; i--) {
  176432. result[currow++] = workspace;
  176433. workspace += samplesperrow;
  176434. }
  176435. }
  176436. return result;
  176437. }
  176438. /*
  176439. * Creation of 2-D coefficient-block arrays.
  176440. * This is essentially the same as the code for sample arrays, above.
  176441. */
  176442. METHODDEF(JBLOCKARRAY)
  176443. alloc_barray (j_common_ptr cinfo, int pool_id,
  176444. JDIMENSION blocksperrow, JDIMENSION numrows)
  176445. /* Allocate a 2-D coefficient-block array */
  176446. {
  176447. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176448. JBLOCKARRAY result;
  176449. JBLOCKROW workspace;
  176450. JDIMENSION rowsperchunk, currow, i;
  176451. long ltemp;
  176452. /* Calculate max # of rows allowed in one allocation chunk */
  176453. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176454. ((long) blocksperrow * SIZEOF(JBLOCK));
  176455. if (ltemp <= 0)
  176456. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176457. if (ltemp < (long) numrows)
  176458. rowsperchunk = (JDIMENSION) ltemp;
  176459. else
  176460. rowsperchunk = numrows;
  176461. mem->last_rowsperchunk = rowsperchunk;
  176462. /* Get space for row pointers (small object) */
  176463. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176464. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176465. /* Get the rows themselves (large objects) */
  176466. currow = 0;
  176467. while (currow < numrows) {
  176468. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176469. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176470. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176471. * SIZEOF(JBLOCK)));
  176472. for (i = rowsperchunk; i > 0; i--) {
  176473. result[currow++] = workspace;
  176474. workspace += blocksperrow;
  176475. }
  176476. }
  176477. return result;
  176478. }
  176479. /*
  176480. * About virtual array management:
  176481. *
  176482. * The above "normal" array routines are only used to allocate strip buffers
  176483. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176484. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176485. * time, but the memory manager must save the whole array for repeated
  176486. * accesses. The intended implementation is that there is a strip buffer in
  176487. * memory (as high as is possible given the desired memory limit), plus a
  176488. * backing file that holds the rest of the array.
  176489. *
  176490. * The request_virt_array routines are told the total size of the image and
  176491. * the maximum number of rows that will be accessed at once. The in-memory
  176492. * buffer must be at least as large as the maxaccess value.
  176493. *
  176494. * The request routines create control blocks but not the in-memory buffers.
  176495. * That is postponed until realize_virt_arrays is called. At that time the
  176496. * total amount of space needed is known (approximately, anyway), so free
  176497. * memory can be divided up fairly.
  176498. *
  176499. * The access_virt_array routines are responsible for making a specific strip
  176500. * area accessible (after reading or writing the backing file, if necessary).
  176501. * Note that the access routines are told whether the caller intends to modify
  176502. * the accessed strip; during a read-only pass this saves having to rewrite
  176503. * data to disk. The access routines are also responsible for pre-zeroing
  176504. * any newly accessed rows, if pre-zeroing was requested.
  176505. *
  176506. * In current usage, the access requests are usually for nonoverlapping
  176507. * strips; that is, successive access start_row numbers differ by exactly
  176508. * num_rows = maxaccess. This means we can get good performance with simple
  176509. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176510. * of the access height; then there will never be accesses across bufferload
  176511. * boundaries. The code will still work with overlapping access requests,
  176512. * but it doesn't handle bufferload overlaps very efficiently.
  176513. */
  176514. METHODDEF(jvirt_sarray_ptr)
  176515. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176516. JDIMENSION samplesperrow, JDIMENSION numrows,
  176517. JDIMENSION maxaccess)
  176518. /* Request a virtual 2-D sample array */
  176519. {
  176520. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176521. jvirt_sarray_ptr result;
  176522. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176523. if (pool_id != JPOOL_IMAGE)
  176524. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176525. /* get control block */
  176526. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176527. SIZEOF(struct jvirt_sarray_control));
  176528. result->mem_buffer = NULL; /* marks array not yet realized */
  176529. result->rows_in_array = numrows;
  176530. result->samplesperrow = samplesperrow;
  176531. result->maxaccess = maxaccess;
  176532. result->pre_zero = pre_zero;
  176533. result->b_s_open = FALSE; /* no associated backing-store object */
  176534. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176535. mem->virt_sarray_list = result;
  176536. return result;
  176537. }
  176538. METHODDEF(jvirt_barray_ptr)
  176539. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176540. JDIMENSION blocksperrow, JDIMENSION numrows,
  176541. JDIMENSION maxaccess)
  176542. /* Request a virtual 2-D coefficient-block array */
  176543. {
  176544. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176545. jvirt_barray_ptr result;
  176546. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176547. if (pool_id != JPOOL_IMAGE)
  176548. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176549. /* get control block */
  176550. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176551. SIZEOF(struct jvirt_barray_control));
  176552. result->mem_buffer = NULL; /* marks array not yet realized */
  176553. result->rows_in_array = numrows;
  176554. result->blocksperrow = blocksperrow;
  176555. result->maxaccess = maxaccess;
  176556. result->pre_zero = pre_zero;
  176557. result->b_s_open = FALSE; /* no associated backing-store object */
  176558. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176559. mem->virt_barray_list = result;
  176560. return result;
  176561. }
  176562. METHODDEF(void)
  176563. realize_virt_arrays (j_common_ptr cinfo)
  176564. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176565. {
  176566. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176567. long space_per_minheight, maximum_space, avail_mem;
  176568. long minheights, max_minheights;
  176569. jvirt_sarray_ptr sptr;
  176570. jvirt_barray_ptr bptr;
  176571. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176572. * and the maximum space needed (full image height in each buffer).
  176573. * These may be of use to the system-dependent jpeg_mem_available routine.
  176574. */
  176575. space_per_minheight = 0;
  176576. maximum_space = 0;
  176577. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176578. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176579. space_per_minheight += (long) sptr->maxaccess *
  176580. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176581. maximum_space += (long) sptr->rows_in_array *
  176582. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176583. }
  176584. }
  176585. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176586. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176587. space_per_minheight += (long) bptr->maxaccess *
  176588. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176589. maximum_space += (long) bptr->rows_in_array *
  176590. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176591. }
  176592. }
  176593. if (space_per_minheight <= 0)
  176594. return; /* no unrealized arrays, no work */
  176595. /* Determine amount of memory to actually use; this is system-dependent. */
  176596. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176597. mem->total_space_allocated);
  176598. /* If the maximum space needed is available, make all the buffers full
  176599. * height; otherwise parcel it out with the same number of minheights
  176600. * in each buffer.
  176601. */
  176602. if (avail_mem >= maximum_space)
  176603. max_minheights = 1000000000L;
  176604. else {
  176605. max_minheights = avail_mem / space_per_minheight;
  176606. /* If there doesn't seem to be enough space, try to get the minimum
  176607. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176608. */
  176609. if (max_minheights <= 0)
  176610. max_minheights = 1;
  176611. }
  176612. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176613. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176614. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176615. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176616. if (minheights <= max_minheights) {
  176617. /* This buffer fits in memory */
  176618. sptr->rows_in_mem = sptr->rows_in_array;
  176619. } else {
  176620. /* It doesn't fit in memory, create backing store. */
  176621. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176622. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176623. (long) sptr->rows_in_array *
  176624. (long) sptr->samplesperrow *
  176625. (long) SIZEOF(JSAMPLE));
  176626. sptr->b_s_open = TRUE;
  176627. }
  176628. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176629. sptr->samplesperrow, sptr->rows_in_mem);
  176630. sptr->rowsperchunk = mem->last_rowsperchunk;
  176631. sptr->cur_start_row = 0;
  176632. sptr->first_undef_row = 0;
  176633. sptr->dirty = FALSE;
  176634. }
  176635. }
  176636. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176637. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176638. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176639. if (minheights <= max_minheights) {
  176640. /* This buffer fits in memory */
  176641. bptr->rows_in_mem = bptr->rows_in_array;
  176642. } else {
  176643. /* It doesn't fit in memory, create backing store. */
  176644. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176645. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176646. (long) bptr->rows_in_array *
  176647. (long) bptr->blocksperrow *
  176648. (long) SIZEOF(JBLOCK));
  176649. bptr->b_s_open = TRUE;
  176650. }
  176651. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176652. bptr->blocksperrow, bptr->rows_in_mem);
  176653. bptr->rowsperchunk = mem->last_rowsperchunk;
  176654. bptr->cur_start_row = 0;
  176655. bptr->first_undef_row = 0;
  176656. bptr->dirty = FALSE;
  176657. }
  176658. }
  176659. }
  176660. LOCAL(void)
  176661. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176662. /* Do backing store read or write of a virtual sample array */
  176663. {
  176664. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176665. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176666. file_offset = ptr->cur_start_row * bytesperrow;
  176667. /* Loop to read or write each allocation chunk in mem_buffer */
  176668. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176669. /* One chunk, but check for short chunk at end of buffer */
  176670. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176671. /* Transfer no more than is currently defined */
  176672. thisrow = (long) ptr->cur_start_row + i;
  176673. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176674. /* Transfer no more than fits in file */
  176675. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176676. if (rows <= 0) /* this chunk might be past end of file! */
  176677. break;
  176678. byte_count = rows * bytesperrow;
  176679. if (writing)
  176680. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176681. (void FAR *) ptr->mem_buffer[i],
  176682. file_offset, byte_count);
  176683. else
  176684. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176685. (void FAR *) ptr->mem_buffer[i],
  176686. file_offset, byte_count);
  176687. file_offset += byte_count;
  176688. }
  176689. }
  176690. LOCAL(void)
  176691. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176692. /* Do backing store read or write of a virtual coefficient-block array */
  176693. {
  176694. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176695. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176696. file_offset = ptr->cur_start_row * bytesperrow;
  176697. /* Loop to read or write each allocation chunk in mem_buffer */
  176698. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176699. /* One chunk, but check for short chunk at end of buffer */
  176700. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176701. /* Transfer no more than is currently defined */
  176702. thisrow = (long) ptr->cur_start_row + i;
  176703. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176704. /* Transfer no more than fits in file */
  176705. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176706. if (rows <= 0) /* this chunk might be past end of file! */
  176707. break;
  176708. byte_count = rows * bytesperrow;
  176709. if (writing)
  176710. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176711. (void FAR *) ptr->mem_buffer[i],
  176712. file_offset, byte_count);
  176713. else
  176714. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176715. (void FAR *) ptr->mem_buffer[i],
  176716. file_offset, byte_count);
  176717. file_offset += byte_count;
  176718. }
  176719. }
  176720. METHODDEF(JSAMPARRAY)
  176721. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176722. JDIMENSION start_row, JDIMENSION num_rows,
  176723. boolean writable)
  176724. /* Access the part of a virtual sample array starting at start_row */
  176725. /* and extending for num_rows rows. writable is true if */
  176726. /* caller intends to modify the accessed area. */
  176727. {
  176728. JDIMENSION end_row = start_row + num_rows;
  176729. JDIMENSION undef_row;
  176730. /* debugging check */
  176731. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176732. ptr->mem_buffer == NULL)
  176733. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176734. /* Make the desired part of the virtual array accessible */
  176735. if (start_row < ptr->cur_start_row ||
  176736. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176737. if (! ptr->b_s_open)
  176738. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176739. /* Flush old buffer contents if necessary */
  176740. if (ptr->dirty) {
  176741. do_sarray_io(cinfo, ptr, TRUE);
  176742. ptr->dirty = FALSE;
  176743. }
  176744. /* Decide what part of virtual array to access.
  176745. * Algorithm: if target address > current window, assume forward scan,
  176746. * load starting at target address. If target address < current window,
  176747. * assume backward scan, load so that target area is top of window.
  176748. * Note that when switching from forward write to forward read, will have
  176749. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176750. */
  176751. if (start_row > ptr->cur_start_row) {
  176752. ptr->cur_start_row = start_row;
  176753. } else {
  176754. /* use long arithmetic here to avoid overflow & unsigned problems */
  176755. long ltemp;
  176756. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176757. if (ltemp < 0)
  176758. ltemp = 0; /* don't fall off front end of file */
  176759. ptr->cur_start_row = (JDIMENSION) ltemp;
  176760. }
  176761. /* Read in the selected part of the array.
  176762. * During the initial write pass, we will do no actual read
  176763. * because the selected part is all undefined.
  176764. */
  176765. do_sarray_io(cinfo, ptr, FALSE);
  176766. }
  176767. /* Ensure the accessed part of the array is defined; prezero if needed.
  176768. * To improve locality of access, we only prezero the part of the array
  176769. * that the caller is about to access, not the entire in-memory array.
  176770. */
  176771. if (ptr->first_undef_row < end_row) {
  176772. if (ptr->first_undef_row < start_row) {
  176773. if (writable) /* writer skipped over a section of array */
  176774. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176775. undef_row = start_row; /* but reader is allowed to read ahead */
  176776. } else {
  176777. undef_row = ptr->first_undef_row;
  176778. }
  176779. if (writable)
  176780. ptr->first_undef_row = end_row;
  176781. if (ptr->pre_zero) {
  176782. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176783. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176784. end_row -= ptr->cur_start_row;
  176785. while (undef_row < end_row) {
  176786. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176787. undef_row++;
  176788. }
  176789. } else {
  176790. if (! writable) /* reader looking at undefined data */
  176791. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176792. }
  176793. }
  176794. /* Flag the buffer dirty if caller will write in it */
  176795. if (writable)
  176796. ptr->dirty = TRUE;
  176797. /* Return address of proper part of the buffer */
  176798. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176799. }
  176800. METHODDEF(JBLOCKARRAY)
  176801. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176802. JDIMENSION start_row, JDIMENSION num_rows,
  176803. boolean writable)
  176804. /* Access the part of a virtual block array starting at start_row */
  176805. /* and extending for num_rows rows. writable is true if */
  176806. /* caller intends to modify the accessed area. */
  176807. {
  176808. JDIMENSION end_row = start_row + num_rows;
  176809. JDIMENSION undef_row;
  176810. /* debugging check */
  176811. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176812. ptr->mem_buffer == NULL)
  176813. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176814. /* Make the desired part of the virtual array accessible */
  176815. if (start_row < ptr->cur_start_row ||
  176816. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176817. if (! ptr->b_s_open)
  176818. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176819. /* Flush old buffer contents if necessary */
  176820. if (ptr->dirty) {
  176821. do_barray_io(cinfo, ptr, TRUE);
  176822. ptr->dirty = FALSE;
  176823. }
  176824. /* Decide what part of virtual array to access.
  176825. * Algorithm: if target address > current window, assume forward scan,
  176826. * load starting at target address. If target address < current window,
  176827. * assume backward scan, load so that target area is top of window.
  176828. * Note that when switching from forward write to forward read, will have
  176829. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176830. */
  176831. if (start_row > ptr->cur_start_row) {
  176832. ptr->cur_start_row = start_row;
  176833. } else {
  176834. /* use long arithmetic here to avoid overflow & unsigned problems */
  176835. long ltemp;
  176836. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176837. if (ltemp < 0)
  176838. ltemp = 0; /* don't fall off front end of file */
  176839. ptr->cur_start_row = (JDIMENSION) ltemp;
  176840. }
  176841. /* Read in the selected part of the array.
  176842. * During the initial write pass, we will do no actual read
  176843. * because the selected part is all undefined.
  176844. */
  176845. do_barray_io(cinfo, ptr, FALSE);
  176846. }
  176847. /* Ensure the accessed part of the array is defined; prezero if needed.
  176848. * To improve locality of access, we only prezero the part of the array
  176849. * that the caller is about to access, not the entire in-memory array.
  176850. */
  176851. if (ptr->first_undef_row < end_row) {
  176852. if (ptr->first_undef_row < start_row) {
  176853. if (writable) /* writer skipped over a section of array */
  176854. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176855. undef_row = start_row; /* but reader is allowed to read ahead */
  176856. } else {
  176857. undef_row = ptr->first_undef_row;
  176858. }
  176859. if (writable)
  176860. ptr->first_undef_row = end_row;
  176861. if (ptr->pre_zero) {
  176862. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176863. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176864. end_row -= ptr->cur_start_row;
  176865. while (undef_row < end_row) {
  176866. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176867. undef_row++;
  176868. }
  176869. } else {
  176870. if (! writable) /* reader looking at undefined data */
  176871. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176872. }
  176873. }
  176874. /* Flag the buffer dirty if caller will write in it */
  176875. if (writable)
  176876. ptr->dirty = TRUE;
  176877. /* Return address of proper part of the buffer */
  176878. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176879. }
  176880. /*
  176881. * Release all objects belonging to a specified pool.
  176882. */
  176883. METHODDEF(void)
  176884. free_pool (j_common_ptr cinfo, int pool_id)
  176885. {
  176886. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176887. small_pool_ptr shdr_ptr;
  176888. large_pool_ptr lhdr_ptr;
  176889. size_t space_freed;
  176890. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176891. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176892. #ifdef MEM_STATS
  176893. if (cinfo->err->trace_level > 1)
  176894. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176895. #endif
  176896. /* If freeing IMAGE pool, close any virtual arrays first */
  176897. if (pool_id == JPOOL_IMAGE) {
  176898. jvirt_sarray_ptr sptr;
  176899. jvirt_barray_ptr bptr;
  176900. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176901. if (sptr->b_s_open) { /* there may be no backing store */
  176902. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176903. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176904. }
  176905. }
  176906. mem->virt_sarray_list = NULL;
  176907. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176908. if (bptr->b_s_open) { /* there may be no backing store */
  176909. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176910. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176911. }
  176912. }
  176913. mem->virt_barray_list = NULL;
  176914. }
  176915. /* Release large objects */
  176916. lhdr_ptr = mem->large_list[pool_id];
  176917. mem->large_list[pool_id] = NULL;
  176918. while (lhdr_ptr != NULL) {
  176919. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176920. space_freed = lhdr_ptr->hdr.bytes_used +
  176921. lhdr_ptr->hdr.bytes_left +
  176922. SIZEOF(large_pool_hdr);
  176923. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176924. mem->total_space_allocated -= space_freed;
  176925. lhdr_ptr = next_lhdr_ptr;
  176926. }
  176927. /* Release small objects */
  176928. shdr_ptr = mem->small_list[pool_id];
  176929. mem->small_list[pool_id] = NULL;
  176930. while (shdr_ptr != NULL) {
  176931. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176932. space_freed = shdr_ptr->hdr.bytes_used +
  176933. shdr_ptr->hdr.bytes_left +
  176934. SIZEOF(small_pool_hdr);
  176935. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176936. mem->total_space_allocated -= space_freed;
  176937. shdr_ptr = next_shdr_ptr;
  176938. }
  176939. }
  176940. /*
  176941. * Close up shop entirely.
  176942. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176943. */
  176944. METHODDEF(void)
  176945. self_destruct (j_common_ptr cinfo)
  176946. {
  176947. int pool;
  176948. /* Close all backing store, release all memory.
  176949. * Releasing pools in reverse order might help avoid fragmentation
  176950. * with some (brain-damaged) malloc libraries.
  176951. */
  176952. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176953. free_pool(cinfo, pool);
  176954. }
  176955. /* Release the memory manager control block too. */
  176956. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176957. cinfo->mem = NULL; /* ensures I will be called only once */
  176958. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176959. }
  176960. /*
  176961. * Memory manager initialization.
  176962. * When this is called, only the error manager pointer is valid in cinfo!
  176963. */
  176964. GLOBAL(void)
  176965. jinit_memory_mgr (j_common_ptr cinfo)
  176966. {
  176967. my_mem_ptr mem;
  176968. long max_to_use;
  176969. int pool;
  176970. size_t test_mac;
  176971. cinfo->mem = NULL; /* for safety if init fails */
  176972. /* Check for configuration errors.
  176973. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176974. * doesn't reflect any real hardware alignment requirement.
  176975. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176976. * in common if and only if X is a power of 2, ie has only one one-bit.
  176977. * Some compilers may give an "unreachable code" warning here; ignore it.
  176978. */
  176979. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176980. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176981. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176982. * a multiple of SIZEOF(ALIGN_TYPE).
  176983. * Again, an "unreachable code" warning may be ignored here.
  176984. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176985. */
  176986. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176987. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176988. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176989. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176990. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176991. /* Attempt to allocate memory manager's control block */
  176992. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176993. if (mem == NULL) {
  176994. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176995. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176996. }
  176997. /* OK, fill in the method pointers */
  176998. mem->pub.alloc_small = alloc_small;
  176999. mem->pub.alloc_large = alloc_large;
  177000. mem->pub.alloc_sarray = alloc_sarray;
  177001. mem->pub.alloc_barray = alloc_barray;
  177002. mem->pub.request_virt_sarray = request_virt_sarray;
  177003. mem->pub.request_virt_barray = request_virt_barray;
  177004. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177005. mem->pub.access_virt_sarray = access_virt_sarray;
  177006. mem->pub.access_virt_barray = access_virt_barray;
  177007. mem->pub.free_pool = free_pool;
  177008. mem->pub.self_destruct = self_destruct;
  177009. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177010. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177011. /* Initialize working state */
  177012. mem->pub.max_memory_to_use = max_to_use;
  177013. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177014. mem->small_list[pool] = NULL;
  177015. mem->large_list[pool] = NULL;
  177016. }
  177017. mem->virt_sarray_list = NULL;
  177018. mem->virt_barray_list = NULL;
  177019. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177020. /* Declare ourselves open for business */
  177021. cinfo->mem = & mem->pub;
  177022. /* Check for an environment variable JPEGMEM; if found, override the
  177023. * default max_memory setting from jpeg_mem_init. Note that the
  177024. * surrounding application may again override this value.
  177025. * If your system doesn't support getenv(), define NO_GETENV to disable
  177026. * this feature.
  177027. */
  177028. #ifndef NO_GETENV
  177029. { char * memenv;
  177030. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177031. char ch = 'x';
  177032. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177033. if (ch == 'm' || ch == 'M')
  177034. max_to_use *= 1000L;
  177035. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177036. }
  177037. }
  177038. }
  177039. #endif
  177040. }
  177041. /*** End of inlined file: jmemmgr.c ***/
  177042. /*** Start of inlined file: jmemnobs.c ***/
  177043. #define JPEG_INTERNALS
  177044. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177045. extern void * malloc JPP((size_t size));
  177046. extern void free JPP((void *ptr));
  177047. #endif
  177048. /*
  177049. * Memory allocation and freeing are controlled by the regular library
  177050. * routines malloc() and free().
  177051. */
  177052. GLOBAL(void *)
  177053. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177054. {
  177055. return (void *) malloc(sizeofobject);
  177056. }
  177057. GLOBAL(void)
  177058. jpeg_free_small (j_common_ptr , void * object, size_t)
  177059. {
  177060. free(object);
  177061. }
  177062. /*
  177063. * "Large" objects are treated the same as "small" ones.
  177064. * NB: although we include FAR keywords in the routine declarations,
  177065. * this file won't actually work in 80x86 small/medium model; at least,
  177066. * you probably won't be able to process useful-size images in only 64KB.
  177067. */
  177068. GLOBAL(void FAR *)
  177069. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177070. {
  177071. return (void FAR *) malloc(sizeofobject);
  177072. }
  177073. GLOBAL(void)
  177074. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177075. {
  177076. free(object);
  177077. }
  177078. /*
  177079. * This routine computes the total memory space available for allocation.
  177080. * Here we always say, "we got all you want bud!"
  177081. */
  177082. GLOBAL(long)
  177083. jpeg_mem_available (j_common_ptr, long,
  177084. long max_bytes_needed, long)
  177085. {
  177086. return max_bytes_needed;
  177087. }
  177088. /*
  177089. * Backing store (temporary file) management.
  177090. * Since jpeg_mem_available always promised the moon,
  177091. * this should never be called and we can just error out.
  177092. */
  177093. GLOBAL(void)
  177094. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177095. long )
  177096. {
  177097. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177098. }
  177099. /*
  177100. * These routines take care of any system-dependent initialization and
  177101. * cleanup required. Here, there isn't any.
  177102. */
  177103. GLOBAL(long)
  177104. jpeg_mem_init (j_common_ptr)
  177105. {
  177106. return 0; /* just set max_memory_to_use to 0 */
  177107. }
  177108. GLOBAL(void)
  177109. jpeg_mem_term (j_common_ptr)
  177110. {
  177111. /* no work */
  177112. }
  177113. /*** End of inlined file: jmemnobs.c ***/
  177114. /*** Start of inlined file: jquant1.c ***/
  177115. #define JPEG_INTERNALS
  177116. #ifdef QUANT_1PASS_SUPPORTED
  177117. /*
  177118. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177119. * high quality, colormapped output capability. A 2-pass quantizer usually
  177120. * gives better visual quality; however, for quantized grayscale output this
  177121. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177122. * quantizer, though you can turn it off if you really want to.
  177123. *
  177124. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177125. * image. We use a map consisting of all combinations of Ncolors[i] color
  177126. * values for the i'th component. The Ncolors[] values are chosen so that
  177127. * their product, the total number of colors, is no more than that requested.
  177128. * (In most cases, the product will be somewhat less.)
  177129. *
  177130. * Since the colormap is orthogonal, the representative value for each color
  177131. * component can be determined without considering the other components;
  177132. * then these indexes can be combined into a colormap index by a standard
  177133. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177134. * can be precalculated and stored in the lookup table colorindex[].
  177135. * colorindex[i][j] maps pixel value j in component i to the nearest
  177136. * representative value (grid plane) for that component; this index is
  177137. * multiplied by the array stride for component i, so that the
  177138. * index of the colormap entry closest to a given pixel value is just
  177139. * sum( colorindex[component-number][pixel-component-value] )
  177140. * Aside from being fast, this scheme allows for variable spacing between
  177141. * representative values with no additional lookup cost.
  177142. *
  177143. * If gamma correction has been applied in color conversion, it might be wise
  177144. * to adjust the color grid spacing so that the representative colors are
  177145. * equidistant in linear space. At this writing, gamma correction is not
  177146. * implemented by jdcolor, so nothing is done here.
  177147. */
  177148. /* Declarations for ordered dithering.
  177149. *
  177150. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177151. * dithering is described in many references, for instance Dale Schumacher's
  177152. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177153. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177154. * "dither" value to the input pixel and then round the result to the nearest
  177155. * output value. The dither value is equivalent to (0.5 - threshold) times
  177156. * the distance between output values. For ordered dithering, we assume that
  177157. * the output colors are equally spaced; if not, results will probably be
  177158. * worse, since the dither may be too much or too little at a given point.
  177159. *
  177160. * The normal calculation would be to form pixel value + dither, range-limit
  177161. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177162. * We can skip the separate range-limiting step by extending the colorindex
  177163. * table in both directions.
  177164. */
  177165. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177166. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177167. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177168. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177169. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177170. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177171. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177172. /* Bayer's order-4 dither array. Generated by the code given in
  177173. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177174. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177175. */
  177176. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177177. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177178. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177179. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177180. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177181. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177182. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177183. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177184. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177185. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177186. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177187. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177188. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177189. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177190. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177191. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177192. };
  177193. /* Declarations for Floyd-Steinberg dithering.
  177194. *
  177195. * Errors are accumulated into the array fserrors[], at a resolution of
  177196. * 1/16th of a pixel count. The error at a given pixel is propagated
  177197. * to its not-yet-processed neighbors using the standard F-S fractions,
  177198. * ... (here) 7/16
  177199. * 3/16 5/16 1/16
  177200. * We work left-to-right on even rows, right-to-left on odd rows.
  177201. *
  177202. * We can get away with a single array (holding one row's worth of errors)
  177203. * by using it to store the current row's errors at pixel columns not yet
  177204. * processed, but the next row's errors at columns already processed. We
  177205. * need only a few extra variables to hold the errors immediately around the
  177206. * current column. (If we are lucky, those variables are in registers, but
  177207. * even if not, they're probably cheaper to access than array elements are.)
  177208. *
  177209. * The fserrors[] array is indexed [component#][position].
  177210. * We provide (#columns + 2) entries per component; the extra entry at each
  177211. * end saves us from special-casing the first and last pixels.
  177212. *
  177213. * Note: on a wide image, we might not have enough room in a PC's near data
  177214. * segment to hold the error array; so it is allocated with alloc_large.
  177215. */
  177216. #if BITS_IN_JSAMPLE == 8
  177217. typedef INT16 FSERROR; /* 16 bits should be enough */
  177218. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177219. #else
  177220. typedef INT32 FSERROR; /* may need more than 16 bits */
  177221. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177222. #endif
  177223. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177224. /* Private subobject */
  177225. #define MAX_Q_COMPS 4 /* max components I can handle */
  177226. typedef struct {
  177227. struct jpeg_color_quantizer pub; /* public fields */
  177228. /* Initially allocated colormap is saved here */
  177229. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177230. int sv_actual; /* number of entries in use */
  177231. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177232. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177233. * premultiplied as described above. Since colormap indexes must fit into
  177234. * JSAMPLEs, the entries of this array will too.
  177235. */
  177236. boolean is_padded; /* is the colorindex padded for odither? */
  177237. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177238. /* Variables for ordered dithering */
  177239. int row_index; /* cur row's vertical index in dither matrix */
  177240. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177241. /* Variables for Floyd-Steinberg dithering */
  177242. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177243. boolean on_odd_row; /* flag to remember which row we are on */
  177244. } my_cquantizer;
  177245. typedef my_cquantizer * my_cquantize_ptr;
  177246. /*
  177247. * Policy-making subroutines for create_colormap and create_colorindex.
  177248. * These routines determine the colormap to be used. The rest of the module
  177249. * only assumes that the colormap is orthogonal.
  177250. *
  177251. * * select_ncolors decides how to divvy up the available colors
  177252. * among the components.
  177253. * * output_value defines the set of representative values for a component.
  177254. * * largest_input_value defines the mapping from input values to
  177255. * representative values for a component.
  177256. * Note that the latter two routines may impose different policies for
  177257. * different components, though this is not currently done.
  177258. */
  177259. LOCAL(int)
  177260. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177261. /* Determine allocation of desired colors to components, */
  177262. /* and fill in Ncolors[] array to indicate choice. */
  177263. /* Return value is total number of colors (product of Ncolors[] values). */
  177264. {
  177265. int nc = cinfo->out_color_components; /* number of color components */
  177266. int max_colors = cinfo->desired_number_of_colors;
  177267. int total_colors, iroot, i, j;
  177268. boolean changed;
  177269. long temp;
  177270. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177271. /* We can allocate at least the nc'th root of max_colors per component. */
  177272. /* Compute floor(nc'th root of max_colors). */
  177273. iroot = 1;
  177274. do {
  177275. iroot++;
  177276. temp = iroot; /* set temp = iroot ** nc */
  177277. for (i = 1; i < nc; i++)
  177278. temp *= iroot;
  177279. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177280. iroot--; /* now iroot = floor(root) */
  177281. /* Must have at least 2 color values per component */
  177282. if (iroot < 2)
  177283. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177284. /* Initialize to iroot color values for each component */
  177285. total_colors = 1;
  177286. for (i = 0; i < nc; i++) {
  177287. Ncolors[i] = iroot;
  177288. total_colors *= iroot;
  177289. }
  177290. /* We may be able to increment the count for one or more components without
  177291. * exceeding max_colors, though we know not all can be incremented.
  177292. * Sometimes, the first component can be incremented more than once!
  177293. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177294. * In RGB colorspace, try to increment G first, then R, then B.
  177295. */
  177296. do {
  177297. changed = FALSE;
  177298. for (i = 0; i < nc; i++) {
  177299. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177300. /* calculate new total_colors if Ncolors[j] is incremented */
  177301. temp = total_colors / Ncolors[j];
  177302. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177303. if (temp > (long) max_colors)
  177304. break; /* won't fit, done with this pass */
  177305. Ncolors[j]++; /* OK, apply the increment */
  177306. total_colors = (int) temp;
  177307. changed = TRUE;
  177308. }
  177309. } while (changed);
  177310. return total_colors;
  177311. }
  177312. LOCAL(int)
  177313. output_value (j_decompress_ptr, int, int j, int maxj)
  177314. /* Return j'th output value, where j will range from 0 to maxj */
  177315. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177316. {
  177317. /* We always provide values 0 and MAXJSAMPLE for each component;
  177318. * any additional values are equally spaced between these limits.
  177319. * (Forcing the upper and lower values to the limits ensures that
  177320. * dithering can't produce a color outside the selected gamut.)
  177321. */
  177322. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177323. }
  177324. LOCAL(int)
  177325. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177326. /* Return largest input value that should map to j'th output value */
  177327. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177328. {
  177329. /* Breakpoints are halfway between values returned by output_value */
  177330. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177331. }
  177332. /*
  177333. * Create the colormap.
  177334. */
  177335. LOCAL(void)
  177336. create_colormap (j_decompress_ptr cinfo)
  177337. {
  177338. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177339. JSAMPARRAY colormap; /* Created colormap */
  177340. int total_colors; /* Number of distinct output colors */
  177341. int i,j,k, nci, blksize, blkdist, ptr, val;
  177342. /* Select number of colors for each component */
  177343. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177344. /* Report selected color counts */
  177345. if (cinfo->out_color_components == 3)
  177346. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177347. total_colors, cquantize->Ncolors[0],
  177348. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177349. else
  177350. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177351. /* Allocate and fill in the colormap. */
  177352. /* The colors are ordered in the map in standard row-major order, */
  177353. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177354. colormap = (*cinfo->mem->alloc_sarray)
  177355. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177356. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177357. /* blksize is number of adjacent repeated entries for a component */
  177358. /* blkdist is distance between groups of identical entries for a component */
  177359. blkdist = total_colors;
  177360. for (i = 0; i < cinfo->out_color_components; i++) {
  177361. /* fill in colormap entries for i'th color component */
  177362. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177363. blksize = blkdist / nci;
  177364. for (j = 0; j < nci; j++) {
  177365. /* Compute j'th output value (out of nci) for component */
  177366. val = output_value(cinfo, i, j, nci-1);
  177367. /* Fill in all colormap entries that have this value of this component */
  177368. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177369. /* fill in blksize entries beginning at ptr */
  177370. for (k = 0; k < blksize; k++)
  177371. colormap[i][ptr+k] = (JSAMPLE) val;
  177372. }
  177373. }
  177374. blkdist = blksize; /* blksize of this color is blkdist of next */
  177375. }
  177376. /* Save the colormap in private storage,
  177377. * where it will survive color quantization mode changes.
  177378. */
  177379. cquantize->sv_colormap = colormap;
  177380. cquantize->sv_actual = total_colors;
  177381. }
  177382. /*
  177383. * Create the color index table.
  177384. */
  177385. LOCAL(void)
  177386. create_colorindex (j_decompress_ptr cinfo)
  177387. {
  177388. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177389. JSAMPROW indexptr;
  177390. int i,j,k, nci, blksize, val, pad;
  177391. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177392. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177393. * This is not necessary in the other dithering modes. However, we
  177394. * flag whether it was done in case user changes dithering mode.
  177395. */
  177396. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177397. pad = MAXJSAMPLE*2;
  177398. cquantize->is_padded = TRUE;
  177399. } else {
  177400. pad = 0;
  177401. cquantize->is_padded = FALSE;
  177402. }
  177403. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177404. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177405. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177406. (JDIMENSION) cinfo->out_color_components);
  177407. /* blksize is number of adjacent repeated entries for a component */
  177408. blksize = cquantize->sv_actual;
  177409. for (i = 0; i < cinfo->out_color_components; i++) {
  177410. /* fill in colorindex entries for i'th color component */
  177411. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177412. blksize = blksize / nci;
  177413. /* adjust colorindex pointers to provide padding at negative indexes. */
  177414. if (pad)
  177415. cquantize->colorindex[i] += MAXJSAMPLE;
  177416. /* in loop, val = index of current output value, */
  177417. /* and k = largest j that maps to current val */
  177418. indexptr = cquantize->colorindex[i];
  177419. val = 0;
  177420. k = largest_input_value(cinfo, i, 0, nci-1);
  177421. for (j = 0; j <= MAXJSAMPLE; j++) {
  177422. while (j > k) /* advance val if past boundary */
  177423. k = largest_input_value(cinfo, i, ++val, nci-1);
  177424. /* premultiply so that no multiplication needed in main processing */
  177425. indexptr[j] = (JSAMPLE) (val * blksize);
  177426. }
  177427. /* Pad at both ends if necessary */
  177428. if (pad)
  177429. for (j = 1; j <= MAXJSAMPLE; j++) {
  177430. indexptr[-j] = indexptr[0];
  177431. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177432. }
  177433. }
  177434. }
  177435. /*
  177436. * Create an ordered-dither array for a component having ncolors
  177437. * distinct output values.
  177438. */
  177439. LOCAL(ODITHER_MATRIX_PTR)
  177440. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177441. {
  177442. ODITHER_MATRIX_PTR odither;
  177443. int j,k;
  177444. INT32 num,den;
  177445. odither = (ODITHER_MATRIX_PTR)
  177446. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177447. SIZEOF(ODITHER_MATRIX));
  177448. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177449. * Hence the dither value for the matrix cell with fill order f
  177450. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177451. * On 16-bit-int machine, be careful to avoid overflow.
  177452. */
  177453. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177454. for (j = 0; j < ODITHER_SIZE; j++) {
  177455. for (k = 0; k < ODITHER_SIZE; k++) {
  177456. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177457. * MAXJSAMPLE;
  177458. /* Ensure round towards zero despite C's lack of consistency
  177459. * about rounding negative values in integer division...
  177460. */
  177461. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177462. }
  177463. }
  177464. return odither;
  177465. }
  177466. /*
  177467. * Create the ordered-dither tables.
  177468. * Components having the same number of representative colors may
  177469. * share a dither table.
  177470. */
  177471. LOCAL(void)
  177472. create_odither_tables (j_decompress_ptr cinfo)
  177473. {
  177474. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177475. ODITHER_MATRIX_PTR odither;
  177476. int i, j, nci;
  177477. for (i = 0; i < cinfo->out_color_components; i++) {
  177478. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177479. odither = NULL; /* search for matching prior component */
  177480. for (j = 0; j < i; j++) {
  177481. if (nci == cquantize->Ncolors[j]) {
  177482. odither = cquantize->odither[j];
  177483. break;
  177484. }
  177485. }
  177486. if (odither == NULL) /* need a new table? */
  177487. odither = make_odither_array(cinfo, nci);
  177488. cquantize->odither[i] = odither;
  177489. }
  177490. }
  177491. /*
  177492. * Map some rows of pixels to the output colormapped representation.
  177493. */
  177494. METHODDEF(void)
  177495. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177496. JSAMPARRAY output_buf, int num_rows)
  177497. /* General case, no dithering */
  177498. {
  177499. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177500. JSAMPARRAY colorindex = cquantize->colorindex;
  177501. register int pixcode, ci;
  177502. register JSAMPROW ptrin, ptrout;
  177503. int row;
  177504. JDIMENSION col;
  177505. JDIMENSION width = cinfo->output_width;
  177506. register int nc = cinfo->out_color_components;
  177507. for (row = 0; row < num_rows; row++) {
  177508. ptrin = input_buf[row];
  177509. ptrout = output_buf[row];
  177510. for (col = width; col > 0; col--) {
  177511. pixcode = 0;
  177512. for (ci = 0; ci < nc; ci++) {
  177513. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177514. }
  177515. *ptrout++ = (JSAMPLE) pixcode;
  177516. }
  177517. }
  177518. }
  177519. METHODDEF(void)
  177520. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177521. JSAMPARRAY output_buf, int num_rows)
  177522. /* Fast path for out_color_components==3, no dithering */
  177523. {
  177524. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177525. register int pixcode;
  177526. register JSAMPROW ptrin, ptrout;
  177527. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177528. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177529. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177530. int row;
  177531. JDIMENSION col;
  177532. JDIMENSION width = cinfo->output_width;
  177533. for (row = 0; row < num_rows; row++) {
  177534. ptrin = input_buf[row];
  177535. ptrout = output_buf[row];
  177536. for (col = width; col > 0; col--) {
  177537. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177538. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177539. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177540. *ptrout++ = (JSAMPLE) pixcode;
  177541. }
  177542. }
  177543. }
  177544. METHODDEF(void)
  177545. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177546. JSAMPARRAY output_buf, int num_rows)
  177547. /* General case, with ordered dithering */
  177548. {
  177549. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177550. register JSAMPROW input_ptr;
  177551. register JSAMPROW output_ptr;
  177552. JSAMPROW colorindex_ci;
  177553. int * dither; /* points to active row of dither matrix */
  177554. int row_index, col_index; /* current indexes into dither matrix */
  177555. int nc = cinfo->out_color_components;
  177556. int ci;
  177557. int row;
  177558. JDIMENSION col;
  177559. JDIMENSION width = cinfo->output_width;
  177560. for (row = 0; row < num_rows; row++) {
  177561. /* Initialize output values to 0 so can process components separately */
  177562. jzero_far((void FAR *) output_buf[row],
  177563. (size_t) (width * SIZEOF(JSAMPLE)));
  177564. row_index = cquantize->row_index;
  177565. for (ci = 0; ci < nc; ci++) {
  177566. input_ptr = input_buf[row] + ci;
  177567. output_ptr = output_buf[row];
  177568. colorindex_ci = cquantize->colorindex[ci];
  177569. dither = cquantize->odither[ci][row_index];
  177570. col_index = 0;
  177571. for (col = width; col > 0; col--) {
  177572. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177573. * select output value, accumulate into output code for this pixel.
  177574. * Range-limiting need not be done explicitly, as we have extended
  177575. * the colorindex table to produce the right answers for out-of-range
  177576. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177577. * required amount of padding.
  177578. */
  177579. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177580. input_ptr += nc;
  177581. output_ptr++;
  177582. col_index = (col_index + 1) & ODITHER_MASK;
  177583. }
  177584. }
  177585. /* Advance row index for next row */
  177586. row_index = (row_index + 1) & ODITHER_MASK;
  177587. cquantize->row_index = row_index;
  177588. }
  177589. }
  177590. METHODDEF(void)
  177591. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177592. JSAMPARRAY output_buf, int num_rows)
  177593. /* Fast path for out_color_components==3, with ordered dithering */
  177594. {
  177595. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177596. register int pixcode;
  177597. register JSAMPROW input_ptr;
  177598. register JSAMPROW output_ptr;
  177599. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177600. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177601. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177602. int * dither0; /* points to active row of dither matrix */
  177603. int * dither1;
  177604. int * dither2;
  177605. int row_index, col_index; /* current indexes into dither matrix */
  177606. int row;
  177607. JDIMENSION col;
  177608. JDIMENSION width = cinfo->output_width;
  177609. for (row = 0; row < num_rows; row++) {
  177610. row_index = cquantize->row_index;
  177611. input_ptr = input_buf[row];
  177612. output_ptr = output_buf[row];
  177613. dither0 = cquantize->odither[0][row_index];
  177614. dither1 = cquantize->odither[1][row_index];
  177615. dither2 = cquantize->odither[2][row_index];
  177616. col_index = 0;
  177617. for (col = width; col > 0; col--) {
  177618. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177619. dither0[col_index]]);
  177620. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177621. dither1[col_index]]);
  177622. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177623. dither2[col_index]]);
  177624. *output_ptr++ = (JSAMPLE) pixcode;
  177625. col_index = (col_index + 1) & ODITHER_MASK;
  177626. }
  177627. row_index = (row_index + 1) & ODITHER_MASK;
  177628. cquantize->row_index = row_index;
  177629. }
  177630. }
  177631. METHODDEF(void)
  177632. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177633. JSAMPARRAY output_buf, int num_rows)
  177634. /* General case, with Floyd-Steinberg dithering */
  177635. {
  177636. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177637. register LOCFSERROR cur; /* current error or pixel value */
  177638. LOCFSERROR belowerr; /* error for pixel below cur */
  177639. LOCFSERROR bpreverr; /* error for below/prev col */
  177640. LOCFSERROR bnexterr; /* error for below/next col */
  177641. LOCFSERROR delta;
  177642. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177643. register JSAMPROW input_ptr;
  177644. register JSAMPROW output_ptr;
  177645. JSAMPROW colorindex_ci;
  177646. JSAMPROW colormap_ci;
  177647. int pixcode;
  177648. int nc = cinfo->out_color_components;
  177649. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177650. int dirnc; /* dir * nc */
  177651. int ci;
  177652. int row;
  177653. JDIMENSION col;
  177654. JDIMENSION width = cinfo->output_width;
  177655. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177656. SHIFT_TEMPS
  177657. for (row = 0; row < num_rows; row++) {
  177658. /* Initialize output values to 0 so can process components separately */
  177659. jzero_far((void FAR *) output_buf[row],
  177660. (size_t) (width * SIZEOF(JSAMPLE)));
  177661. for (ci = 0; ci < nc; ci++) {
  177662. input_ptr = input_buf[row] + ci;
  177663. output_ptr = output_buf[row];
  177664. if (cquantize->on_odd_row) {
  177665. /* work right to left in this row */
  177666. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177667. output_ptr += width-1;
  177668. dir = -1;
  177669. dirnc = -nc;
  177670. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177671. } else {
  177672. /* work left to right in this row */
  177673. dir = 1;
  177674. dirnc = nc;
  177675. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177676. }
  177677. colorindex_ci = cquantize->colorindex[ci];
  177678. colormap_ci = cquantize->sv_colormap[ci];
  177679. /* Preset error values: no error propagated to first pixel from left */
  177680. cur = 0;
  177681. /* and no error propagated to row below yet */
  177682. belowerr = bpreverr = 0;
  177683. for (col = width; col > 0; col--) {
  177684. /* cur holds the error propagated from the previous pixel on the
  177685. * current line. Add the error propagated from the previous line
  177686. * to form the complete error correction term for this pixel, and
  177687. * round the error term (which is expressed * 16) to an integer.
  177688. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177689. * for either sign of the error value.
  177690. * Note: errorptr points to *previous* column's array entry.
  177691. */
  177692. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177693. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177694. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177695. * of the range_limit array.
  177696. */
  177697. cur += GETJSAMPLE(*input_ptr);
  177698. cur = GETJSAMPLE(range_limit[cur]);
  177699. /* Select output value, accumulate into output code for this pixel */
  177700. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177701. *output_ptr += (JSAMPLE) pixcode;
  177702. /* Compute actual representation error at this pixel */
  177703. /* Note: we can do this even though we don't have the final */
  177704. /* pixel code, because the colormap is orthogonal. */
  177705. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177706. /* Compute error fractions to be propagated to adjacent pixels.
  177707. * Add these into the running sums, and simultaneously shift the
  177708. * next-line error sums left by 1 column.
  177709. */
  177710. bnexterr = cur;
  177711. delta = cur * 2;
  177712. cur += delta; /* form error * 3 */
  177713. errorptr[0] = (FSERROR) (bpreverr + cur);
  177714. cur += delta; /* form error * 5 */
  177715. bpreverr = belowerr + cur;
  177716. belowerr = bnexterr;
  177717. cur += delta; /* form error * 7 */
  177718. /* At this point cur contains the 7/16 error value to be propagated
  177719. * to the next pixel on the current line, and all the errors for the
  177720. * next line have been shifted over. We are therefore ready to move on.
  177721. */
  177722. input_ptr += dirnc; /* advance input ptr to next column */
  177723. output_ptr += dir; /* advance output ptr to next column */
  177724. errorptr += dir; /* advance errorptr to current column */
  177725. }
  177726. /* Post-loop cleanup: we must unload the final error value into the
  177727. * final fserrors[] entry. Note we need not unload belowerr because
  177728. * it is for the dummy column before or after the actual array.
  177729. */
  177730. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177731. }
  177732. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177733. }
  177734. }
  177735. /*
  177736. * Allocate workspace for Floyd-Steinberg errors.
  177737. */
  177738. LOCAL(void)
  177739. alloc_fs_workspace (j_decompress_ptr cinfo)
  177740. {
  177741. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177742. size_t arraysize;
  177743. int i;
  177744. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177745. for (i = 0; i < cinfo->out_color_components; i++) {
  177746. cquantize->fserrors[i] = (FSERRPTR)
  177747. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177748. }
  177749. }
  177750. /*
  177751. * Initialize for one-pass color quantization.
  177752. */
  177753. METHODDEF(void)
  177754. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177755. {
  177756. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177757. size_t arraysize;
  177758. int i;
  177759. /* Install my colormap. */
  177760. cinfo->colormap = cquantize->sv_colormap;
  177761. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177762. /* Initialize for desired dithering mode. */
  177763. switch (cinfo->dither_mode) {
  177764. case JDITHER_NONE:
  177765. if (cinfo->out_color_components == 3)
  177766. cquantize->pub.color_quantize = color_quantize3;
  177767. else
  177768. cquantize->pub.color_quantize = color_quantize;
  177769. break;
  177770. case JDITHER_ORDERED:
  177771. if (cinfo->out_color_components == 3)
  177772. cquantize->pub.color_quantize = quantize3_ord_dither;
  177773. else
  177774. cquantize->pub.color_quantize = quantize_ord_dither;
  177775. cquantize->row_index = 0; /* initialize state for ordered dither */
  177776. /* If user changed to ordered dither from another mode,
  177777. * we must recreate the color index table with padding.
  177778. * This will cost extra space, but probably isn't very likely.
  177779. */
  177780. if (! cquantize->is_padded)
  177781. create_colorindex(cinfo);
  177782. /* Create ordered-dither tables if we didn't already. */
  177783. if (cquantize->odither[0] == NULL)
  177784. create_odither_tables(cinfo);
  177785. break;
  177786. case JDITHER_FS:
  177787. cquantize->pub.color_quantize = quantize_fs_dither;
  177788. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177789. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177790. if (cquantize->fserrors[0] == NULL)
  177791. alloc_fs_workspace(cinfo);
  177792. /* Initialize the propagated errors to zero. */
  177793. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177794. for (i = 0; i < cinfo->out_color_components; i++)
  177795. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177796. break;
  177797. default:
  177798. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177799. break;
  177800. }
  177801. }
  177802. /*
  177803. * Finish up at the end of the pass.
  177804. */
  177805. METHODDEF(void)
  177806. finish_pass_1_quant (j_decompress_ptr)
  177807. {
  177808. /* no work in 1-pass case */
  177809. }
  177810. /*
  177811. * Switch to a new external colormap between output passes.
  177812. * Shouldn't get to this module!
  177813. */
  177814. METHODDEF(void)
  177815. new_color_map_1_quant (j_decompress_ptr cinfo)
  177816. {
  177817. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177818. }
  177819. /*
  177820. * Module initialization routine for 1-pass color quantization.
  177821. */
  177822. GLOBAL(void)
  177823. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177824. {
  177825. my_cquantize_ptr cquantize;
  177826. cquantize = (my_cquantize_ptr)
  177827. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177828. SIZEOF(my_cquantizer));
  177829. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177830. cquantize->pub.start_pass = start_pass_1_quant;
  177831. cquantize->pub.finish_pass = finish_pass_1_quant;
  177832. cquantize->pub.new_color_map = new_color_map_1_quant;
  177833. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177834. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177835. /* Make sure my internal arrays won't overflow */
  177836. if (cinfo->out_color_components > MAX_Q_COMPS)
  177837. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177838. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177839. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177840. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177841. /* Create the colormap and color index table. */
  177842. create_colormap(cinfo);
  177843. create_colorindex(cinfo);
  177844. /* Allocate Floyd-Steinberg workspace now if requested.
  177845. * We do this now since it is FAR storage and may affect the memory
  177846. * manager's space calculations. If the user changes to FS dither
  177847. * mode in a later pass, we will allocate the space then, and will
  177848. * possibly overrun the max_memory_to_use setting.
  177849. */
  177850. if (cinfo->dither_mode == JDITHER_FS)
  177851. alloc_fs_workspace(cinfo);
  177852. }
  177853. #endif /* QUANT_1PASS_SUPPORTED */
  177854. /*** End of inlined file: jquant1.c ***/
  177855. /*** Start of inlined file: jquant2.c ***/
  177856. #define JPEG_INTERNALS
  177857. #ifdef QUANT_2PASS_SUPPORTED
  177858. /*
  177859. * This module implements the well-known Heckbert paradigm for color
  177860. * quantization. Most of the ideas used here can be traced back to
  177861. * Heckbert's seminal paper
  177862. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177863. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177864. *
  177865. * In the first pass over the image, we accumulate a histogram showing the
  177866. * usage count of each possible color. To keep the histogram to a reasonable
  177867. * size, we reduce the precision of the input; typical practice is to retain
  177868. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177869. * in the same histogram cell.
  177870. *
  177871. * Next, the color-selection step begins with a box representing the whole
  177872. * color space, and repeatedly splits the "largest" remaining box until we
  177873. * have as many boxes as desired colors. Then the mean color in each
  177874. * remaining box becomes one of the possible output colors.
  177875. *
  177876. * The second pass over the image maps each input pixel to the closest output
  177877. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177878. * This mapping is logically trivial, but making it go fast enough requires
  177879. * considerable care.
  177880. *
  177881. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177882. * the "largest" box and deciding where to cut it. The particular policies
  177883. * used here have proved out well in experimental comparisons, but better ones
  177884. * may yet be found.
  177885. *
  177886. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177887. * space, processing the raw upsampled data without a color conversion step.
  177888. * This allowed the color conversion math to be done only once per colormap
  177889. * entry, not once per pixel. However, that optimization precluded other
  177890. * useful optimizations (such as merging color conversion with upsampling)
  177891. * and it also interfered with desired capabilities such as quantizing to an
  177892. * externally-supplied colormap. We have therefore abandoned that approach.
  177893. * The present code works in the post-conversion color space, typically RGB.
  177894. *
  177895. * To improve the visual quality of the results, we actually work in scaled
  177896. * RGB space, giving G distances more weight than R, and R in turn more than
  177897. * B. To do everything in integer math, we must use integer scale factors.
  177898. * The 2/3/1 scale factors used here correspond loosely to the relative
  177899. * weights of the colors in the NTSC grayscale equation.
  177900. * If you want to use this code to quantize a non-RGB color space, you'll
  177901. * probably need to change these scale factors.
  177902. */
  177903. #define R_SCALE 2 /* scale R distances by this much */
  177904. #define G_SCALE 3 /* scale G distances by this much */
  177905. #define B_SCALE 1 /* and B by this much */
  177906. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177907. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177908. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177909. * you'll get compile errors until you extend this logic. In that case
  177910. * you'll probably want to tweak the histogram sizes too.
  177911. */
  177912. #if RGB_RED == 0
  177913. #define C0_SCALE R_SCALE
  177914. #endif
  177915. #if RGB_BLUE == 0
  177916. #define C0_SCALE B_SCALE
  177917. #endif
  177918. #if RGB_GREEN == 1
  177919. #define C1_SCALE G_SCALE
  177920. #endif
  177921. #if RGB_RED == 2
  177922. #define C2_SCALE R_SCALE
  177923. #endif
  177924. #if RGB_BLUE == 2
  177925. #define C2_SCALE B_SCALE
  177926. #endif
  177927. /*
  177928. * First we have the histogram data structure and routines for creating it.
  177929. *
  177930. * The number of bits of precision can be adjusted by changing these symbols.
  177931. * We recommend keeping 6 bits for G and 5 each for R and B.
  177932. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177933. * better results; if you are short of memory, 5 bits all around will save
  177934. * some space but degrade the results.
  177935. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177936. * (preferably unsigned long) for each cell. In practice this is overkill;
  177937. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177938. * and clamping those that do overflow to the maximum value will give close-
  177939. * enough results. This reduces the recommended histogram size from 256Kb
  177940. * to 128Kb, which is a useful savings on PC-class machines.
  177941. * (In the second pass the histogram space is re-used for pixel mapping data;
  177942. * in that capacity, each cell must be able to store zero to the number of
  177943. * desired colors. 16 bits/cell is plenty for that too.)
  177944. * Since the JPEG code is intended to run in small memory model on 80x86
  177945. * machines, we can't just allocate the histogram in one chunk. Instead
  177946. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177947. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177948. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177949. * on 80x86 machines, the pointer row is in near memory but the actual
  177950. * arrays are in far memory (same arrangement as we use for image arrays).
  177951. */
  177952. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177953. /* These will do the right thing for either R,G,B or B,G,R color order,
  177954. * but you may not like the results for other color orders.
  177955. */
  177956. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177957. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177958. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177959. /* Number of elements along histogram axes. */
  177960. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177961. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177962. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177963. /* These are the amounts to shift an input value to get a histogram index. */
  177964. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177965. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177966. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177967. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177968. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177969. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177970. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177971. typedef hist2d * hist3d; /* type for top-level pointer */
  177972. /* Declarations for Floyd-Steinberg dithering.
  177973. *
  177974. * Errors are accumulated into the array fserrors[], at a resolution of
  177975. * 1/16th of a pixel count. The error at a given pixel is propagated
  177976. * to its not-yet-processed neighbors using the standard F-S fractions,
  177977. * ... (here) 7/16
  177978. * 3/16 5/16 1/16
  177979. * We work left-to-right on even rows, right-to-left on odd rows.
  177980. *
  177981. * We can get away with a single array (holding one row's worth of errors)
  177982. * by using it to store the current row's errors at pixel columns not yet
  177983. * processed, but the next row's errors at columns already processed. We
  177984. * need only a few extra variables to hold the errors immediately around the
  177985. * current column. (If we are lucky, those variables are in registers, but
  177986. * even if not, they're probably cheaper to access than array elements are.)
  177987. *
  177988. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177989. * each end saves us from special-casing the first and last pixels.
  177990. * Each entry is three values long, one value for each color component.
  177991. *
  177992. * Note: on a wide image, we might not have enough room in a PC's near data
  177993. * segment to hold the error array; so it is allocated with alloc_large.
  177994. */
  177995. #if BITS_IN_JSAMPLE == 8
  177996. typedef INT16 FSERROR; /* 16 bits should be enough */
  177997. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177998. #else
  177999. typedef INT32 FSERROR; /* may need more than 16 bits */
  178000. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178001. #endif
  178002. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178003. /* Private subobject */
  178004. typedef struct {
  178005. struct jpeg_color_quantizer pub; /* public fields */
  178006. /* Space for the eventually created colormap is stashed here */
  178007. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178008. int desired; /* desired # of colors = size of colormap */
  178009. /* Variables for accumulating image statistics */
  178010. hist3d histogram; /* pointer to the histogram */
  178011. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178012. /* Variables for Floyd-Steinberg dithering */
  178013. FSERRPTR fserrors; /* accumulated errors */
  178014. boolean on_odd_row; /* flag to remember which row we are on */
  178015. int * error_limiter; /* table for clamping the applied error */
  178016. } my_cquantizer2;
  178017. typedef my_cquantizer2 * my_cquantize_ptr2;
  178018. /*
  178019. * Prescan some rows of pixels.
  178020. * In this module the prescan simply updates the histogram, which has been
  178021. * initialized to zeroes by start_pass.
  178022. * An output_buf parameter is required by the method signature, but no data
  178023. * is actually output (in fact the buffer controller is probably passing a
  178024. * NULL pointer).
  178025. */
  178026. METHODDEF(void)
  178027. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178028. JSAMPARRAY, int num_rows)
  178029. {
  178030. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178031. register JSAMPROW ptr;
  178032. register histptr histp;
  178033. register hist3d histogram = cquantize->histogram;
  178034. int row;
  178035. JDIMENSION col;
  178036. JDIMENSION width = cinfo->output_width;
  178037. for (row = 0; row < num_rows; row++) {
  178038. ptr = input_buf[row];
  178039. for (col = width; col > 0; col--) {
  178040. /* get pixel value and index into the histogram */
  178041. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178042. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178043. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178044. /* increment, check for overflow and undo increment if so. */
  178045. if (++(*histp) <= 0)
  178046. (*histp)--;
  178047. ptr += 3;
  178048. }
  178049. }
  178050. }
  178051. /*
  178052. * Next we have the really interesting routines: selection of a colormap
  178053. * given the completed histogram.
  178054. * These routines work with a list of "boxes", each representing a rectangular
  178055. * subset of the input color space (to histogram precision).
  178056. */
  178057. typedef struct {
  178058. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178059. int c0min, c0max;
  178060. int c1min, c1max;
  178061. int c2min, c2max;
  178062. /* The volume (actually 2-norm) of the box */
  178063. INT32 volume;
  178064. /* The number of nonzero histogram cells within this box */
  178065. long colorcount;
  178066. } box;
  178067. typedef box * boxptr;
  178068. LOCAL(boxptr)
  178069. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178070. /* Find the splittable box with the largest color population */
  178071. /* Returns NULL if no splittable boxes remain */
  178072. {
  178073. register boxptr boxp;
  178074. register int i;
  178075. register long maxc = 0;
  178076. boxptr which = NULL;
  178077. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178078. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178079. which = boxp;
  178080. maxc = boxp->colorcount;
  178081. }
  178082. }
  178083. return which;
  178084. }
  178085. LOCAL(boxptr)
  178086. find_biggest_volume (boxptr boxlist, int numboxes)
  178087. /* Find the splittable box with the largest (scaled) volume */
  178088. /* Returns NULL if no splittable boxes remain */
  178089. {
  178090. register boxptr boxp;
  178091. register int i;
  178092. register INT32 maxv = 0;
  178093. boxptr which = NULL;
  178094. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178095. if (boxp->volume > maxv) {
  178096. which = boxp;
  178097. maxv = boxp->volume;
  178098. }
  178099. }
  178100. return which;
  178101. }
  178102. LOCAL(void)
  178103. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178104. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178105. /* and recompute its volume and population */
  178106. {
  178107. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178108. hist3d histogram = cquantize->histogram;
  178109. histptr histp;
  178110. int c0,c1,c2;
  178111. int c0min,c0max,c1min,c1max,c2min,c2max;
  178112. INT32 dist0,dist1,dist2;
  178113. long ccount;
  178114. c0min = boxp->c0min; c0max = boxp->c0max;
  178115. c1min = boxp->c1min; c1max = boxp->c1max;
  178116. c2min = boxp->c2min; c2max = boxp->c2max;
  178117. if (c0max > c0min)
  178118. for (c0 = c0min; c0 <= c0max; c0++)
  178119. for (c1 = c1min; c1 <= c1max; c1++) {
  178120. histp = & histogram[c0][c1][c2min];
  178121. for (c2 = c2min; c2 <= c2max; c2++)
  178122. if (*histp++ != 0) {
  178123. boxp->c0min = c0min = c0;
  178124. goto have_c0min;
  178125. }
  178126. }
  178127. have_c0min:
  178128. if (c0max > c0min)
  178129. for (c0 = c0max; c0 >= c0min; c0--)
  178130. for (c1 = c1min; c1 <= c1max; c1++) {
  178131. histp = & histogram[c0][c1][c2min];
  178132. for (c2 = c2min; c2 <= c2max; c2++)
  178133. if (*histp++ != 0) {
  178134. boxp->c0max = c0max = c0;
  178135. goto have_c0max;
  178136. }
  178137. }
  178138. have_c0max:
  178139. if (c1max > c1min)
  178140. for (c1 = c1min; c1 <= c1max; c1++)
  178141. for (c0 = c0min; c0 <= c0max; c0++) {
  178142. histp = & histogram[c0][c1][c2min];
  178143. for (c2 = c2min; c2 <= c2max; c2++)
  178144. if (*histp++ != 0) {
  178145. boxp->c1min = c1min = c1;
  178146. goto have_c1min;
  178147. }
  178148. }
  178149. have_c1min:
  178150. if (c1max > c1min)
  178151. for (c1 = c1max; c1 >= c1min; c1--)
  178152. for (c0 = c0min; c0 <= c0max; c0++) {
  178153. histp = & histogram[c0][c1][c2min];
  178154. for (c2 = c2min; c2 <= c2max; c2++)
  178155. if (*histp++ != 0) {
  178156. boxp->c1max = c1max = c1;
  178157. goto have_c1max;
  178158. }
  178159. }
  178160. have_c1max:
  178161. if (c2max > c2min)
  178162. for (c2 = c2min; c2 <= c2max; c2++)
  178163. for (c0 = c0min; c0 <= c0max; c0++) {
  178164. histp = & histogram[c0][c1min][c2];
  178165. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178166. if (*histp != 0) {
  178167. boxp->c2min = c2min = c2;
  178168. goto have_c2min;
  178169. }
  178170. }
  178171. have_c2min:
  178172. if (c2max > c2min)
  178173. for (c2 = c2max; c2 >= c2min; c2--)
  178174. for (c0 = c0min; c0 <= c0max; c0++) {
  178175. histp = & histogram[c0][c1min][c2];
  178176. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178177. if (*histp != 0) {
  178178. boxp->c2max = c2max = c2;
  178179. goto have_c2max;
  178180. }
  178181. }
  178182. have_c2max:
  178183. /* Update box volume.
  178184. * We use 2-norm rather than real volume here; this biases the method
  178185. * against making long narrow boxes, and it has the side benefit that
  178186. * a box is splittable iff norm > 0.
  178187. * Since the differences are expressed in histogram-cell units,
  178188. * we have to shift back to JSAMPLE units to get consistent distances;
  178189. * after which, we scale according to the selected distance scale factors.
  178190. */
  178191. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178192. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178193. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178194. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178195. /* Now scan remaining volume of box and compute population */
  178196. ccount = 0;
  178197. for (c0 = c0min; c0 <= c0max; c0++)
  178198. for (c1 = c1min; c1 <= c1max; c1++) {
  178199. histp = & histogram[c0][c1][c2min];
  178200. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178201. if (*histp != 0) {
  178202. ccount++;
  178203. }
  178204. }
  178205. boxp->colorcount = ccount;
  178206. }
  178207. LOCAL(int)
  178208. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178209. int desired_colors)
  178210. /* Repeatedly select and split the largest box until we have enough boxes */
  178211. {
  178212. int n,lb;
  178213. int c0,c1,c2,cmax;
  178214. register boxptr b1,b2;
  178215. while (numboxes < desired_colors) {
  178216. /* Select box to split.
  178217. * Current algorithm: by population for first half, then by volume.
  178218. */
  178219. if (numboxes*2 <= desired_colors) {
  178220. b1 = find_biggest_color_pop(boxlist, numboxes);
  178221. } else {
  178222. b1 = find_biggest_volume(boxlist, numboxes);
  178223. }
  178224. if (b1 == NULL) /* no splittable boxes left! */
  178225. break;
  178226. b2 = &boxlist[numboxes]; /* where new box will go */
  178227. /* Copy the color bounds to the new box. */
  178228. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178229. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178230. /* Choose which axis to split the box on.
  178231. * Current algorithm: longest scaled axis.
  178232. * See notes in update_box about scaling distances.
  178233. */
  178234. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178235. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178236. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178237. /* We want to break any ties in favor of green, then red, blue last.
  178238. * This code does the right thing for R,G,B or B,G,R color orders only.
  178239. */
  178240. #if RGB_RED == 0
  178241. cmax = c1; n = 1;
  178242. if (c0 > cmax) { cmax = c0; n = 0; }
  178243. if (c2 > cmax) { n = 2; }
  178244. #else
  178245. cmax = c1; n = 1;
  178246. if (c2 > cmax) { cmax = c2; n = 2; }
  178247. if (c0 > cmax) { n = 0; }
  178248. #endif
  178249. /* Choose split point along selected axis, and update box bounds.
  178250. * Current algorithm: split at halfway point.
  178251. * (Since the box has been shrunk to minimum volume,
  178252. * any split will produce two nonempty subboxes.)
  178253. * Note that lb value is max for lower box, so must be < old max.
  178254. */
  178255. switch (n) {
  178256. case 0:
  178257. lb = (b1->c0max + b1->c0min) / 2;
  178258. b1->c0max = lb;
  178259. b2->c0min = lb+1;
  178260. break;
  178261. case 1:
  178262. lb = (b1->c1max + b1->c1min) / 2;
  178263. b1->c1max = lb;
  178264. b2->c1min = lb+1;
  178265. break;
  178266. case 2:
  178267. lb = (b1->c2max + b1->c2min) / 2;
  178268. b1->c2max = lb;
  178269. b2->c2min = lb+1;
  178270. break;
  178271. }
  178272. /* Update stats for boxes */
  178273. update_box(cinfo, b1);
  178274. update_box(cinfo, b2);
  178275. numboxes++;
  178276. }
  178277. return numboxes;
  178278. }
  178279. LOCAL(void)
  178280. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178281. /* Compute representative color for a box, put it in colormap[icolor] */
  178282. {
  178283. /* Current algorithm: mean weighted by pixels (not colors) */
  178284. /* Note it is important to get the rounding correct! */
  178285. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178286. hist3d histogram = cquantize->histogram;
  178287. histptr histp;
  178288. int c0,c1,c2;
  178289. int c0min,c0max,c1min,c1max,c2min,c2max;
  178290. long count;
  178291. long total = 0;
  178292. long c0total = 0;
  178293. long c1total = 0;
  178294. long c2total = 0;
  178295. c0min = boxp->c0min; c0max = boxp->c0max;
  178296. c1min = boxp->c1min; c1max = boxp->c1max;
  178297. c2min = boxp->c2min; c2max = boxp->c2max;
  178298. for (c0 = c0min; c0 <= c0max; c0++)
  178299. for (c1 = c1min; c1 <= c1max; c1++) {
  178300. histp = & histogram[c0][c1][c2min];
  178301. for (c2 = c2min; c2 <= c2max; c2++) {
  178302. if ((count = *histp++) != 0) {
  178303. total += count;
  178304. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178305. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178306. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178307. }
  178308. }
  178309. }
  178310. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178311. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178312. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178313. }
  178314. LOCAL(void)
  178315. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178316. /* Master routine for color selection */
  178317. {
  178318. boxptr boxlist;
  178319. int numboxes;
  178320. int i;
  178321. /* Allocate workspace for box list */
  178322. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178323. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178324. /* Initialize one box containing whole space */
  178325. numboxes = 1;
  178326. boxlist[0].c0min = 0;
  178327. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178328. boxlist[0].c1min = 0;
  178329. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178330. boxlist[0].c2min = 0;
  178331. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178332. /* Shrink it to actually-used volume and set its statistics */
  178333. update_box(cinfo, & boxlist[0]);
  178334. /* Perform median-cut to produce final box list */
  178335. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178336. /* Compute the representative color for each box, fill colormap */
  178337. for (i = 0; i < numboxes; i++)
  178338. compute_color(cinfo, & boxlist[i], i);
  178339. cinfo->actual_number_of_colors = numboxes;
  178340. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178341. }
  178342. /*
  178343. * These routines are concerned with the time-critical task of mapping input
  178344. * colors to the nearest color in the selected colormap.
  178345. *
  178346. * We re-use the histogram space as an "inverse color map", essentially a
  178347. * cache for the results of nearest-color searches. All colors within a
  178348. * histogram cell will be mapped to the same colormap entry, namely the one
  178349. * closest to the cell's center. This may not be quite the closest entry to
  178350. * the actual input color, but it's almost as good. A zero in the cache
  178351. * indicates we haven't found the nearest color for that cell yet; the array
  178352. * is cleared to zeroes before starting the mapping pass. When we find the
  178353. * nearest color for a cell, its colormap index plus one is recorded in the
  178354. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178355. * when they need to use an unfilled entry in the cache.
  178356. *
  178357. * Our method of efficiently finding nearest colors is based on the "locally
  178358. * sorted search" idea described by Heckbert and on the incremental distance
  178359. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178360. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178361. * the distances from a given colormap entry to each cell of the histogram can
  178362. * be computed quickly using an incremental method: the differences between
  178363. * distances to adjacent cells themselves differ by a constant. This allows a
  178364. * fairly fast implementation of the "brute force" approach of computing the
  178365. * distance from every colormap entry to every histogram cell. Unfortunately,
  178366. * it needs a work array to hold the best-distance-so-far for each histogram
  178367. * cell (because the inner loop has to be over cells, not colormap entries).
  178368. * The work array elements have to be INT32s, so the work array would need
  178369. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178370. *
  178371. * To get around these problems, we apply Thomas' method to compute the
  178372. * nearest colors for only the cells within a small subbox of the histogram.
  178373. * The work array need be only as big as the subbox, so the memory usage
  178374. * problem is solved. Furthermore, we need not fill subboxes that are never
  178375. * referenced in pass2; many images use only part of the color gamut, so a
  178376. * fair amount of work is saved. An additional advantage of this
  178377. * approach is that we can apply Heckbert's locality criterion to quickly
  178378. * eliminate colormap entries that are far away from the subbox; typically
  178379. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178380. * and we need not compute their distances to individual cells in the subbox.
  178381. * The speed of this approach is heavily influenced by the subbox size: too
  178382. * small means too much overhead, too big loses because Heckbert's criterion
  178383. * can't eliminate as many colormap entries. Empirically the best subbox
  178384. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178385. *
  178386. * Thomas' article also describes a refined method which is asymptotically
  178387. * faster than the brute-force method, but it is also far more complex and
  178388. * cannot efficiently be applied to small subboxes. It is therefore not
  178389. * useful for programs intended to be portable to DOS machines. On machines
  178390. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178391. * refined method might be faster than the present code --- but then again,
  178392. * it might not be any faster, and it's certainly more complicated.
  178393. */
  178394. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178395. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178396. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178397. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178398. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178399. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178400. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178401. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178402. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178403. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178404. /*
  178405. * The next three routines implement inverse colormap filling. They could
  178406. * all be folded into one big routine, but splitting them up this way saves
  178407. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178408. * and may allow some compilers to produce better code by registerizing more
  178409. * inner-loop variables.
  178410. */
  178411. LOCAL(int)
  178412. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178413. JSAMPLE colorlist[])
  178414. /* Locate the colormap entries close enough to an update box to be candidates
  178415. * for the nearest entry to some cell(s) in the update box. The update box
  178416. * is specified by the center coordinates of its first cell. The number of
  178417. * candidate colormap entries is returned, and their colormap indexes are
  178418. * placed in colorlist[].
  178419. * This routine uses Heckbert's "locally sorted search" criterion to select
  178420. * the colors that need further consideration.
  178421. */
  178422. {
  178423. int numcolors = cinfo->actual_number_of_colors;
  178424. int maxc0, maxc1, maxc2;
  178425. int centerc0, centerc1, centerc2;
  178426. int i, x, ncolors;
  178427. INT32 minmaxdist, min_dist, max_dist, tdist;
  178428. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178429. /* Compute true coordinates of update box's upper corner and center.
  178430. * Actually we compute the coordinates of the center of the upper-corner
  178431. * histogram cell, which are the upper bounds of the volume we care about.
  178432. * Note that since ">>" rounds down, the "center" values may be closer to
  178433. * min than to max; hence comparisons to them must be "<=", not "<".
  178434. */
  178435. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178436. centerc0 = (minc0 + maxc0) >> 1;
  178437. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178438. centerc1 = (minc1 + maxc1) >> 1;
  178439. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178440. centerc2 = (minc2 + maxc2) >> 1;
  178441. /* For each color in colormap, find:
  178442. * 1. its minimum squared-distance to any point in the update box
  178443. * (zero if color is within update box);
  178444. * 2. its maximum squared-distance to any point in the update box.
  178445. * Both of these can be found by considering only the corners of the box.
  178446. * We save the minimum distance for each color in mindist[];
  178447. * only the smallest maximum distance is of interest.
  178448. */
  178449. minmaxdist = 0x7FFFFFFFL;
  178450. for (i = 0; i < numcolors; i++) {
  178451. /* We compute the squared-c0-distance term, then add in the other two. */
  178452. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178453. if (x < minc0) {
  178454. tdist = (x - minc0) * C0_SCALE;
  178455. min_dist = tdist*tdist;
  178456. tdist = (x - maxc0) * C0_SCALE;
  178457. max_dist = tdist*tdist;
  178458. } else if (x > maxc0) {
  178459. tdist = (x - maxc0) * C0_SCALE;
  178460. min_dist = tdist*tdist;
  178461. tdist = (x - minc0) * C0_SCALE;
  178462. max_dist = tdist*tdist;
  178463. } else {
  178464. /* within cell range so no contribution to min_dist */
  178465. min_dist = 0;
  178466. if (x <= centerc0) {
  178467. tdist = (x - maxc0) * C0_SCALE;
  178468. max_dist = tdist*tdist;
  178469. } else {
  178470. tdist = (x - minc0) * C0_SCALE;
  178471. max_dist = tdist*tdist;
  178472. }
  178473. }
  178474. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178475. if (x < minc1) {
  178476. tdist = (x - minc1) * C1_SCALE;
  178477. min_dist += tdist*tdist;
  178478. tdist = (x - maxc1) * C1_SCALE;
  178479. max_dist += tdist*tdist;
  178480. } else if (x > maxc1) {
  178481. tdist = (x - maxc1) * C1_SCALE;
  178482. min_dist += tdist*tdist;
  178483. tdist = (x - minc1) * C1_SCALE;
  178484. max_dist += tdist*tdist;
  178485. } else {
  178486. /* within cell range so no contribution to min_dist */
  178487. if (x <= centerc1) {
  178488. tdist = (x - maxc1) * C1_SCALE;
  178489. max_dist += tdist*tdist;
  178490. } else {
  178491. tdist = (x - minc1) * C1_SCALE;
  178492. max_dist += tdist*tdist;
  178493. }
  178494. }
  178495. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178496. if (x < minc2) {
  178497. tdist = (x - minc2) * C2_SCALE;
  178498. min_dist += tdist*tdist;
  178499. tdist = (x - maxc2) * C2_SCALE;
  178500. max_dist += tdist*tdist;
  178501. } else if (x > maxc2) {
  178502. tdist = (x - maxc2) * C2_SCALE;
  178503. min_dist += tdist*tdist;
  178504. tdist = (x - minc2) * C2_SCALE;
  178505. max_dist += tdist*tdist;
  178506. } else {
  178507. /* within cell range so no contribution to min_dist */
  178508. if (x <= centerc2) {
  178509. tdist = (x - maxc2) * C2_SCALE;
  178510. max_dist += tdist*tdist;
  178511. } else {
  178512. tdist = (x - minc2) * C2_SCALE;
  178513. max_dist += tdist*tdist;
  178514. }
  178515. }
  178516. mindist[i] = min_dist; /* save away the results */
  178517. if (max_dist < minmaxdist)
  178518. minmaxdist = max_dist;
  178519. }
  178520. /* Now we know that no cell in the update box is more than minmaxdist
  178521. * away from some colormap entry. Therefore, only colors that are
  178522. * within minmaxdist of some part of the box need be considered.
  178523. */
  178524. ncolors = 0;
  178525. for (i = 0; i < numcolors; i++) {
  178526. if (mindist[i] <= minmaxdist)
  178527. colorlist[ncolors++] = (JSAMPLE) i;
  178528. }
  178529. return ncolors;
  178530. }
  178531. LOCAL(void)
  178532. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178533. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178534. /* Find the closest colormap entry for each cell in the update box,
  178535. * given the list of candidate colors prepared by find_nearby_colors.
  178536. * Return the indexes of the closest entries in the bestcolor[] array.
  178537. * This routine uses Thomas' incremental distance calculation method to
  178538. * find the distance from a colormap entry to successive cells in the box.
  178539. */
  178540. {
  178541. int ic0, ic1, ic2;
  178542. int i, icolor;
  178543. register INT32 * bptr; /* pointer into bestdist[] array */
  178544. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178545. INT32 dist0, dist1; /* initial distance values */
  178546. register INT32 dist2; /* current distance in inner loop */
  178547. INT32 xx0, xx1; /* distance increments */
  178548. register INT32 xx2;
  178549. INT32 inc0, inc1, inc2; /* initial values for increments */
  178550. /* This array holds the distance to the nearest-so-far color for each cell */
  178551. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178552. /* Initialize best-distance for each cell of the update box */
  178553. bptr = bestdist;
  178554. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178555. *bptr++ = 0x7FFFFFFFL;
  178556. /* For each color selected by find_nearby_colors,
  178557. * compute its distance to the center of each cell in the box.
  178558. * If that's less than best-so-far, update best distance and color number.
  178559. */
  178560. /* Nominal steps between cell centers ("x" in Thomas article) */
  178561. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178562. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178563. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178564. for (i = 0; i < numcolors; i++) {
  178565. icolor = GETJSAMPLE(colorlist[i]);
  178566. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178567. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178568. dist0 = inc0*inc0;
  178569. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178570. dist0 += inc1*inc1;
  178571. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178572. dist0 += inc2*inc2;
  178573. /* Form the initial difference increments */
  178574. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178575. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178576. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178577. /* Now loop over all cells in box, updating distance per Thomas method */
  178578. bptr = bestdist;
  178579. cptr = bestcolor;
  178580. xx0 = inc0;
  178581. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178582. dist1 = dist0;
  178583. xx1 = inc1;
  178584. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178585. dist2 = dist1;
  178586. xx2 = inc2;
  178587. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178588. if (dist2 < *bptr) {
  178589. *bptr = dist2;
  178590. *cptr = (JSAMPLE) icolor;
  178591. }
  178592. dist2 += xx2;
  178593. xx2 += 2 * STEP_C2 * STEP_C2;
  178594. bptr++;
  178595. cptr++;
  178596. }
  178597. dist1 += xx1;
  178598. xx1 += 2 * STEP_C1 * STEP_C1;
  178599. }
  178600. dist0 += xx0;
  178601. xx0 += 2 * STEP_C0 * STEP_C0;
  178602. }
  178603. }
  178604. }
  178605. LOCAL(void)
  178606. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178607. /* Fill the inverse-colormap entries in the update box that contains */
  178608. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178609. /* we can fill as many others as we wish.) */
  178610. {
  178611. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178612. hist3d histogram = cquantize->histogram;
  178613. int minc0, minc1, minc2; /* lower left corner of update box */
  178614. int ic0, ic1, ic2;
  178615. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178616. register histptr cachep; /* pointer into main cache array */
  178617. /* This array lists the candidate colormap indexes. */
  178618. JSAMPLE colorlist[MAXNUMCOLORS];
  178619. int numcolors; /* number of candidate colors */
  178620. /* This array holds the actually closest colormap index for each cell. */
  178621. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178622. /* Convert cell coordinates to update box ID */
  178623. c0 >>= BOX_C0_LOG;
  178624. c1 >>= BOX_C1_LOG;
  178625. c2 >>= BOX_C2_LOG;
  178626. /* Compute true coordinates of update box's origin corner.
  178627. * Actually we compute the coordinates of the center of the corner
  178628. * histogram cell, which are the lower bounds of the volume we care about.
  178629. */
  178630. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178631. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178632. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178633. /* Determine which colormap entries are close enough to be candidates
  178634. * for the nearest entry to some cell in the update box.
  178635. */
  178636. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178637. /* Determine the actually nearest colors. */
  178638. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178639. bestcolor);
  178640. /* Save the best color numbers (plus 1) in the main cache array */
  178641. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178642. c1 <<= BOX_C1_LOG;
  178643. c2 <<= BOX_C2_LOG;
  178644. cptr = bestcolor;
  178645. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178646. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178647. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178648. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178649. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178650. }
  178651. }
  178652. }
  178653. }
  178654. /*
  178655. * Map some rows of pixels to the output colormapped representation.
  178656. */
  178657. METHODDEF(void)
  178658. pass2_no_dither (j_decompress_ptr cinfo,
  178659. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178660. /* This version performs no dithering */
  178661. {
  178662. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178663. hist3d histogram = cquantize->histogram;
  178664. register JSAMPROW inptr, outptr;
  178665. register histptr cachep;
  178666. register int c0, c1, c2;
  178667. int row;
  178668. JDIMENSION col;
  178669. JDIMENSION width = cinfo->output_width;
  178670. for (row = 0; row < num_rows; row++) {
  178671. inptr = input_buf[row];
  178672. outptr = output_buf[row];
  178673. for (col = width; col > 0; col--) {
  178674. /* get pixel value and index into the cache */
  178675. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178676. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178677. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178678. cachep = & histogram[c0][c1][c2];
  178679. /* If we have not seen this color before, find nearest colormap entry */
  178680. /* and update the cache */
  178681. if (*cachep == 0)
  178682. fill_inverse_cmap(cinfo, c0,c1,c2);
  178683. /* Now emit the colormap index for this cell */
  178684. *outptr++ = (JSAMPLE) (*cachep - 1);
  178685. }
  178686. }
  178687. }
  178688. METHODDEF(void)
  178689. pass2_fs_dither (j_decompress_ptr cinfo,
  178690. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178691. /* This version performs Floyd-Steinberg dithering */
  178692. {
  178693. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178694. hist3d histogram = cquantize->histogram;
  178695. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178696. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178697. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178698. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178699. JSAMPROW inptr; /* => current input pixel */
  178700. JSAMPROW outptr; /* => current output pixel */
  178701. histptr cachep;
  178702. int dir; /* +1 or -1 depending on direction */
  178703. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178704. int row;
  178705. JDIMENSION col;
  178706. JDIMENSION width = cinfo->output_width;
  178707. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178708. int *error_limit = cquantize->error_limiter;
  178709. JSAMPROW colormap0 = cinfo->colormap[0];
  178710. JSAMPROW colormap1 = cinfo->colormap[1];
  178711. JSAMPROW colormap2 = cinfo->colormap[2];
  178712. SHIFT_TEMPS
  178713. for (row = 0; row < num_rows; row++) {
  178714. inptr = input_buf[row];
  178715. outptr = output_buf[row];
  178716. if (cquantize->on_odd_row) {
  178717. /* work right to left in this row */
  178718. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178719. outptr += width-1;
  178720. dir = -1;
  178721. dir3 = -3;
  178722. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178723. cquantize->on_odd_row = FALSE; /* flip for next time */
  178724. } else {
  178725. /* work left to right in this row */
  178726. dir = 1;
  178727. dir3 = 3;
  178728. errorptr = cquantize->fserrors; /* => entry before first real column */
  178729. cquantize->on_odd_row = TRUE; /* flip for next time */
  178730. }
  178731. /* Preset error values: no error propagated to first pixel from left */
  178732. cur0 = cur1 = cur2 = 0;
  178733. /* and no error propagated to row below yet */
  178734. belowerr0 = belowerr1 = belowerr2 = 0;
  178735. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178736. for (col = width; col > 0; col--) {
  178737. /* curN holds the error propagated from the previous pixel on the
  178738. * current line. Add the error propagated from the previous line
  178739. * to form the complete error correction term for this pixel, and
  178740. * round the error term (which is expressed * 16) to an integer.
  178741. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178742. * for either sign of the error value.
  178743. * Note: errorptr points to *previous* column's array entry.
  178744. */
  178745. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178746. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178747. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178748. /* Limit the error using transfer function set by init_error_limit.
  178749. * See comments with init_error_limit for rationale.
  178750. */
  178751. cur0 = error_limit[cur0];
  178752. cur1 = error_limit[cur1];
  178753. cur2 = error_limit[cur2];
  178754. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178755. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178756. * this sets the required size of the range_limit array.
  178757. */
  178758. cur0 += GETJSAMPLE(inptr[0]);
  178759. cur1 += GETJSAMPLE(inptr[1]);
  178760. cur2 += GETJSAMPLE(inptr[2]);
  178761. cur0 = GETJSAMPLE(range_limit[cur0]);
  178762. cur1 = GETJSAMPLE(range_limit[cur1]);
  178763. cur2 = GETJSAMPLE(range_limit[cur2]);
  178764. /* Index into the cache with adjusted pixel value */
  178765. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178766. /* If we have not seen this color before, find nearest colormap */
  178767. /* entry and update the cache */
  178768. if (*cachep == 0)
  178769. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178770. /* Now emit the colormap index for this cell */
  178771. { register int pixcode = *cachep - 1;
  178772. *outptr = (JSAMPLE) pixcode;
  178773. /* Compute representation error for this pixel */
  178774. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178775. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178776. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178777. }
  178778. /* Compute error fractions to be propagated to adjacent pixels.
  178779. * Add these into the running sums, and simultaneously shift the
  178780. * next-line error sums left by 1 column.
  178781. */
  178782. { register LOCFSERROR bnexterr, delta;
  178783. bnexterr = cur0; /* Process component 0 */
  178784. delta = cur0 * 2;
  178785. cur0 += delta; /* form error * 3 */
  178786. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178787. cur0 += delta; /* form error * 5 */
  178788. bpreverr0 = belowerr0 + cur0;
  178789. belowerr0 = bnexterr;
  178790. cur0 += delta; /* form error * 7 */
  178791. bnexterr = cur1; /* Process component 1 */
  178792. delta = cur1 * 2;
  178793. cur1 += delta; /* form error * 3 */
  178794. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178795. cur1 += delta; /* form error * 5 */
  178796. bpreverr1 = belowerr1 + cur1;
  178797. belowerr1 = bnexterr;
  178798. cur1 += delta; /* form error * 7 */
  178799. bnexterr = cur2; /* Process component 2 */
  178800. delta = cur2 * 2;
  178801. cur2 += delta; /* form error * 3 */
  178802. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178803. cur2 += delta; /* form error * 5 */
  178804. bpreverr2 = belowerr2 + cur2;
  178805. belowerr2 = bnexterr;
  178806. cur2 += delta; /* form error * 7 */
  178807. }
  178808. /* At this point curN contains the 7/16 error value to be propagated
  178809. * to the next pixel on the current line, and all the errors for the
  178810. * next line have been shifted over. We are therefore ready to move on.
  178811. */
  178812. inptr += dir3; /* Advance pixel pointers to next column */
  178813. outptr += dir;
  178814. errorptr += dir3; /* advance errorptr to current column */
  178815. }
  178816. /* Post-loop cleanup: we must unload the final error values into the
  178817. * final fserrors[] entry. Note we need not unload belowerrN because
  178818. * it is for the dummy column before or after the actual array.
  178819. */
  178820. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178821. errorptr[1] = (FSERROR) bpreverr1;
  178822. errorptr[2] = (FSERROR) bpreverr2;
  178823. }
  178824. }
  178825. /*
  178826. * Initialize the error-limiting transfer function (lookup table).
  178827. * The raw F-S error computation can potentially compute error values of up to
  178828. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178829. * much less, otherwise obviously wrong pixels will be created. (Typical
  178830. * effects include weird fringes at color-area boundaries, isolated bright
  178831. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178832. * is to ensure that the "corners" of the color cube are allocated as output
  178833. * colors; then repeated errors in the same direction cannot cause cascading
  178834. * error buildup. However, that only prevents the error from getting
  178835. * completely out of hand; Aaron Giles reports that error limiting improves
  178836. * the results even with corner colors allocated.
  178837. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178838. * well, but the smoother transfer function used below is even better. Thanks
  178839. * to Aaron Giles for this idea.
  178840. */
  178841. LOCAL(void)
  178842. init_error_limit (j_decompress_ptr cinfo)
  178843. /* Allocate and fill in the error_limiter table */
  178844. {
  178845. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178846. int * table;
  178847. int in, out;
  178848. table = (int *) (*cinfo->mem->alloc_small)
  178849. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178850. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178851. cquantize->error_limiter = table;
  178852. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178853. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178854. out = 0;
  178855. for (in = 0; in < STEPSIZE; in++, out++) {
  178856. table[in] = out; table[-in] = -out;
  178857. }
  178858. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178859. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178860. table[in] = out; table[-in] = -out;
  178861. }
  178862. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178863. for (; in <= MAXJSAMPLE; in++) {
  178864. table[in] = out; table[-in] = -out;
  178865. }
  178866. #undef STEPSIZE
  178867. }
  178868. /*
  178869. * Finish up at the end of each pass.
  178870. */
  178871. METHODDEF(void)
  178872. finish_pass1 (j_decompress_ptr cinfo)
  178873. {
  178874. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178875. /* Select the representative colors and fill in cinfo->colormap */
  178876. cinfo->colormap = cquantize->sv_colormap;
  178877. select_colors(cinfo, cquantize->desired);
  178878. /* Force next pass to zero the color index table */
  178879. cquantize->needs_zeroed = TRUE;
  178880. }
  178881. METHODDEF(void)
  178882. finish_pass2 (j_decompress_ptr)
  178883. {
  178884. /* no work */
  178885. }
  178886. /*
  178887. * Initialize for each processing pass.
  178888. */
  178889. METHODDEF(void)
  178890. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178891. {
  178892. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178893. hist3d histogram = cquantize->histogram;
  178894. int i;
  178895. /* Only F-S dithering or no dithering is supported. */
  178896. /* If user asks for ordered dither, give him F-S. */
  178897. if (cinfo->dither_mode != JDITHER_NONE)
  178898. cinfo->dither_mode = JDITHER_FS;
  178899. if (is_pre_scan) {
  178900. /* Set up method pointers */
  178901. cquantize->pub.color_quantize = prescan_quantize;
  178902. cquantize->pub.finish_pass = finish_pass1;
  178903. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178904. } else {
  178905. /* Set up method pointers */
  178906. if (cinfo->dither_mode == JDITHER_FS)
  178907. cquantize->pub.color_quantize = pass2_fs_dither;
  178908. else
  178909. cquantize->pub.color_quantize = pass2_no_dither;
  178910. cquantize->pub.finish_pass = finish_pass2;
  178911. /* Make sure color count is acceptable */
  178912. i = cinfo->actual_number_of_colors;
  178913. if (i < 1)
  178914. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178915. if (i > MAXNUMCOLORS)
  178916. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178917. if (cinfo->dither_mode == JDITHER_FS) {
  178918. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178919. (3 * SIZEOF(FSERROR)));
  178920. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178921. if (cquantize->fserrors == NULL)
  178922. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178923. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178924. /* Initialize the propagated errors to zero. */
  178925. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178926. /* Make the error-limit table if we didn't already. */
  178927. if (cquantize->error_limiter == NULL)
  178928. init_error_limit(cinfo);
  178929. cquantize->on_odd_row = FALSE;
  178930. }
  178931. }
  178932. /* Zero the histogram or inverse color map, if necessary */
  178933. if (cquantize->needs_zeroed) {
  178934. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178935. jzero_far((void FAR *) histogram[i],
  178936. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178937. }
  178938. cquantize->needs_zeroed = FALSE;
  178939. }
  178940. }
  178941. /*
  178942. * Switch to a new external colormap between output passes.
  178943. */
  178944. METHODDEF(void)
  178945. new_color_map_2_quant (j_decompress_ptr cinfo)
  178946. {
  178947. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178948. /* Reset the inverse color map */
  178949. cquantize->needs_zeroed = TRUE;
  178950. }
  178951. /*
  178952. * Module initialization routine for 2-pass color quantization.
  178953. */
  178954. GLOBAL(void)
  178955. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178956. {
  178957. my_cquantize_ptr2 cquantize;
  178958. int i;
  178959. cquantize = (my_cquantize_ptr2)
  178960. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178961. SIZEOF(my_cquantizer2));
  178962. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178963. cquantize->pub.start_pass = start_pass_2_quant;
  178964. cquantize->pub.new_color_map = new_color_map_2_quant;
  178965. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178966. cquantize->error_limiter = NULL;
  178967. /* Make sure jdmaster didn't give me a case I can't handle */
  178968. if (cinfo->out_color_components != 3)
  178969. ERREXIT(cinfo, JERR_NOTIMPL);
  178970. /* Allocate the histogram/inverse colormap storage */
  178971. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178972. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178973. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178974. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178975. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178976. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178977. }
  178978. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178979. /* Allocate storage for the completed colormap, if required.
  178980. * We do this now since it is FAR storage and may affect
  178981. * the memory manager's space calculations.
  178982. */
  178983. if (cinfo->enable_2pass_quant) {
  178984. /* Make sure color count is acceptable */
  178985. int desired = cinfo->desired_number_of_colors;
  178986. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178987. if (desired < 8)
  178988. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178989. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178990. if (desired > MAXNUMCOLORS)
  178991. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178992. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178993. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178994. cquantize->desired = desired;
  178995. } else
  178996. cquantize->sv_colormap = NULL;
  178997. /* Only F-S dithering or no dithering is supported. */
  178998. /* If user asks for ordered dither, give him F-S. */
  178999. if (cinfo->dither_mode != JDITHER_NONE)
  179000. cinfo->dither_mode = JDITHER_FS;
  179001. /* Allocate Floyd-Steinberg workspace if necessary.
  179002. * This isn't really needed until pass 2, but again it is FAR storage.
  179003. * Although we will cope with a later change in dither_mode,
  179004. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179005. */
  179006. if (cinfo->dither_mode == JDITHER_FS) {
  179007. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179008. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179009. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179010. /* Might as well create the error-limiting table too. */
  179011. init_error_limit(cinfo);
  179012. }
  179013. }
  179014. #endif /* QUANT_2PASS_SUPPORTED */
  179015. /*** End of inlined file: jquant2.c ***/
  179016. /*** Start of inlined file: jutils.c ***/
  179017. #define JPEG_INTERNALS
  179018. /*
  179019. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179020. * of a DCT block read in natural order (left to right, top to bottom).
  179021. */
  179022. #if 0 /* This table is not actually needed in v6a */
  179023. const int jpeg_zigzag_order[DCTSIZE2] = {
  179024. 0, 1, 5, 6, 14, 15, 27, 28,
  179025. 2, 4, 7, 13, 16, 26, 29, 42,
  179026. 3, 8, 12, 17, 25, 30, 41, 43,
  179027. 9, 11, 18, 24, 31, 40, 44, 53,
  179028. 10, 19, 23, 32, 39, 45, 52, 54,
  179029. 20, 22, 33, 38, 46, 51, 55, 60,
  179030. 21, 34, 37, 47, 50, 56, 59, 61,
  179031. 35, 36, 48, 49, 57, 58, 62, 63
  179032. };
  179033. #endif
  179034. /*
  179035. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179036. * of zigzag order.
  179037. *
  179038. * When reading corrupted data, the Huffman decoders could attempt
  179039. * to reference an entry beyond the end of this array (if the decoded
  179040. * zero run length reaches past the end of the block). To prevent
  179041. * wild stores without adding an inner-loop test, we put some extra
  179042. * "63"s after the real entries. This will cause the extra coefficient
  179043. * to be stored in location 63 of the block, not somewhere random.
  179044. * The worst case would be a run-length of 15, which means we need 16
  179045. * fake entries.
  179046. */
  179047. const int jpeg_natural_order[DCTSIZE2+16] = {
  179048. 0, 1, 8, 16, 9, 2, 3, 10,
  179049. 17, 24, 32, 25, 18, 11, 4, 5,
  179050. 12, 19, 26, 33, 40, 48, 41, 34,
  179051. 27, 20, 13, 6, 7, 14, 21, 28,
  179052. 35, 42, 49, 56, 57, 50, 43, 36,
  179053. 29, 22, 15, 23, 30, 37, 44, 51,
  179054. 58, 59, 52, 45, 38, 31, 39, 46,
  179055. 53, 60, 61, 54, 47, 55, 62, 63,
  179056. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179057. 63, 63, 63, 63, 63, 63, 63, 63
  179058. };
  179059. /*
  179060. * Arithmetic utilities
  179061. */
  179062. GLOBAL(long)
  179063. jdiv_round_up (long a, long b)
  179064. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179065. /* Assumes a >= 0, b > 0 */
  179066. {
  179067. return (a + b - 1L) / b;
  179068. }
  179069. GLOBAL(long)
  179070. jround_up (long a, long b)
  179071. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179072. /* Assumes a >= 0, b > 0 */
  179073. {
  179074. a += b - 1L;
  179075. return a - (a % b);
  179076. }
  179077. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179078. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179079. * are FAR and we're assuming a small-pointer memory model. However, some
  179080. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179081. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179082. * Otherwise, the routines below do it the hard way. (The performance cost
  179083. * is not all that great, because these routines aren't very heavily used.)
  179084. */
  179085. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179086. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179087. #define FMEMZERO(target,size) MEMZERO(target,size)
  179088. #else /* 80x86 case, define if we can */
  179089. #ifdef USE_FMEM
  179090. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179091. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179092. #endif
  179093. #endif
  179094. GLOBAL(void)
  179095. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179096. JSAMPARRAY output_array, int dest_row,
  179097. int num_rows, JDIMENSION num_cols)
  179098. /* Copy some rows of samples from one place to another.
  179099. * num_rows rows are copied from input_array[source_row++]
  179100. * to output_array[dest_row++]; these areas may overlap for duplication.
  179101. * The source and destination arrays must be at least as wide as num_cols.
  179102. */
  179103. {
  179104. register JSAMPROW inptr, outptr;
  179105. #ifdef FMEMCOPY
  179106. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179107. #else
  179108. register JDIMENSION count;
  179109. #endif
  179110. register int row;
  179111. input_array += source_row;
  179112. output_array += dest_row;
  179113. for (row = num_rows; row > 0; row--) {
  179114. inptr = *input_array++;
  179115. outptr = *output_array++;
  179116. #ifdef FMEMCOPY
  179117. FMEMCOPY(outptr, inptr, count);
  179118. #else
  179119. for (count = num_cols; count > 0; count--)
  179120. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179121. #endif
  179122. }
  179123. }
  179124. GLOBAL(void)
  179125. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179126. JDIMENSION num_blocks)
  179127. /* Copy a row of coefficient blocks from one place to another. */
  179128. {
  179129. #ifdef FMEMCOPY
  179130. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179131. #else
  179132. register JCOEFPTR inptr, outptr;
  179133. register long count;
  179134. inptr = (JCOEFPTR) input_row;
  179135. outptr = (JCOEFPTR) output_row;
  179136. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179137. *outptr++ = *inptr++;
  179138. }
  179139. #endif
  179140. }
  179141. GLOBAL(void)
  179142. jzero_far (void FAR * target, size_t bytestozero)
  179143. /* Zero out a chunk of FAR memory. */
  179144. /* This might be sample-array data, block-array data, or alloc_large data. */
  179145. {
  179146. #ifdef FMEMZERO
  179147. FMEMZERO(target, bytestozero);
  179148. #else
  179149. register char FAR * ptr = (char FAR *) target;
  179150. register size_t count;
  179151. for (count = bytestozero; count > 0; count--) {
  179152. *ptr++ = 0;
  179153. }
  179154. #endif
  179155. }
  179156. /*** End of inlined file: jutils.c ***/
  179157. /*** Start of inlined file: transupp.c ***/
  179158. /* Although this file really shouldn't have access to the library internals,
  179159. * it's helpful to let it call jround_up() and jcopy_block_row().
  179160. */
  179161. #define JPEG_INTERNALS
  179162. /*** Start of inlined file: transupp.h ***/
  179163. /* If you happen not to want the image transform support, disable it here */
  179164. #ifndef TRANSFORMS_SUPPORTED
  179165. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179166. #endif
  179167. /* Short forms of external names for systems with brain-damaged linkers. */
  179168. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179169. #define jtransform_request_workspace jTrRequest
  179170. #define jtransform_adjust_parameters jTrAdjust
  179171. #define jtransform_execute_transformation jTrExec
  179172. #define jcopy_markers_setup jCMrkSetup
  179173. #define jcopy_markers_execute jCMrkExec
  179174. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179175. /*
  179176. * Codes for supported types of image transformations.
  179177. */
  179178. typedef enum {
  179179. JXFORM_NONE, /* no transformation */
  179180. JXFORM_FLIP_H, /* horizontal flip */
  179181. JXFORM_FLIP_V, /* vertical flip */
  179182. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179183. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179184. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179185. JXFORM_ROT_180, /* 180-degree rotation */
  179186. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179187. } JXFORM_CODE;
  179188. /*
  179189. * Although rotating and flipping data expressed as DCT coefficients is not
  179190. * hard, there is an asymmetry in the JPEG format specification for images
  179191. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179192. * image edges are padded out to the next iMCU boundary with junk data; but
  179193. * no padding is possible at the top and left edges. If we were to flip
  179194. * the whole image including the pad data, then pad garbage would become
  179195. * visible at the top and/or left, and real pixels would disappear into the
  179196. * pad margins --- perhaps permanently, since encoders & decoders may not
  179197. * bother to preserve DCT blocks that appear to be completely outside the
  179198. * nominal image area. So, we have to exclude any partial iMCUs from the
  179199. * basic transformation.
  179200. *
  179201. * Transpose is the only transformation that can handle partial iMCUs at the
  179202. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179203. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179204. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179205. * The other transforms are defined as combinations of these basic transforms
  179206. * and process edge blocks in a way that preserves the equivalence.
  179207. *
  179208. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179209. * this is not strictly lossless, but it usually gives the best-looking
  179210. * result for odd-size images. Note that when this option is active,
  179211. * the expected mathematical equivalences between the transforms may not hold.
  179212. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179213. * followed by -rot 180 -trim trims both edges.)
  179214. *
  179215. * We also offer a "force to grayscale" option, which simply discards the
  179216. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179217. * the luminance channel is preserved exactly. It's not the same kind of
  179218. * thing as the rotate/flip transformations, but it's convenient to handle it
  179219. * as part of this package, mainly because the transformation routines have to
  179220. * be aware of the option to know how many components to work on.
  179221. */
  179222. typedef struct {
  179223. /* Options: set by caller */
  179224. JXFORM_CODE transform; /* image transform operator */
  179225. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179226. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179227. /* Internal workspace: caller should not touch these */
  179228. int num_components; /* # of components in workspace */
  179229. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179230. } jpeg_transform_info;
  179231. #if TRANSFORMS_SUPPORTED
  179232. /* Request any required workspace */
  179233. EXTERN(void) jtransform_request_workspace
  179234. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179235. /* Adjust output image parameters */
  179236. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179237. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179238. jvirt_barray_ptr *src_coef_arrays,
  179239. jpeg_transform_info *info));
  179240. /* Execute the actual transformation, if any */
  179241. EXTERN(void) jtransform_execute_transformation
  179242. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179243. jvirt_barray_ptr *src_coef_arrays,
  179244. jpeg_transform_info *info));
  179245. #endif /* TRANSFORMS_SUPPORTED */
  179246. /*
  179247. * Support for copying optional markers from source to destination file.
  179248. */
  179249. typedef enum {
  179250. JCOPYOPT_NONE, /* copy no optional markers */
  179251. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179252. JCOPYOPT_ALL /* copy all optional markers */
  179253. } JCOPY_OPTION;
  179254. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179255. /* Setup decompression object to save desired markers in memory */
  179256. EXTERN(void) jcopy_markers_setup
  179257. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179258. /* Copy markers saved in the given source object to the destination object */
  179259. EXTERN(void) jcopy_markers_execute
  179260. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179261. JCOPY_OPTION option));
  179262. /*** End of inlined file: transupp.h ***/
  179263. /* My own external interface */
  179264. #if TRANSFORMS_SUPPORTED
  179265. /*
  179266. * Lossless image transformation routines. These routines work on DCT
  179267. * coefficient arrays and thus do not require any lossy decompression
  179268. * or recompression of the image.
  179269. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179270. *
  179271. * Horizontal flipping is done in-place, using a single top-to-bottom
  179272. * pass through the virtual source array. It will thus be much the
  179273. * fastest option for images larger than main memory.
  179274. *
  179275. * The other routines require a set of destination virtual arrays, so they
  179276. * need twice as much memory as jpegtran normally does. The destination
  179277. * arrays are always written in normal scan order (top to bottom) because
  179278. * the virtual array manager expects this. The source arrays will be scanned
  179279. * in the corresponding order, which means multiple passes through the source
  179280. * arrays for most of the transforms. That could result in much thrashing
  179281. * if the image is larger than main memory.
  179282. *
  179283. * Some notes about the operating environment of the individual transform
  179284. * routines:
  179285. * 1. Both the source and destination virtual arrays are allocated from the
  179286. * source JPEG object, and therefore should be manipulated by calling the
  179287. * source's memory manager.
  179288. * 2. The destination's component count should be used. It may be smaller
  179289. * than the source's when forcing to grayscale.
  179290. * 3. Likewise the destination's sampling factors should be used. When
  179291. * forcing to grayscale the destination's sampling factors will be all 1,
  179292. * and we may as well take that as the effective iMCU size.
  179293. * 4. When "trim" is in effect, the destination's dimensions will be the
  179294. * trimmed values but the source's will be untrimmed.
  179295. * 5. All the routines assume that the source and destination buffers are
  179296. * padded out to a full iMCU boundary. This is true, although for the
  179297. * source buffer it is an undocumented property of jdcoefct.c.
  179298. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179299. * dimensions and ignore the source's.
  179300. */
  179301. LOCAL(void)
  179302. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179303. jvirt_barray_ptr *src_coef_arrays)
  179304. /* Horizontal flip; done in-place, so no separate dest array is required */
  179305. {
  179306. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179307. int ci, k, offset_y;
  179308. JBLOCKARRAY buffer;
  179309. JCOEFPTR ptr1, ptr2;
  179310. JCOEF temp1, temp2;
  179311. jpeg_component_info *compptr;
  179312. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179313. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179314. * mirroring by changing the signs of odd-numbered columns.
  179315. * Partial iMCUs at the right edge are left untouched.
  179316. */
  179317. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179318. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179319. compptr = dstinfo->comp_info + ci;
  179320. comp_width = MCU_cols * compptr->h_samp_factor;
  179321. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179322. blk_y += compptr->v_samp_factor) {
  179323. buffer = (*srcinfo->mem->access_virt_barray)
  179324. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179325. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179326. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179327. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179328. ptr1 = buffer[offset_y][blk_x];
  179329. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179330. /* this unrolled loop doesn't need to know which row it's on... */
  179331. for (k = 0; k < DCTSIZE2; k += 2) {
  179332. temp1 = *ptr1; /* swap even column */
  179333. temp2 = *ptr2;
  179334. *ptr1++ = temp2;
  179335. *ptr2++ = temp1;
  179336. temp1 = *ptr1; /* swap odd column with sign change */
  179337. temp2 = *ptr2;
  179338. *ptr1++ = -temp2;
  179339. *ptr2++ = -temp1;
  179340. }
  179341. }
  179342. }
  179343. }
  179344. }
  179345. }
  179346. LOCAL(void)
  179347. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179348. jvirt_barray_ptr *src_coef_arrays,
  179349. jvirt_barray_ptr *dst_coef_arrays)
  179350. /* Vertical flip */
  179351. {
  179352. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179353. int ci, i, j, offset_y;
  179354. JBLOCKARRAY src_buffer, dst_buffer;
  179355. JBLOCKROW src_row_ptr, dst_row_ptr;
  179356. JCOEFPTR src_ptr, dst_ptr;
  179357. jpeg_component_info *compptr;
  179358. /* We output into a separate array because we can't touch different
  179359. * rows of the source virtual array simultaneously. Otherwise, this
  179360. * is a pretty straightforward analog of horizontal flip.
  179361. * Within a DCT block, vertical mirroring is done by changing the signs
  179362. * of odd-numbered rows.
  179363. * Partial iMCUs at the bottom edge are copied verbatim.
  179364. */
  179365. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179366. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179367. compptr = dstinfo->comp_info + ci;
  179368. comp_height = MCU_rows * compptr->v_samp_factor;
  179369. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179370. dst_blk_y += compptr->v_samp_factor) {
  179371. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179372. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179373. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179374. if (dst_blk_y < comp_height) {
  179375. /* Row is within the mirrorable area. */
  179376. src_buffer = (*srcinfo->mem->access_virt_barray)
  179377. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179378. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179379. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179380. } else {
  179381. /* Bottom-edge blocks will be copied verbatim. */
  179382. src_buffer = (*srcinfo->mem->access_virt_barray)
  179383. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179384. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179385. }
  179386. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179387. if (dst_blk_y < comp_height) {
  179388. /* Row is within the mirrorable area. */
  179389. dst_row_ptr = dst_buffer[offset_y];
  179390. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179391. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179392. dst_blk_x++) {
  179393. dst_ptr = dst_row_ptr[dst_blk_x];
  179394. src_ptr = src_row_ptr[dst_blk_x];
  179395. for (i = 0; i < DCTSIZE; i += 2) {
  179396. /* copy even row */
  179397. for (j = 0; j < DCTSIZE; j++)
  179398. *dst_ptr++ = *src_ptr++;
  179399. /* copy odd row with sign change */
  179400. for (j = 0; j < DCTSIZE; j++)
  179401. *dst_ptr++ = - *src_ptr++;
  179402. }
  179403. }
  179404. } else {
  179405. /* Just copy row verbatim. */
  179406. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179407. compptr->width_in_blocks);
  179408. }
  179409. }
  179410. }
  179411. }
  179412. }
  179413. LOCAL(void)
  179414. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179415. jvirt_barray_ptr *src_coef_arrays,
  179416. jvirt_barray_ptr *dst_coef_arrays)
  179417. /* Transpose source into destination */
  179418. {
  179419. JDIMENSION dst_blk_x, dst_blk_y;
  179420. int ci, i, j, offset_x, offset_y;
  179421. JBLOCKARRAY src_buffer, dst_buffer;
  179422. JCOEFPTR src_ptr, dst_ptr;
  179423. jpeg_component_info *compptr;
  179424. /* Transposing pixels within a block just requires transposing the
  179425. * DCT coefficients.
  179426. * Partial iMCUs at the edges require no special treatment; we simply
  179427. * process all the available DCT blocks for every component.
  179428. */
  179429. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179430. compptr = dstinfo->comp_info + ci;
  179431. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179432. dst_blk_y += compptr->v_samp_factor) {
  179433. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179434. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179435. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179436. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179437. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179438. dst_blk_x += compptr->h_samp_factor) {
  179439. src_buffer = (*srcinfo->mem->access_virt_barray)
  179440. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179441. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179442. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179443. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179444. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179445. for (i = 0; i < DCTSIZE; i++)
  179446. for (j = 0; j < DCTSIZE; j++)
  179447. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179448. }
  179449. }
  179450. }
  179451. }
  179452. }
  179453. }
  179454. LOCAL(void)
  179455. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179456. jvirt_barray_ptr *src_coef_arrays,
  179457. jvirt_barray_ptr *dst_coef_arrays)
  179458. /* 90 degree rotation is equivalent to
  179459. * 1. Transposing the image;
  179460. * 2. Horizontal mirroring.
  179461. * These two steps are merged into a single processing routine.
  179462. */
  179463. {
  179464. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179465. int ci, i, j, offset_x, offset_y;
  179466. JBLOCKARRAY src_buffer, dst_buffer;
  179467. JCOEFPTR src_ptr, dst_ptr;
  179468. jpeg_component_info *compptr;
  179469. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179470. * at the (output) right edge properly. They just get transposed and
  179471. * not mirrored.
  179472. */
  179473. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179474. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179475. compptr = dstinfo->comp_info + ci;
  179476. comp_width = MCU_cols * compptr->h_samp_factor;
  179477. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179478. dst_blk_y += compptr->v_samp_factor) {
  179479. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179480. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179481. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179482. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179483. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179484. dst_blk_x += compptr->h_samp_factor) {
  179485. src_buffer = (*srcinfo->mem->access_virt_barray)
  179486. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179487. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179488. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179489. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179490. if (dst_blk_x < comp_width) {
  179491. /* Block is within the mirrorable area. */
  179492. dst_ptr = dst_buffer[offset_y]
  179493. [comp_width - dst_blk_x - offset_x - 1];
  179494. for (i = 0; i < DCTSIZE; i++) {
  179495. for (j = 0; j < DCTSIZE; j++)
  179496. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179497. i++;
  179498. for (j = 0; j < DCTSIZE; j++)
  179499. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179500. }
  179501. } else {
  179502. /* Edge blocks are transposed but not mirrored. */
  179503. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179504. for (i = 0; i < DCTSIZE; i++)
  179505. for (j = 0; j < DCTSIZE; j++)
  179506. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179507. }
  179508. }
  179509. }
  179510. }
  179511. }
  179512. }
  179513. }
  179514. LOCAL(void)
  179515. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179516. jvirt_barray_ptr *src_coef_arrays,
  179517. jvirt_barray_ptr *dst_coef_arrays)
  179518. /* 270 degree rotation is equivalent to
  179519. * 1. Horizontal mirroring;
  179520. * 2. Transposing the image.
  179521. * These two steps are merged into a single processing routine.
  179522. */
  179523. {
  179524. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179525. int ci, i, j, offset_x, offset_y;
  179526. JBLOCKARRAY src_buffer, dst_buffer;
  179527. JCOEFPTR src_ptr, dst_ptr;
  179528. jpeg_component_info *compptr;
  179529. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179530. * at the (output) bottom edge properly. They just get transposed and
  179531. * not mirrored.
  179532. */
  179533. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179534. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179535. compptr = dstinfo->comp_info + ci;
  179536. comp_height = MCU_rows * compptr->v_samp_factor;
  179537. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179538. dst_blk_y += compptr->v_samp_factor) {
  179539. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179540. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179541. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179542. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179543. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179544. dst_blk_x += compptr->h_samp_factor) {
  179545. src_buffer = (*srcinfo->mem->access_virt_barray)
  179546. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179547. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179548. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179549. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179550. if (dst_blk_y < comp_height) {
  179551. /* Block is within the mirrorable area. */
  179552. src_ptr = src_buffer[offset_x]
  179553. [comp_height - dst_blk_y - offset_y - 1];
  179554. for (i = 0; i < DCTSIZE; i++) {
  179555. for (j = 0; j < DCTSIZE; j++) {
  179556. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179557. j++;
  179558. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179559. }
  179560. }
  179561. } else {
  179562. /* Edge blocks are transposed but not mirrored. */
  179563. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179564. for (i = 0; i < DCTSIZE; i++)
  179565. for (j = 0; j < DCTSIZE; j++)
  179566. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179567. }
  179568. }
  179569. }
  179570. }
  179571. }
  179572. }
  179573. }
  179574. LOCAL(void)
  179575. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179576. jvirt_barray_ptr *src_coef_arrays,
  179577. jvirt_barray_ptr *dst_coef_arrays)
  179578. /* 180 degree rotation is equivalent to
  179579. * 1. Vertical mirroring;
  179580. * 2. Horizontal mirroring.
  179581. * These two steps are merged into a single processing routine.
  179582. */
  179583. {
  179584. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179585. int ci, i, j, offset_y;
  179586. JBLOCKARRAY src_buffer, dst_buffer;
  179587. JBLOCKROW src_row_ptr, dst_row_ptr;
  179588. JCOEFPTR src_ptr, dst_ptr;
  179589. jpeg_component_info *compptr;
  179590. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179591. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179592. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179593. compptr = dstinfo->comp_info + ci;
  179594. comp_width = MCU_cols * compptr->h_samp_factor;
  179595. comp_height = MCU_rows * compptr->v_samp_factor;
  179596. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179597. dst_blk_y += compptr->v_samp_factor) {
  179598. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179599. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179600. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179601. if (dst_blk_y < comp_height) {
  179602. /* Row is within the vertically mirrorable area. */
  179603. src_buffer = (*srcinfo->mem->access_virt_barray)
  179604. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179605. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179606. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179607. } else {
  179608. /* Bottom-edge rows are only mirrored horizontally. */
  179609. src_buffer = (*srcinfo->mem->access_virt_barray)
  179610. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179611. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179612. }
  179613. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179614. if (dst_blk_y < comp_height) {
  179615. /* Row is within the mirrorable area. */
  179616. dst_row_ptr = dst_buffer[offset_y];
  179617. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179618. /* Process the blocks that can be mirrored both ways. */
  179619. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179620. dst_ptr = dst_row_ptr[dst_blk_x];
  179621. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179622. for (i = 0; i < DCTSIZE; i += 2) {
  179623. /* For even row, negate every odd column. */
  179624. for (j = 0; j < DCTSIZE; j += 2) {
  179625. *dst_ptr++ = *src_ptr++;
  179626. *dst_ptr++ = - *src_ptr++;
  179627. }
  179628. /* For odd row, negate every even column. */
  179629. for (j = 0; j < DCTSIZE; j += 2) {
  179630. *dst_ptr++ = - *src_ptr++;
  179631. *dst_ptr++ = *src_ptr++;
  179632. }
  179633. }
  179634. }
  179635. /* Any remaining right-edge blocks are only mirrored vertically. */
  179636. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179637. dst_ptr = dst_row_ptr[dst_blk_x];
  179638. src_ptr = src_row_ptr[dst_blk_x];
  179639. for (i = 0; i < DCTSIZE; i += 2) {
  179640. for (j = 0; j < DCTSIZE; j++)
  179641. *dst_ptr++ = *src_ptr++;
  179642. for (j = 0; j < DCTSIZE; j++)
  179643. *dst_ptr++ = - *src_ptr++;
  179644. }
  179645. }
  179646. } else {
  179647. /* Remaining rows are just mirrored horizontally. */
  179648. dst_row_ptr = dst_buffer[offset_y];
  179649. src_row_ptr = src_buffer[offset_y];
  179650. /* Process the blocks that can be mirrored. */
  179651. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179652. dst_ptr = dst_row_ptr[dst_blk_x];
  179653. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179654. for (i = 0; i < DCTSIZE2; i += 2) {
  179655. *dst_ptr++ = *src_ptr++;
  179656. *dst_ptr++ = - *src_ptr++;
  179657. }
  179658. }
  179659. /* Any remaining right-edge blocks are only copied. */
  179660. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179661. dst_ptr = dst_row_ptr[dst_blk_x];
  179662. src_ptr = src_row_ptr[dst_blk_x];
  179663. for (i = 0; i < DCTSIZE2; i++)
  179664. *dst_ptr++ = *src_ptr++;
  179665. }
  179666. }
  179667. }
  179668. }
  179669. }
  179670. }
  179671. LOCAL(void)
  179672. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179673. jvirt_barray_ptr *src_coef_arrays,
  179674. jvirt_barray_ptr *dst_coef_arrays)
  179675. /* Transverse transpose is equivalent to
  179676. * 1. 180 degree rotation;
  179677. * 2. Transposition;
  179678. * or
  179679. * 1. Horizontal mirroring;
  179680. * 2. Transposition;
  179681. * 3. Horizontal mirroring.
  179682. * These steps are merged into a single processing routine.
  179683. */
  179684. {
  179685. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179686. int ci, i, j, offset_x, offset_y;
  179687. JBLOCKARRAY src_buffer, dst_buffer;
  179688. JCOEFPTR src_ptr, dst_ptr;
  179689. jpeg_component_info *compptr;
  179690. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179691. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179692. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179693. compptr = dstinfo->comp_info + ci;
  179694. comp_width = MCU_cols * compptr->h_samp_factor;
  179695. comp_height = MCU_rows * compptr->v_samp_factor;
  179696. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179697. dst_blk_y += compptr->v_samp_factor) {
  179698. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179699. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179700. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179701. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179702. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179703. dst_blk_x += compptr->h_samp_factor) {
  179704. src_buffer = (*srcinfo->mem->access_virt_barray)
  179705. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179706. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179707. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179708. if (dst_blk_y < comp_height) {
  179709. src_ptr = src_buffer[offset_x]
  179710. [comp_height - dst_blk_y - offset_y - 1];
  179711. if (dst_blk_x < comp_width) {
  179712. /* Block is within the mirrorable area. */
  179713. dst_ptr = dst_buffer[offset_y]
  179714. [comp_width - dst_blk_x - offset_x - 1];
  179715. for (i = 0; i < DCTSIZE; i++) {
  179716. for (j = 0; j < DCTSIZE; j++) {
  179717. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179718. j++;
  179719. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179720. }
  179721. i++;
  179722. for (j = 0; j < DCTSIZE; j++) {
  179723. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179724. j++;
  179725. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179726. }
  179727. }
  179728. } else {
  179729. /* Right-edge blocks are mirrored in y only */
  179730. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179731. for (i = 0; i < DCTSIZE; i++) {
  179732. for (j = 0; j < DCTSIZE; j++) {
  179733. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179734. j++;
  179735. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179736. }
  179737. }
  179738. }
  179739. } else {
  179740. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179741. if (dst_blk_x < comp_width) {
  179742. /* Bottom-edge blocks are mirrored in x only */
  179743. dst_ptr = dst_buffer[offset_y]
  179744. [comp_width - dst_blk_x - offset_x - 1];
  179745. for (i = 0; i < DCTSIZE; i++) {
  179746. for (j = 0; j < DCTSIZE; j++)
  179747. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179748. i++;
  179749. for (j = 0; j < DCTSIZE; j++)
  179750. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179751. }
  179752. } else {
  179753. /* At lower right corner, just transpose, no mirroring */
  179754. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179755. for (i = 0; i < DCTSIZE; i++)
  179756. for (j = 0; j < DCTSIZE; j++)
  179757. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179758. }
  179759. }
  179760. }
  179761. }
  179762. }
  179763. }
  179764. }
  179765. }
  179766. /* Request any required workspace.
  179767. *
  179768. * We allocate the workspace virtual arrays from the source decompression
  179769. * object, so that all the arrays (both the original data and the workspace)
  179770. * will be taken into account while making memory management decisions.
  179771. * Hence, this routine must be called after jpeg_read_header (which reads
  179772. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179773. * the source's virtual arrays).
  179774. */
  179775. GLOBAL(void)
  179776. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179777. jpeg_transform_info *info)
  179778. {
  179779. jvirt_barray_ptr *coef_arrays = NULL;
  179780. jpeg_component_info *compptr;
  179781. int ci;
  179782. if (info->force_grayscale &&
  179783. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179784. srcinfo->num_components == 3) {
  179785. /* We'll only process the first component */
  179786. info->num_components = 1;
  179787. } else {
  179788. /* Process all the components */
  179789. info->num_components = srcinfo->num_components;
  179790. }
  179791. switch (info->transform) {
  179792. case JXFORM_NONE:
  179793. case JXFORM_FLIP_H:
  179794. /* Don't need a workspace array */
  179795. break;
  179796. case JXFORM_FLIP_V:
  179797. case JXFORM_ROT_180:
  179798. /* Need workspace arrays having same dimensions as source image.
  179799. * Note that we allocate arrays padded out to the next iMCU boundary,
  179800. * so that transform routines need not worry about missing edge blocks.
  179801. */
  179802. coef_arrays = (jvirt_barray_ptr *)
  179803. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179804. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179805. for (ci = 0; ci < info->num_components; ci++) {
  179806. compptr = srcinfo->comp_info + ci;
  179807. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179808. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179809. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179810. (long) compptr->h_samp_factor),
  179811. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179812. (long) compptr->v_samp_factor),
  179813. (JDIMENSION) compptr->v_samp_factor);
  179814. }
  179815. break;
  179816. case JXFORM_TRANSPOSE:
  179817. case JXFORM_TRANSVERSE:
  179818. case JXFORM_ROT_90:
  179819. case JXFORM_ROT_270:
  179820. /* Need workspace arrays having transposed dimensions.
  179821. * Note that we allocate arrays padded out to the next iMCU boundary,
  179822. * so that transform routines need not worry about missing edge blocks.
  179823. */
  179824. coef_arrays = (jvirt_barray_ptr *)
  179825. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179826. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179827. for (ci = 0; ci < info->num_components; ci++) {
  179828. compptr = srcinfo->comp_info + ci;
  179829. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179830. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179831. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179832. (long) compptr->v_samp_factor),
  179833. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179834. (long) compptr->h_samp_factor),
  179835. (JDIMENSION) compptr->h_samp_factor);
  179836. }
  179837. break;
  179838. }
  179839. info->workspace_coef_arrays = coef_arrays;
  179840. }
  179841. /* Transpose destination image parameters */
  179842. LOCAL(void)
  179843. transpose_critical_parameters (j_compress_ptr dstinfo)
  179844. {
  179845. int tblno, i, j, ci, itemp;
  179846. jpeg_component_info *compptr;
  179847. JQUANT_TBL *qtblptr;
  179848. JDIMENSION dtemp;
  179849. UINT16 qtemp;
  179850. /* Transpose basic image dimensions */
  179851. dtemp = dstinfo->image_width;
  179852. dstinfo->image_width = dstinfo->image_height;
  179853. dstinfo->image_height = dtemp;
  179854. /* Transpose sampling factors */
  179855. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179856. compptr = dstinfo->comp_info + ci;
  179857. itemp = compptr->h_samp_factor;
  179858. compptr->h_samp_factor = compptr->v_samp_factor;
  179859. compptr->v_samp_factor = itemp;
  179860. }
  179861. /* Transpose quantization tables */
  179862. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179863. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179864. if (qtblptr != NULL) {
  179865. for (i = 0; i < DCTSIZE; i++) {
  179866. for (j = 0; j < i; j++) {
  179867. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179868. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179869. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179870. }
  179871. }
  179872. }
  179873. }
  179874. }
  179875. /* Trim off any partial iMCUs on the indicated destination edge */
  179876. LOCAL(void)
  179877. trim_right_edge (j_compress_ptr dstinfo)
  179878. {
  179879. int ci, max_h_samp_factor;
  179880. JDIMENSION MCU_cols;
  179881. /* We have to compute max_h_samp_factor ourselves,
  179882. * because it hasn't been set yet in the destination
  179883. * (and we don't want to use the source's value).
  179884. */
  179885. max_h_samp_factor = 1;
  179886. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179887. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179888. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179889. }
  179890. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179891. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179892. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179893. }
  179894. LOCAL(void)
  179895. trim_bottom_edge (j_compress_ptr dstinfo)
  179896. {
  179897. int ci, max_v_samp_factor;
  179898. JDIMENSION MCU_rows;
  179899. /* We have to compute max_v_samp_factor ourselves,
  179900. * because it hasn't been set yet in the destination
  179901. * (and we don't want to use the source's value).
  179902. */
  179903. max_v_samp_factor = 1;
  179904. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179905. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179906. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179907. }
  179908. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179909. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179910. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179911. }
  179912. /* Adjust output image parameters as needed.
  179913. *
  179914. * This must be called after jpeg_copy_critical_parameters()
  179915. * and before jpeg_write_coefficients().
  179916. *
  179917. * The return value is the set of virtual coefficient arrays to be written
  179918. * (either the ones allocated by jtransform_request_workspace, or the
  179919. * original source data arrays). The caller will need to pass this value
  179920. * to jpeg_write_coefficients().
  179921. */
  179922. GLOBAL(jvirt_barray_ptr *)
  179923. jtransform_adjust_parameters (j_decompress_ptr,
  179924. j_compress_ptr dstinfo,
  179925. jvirt_barray_ptr *src_coef_arrays,
  179926. jpeg_transform_info *info)
  179927. {
  179928. /* If force-to-grayscale is requested, adjust destination parameters */
  179929. if (info->force_grayscale) {
  179930. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179931. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179932. * will get set to 1, which typically won't match the source.
  179933. * In fact we do this even if the source is already grayscale; that
  179934. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179935. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179936. */
  179937. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179938. dstinfo->num_components == 3) ||
  179939. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179940. dstinfo->num_components == 1)) {
  179941. /* We have to preserve the source's quantization table number. */
  179942. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179943. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179944. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179945. } else {
  179946. /* Sorry, can't do it */
  179947. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179948. }
  179949. }
  179950. /* Correct the destination's image dimensions etc if necessary */
  179951. switch (info->transform) {
  179952. case JXFORM_NONE:
  179953. /* Nothing to do */
  179954. break;
  179955. case JXFORM_FLIP_H:
  179956. if (info->trim)
  179957. trim_right_edge(dstinfo);
  179958. break;
  179959. case JXFORM_FLIP_V:
  179960. if (info->trim)
  179961. trim_bottom_edge(dstinfo);
  179962. break;
  179963. case JXFORM_TRANSPOSE:
  179964. transpose_critical_parameters(dstinfo);
  179965. /* transpose does NOT have to trim anything */
  179966. break;
  179967. case JXFORM_TRANSVERSE:
  179968. transpose_critical_parameters(dstinfo);
  179969. if (info->trim) {
  179970. trim_right_edge(dstinfo);
  179971. trim_bottom_edge(dstinfo);
  179972. }
  179973. break;
  179974. case JXFORM_ROT_90:
  179975. transpose_critical_parameters(dstinfo);
  179976. if (info->trim)
  179977. trim_right_edge(dstinfo);
  179978. break;
  179979. case JXFORM_ROT_180:
  179980. if (info->trim) {
  179981. trim_right_edge(dstinfo);
  179982. trim_bottom_edge(dstinfo);
  179983. }
  179984. break;
  179985. case JXFORM_ROT_270:
  179986. transpose_critical_parameters(dstinfo);
  179987. if (info->trim)
  179988. trim_bottom_edge(dstinfo);
  179989. break;
  179990. }
  179991. /* Return the appropriate output data set */
  179992. if (info->workspace_coef_arrays != NULL)
  179993. return info->workspace_coef_arrays;
  179994. return src_coef_arrays;
  179995. }
  179996. /* Execute the actual transformation, if any.
  179997. *
  179998. * This must be called *after* jpeg_write_coefficients, because it depends
  179999. * on jpeg_write_coefficients to have computed subsidiary values such as
  180000. * the per-component width and height fields in the destination object.
  180001. *
  180002. * Note that some transformations will modify the source data arrays!
  180003. */
  180004. GLOBAL(void)
  180005. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180006. j_compress_ptr dstinfo,
  180007. jvirt_barray_ptr *src_coef_arrays,
  180008. jpeg_transform_info *info)
  180009. {
  180010. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180011. switch (info->transform) {
  180012. case JXFORM_NONE:
  180013. break;
  180014. case JXFORM_FLIP_H:
  180015. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180016. break;
  180017. case JXFORM_FLIP_V:
  180018. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180019. break;
  180020. case JXFORM_TRANSPOSE:
  180021. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180022. break;
  180023. case JXFORM_TRANSVERSE:
  180024. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180025. break;
  180026. case JXFORM_ROT_90:
  180027. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180028. break;
  180029. case JXFORM_ROT_180:
  180030. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180031. break;
  180032. case JXFORM_ROT_270:
  180033. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180034. break;
  180035. }
  180036. }
  180037. #endif /* TRANSFORMS_SUPPORTED */
  180038. /* Setup decompression object to save desired markers in memory.
  180039. * This must be called before jpeg_read_header() to have the desired effect.
  180040. */
  180041. GLOBAL(void)
  180042. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180043. {
  180044. #ifdef SAVE_MARKERS_SUPPORTED
  180045. int m;
  180046. /* Save comments except under NONE option */
  180047. if (option != JCOPYOPT_NONE) {
  180048. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180049. }
  180050. /* Save all types of APPn markers iff ALL option */
  180051. if (option == JCOPYOPT_ALL) {
  180052. for (m = 0; m < 16; m++)
  180053. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180054. }
  180055. #endif /* SAVE_MARKERS_SUPPORTED */
  180056. }
  180057. /* Copy markers saved in the given source object to the destination object.
  180058. * This should be called just after jpeg_start_compress() or
  180059. * jpeg_write_coefficients().
  180060. * Note that those routines will have written the SOI, and also the
  180061. * JFIF APP0 or Adobe APP14 markers if selected.
  180062. */
  180063. GLOBAL(void)
  180064. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180065. JCOPY_OPTION)
  180066. {
  180067. jpeg_saved_marker_ptr marker;
  180068. /* In the current implementation, we don't actually need to examine the
  180069. * option flag here; we just copy everything that got saved.
  180070. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180071. * if the encoder library already wrote one.
  180072. */
  180073. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180074. if (dstinfo->write_JFIF_header &&
  180075. marker->marker == JPEG_APP0 &&
  180076. marker->data_length >= 5 &&
  180077. GETJOCTET(marker->data[0]) == 0x4A &&
  180078. GETJOCTET(marker->data[1]) == 0x46 &&
  180079. GETJOCTET(marker->data[2]) == 0x49 &&
  180080. GETJOCTET(marker->data[3]) == 0x46 &&
  180081. GETJOCTET(marker->data[4]) == 0)
  180082. continue; /* reject duplicate JFIF */
  180083. if (dstinfo->write_Adobe_marker &&
  180084. marker->marker == JPEG_APP0+14 &&
  180085. marker->data_length >= 5 &&
  180086. GETJOCTET(marker->data[0]) == 0x41 &&
  180087. GETJOCTET(marker->data[1]) == 0x64 &&
  180088. GETJOCTET(marker->data[2]) == 0x6F &&
  180089. GETJOCTET(marker->data[3]) == 0x62 &&
  180090. GETJOCTET(marker->data[4]) == 0x65)
  180091. continue; /* reject duplicate Adobe */
  180092. #ifdef NEED_FAR_POINTERS
  180093. /* We could use jpeg_write_marker if the data weren't FAR... */
  180094. {
  180095. unsigned int i;
  180096. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180097. for (i = 0; i < marker->data_length; i++)
  180098. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180099. }
  180100. #else
  180101. jpeg_write_marker(dstinfo, marker->marker,
  180102. marker->data, marker->data_length);
  180103. #endif
  180104. }
  180105. }
  180106. /*** End of inlined file: transupp.c ***/
  180107. #else
  180108. #define JPEG_INTERNALS
  180109. #undef FAR
  180110. #include <jpeglib.h>
  180111. #endif
  180112. }
  180113. #undef max
  180114. #undef min
  180115. #if JUCE_MSVC
  180116. #pragma warning (pop)
  180117. #endif
  180118. BEGIN_JUCE_NAMESPACE
  180119. namespace JPEGHelpers
  180120. {
  180121. using namespace jpeglibNamespace;
  180122. #if ! JUCE_MSVC
  180123. using jpeglibNamespace::boolean;
  180124. #endif
  180125. struct JPEGDecodingFailure {};
  180126. void fatalErrorHandler (j_common_ptr)
  180127. {
  180128. throw JPEGDecodingFailure();
  180129. }
  180130. void silentErrorCallback1 (j_common_ptr) {}
  180131. void silentErrorCallback2 (j_common_ptr, int) {}
  180132. void silentErrorCallback3 (j_common_ptr, char*) {}
  180133. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180134. {
  180135. zerostruct (err);
  180136. err.error_exit = fatalErrorHandler;
  180137. err.emit_message = silentErrorCallback2;
  180138. err.output_message = silentErrorCallback1;
  180139. err.format_message = silentErrorCallback3;
  180140. err.reset_error_mgr = silentErrorCallback1;
  180141. }
  180142. void dummyCallback1 (j_decompress_ptr)
  180143. {
  180144. }
  180145. void jpegSkip (j_decompress_ptr decompStruct, long num)
  180146. {
  180147. decompStruct->src->next_input_byte += num;
  180148. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180149. decompStruct->src->bytes_in_buffer -= num;
  180150. }
  180151. boolean jpegFill (j_decompress_ptr)
  180152. {
  180153. return 0;
  180154. }
  180155. const int jpegBufferSize = 512;
  180156. struct JuceJpegDest : public jpeg_destination_mgr
  180157. {
  180158. OutputStream* output;
  180159. char* buffer;
  180160. };
  180161. void jpegWriteInit (j_compress_ptr)
  180162. {
  180163. }
  180164. void jpegWriteTerminate (j_compress_ptr cinfo)
  180165. {
  180166. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180167. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180168. dest->output->write (dest->buffer, (int) numToWrite);
  180169. }
  180170. boolean jpegWriteFlush (j_compress_ptr cinfo)
  180171. {
  180172. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180173. const int numToWrite = jpegBufferSize;
  180174. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180175. dest->free_in_buffer = jpegBufferSize;
  180176. return dest->output->write (dest->buffer, numToWrite);
  180177. }
  180178. }
  180179. JPEGImageFormat::JPEGImageFormat()
  180180. : quality (-1.0f)
  180181. {
  180182. }
  180183. JPEGImageFormat::~JPEGImageFormat() {}
  180184. void JPEGImageFormat::setQuality (const float newQuality)
  180185. {
  180186. quality = newQuality;
  180187. }
  180188. const String JPEGImageFormat::getFormatName()
  180189. {
  180190. return "JPEG";
  180191. }
  180192. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180193. {
  180194. const int bytesNeeded = 10;
  180195. uint8 header [bytesNeeded];
  180196. if (in.read (header, bytesNeeded) == bytesNeeded)
  180197. {
  180198. return header[0] == 0xff
  180199. && header[1] == 0xd8
  180200. && header[2] == 0xff
  180201. && (header[3] == 0xe0 || header[3] == 0xe1);
  180202. }
  180203. return false;
  180204. }
  180205. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180206. const Image juce_loadWithCoreImage (InputStream& input);
  180207. #endif
  180208. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180209. {
  180210. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180211. return juce_loadWithCoreImage (in);
  180212. #else
  180213. using namespace jpeglibNamespace;
  180214. using namespace JPEGHelpers;
  180215. MemoryOutputStream mb;
  180216. mb.writeFromInputStream (in, -1);
  180217. Image image;
  180218. if (mb.getDataSize() > 16)
  180219. {
  180220. struct jpeg_decompress_struct jpegDecompStruct;
  180221. struct jpeg_error_mgr jerr;
  180222. setupSilentErrorHandler (jerr);
  180223. jpegDecompStruct.err = &jerr;
  180224. jpeg_create_decompress (&jpegDecompStruct);
  180225. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180226. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180227. jpegDecompStruct.src->init_source = dummyCallback1;
  180228. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180229. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180230. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180231. jpegDecompStruct.src->term_source = dummyCallback1;
  180232. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180233. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180234. try
  180235. {
  180236. jpeg_read_header (&jpegDecompStruct, TRUE);
  180237. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180238. const int width = jpegDecompStruct.output_width;
  180239. const int height = jpegDecompStruct.output_height;
  180240. jpegDecompStruct.out_color_space = JCS_RGB;
  180241. JSAMPARRAY buffer
  180242. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180243. JPOOL_IMAGE,
  180244. width * 3, 1);
  180245. if (jpeg_start_decompress (&jpegDecompStruct))
  180246. {
  180247. image = Image (Image::RGB, width, height, false);
  180248. image.getProperties()->set ("originalImageHadAlpha", false);
  180249. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180250. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  180251. for (int y = 0; y < height; ++y)
  180252. {
  180253. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180254. const uint8* src = *buffer;
  180255. uint8* dest = destData.getLinePointer (y);
  180256. if (hasAlphaChan)
  180257. {
  180258. for (int i = width; --i >= 0;)
  180259. {
  180260. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180261. ((PixelARGB*) dest)->premultiply();
  180262. dest += destData.pixelStride;
  180263. src += 3;
  180264. }
  180265. }
  180266. else
  180267. {
  180268. for (int i = width; --i >= 0;)
  180269. {
  180270. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180271. dest += destData.pixelStride;
  180272. src += 3;
  180273. }
  180274. }
  180275. }
  180276. jpeg_finish_decompress (&jpegDecompStruct);
  180277. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180278. }
  180279. jpeg_destroy_decompress (&jpegDecompStruct);
  180280. }
  180281. catch (...)
  180282. {}
  180283. }
  180284. return image;
  180285. #endif
  180286. }
  180287. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180288. {
  180289. using namespace jpeglibNamespace;
  180290. using namespace JPEGHelpers;
  180291. if (image.hasAlphaChannel())
  180292. {
  180293. // this method could fill the background in white and still save the image..
  180294. jassertfalse;
  180295. return true;
  180296. }
  180297. struct jpeg_compress_struct jpegCompStruct;
  180298. struct jpeg_error_mgr jerr;
  180299. setupSilentErrorHandler (jerr);
  180300. jpegCompStruct.err = &jerr;
  180301. jpeg_create_compress (&jpegCompStruct);
  180302. JuceJpegDest dest;
  180303. jpegCompStruct.dest = &dest;
  180304. dest.output = &out;
  180305. HeapBlock <char> tempBuffer (jpegBufferSize);
  180306. dest.buffer = tempBuffer;
  180307. dest.next_output_byte = (JOCTET*) dest.buffer;
  180308. dest.free_in_buffer = jpegBufferSize;
  180309. dest.init_destination = jpegWriteInit;
  180310. dest.empty_output_buffer = jpegWriteFlush;
  180311. dest.term_destination = jpegWriteTerminate;
  180312. jpegCompStruct.image_width = image.getWidth();
  180313. jpegCompStruct.image_height = image.getHeight();
  180314. jpegCompStruct.input_components = 3;
  180315. jpegCompStruct.in_color_space = JCS_RGB;
  180316. jpegCompStruct.write_JFIF_header = 1;
  180317. jpegCompStruct.X_density = 72;
  180318. jpegCompStruct.Y_density = 72;
  180319. jpeg_set_defaults (&jpegCompStruct);
  180320. jpegCompStruct.dct_method = JDCT_FLOAT;
  180321. jpegCompStruct.optimize_coding = 1;
  180322. //jpegCompStruct.smoothing_factor = 10;
  180323. if (quality < 0.0f)
  180324. quality = 0.85f;
  180325. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180326. jpeg_start_compress (&jpegCompStruct, TRUE);
  180327. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180328. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180329. JPOOL_IMAGE, strideBytes, 1);
  180330. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  180331. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180332. {
  180333. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180334. uint8* dst = *buffer;
  180335. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180336. {
  180337. *dst++ = ((const PixelRGB*) src)->getRed();
  180338. *dst++ = ((const PixelRGB*) src)->getGreen();
  180339. *dst++ = ((const PixelRGB*) src)->getBlue();
  180340. src += srcData.pixelStride;
  180341. }
  180342. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180343. }
  180344. jpeg_finish_compress (&jpegCompStruct);
  180345. jpeg_destroy_compress (&jpegCompStruct);
  180346. out.flush();
  180347. return true;
  180348. }
  180349. END_JUCE_NAMESPACE
  180350. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180351. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180352. #if JUCE_MSVC
  180353. #pragma warning (push)
  180354. #pragma warning (disable: 4390 4611)
  180355. #ifdef __INTEL_COMPILER
  180356. #pragma warning (disable: 2544 2545)
  180357. #endif
  180358. #endif
  180359. namespace zlibNamespace
  180360. {
  180361. #if JUCE_INCLUDE_ZLIB_CODE
  180362. #undef OS_CODE
  180363. #undef fdopen
  180364. #undef OS_CODE
  180365. #else
  180366. #include <zlib.h>
  180367. #endif
  180368. }
  180369. namespace pnglibNamespace
  180370. {
  180371. using namespace zlibNamespace;
  180372. #if JUCE_INCLUDE_PNGLIB_CODE
  180373. #if _MSC_VER != 1310
  180374. using ::calloc; // (causes conflict in VS.NET 2003)
  180375. using ::malloc;
  180376. using ::free;
  180377. #endif
  180378. using ::abs;
  180379. #define PNG_INTERNAL
  180380. #define NO_DUMMY_DECL
  180381. #define PNG_SETJMP_NOT_SUPPORTED
  180382. /*** Start of inlined file: png.h ***/
  180383. /* png.h - header file for PNG reference library
  180384. *
  180385. * libpng version 1.2.21 - October 4, 2007
  180386. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180387. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180388. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180389. *
  180390. * Authors and maintainers:
  180391. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180392. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180393. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180394. * See also "Contributing Authors", below.
  180395. *
  180396. * Note about libpng version numbers:
  180397. *
  180398. * Due to various miscommunications, unforeseen code incompatibilities
  180399. * and occasional factors outside the authors' control, version numbering
  180400. * on the library has not always been consistent and straightforward.
  180401. * The following table summarizes matters since version 0.89c, which was
  180402. * the first widely used release:
  180403. *
  180404. * source png.h png.h shared-lib
  180405. * version string int version
  180406. * ------- ------ ----- ----------
  180407. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180408. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180409. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180410. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180411. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180412. * 0.97c 0.97 97 2.0.97
  180413. * 0.98 0.98 98 2.0.98
  180414. * 0.99 0.99 98 2.0.99
  180415. * 0.99a-m 0.99 99 2.0.99
  180416. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180417. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180418. * 1.0.1 png.h string is 10001 2.1.0
  180419. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180420. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180421. * 1.0.2a-b 10003 version, except as noted.
  180422. * 1.0.3 10003
  180423. * 1.0.3a-d 10004
  180424. * 1.0.4 10004
  180425. * 1.0.4a-f 10005
  180426. * 1.0.5 (+ 2 patches) 10005
  180427. * 1.0.5a-d 10006
  180428. * 1.0.5e-r 10100 (not source compatible)
  180429. * 1.0.5s-v 10006 (not binary compatible)
  180430. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180431. * 1.0.6d-f 10007 (still binary incompatible)
  180432. * 1.0.6g 10007
  180433. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180434. * 1.0.6i 10007 10.6i
  180435. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180436. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180437. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180438. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180439. * 1.0.7 1 10007 (still compatible)
  180440. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180441. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180442. * 1.0.8 1 10008 2.1.0.8
  180443. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180444. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180445. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180446. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180447. * 1.0.9 1 10009 2.1.0.9
  180448. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180449. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180450. * 1.0.10 1 10010 2.1.0.10
  180451. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180452. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180453. * 1.0.11 1 10011 2.1.0.11
  180454. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180455. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180456. * 1.0.12 2 10012 2.1.0.12
  180457. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180458. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180459. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180460. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180461. * 1.2.0 3 10200 3.1.2.0
  180462. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180463. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180464. * 1.2.1 3 10201 3.1.2.1
  180465. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180466. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180467. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180468. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180469. * 1.0.13 10 10013 10.so.0.1.0.13
  180470. * 1.2.2 12 10202 12.so.0.1.2.2
  180471. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180472. * 1.2.3 12 10203 12.so.0.1.2.3
  180473. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180474. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180475. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180476. * 1.0.14 10 10014 10.so.0.1.0.14
  180477. * 1.2.4 13 10204 12.so.0.1.2.4
  180478. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180479. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180480. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180481. * 1.0.15 10 10015 10.so.0.1.0.15
  180482. * 1.2.5 13 10205 12.so.0.1.2.5
  180483. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180484. * 1.0.16 10 10016 10.so.0.1.0.16
  180485. * 1.2.6 13 10206 12.so.0.1.2.6
  180486. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180487. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180488. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180489. * 1.0.17 10 10017 10.so.0.1.0.17
  180490. * 1.2.7 13 10207 12.so.0.1.2.7
  180491. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180492. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180493. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180494. * 1.0.18 10 10018 10.so.0.1.0.18
  180495. * 1.2.8 13 10208 12.so.0.1.2.8
  180496. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180497. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180498. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180499. * 1.2.9 13 10209 12.so.0.9[.0]
  180500. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180501. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180502. * 1.2.10 13 10210 12.so.0.10[.0]
  180503. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180504. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180505. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180506. * 1.0.19 10 10019 10.so.0.19[.0]
  180507. * 1.2.11 13 10211 12.so.0.11[.0]
  180508. * 1.0.20 10 10020 10.so.0.20[.0]
  180509. * 1.2.12 13 10212 12.so.0.12[.0]
  180510. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180511. * 1.0.21 10 10021 10.so.0.21[.0]
  180512. * 1.2.13 13 10213 12.so.0.13[.0]
  180513. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180514. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180515. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180516. * 1.0.22 10 10022 10.so.0.22[.0]
  180517. * 1.2.14 13 10214 12.so.0.14[.0]
  180518. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180519. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180520. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180521. * 1.0.23 10 10023 10.so.0.23[.0]
  180522. * 1.2.15 13 10215 12.so.0.15[.0]
  180523. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180524. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180525. * 1.0.24 10 10024 10.so.0.24[.0]
  180526. * 1.2.16 13 10216 12.so.0.16[.0]
  180527. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180528. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180529. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180530. * 1.0.25 10 10025 10.so.0.25[.0]
  180531. * 1.2.17 13 10217 12.so.0.17[.0]
  180532. * 1.0.26 10 10026 10.so.0.26[.0]
  180533. * 1.2.18 13 10218 12.so.0.18[.0]
  180534. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180535. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180536. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180537. * 1.0.27 10 10027 10.so.0.27[.0]
  180538. * 1.2.19 13 10219 12.so.0.19[.0]
  180539. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180540. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180541. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180542. * 1.0.28 10 10028 10.so.0.28[.0]
  180543. * 1.2.20 13 10220 12.so.0.20[.0]
  180544. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180545. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180546. * 1.0.29 10 10029 10.so.0.29[.0]
  180547. * 1.2.21 13 10221 12.so.0.21[.0]
  180548. *
  180549. * Henceforth the source version will match the shared-library major
  180550. * and minor numbers; the shared-library major version number will be
  180551. * used for changes in backward compatibility, as it is intended. The
  180552. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180553. * for applications, is an unsigned integer of the form xyyzz corresponding
  180554. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180555. * were given the previous public release number plus a letter, until
  180556. * version 1.0.6j; from then on they were given the upcoming public
  180557. * release number plus "betaNN" or "rcN".
  180558. *
  180559. * Binary incompatibility exists only when applications make direct access
  180560. * to the info_ptr or png_ptr members through png.h, and the compiled
  180561. * application is loaded with a different version of the library.
  180562. *
  180563. * DLLNUM will change each time there are forward or backward changes
  180564. * in binary compatibility (e.g., when a new feature is added).
  180565. *
  180566. * See libpng.txt or libpng.3 for more information. The PNG specification
  180567. * is available as a W3C Recommendation and as an ISO Specification,
  180568. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180569. */
  180570. /*
  180571. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180572. *
  180573. * If you modify libpng you may insert additional notices immediately following
  180574. * this sentence.
  180575. *
  180576. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180577. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180578. * distributed according to the same disclaimer and license as libpng-1.2.5
  180579. * with the following individual added to the list of Contributing Authors:
  180580. *
  180581. * Cosmin Truta
  180582. *
  180583. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180584. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180585. * distributed according to the same disclaimer and license as libpng-1.0.6
  180586. * with the following individuals added to the list of Contributing Authors:
  180587. *
  180588. * Simon-Pierre Cadieux
  180589. * Eric S. Raymond
  180590. * Gilles Vollant
  180591. *
  180592. * and with the following additions to the disclaimer:
  180593. *
  180594. * There is no warranty against interference with your enjoyment of the
  180595. * library or against infringement. There is no warranty that our
  180596. * efforts or the library will fulfill any of your particular purposes
  180597. * or needs. This library is provided with all faults, and the entire
  180598. * risk of satisfactory quality, performance, accuracy, and effort is with
  180599. * the user.
  180600. *
  180601. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180602. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180603. * distributed according to the same disclaimer and license as libpng-0.96,
  180604. * with the following individuals added to the list of Contributing Authors:
  180605. *
  180606. * Tom Lane
  180607. * Glenn Randers-Pehrson
  180608. * Willem van Schaik
  180609. *
  180610. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180611. * Copyright (c) 1996, 1997 Andreas Dilger
  180612. * Distributed according to the same disclaimer and license as libpng-0.88,
  180613. * with the following individuals added to the list of Contributing Authors:
  180614. *
  180615. * John Bowler
  180616. * Kevin Bracey
  180617. * Sam Bushell
  180618. * Magnus Holmgren
  180619. * Greg Roelofs
  180620. * Tom Tanner
  180621. *
  180622. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180623. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180624. *
  180625. * For the purposes of this copyright and license, "Contributing Authors"
  180626. * is defined as the following set of individuals:
  180627. *
  180628. * Andreas Dilger
  180629. * Dave Martindale
  180630. * Guy Eric Schalnat
  180631. * Paul Schmidt
  180632. * Tim Wegner
  180633. *
  180634. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180635. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180636. * including, without limitation, the warranties of merchantability and of
  180637. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180638. * assume no liability for direct, indirect, incidental, special, exemplary,
  180639. * or consequential damages, which may result from the use of the PNG
  180640. * Reference Library, even if advised of the possibility of such damage.
  180641. *
  180642. * Permission is hereby granted to use, copy, modify, and distribute this
  180643. * source code, or portions hereof, for any purpose, without fee, subject
  180644. * to the following restrictions:
  180645. *
  180646. * 1. The origin of this source code must not be misrepresented.
  180647. *
  180648. * 2. Altered versions must be plainly marked as such and
  180649. * must not be misrepresented as being the original source.
  180650. *
  180651. * 3. This Copyright notice may not be removed or altered from
  180652. * any source or altered source distribution.
  180653. *
  180654. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180655. * fee, and encourage the use of this source code as a component to
  180656. * supporting the PNG file format in commercial products. If you use this
  180657. * source code in a product, acknowledgment is not required but would be
  180658. * appreciated.
  180659. */
  180660. /*
  180661. * A "png_get_copyright" function is available, for convenient use in "about"
  180662. * boxes and the like:
  180663. *
  180664. * printf("%s",png_get_copyright(NULL));
  180665. *
  180666. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180667. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180668. */
  180669. /*
  180670. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180671. * certification mark of the Open Source Initiative.
  180672. */
  180673. /*
  180674. * The contributing authors would like to thank all those who helped
  180675. * with testing, bug fixes, and patience. This wouldn't have been
  180676. * possible without all of you.
  180677. *
  180678. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180679. */
  180680. /*
  180681. * Y2K compliance in libpng:
  180682. * =========================
  180683. *
  180684. * October 4, 2007
  180685. *
  180686. * Since the PNG Development group is an ad-hoc body, we can't make
  180687. * an official declaration.
  180688. *
  180689. * This is your unofficial assurance that libpng from version 0.71 and
  180690. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180691. * versions were also Y2K compliant.
  180692. *
  180693. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180694. * that will hold years up to 65535. The other two hold the date in text
  180695. * format, and will hold years up to 9999.
  180696. *
  180697. * The integer is
  180698. * "png_uint_16 year" in png_time_struct.
  180699. *
  180700. * The strings are
  180701. * "png_charp time_buffer" in png_struct and
  180702. * "near_time_buffer", which is a local character string in png.c.
  180703. *
  180704. * There are seven time-related functions:
  180705. * png.c: png_convert_to_rfc_1123() in png.c
  180706. * (formerly png_convert_to_rfc_1152() in error)
  180707. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180708. * png_convert_from_time_t() in pngwrite.c
  180709. * png_get_tIME() in pngget.c
  180710. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180711. * png_set_tIME() in pngset.c
  180712. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180713. *
  180714. * All handle dates properly in a Y2K environment. The
  180715. * png_convert_from_time_t() function calls gmtime() to convert from system
  180716. * clock time, which returns (year - 1900), which we properly convert to
  180717. * the full 4-digit year. There is a possibility that applications using
  180718. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180719. * function, or that they are incorrectly passing only a 2-digit year
  180720. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180721. * but this is not under our control. The libpng documentation has always
  180722. * stated that it works with 4-digit years, and the APIs have been
  180723. * documented as such.
  180724. *
  180725. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180726. * integer to hold the year, and can hold years as large as 65535.
  180727. *
  180728. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180729. * no date-related code.
  180730. *
  180731. * Glenn Randers-Pehrson
  180732. * libpng maintainer
  180733. * PNG Development Group
  180734. */
  180735. #ifndef PNG_H
  180736. #define PNG_H
  180737. /* This is not the place to learn how to use libpng. The file libpng.txt
  180738. * describes how to use libpng, and the file example.c summarizes it
  180739. * with some code on which to build. This file is useful for looking
  180740. * at the actual function definitions and structure components.
  180741. */
  180742. /* Version information for png.h - this should match the version in png.c */
  180743. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180744. #define PNG_HEADER_VERSION_STRING \
  180745. " libpng version 1.2.21 - October 4, 2007\n"
  180746. #define PNG_LIBPNG_VER_SONUM 0
  180747. #define PNG_LIBPNG_VER_DLLNUM 13
  180748. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180749. #define PNG_LIBPNG_VER_MAJOR 1
  180750. #define PNG_LIBPNG_VER_MINOR 2
  180751. #define PNG_LIBPNG_VER_RELEASE 21
  180752. /* This should match the numeric part of the final component of
  180753. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180754. #define PNG_LIBPNG_VER_BUILD 0
  180755. /* Release Status */
  180756. #define PNG_LIBPNG_BUILD_ALPHA 1
  180757. #define PNG_LIBPNG_BUILD_BETA 2
  180758. #define PNG_LIBPNG_BUILD_RC 3
  180759. #define PNG_LIBPNG_BUILD_STABLE 4
  180760. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180761. /* Release-Specific Flags */
  180762. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180763. PNG_LIBPNG_BUILD_STABLE only */
  180764. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180765. PNG_LIBPNG_BUILD_SPECIAL */
  180766. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180767. PNG_LIBPNG_BUILD_PRIVATE */
  180768. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180769. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180770. * We must not include leading zeros.
  180771. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180772. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180773. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180774. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180775. #ifndef PNG_VERSION_INFO_ONLY
  180776. /* include the compression library's header */
  180777. #endif
  180778. /* include all user configurable info, including optional assembler routines */
  180779. /*** Start of inlined file: pngconf.h ***/
  180780. /* pngconf.h - machine configurable file for libpng
  180781. *
  180782. * libpng version 1.2.21 - October 4, 2007
  180783. * For conditions of distribution and use, see copyright notice in png.h
  180784. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180785. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180786. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180787. */
  180788. /* Any machine specific code is near the front of this file, so if you
  180789. * are configuring libpng for a machine, you may want to read the section
  180790. * starting here down to where it starts to typedef png_color, png_text,
  180791. * and png_info.
  180792. */
  180793. #ifndef PNGCONF_H
  180794. #define PNGCONF_H
  180795. #define PNG_1_2_X
  180796. // These are some Juce config settings that should remove any unnecessary code bloat..
  180797. #define PNG_NO_STDIO 1
  180798. #define PNG_DEBUG 0
  180799. #define PNG_NO_WARNINGS 1
  180800. #define PNG_NO_ERROR_TEXT 1
  180801. #define PNG_NO_ERROR_NUMBERS 1
  180802. #define PNG_NO_USER_MEM 1
  180803. #define PNG_NO_READ_iCCP 1
  180804. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180805. #define PNG_NO_READ_USER_CHUNKS 1
  180806. #define PNG_NO_READ_iTXt 1
  180807. #define PNG_NO_READ_sCAL 1
  180808. #define PNG_NO_READ_sPLT 1
  180809. #define png_error(a, b) png_err(a)
  180810. #define png_warning(a, b)
  180811. #define png_chunk_error(a, b) png_err(a)
  180812. #define png_chunk_warning(a, b)
  180813. /*
  180814. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180815. * includes the resource compiler for Windows DLL configurations.
  180816. */
  180817. #ifdef PNG_USER_CONFIG
  180818. # ifndef PNG_USER_PRIVATEBUILD
  180819. # define PNG_USER_PRIVATEBUILD
  180820. # endif
  180821. #include "pngusr.h"
  180822. #endif
  180823. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180824. #ifdef PNG_CONFIGURE_LIBPNG
  180825. #ifdef HAVE_CONFIG_H
  180826. #include "config.h"
  180827. #endif
  180828. #endif
  180829. /*
  180830. * Added at libpng-1.2.8
  180831. *
  180832. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180833. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180834. * the DLL was built>
  180835. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180836. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180837. * distinguish your DLL from those of the official release. These
  180838. * correspond to the trailing letters that come after the version
  180839. * number and must match your private DLL name>
  180840. * e.g. // private DLL "libpng13gx.dll"
  180841. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180842. *
  180843. * The following macros are also at your disposal if you want to complete the
  180844. * DLL VERSIONINFO structure.
  180845. * - PNG_USER_VERSIONINFO_COMMENTS
  180846. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180847. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180848. */
  180849. #ifdef __STDC__
  180850. #ifdef SPECIALBUILD
  180851. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180852. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180853. #endif
  180854. #ifdef PRIVATEBUILD
  180855. # pragma message("PRIVATEBUILD is deprecated.\
  180856. Use PNG_USER_PRIVATEBUILD instead.")
  180857. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180858. #endif
  180859. #endif /* __STDC__ */
  180860. #ifndef PNG_VERSION_INFO_ONLY
  180861. /* End of material added to libpng-1.2.8 */
  180862. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180863. Restored at libpng-1.2.21 */
  180864. # define PNG_WARN_UNINITIALIZED_ROW 1
  180865. /* End of material added at libpng-1.2.19/1.2.21 */
  180866. /* This is the size of the compression buffer, and thus the size of
  180867. * an IDAT chunk. Make this whatever size you feel is best for your
  180868. * machine. One of these will be allocated per png_struct. When this
  180869. * is full, it writes the data to the disk, and does some other
  180870. * calculations. Making this an extremely small size will slow
  180871. * the library down, but you may want to experiment to determine
  180872. * where it becomes significant, if you are concerned with memory
  180873. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180874. * this describes the size of the buffer available to read the data in.
  180875. * Unless this gets smaller than the size of a row (compressed),
  180876. * it should not make much difference how big this is.
  180877. */
  180878. #ifndef PNG_ZBUF_SIZE
  180879. # define PNG_ZBUF_SIZE 8192
  180880. #endif
  180881. /* Enable if you want a write-only libpng */
  180882. #ifndef PNG_NO_READ_SUPPORTED
  180883. # define PNG_READ_SUPPORTED
  180884. #endif
  180885. /* Enable if you want a read-only libpng */
  180886. #ifndef PNG_NO_WRITE_SUPPORTED
  180887. # define PNG_WRITE_SUPPORTED
  180888. #endif
  180889. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180890. support PNGs that are embedded in MNG datastreams */
  180891. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180892. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180893. # define PNG_MNG_FEATURES_SUPPORTED
  180894. # endif
  180895. #endif
  180896. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180897. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180898. # define PNG_FLOATING_POINT_SUPPORTED
  180899. # endif
  180900. #endif
  180901. /* If you are running on a machine where you cannot allocate more
  180902. * than 64K of memory at once, uncomment this. While libpng will not
  180903. * normally need that much memory in a chunk (unless you load up a very
  180904. * large file), zlib needs to know how big of a chunk it can use, and
  180905. * libpng thus makes sure to check any memory allocation to verify it
  180906. * will fit into memory.
  180907. #define PNG_MAX_MALLOC_64K
  180908. */
  180909. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180910. # define PNG_MAX_MALLOC_64K
  180911. #endif
  180912. /* Special munging to support doing things the 'cygwin' way:
  180913. * 'Normal' png-on-win32 defines/defaults:
  180914. * PNG_BUILD_DLL -- building dll
  180915. * PNG_USE_DLL -- building an application, linking to dll
  180916. * (no define) -- building static library, or building an
  180917. * application and linking to the static lib
  180918. * 'Cygwin' defines/defaults:
  180919. * PNG_BUILD_DLL -- (ignored) building the dll
  180920. * (no define) -- (ignored) building an application, linking to the dll
  180921. * PNG_STATIC -- (ignored) building the static lib, or building an
  180922. * application that links to the static lib.
  180923. * ALL_STATIC -- (ignored) building various static libs, or building an
  180924. * application that links to the static libs.
  180925. * Thus,
  180926. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180927. * this bit of #ifdefs will define the 'correct' config variables based on
  180928. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180929. * unnecessary.
  180930. *
  180931. * Also, the precedence order is:
  180932. * ALL_STATIC (since we can't #undef something outside our namespace)
  180933. * PNG_BUILD_DLL
  180934. * PNG_STATIC
  180935. * (nothing) == PNG_USE_DLL
  180936. *
  180937. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180938. * of auto-import in binutils, we no longer need to worry about
  180939. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180940. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180941. * to __declspec() stuff. However, we DO need to worry about
  180942. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180943. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180944. */
  180945. #if defined(__CYGWIN__)
  180946. # if defined(ALL_STATIC)
  180947. # if defined(PNG_BUILD_DLL)
  180948. # undef PNG_BUILD_DLL
  180949. # endif
  180950. # if defined(PNG_USE_DLL)
  180951. # undef PNG_USE_DLL
  180952. # endif
  180953. # if defined(PNG_DLL)
  180954. # undef PNG_DLL
  180955. # endif
  180956. # if !defined(PNG_STATIC)
  180957. # define PNG_STATIC
  180958. # endif
  180959. # else
  180960. # if defined (PNG_BUILD_DLL)
  180961. # if defined(PNG_STATIC)
  180962. # undef PNG_STATIC
  180963. # endif
  180964. # if defined(PNG_USE_DLL)
  180965. # undef PNG_USE_DLL
  180966. # endif
  180967. # if !defined(PNG_DLL)
  180968. # define PNG_DLL
  180969. # endif
  180970. # else
  180971. # if defined(PNG_STATIC)
  180972. # if defined(PNG_USE_DLL)
  180973. # undef PNG_USE_DLL
  180974. # endif
  180975. # if defined(PNG_DLL)
  180976. # undef PNG_DLL
  180977. # endif
  180978. # else
  180979. # if !defined(PNG_USE_DLL)
  180980. # define PNG_USE_DLL
  180981. # endif
  180982. # if !defined(PNG_DLL)
  180983. # define PNG_DLL
  180984. # endif
  180985. # endif
  180986. # endif
  180987. # endif
  180988. #endif
  180989. /* This protects us against compilers that run on a windowing system
  180990. * and thus don't have or would rather us not use the stdio types:
  180991. * stdin, stdout, and stderr. The only one currently used is stderr
  180992. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180993. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180994. * will also prevent these, plus will prevent the entire set of stdio
  180995. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180996. * unless (PNG_DEBUG > 0) has been #defined.
  180997. *
  180998. * #define PNG_NO_CONSOLE_IO
  180999. * #define PNG_NO_STDIO
  181000. */
  181001. #if defined(_WIN32_WCE)
  181002. # include <windows.h>
  181003. /* Console I/O functions are not supported on WindowsCE */
  181004. # define PNG_NO_CONSOLE_IO
  181005. # ifdef PNG_DEBUG
  181006. # undef PNG_DEBUG
  181007. # endif
  181008. #endif
  181009. #ifdef PNG_BUILD_DLL
  181010. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181011. # ifndef PNG_NO_CONSOLE_IO
  181012. # define PNG_NO_CONSOLE_IO
  181013. # endif
  181014. # endif
  181015. #endif
  181016. # ifdef PNG_NO_STDIO
  181017. # ifndef PNG_NO_CONSOLE_IO
  181018. # define PNG_NO_CONSOLE_IO
  181019. # endif
  181020. # ifdef PNG_DEBUG
  181021. # if (PNG_DEBUG > 0)
  181022. # include <stdio.h>
  181023. # endif
  181024. # endif
  181025. # else
  181026. # if !defined(_WIN32_WCE)
  181027. /* "stdio.h" functions are not supported on WindowsCE */
  181028. # include <stdio.h>
  181029. # endif
  181030. # endif
  181031. /* This macro protects us against machines that don't have function
  181032. * prototypes (ie K&R style headers). If your compiler does not handle
  181033. * function prototypes, define this macro and use the included ansi2knr.
  181034. * I've always been able to use _NO_PROTO as the indicator, but you may
  181035. * need to drag the empty declaration out in front of here, or change the
  181036. * ifdef to suit your own needs.
  181037. */
  181038. #ifndef PNGARG
  181039. #ifdef OF /* zlib prototype munger */
  181040. # define PNGARG(arglist) OF(arglist)
  181041. #else
  181042. #ifdef _NO_PROTO
  181043. # define PNGARG(arglist) ()
  181044. # ifndef PNG_TYPECAST_NULL
  181045. # define PNG_TYPECAST_NULL
  181046. # endif
  181047. #else
  181048. # define PNGARG(arglist) arglist
  181049. #endif /* _NO_PROTO */
  181050. #endif /* OF */
  181051. #endif /* PNGARG */
  181052. /* Try to determine if we are compiling on a Mac. Note that testing for
  181053. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181054. * on non-Mac platforms.
  181055. */
  181056. #ifndef MACOS
  181057. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181058. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181059. # define MACOS
  181060. # endif
  181061. #endif
  181062. /* enough people need this for various reasons to include it here */
  181063. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181064. # include <sys/types.h>
  181065. #endif
  181066. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181067. # define PNG_SETJMP_SUPPORTED
  181068. #endif
  181069. #ifdef PNG_SETJMP_SUPPORTED
  181070. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181071. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181072. */
  181073. # ifdef __linux__
  181074. # ifdef _BSD_SOURCE
  181075. # define PNG_SAVE_BSD_SOURCE
  181076. # undef _BSD_SOURCE
  181077. # endif
  181078. # ifdef _SETJMP_H
  181079. /* If you encounter a compiler error here, see the explanation
  181080. * near the end of INSTALL.
  181081. */
  181082. __png.h__ already includes setjmp.h;
  181083. __dont__ include it again.;
  181084. # endif
  181085. # endif /* __linux__ */
  181086. /* include setjmp.h for error handling */
  181087. # include <setjmp.h>
  181088. # ifdef __linux__
  181089. # ifdef PNG_SAVE_BSD_SOURCE
  181090. # define _BSD_SOURCE
  181091. # undef PNG_SAVE_BSD_SOURCE
  181092. # endif
  181093. # endif /* __linux__ */
  181094. #endif /* PNG_SETJMP_SUPPORTED */
  181095. #ifdef BSD
  181096. #if ! JUCE_MAC
  181097. # include <strings.h>
  181098. #endif
  181099. #else
  181100. # include <string.h>
  181101. #endif
  181102. /* Other defines for things like memory and the like can go here. */
  181103. #ifdef PNG_INTERNAL
  181104. #include <stdlib.h>
  181105. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181106. * aren't usually used outside the library (as far as I know), so it is
  181107. * debatable if they should be exported at all. In the future, when it is
  181108. * possible to have run-time registry of chunk-handling functions, some of
  181109. * these will be made available again.
  181110. #define PNG_EXTERN extern
  181111. */
  181112. #define PNG_EXTERN
  181113. /* Other defines specific to compilers can go here. Try to keep
  181114. * them inside an appropriate ifdef/endif pair for portability.
  181115. */
  181116. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181117. # if defined(MACOS)
  181118. /* We need to check that <math.h> hasn't already been included earlier
  181119. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181120. * <fp.h> if possible.
  181121. */
  181122. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181123. # include <fp.h>
  181124. # endif
  181125. # else
  181126. # include <math.h>
  181127. # endif
  181128. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181129. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181130. * MATH=68881
  181131. */
  181132. # include <m68881.h>
  181133. # endif
  181134. #endif
  181135. /* Codewarrior on NT has linking problems without this. */
  181136. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181137. # define PNG_ALWAYS_EXTERN
  181138. #endif
  181139. /* This provides the non-ANSI (far) memory allocation routines. */
  181140. #if defined(__TURBOC__) && defined(__MSDOS__)
  181141. # include <mem.h>
  181142. # include <alloc.h>
  181143. #endif
  181144. /* I have no idea why is this necessary... */
  181145. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181146. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181147. # include <malloc.h>
  181148. #endif
  181149. /* This controls how fine the dithering gets. As this allocates
  181150. * a largish chunk of memory (32K), those who are not as concerned
  181151. * with dithering quality can decrease some or all of these.
  181152. */
  181153. #ifndef PNG_DITHER_RED_BITS
  181154. # define PNG_DITHER_RED_BITS 5
  181155. #endif
  181156. #ifndef PNG_DITHER_GREEN_BITS
  181157. # define PNG_DITHER_GREEN_BITS 5
  181158. #endif
  181159. #ifndef PNG_DITHER_BLUE_BITS
  181160. # define PNG_DITHER_BLUE_BITS 5
  181161. #endif
  181162. /* This controls how fine the gamma correction becomes when you
  181163. * are only interested in 8 bits anyway. Increasing this value
  181164. * results in more memory being used, and more pow() functions
  181165. * being called to fill in the gamma tables. Don't set this value
  181166. * less then 8, and even that may not work (I haven't tested it).
  181167. */
  181168. #ifndef PNG_MAX_GAMMA_8
  181169. # define PNG_MAX_GAMMA_8 11
  181170. #endif
  181171. /* This controls how much a difference in gamma we can tolerate before
  181172. * we actually start doing gamma conversion.
  181173. */
  181174. #ifndef PNG_GAMMA_THRESHOLD
  181175. # define PNG_GAMMA_THRESHOLD 0.05
  181176. #endif
  181177. #endif /* PNG_INTERNAL */
  181178. /* The following uses const char * instead of char * for error
  181179. * and warning message functions, so some compilers won't complain.
  181180. * If you do not want to use const, define PNG_NO_CONST here.
  181181. */
  181182. #ifndef PNG_NO_CONST
  181183. # define PNG_CONST const
  181184. #else
  181185. # define PNG_CONST
  181186. #endif
  181187. /* The following defines give you the ability to remove code from the
  181188. * library that you will not be using. I wish I could figure out how to
  181189. * automate this, but I can't do that without making it seriously hard
  181190. * on the users. So if you are not using an ability, change the #define
  181191. * to and #undef, and that part of the library will not be compiled. If
  181192. * your linker can't find a function, you may want to make sure the
  181193. * ability is defined here. Some of these depend upon some others being
  181194. * defined. I haven't figured out all the interactions here, so you may
  181195. * have to experiment awhile to get everything to compile. If you are
  181196. * creating or using a shared library, you probably shouldn't touch this,
  181197. * as it will affect the size of the structures, and this will cause bad
  181198. * things to happen if the library and/or application ever change.
  181199. */
  181200. /* Any features you will not be using can be undef'ed here */
  181201. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181202. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181203. * on the compile line, then pick and choose which ones to define without
  181204. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181205. * if you only want to have a png-compliant reader/writer but don't need
  181206. * any of the extra transformations. This saves about 80 kbytes in a
  181207. * typical installation of the library. (PNG_NO_* form added in version
  181208. * 1.0.1c, for consistency)
  181209. */
  181210. /* The size of the png_text structure changed in libpng-1.0.6 when
  181211. * iTXt support was added. iTXt support was turned off by default through
  181212. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181213. * instead of calling png_set_text() and letting libpng malloc it. It
  181214. * was turned on by default in libpng-1.3.0.
  181215. */
  181216. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181217. # ifndef PNG_NO_iTXt_SUPPORTED
  181218. # define PNG_NO_iTXt_SUPPORTED
  181219. # endif
  181220. # ifndef PNG_NO_READ_iTXt
  181221. # define PNG_NO_READ_iTXt
  181222. # endif
  181223. # ifndef PNG_NO_WRITE_iTXt
  181224. # define PNG_NO_WRITE_iTXt
  181225. # endif
  181226. #endif
  181227. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181228. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181229. # define PNG_READ_iTXt
  181230. # endif
  181231. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181232. # define PNG_WRITE_iTXt
  181233. # endif
  181234. #endif
  181235. /* The following support, added after version 1.0.0, can be turned off here en
  181236. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181237. * with old applications that require the length of png_struct and png_info
  181238. * to remain unchanged.
  181239. */
  181240. #ifdef PNG_LEGACY_SUPPORTED
  181241. # define PNG_NO_FREE_ME
  181242. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181243. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181244. # define PNG_NO_READ_USER_CHUNKS
  181245. # define PNG_NO_READ_iCCP
  181246. # define PNG_NO_WRITE_iCCP
  181247. # define PNG_NO_READ_iTXt
  181248. # define PNG_NO_WRITE_iTXt
  181249. # define PNG_NO_READ_sCAL
  181250. # define PNG_NO_WRITE_sCAL
  181251. # define PNG_NO_READ_sPLT
  181252. # define PNG_NO_WRITE_sPLT
  181253. # define PNG_NO_INFO_IMAGE
  181254. # define PNG_NO_READ_RGB_TO_GRAY
  181255. # define PNG_NO_READ_USER_TRANSFORM
  181256. # define PNG_NO_WRITE_USER_TRANSFORM
  181257. # define PNG_NO_USER_MEM
  181258. # define PNG_NO_READ_EMPTY_PLTE
  181259. # define PNG_NO_MNG_FEATURES
  181260. # define PNG_NO_FIXED_POINT_SUPPORTED
  181261. #endif
  181262. /* Ignore attempt to turn off both floating and fixed point support */
  181263. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181264. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181265. # define PNG_FIXED_POINT_SUPPORTED
  181266. #endif
  181267. #ifndef PNG_NO_FREE_ME
  181268. # define PNG_FREE_ME_SUPPORTED
  181269. #endif
  181270. #if defined(PNG_READ_SUPPORTED)
  181271. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181272. !defined(PNG_NO_READ_TRANSFORMS)
  181273. # define PNG_READ_TRANSFORMS_SUPPORTED
  181274. #endif
  181275. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181276. # ifndef PNG_NO_READ_EXPAND
  181277. # define PNG_READ_EXPAND_SUPPORTED
  181278. # endif
  181279. # ifndef PNG_NO_READ_SHIFT
  181280. # define PNG_READ_SHIFT_SUPPORTED
  181281. # endif
  181282. # ifndef PNG_NO_READ_PACK
  181283. # define PNG_READ_PACK_SUPPORTED
  181284. # endif
  181285. # ifndef PNG_NO_READ_BGR
  181286. # define PNG_READ_BGR_SUPPORTED
  181287. # endif
  181288. # ifndef PNG_NO_READ_SWAP
  181289. # define PNG_READ_SWAP_SUPPORTED
  181290. # endif
  181291. # ifndef PNG_NO_READ_PACKSWAP
  181292. # define PNG_READ_PACKSWAP_SUPPORTED
  181293. # endif
  181294. # ifndef PNG_NO_READ_INVERT
  181295. # define PNG_READ_INVERT_SUPPORTED
  181296. # endif
  181297. # ifndef PNG_NO_READ_DITHER
  181298. # define PNG_READ_DITHER_SUPPORTED
  181299. # endif
  181300. # ifndef PNG_NO_READ_BACKGROUND
  181301. # define PNG_READ_BACKGROUND_SUPPORTED
  181302. # endif
  181303. # ifndef PNG_NO_READ_16_TO_8
  181304. # define PNG_READ_16_TO_8_SUPPORTED
  181305. # endif
  181306. # ifndef PNG_NO_READ_FILLER
  181307. # define PNG_READ_FILLER_SUPPORTED
  181308. # endif
  181309. # ifndef PNG_NO_READ_GAMMA
  181310. # define PNG_READ_GAMMA_SUPPORTED
  181311. # endif
  181312. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181313. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181314. # endif
  181315. # ifndef PNG_NO_READ_SWAP_ALPHA
  181316. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181317. # endif
  181318. # ifndef PNG_NO_READ_INVERT_ALPHA
  181319. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181320. # endif
  181321. # ifndef PNG_NO_READ_STRIP_ALPHA
  181322. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181323. # endif
  181324. # ifndef PNG_NO_READ_USER_TRANSFORM
  181325. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181326. # endif
  181327. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181328. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181329. # endif
  181330. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181331. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181332. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181333. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181334. #endif /* about interlacing capability! You'll */
  181335. /* still have interlacing unless you change the following line: */
  181336. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181337. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181338. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181339. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181340. # endif
  181341. #endif
  181342. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181343. /* Deprecated, will be removed from version 2.0.0.
  181344. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181345. #ifndef PNG_NO_READ_EMPTY_PLTE
  181346. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181347. #endif
  181348. #endif
  181349. #endif /* PNG_READ_SUPPORTED */
  181350. #if defined(PNG_WRITE_SUPPORTED)
  181351. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181352. !defined(PNG_NO_WRITE_TRANSFORMS)
  181353. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181354. #endif
  181355. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181356. # ifndef PNG_NO_WRITE_SHIFT
  181357. # define PNG_WRITE_SHIFT_SUPPORTED
  181358. # endif
  181359. # ifndef PNG_NO_WRITE_PACK
  181360. # define PNG_WRITE_PACK_SUPPORTED
  181361. # endif
  181362. # ifndef PNG_NO_WRITE_BGR
  181363. # define PNG_WRITE_BGR_SUPPORTED
  181364. # endif
  181365. # ifndef PNG_NO_WRITE_SWAP
  181366. # define PNG_WRITE_SWAP_SUPPORTED
  181367. # endif
  181368. # ifndef PNG_NO_WRITE_PACKSWAP
  181369. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181370. # endif
  181371. # ifndef PNG_NO_WRITE_INVERT
  181372. # define PNG_WRITE_INVERT_SUPPORTED
  181373. # endif
  181374. # ifndef PNG_NO_WRITE_FILLER
  181375. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181376. # endif
  181377. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181378. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181379. # endif
  181380. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181381. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181382. # endif
  181383. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181384. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181385. # endif
  181386. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181387. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181388. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181389. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181390. encoders, but can cause trouble
  181391. if left undefined */
  181392. #endif
  181393. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181394. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181395. defined(PNG_FLOATING_POINT_SUPPORTED)
  181396. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181397. #endif
  181398. #ifndef PNG_NO_WRITE_FLUSH
  181399. # define PNG_WRITE_FLUSH_SUPPORTED
  181400. #endif
  181401. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181402. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181403. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181404. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181405. #endif
  181406. #endif
  181407. #endif /* PNG_WRITE_SUPPORTED */
  181408. #ifndef PNG_1_0_X
  181409. # ifndef PNG_NO_ERROR_NUMBERS
  181410. # define PNG_ERROR_NUMBERS_SUPPORTED
  181411. # endif
  181412. #endif /* PNG_1_0_X */
  181413. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181414. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181415. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181416. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181417. # endif
  181418. #endif
  181419. #ifndef PNG_NO_STDIO
  181420. # define PNG_TIME_RFC1123_SUPPORTED
  181421. #endif
  181422. /* This adds extra functions in pngget.c for accessing data from the
  181423. * info pointer (added in version 0.99)
  181424. * png_get_image_width()
  181425. * png_get_image_height()
  181426. * png_get_bit_depth()
  181427. * png_get_color_type()
  181428. * png_get_compression_type()
  181429. * png_get_filter_type()
  181430. * png_get_interlace_type()
  181431. * png_get_pixel_aspect_ratio()
  181432. * png_get_pixels_per_meter()
  181433. * png_get_x_offset_pixels()
  181434. * png_get_y_offset_pixels()
  181435. * png_get_x_offset_microns()
  181436. * png_get_y_offset_microns()
  181437. */
  181438. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181439. # define PNG_EASY_ACCESS_SUPPORTED
  181440. #endif
  181441. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181442. * and removed from version 1.2.20. The following will be removed
  181443. * from libpng-1.4.0
  181444. */
  181445. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181446. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181447. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181448. # endif
  181449. #endif
  181450. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181451. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181452. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181453. # endif
  181454. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181455. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181456. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181457. # define PNG_NO_MMX_CODE
  181458. # endif
  181459. # endif
  181460. # if defined(__APPLE__)
  181461. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181462. # define PNG_NO_MMX_CODE
  181463. # endif
  181464. # endif
  181465. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181466. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181467. # define PNG_NO_MMX_CODE
  181468. # endif
  181469. # endif
  181470. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181471. # define PNG_MMX_CODE_SUPPORTED
  181472. # endif
  181473. #endif
  181474. /* end of obsolete code to be removed from libpng-1.4.0 */
  181475. #if !defined(PNG_1_0_X)
  181476. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181477. # define PNG_USER_MEM_SUPPORTED
  181478. #endif
  181479. #endif /* PNG_1_0_X */
  181480. /* Added at libpng-1.2.6 */
  181481. #if !defined(PNG_1_0_X)
  181482. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181483. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181484. # define PNG_SET_USER_LIMITS_SUPPORTED
  181485. #endif
  181486. #endif
  181487. #endif /* PNG_1_0_X */
  181488. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181489. * how large, set these limits to 0x7fffffffL
  181490. */
  181491. #ifndef PNG_USER_WIDTH_MAX
  181492. # define PNG_USER_WIDTH_MAX 1000000L
  181493. #endif
  181494. #ifndef PNG_USER_HEIGHT_MAX
  181495. # define PNG_USER_HEIGHT_MAX 1000000L
  181496. #endif
  181497. /* These are currently experimental features, define them if you want */
  181498. /* very little testing */
  181499. /*
  181500. #ifdef PNG_READ_SUPPORTED
  181501. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181502. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181503. # endif
  181504. #endif
  181505. */
  181506. /* This is only for PowerPC big-endian and 680x0 systems */
  181507. /* some testing */
  181508. /*
  181509. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181510. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181511. #endif
  181512. */
  181513. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181514. /*
  181515. #define PNG_NO_POINTER_INDEXING
  181516. */
  181517. /* These functions are turned off by default, as they will be phased out. */
  181518. /*
  181519. #define PNG_USELESS_TESTS_SUPPORTED
  181520. #define PNG_CORRECT_PALETTE_SUPPORTED
  181521. */
  181522. /* Any chunks you are not interested in, you can undef here. The
  181523. * ones that allocate memory may be expecially important (hIST,
  181524. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181525. * a bit smaller.
  181526. */
  181527. #if defined(PNG_READ_SUPPORTED) && \
  181528. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181529. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181530. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181531. #endif
  181532. #if defined(PNG_WRITE_SUPPORTED) && \
  181533. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181534. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181535. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181536. #endif
  181537. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181538. #ifdef PNG_NO_READ_TEXT
  181539. # define PNG_NO_READ_iTXt
  181540. # define PNG_NO_READ_tEXt
  181541. # define PNG_NO_READ_zTXt
  181542. #endif
  181543. #ifndef PNG_NO_READ_bKGD
  181544. # define PNG_READ_bKGD_SUPPORTED
  181545. # define PNG_bKGD_SUPPORTED
  181546. #endif
  181547. #ifndef PNG_NO_READ_cHRM
  181548. # define PNG_READ_cHRM_SUPPORTED
  181549. # define PNG_cHRM_SUPPORTED
  181550. #endif
  181551. #ifndef PNG_NO_READ_gAMA
  181552. # define PNG_READ_gAMA_SUPPORTED
  181553. # define PNG_gAMA_SUPPORTED
  181554. #endif
  181555. #ifndef PNG_NO_READ_hIST
  181556. # define PNG_READ_hIST_SUPPORTED
  181557. # define PNG_hIST_SUPPORTED
  181558. #endif
  181559. #ifndef PNG_NO_READ_iCCP
  181560. # define PNG_READ_iCCP_SUPPORTED
  181561. # define PNG_iCCP_SUPPORTED
  181562. #endif
  181563. #ifndef PNG_NO_READ_iTXt
  181564. # ifndef PNG_READ_iTXt_SUPPORTED
  181565. # define PNG_READ_iTXt_SUPPORTED
  181566. # endif
  181567. # ifndef PNG_iTXt_SUPPORTED
  181568. # define PNG_iTXt_SUPPORTED
  181569. # endif
  181570. #endif
  181571. #ifndef PNG_NO_READ_oFFs
  181572. # define PNG_READ_oFFs_SUPPORTED
  181573. # define PNG_oFFs_SUPPORTED
  181574. #endif
  181575. #ifndef PNG_NO_READ_pCAL
  181576. # define PNG_READ_pCAL_SUPPORTED
  181577. # define PNG_pCAL_SUPPORTED
  181578. #endif
  181579. #ifndef PNG_NO_READ_sCAL
  181580. # define PNG_READ_sCAL_SUPPORTED
  181581. # define PNG_sCAL_SUPPORTED
  181582. #endif
  181583. #ifndef PNG_NO_READ_pHYs
  181584. # define PNG_READ_pHYs_SUPPORTED
  181585. # define PNG_pHYs_SUPPORTED
  181586. #endif
  181587. #ifndef PNG_NO_READ_sBIT
  181588. # define PNG_READ_sBIT_SUPPORTED
  181589. # define PNG_sBIT_SUPPORTED
  181590. #endif
  181591. #ifndef PNG_NO_READ_sPLT
  181592. # define PNG_READ_sPLT_SUPPORTED
  181593. # define PNG_sPLT_SUPPORTED
  181594. #endif
  181595. #ifndef PNG_NO_READ_sRGB
  181596. # define PNG_READ_sRGB_SUPPORTED
  181597. # define PNG_sRGB_SUPPORTED
  181598. #endif
  181599. #ifndef PNG_NO_READ_tEXt
  181600. # define PNG_READ_tEXt_SUPPORTED
  181601. # define PNG_tEXt_SUPPORTED
  181602. #endif
  181603. #ifndef PNG_NO_READ_tIME
  181604. # define PNG_READ_tIME_SUPPORTED
  181605. # define PNG_tIME_SUPPORTED
  181606. #endif
  181607. #ifndef PNG_NO_READ_tRNS
  181608. # define PNG_READ_tRNS_SUPPORTED
  181609. # define PNG_tRNS_SUPPORTED
  181610. #endif
  181611. #ifndef PNG_NO_READ_zTXt
  181612. # define PNG_READ_zTXt_SUPPORTED
  181613. # define PNG_zTXt_SUPPORTED
  181614. #endif
  181615. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181616. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181617. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181618. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181619. # endif
  181620. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181621. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181622. # endif
  181623. #endif
  181624. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181625. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181626. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181627. # define PNG_USER_CHUNKS_SUPPORTED
  181628. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181629. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181630. # endif
  181631. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181632. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181633. # endif
  181634. #endif
  181635. #ifndef PNG_NO_READ_OPT_PLTE
  181636. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181637. #endif /* optional PLTE chunk in RGB and RGBA images */
  181638. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181639. defined(PNG_READ_zTXt_SUPPORTED)
  181640. # define PNG_READ_TEXT_SUPPORTED
  181641. # define PNG_TEXT_SUPPORTED
  181642. #endif
  181643. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181644. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181645. #ifdef PNG_NO_WRITE_TEXT
  181646. # define PNG_NO_WRITE_iTXt
  181647. # define PNG_NO_WRITE_tEXt
  181648. # define PNG_NO_WRITE_zTXt
  181649. #endif
  181650. #ifndef PNG_NO_WRITE_bKGD
  181651. # define PNG_WRITE_bKGD_SUPPORTED
  181652. # ifndef PNG_bKGD_SUPPORTED
  181653. # define PNG_bKGD_SUPPORTED
  181654. # endif
  181655. #endif
  181656. #ifndef PNG_NO_WRITE_cHRM
  181657. # define PNG_WRITE_cHRM_SUPPORTED
  181658. # ifndef PNG_cHRM_SUPPORTED
  181659. # define PNG_cHRM_SUPPORTED
  181660. # endif
  181661. #endif
  181662. #ifndef PNG_NO_WRITE_gAMA
  181663. # define PNG_WRITE_gAMA_SUPPORTED
  181664. # ifndef PNG_gAMA_SUPPORTED
  181665. # define PNG_gAMA_SUPPORTED
  181666. # endif
  181667. #endif
  181668. #ifndef PNG_NO_WRITE_hIST
  181669. # define PNG_WRITE_hIST_SUPPORTED
  181670. # ifndef PNG_hIST_SUPPORTED
  181671. # define PNG_hIST_SUPPORTED
  181672. # endif
  181673. #endif
  181674. #ifndef PNG_NO_WRITE_iCCP
  181675. # define PNG_WRITE_iCCP_SUPPORTED
  181676. # ifndef PNG_iCCP_SUPPORTED
  181677. # define PNG_iCCP_SUPPORTED
  181678. # endif
  181679. #endif
  181680. #ifndef PNG_NO_WRITE_iTXt
  181681. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181682. # define PNG_WRITE_iTXt_SUPPORTED
  181683. # endif
  181684. # ifndef PNG_iTXt_SUPPORTED
  181685. # define PNG_iTXt_SUPPORTED
  181686. # endif
  181687. #endif
  181688. #ifndef PNG_NO_WRITE_oFFs
  181689. # define PNG_WRITE_oFFs_SUPPORTED
  181690. # ifndef PNG_oFFs_SUPPORTED
  181691. # define PNG_oFFs_SUPPORTED
  181692. # endif
  181693. #endif
  181694. #ifndef PNG_NO_WRITE_pCAL
  181695. # define PNG_WRITE_pCAL_SUPPORTED
  181696. # ifndef PNG_pCAL_SUPPORTED
  181697. # define PNG_pCAL_SUPPORTED
  181698. # endif
  181699. #endif
  181700. #ifndef PNG_NO_WRITE_sCAL
  181701. # define PNG_WRITE_sCAL_SUPPORTED
  181702. # ifndef PNG_sCAL_SUPPORTED
  181703. # define PNG_sCAL_SUPPORTED
  181704. # endif
  181705. #endif
  181706. #ifndef PNG_NO_WRITE_pHYs
  181707. # define PNG_WRITE_pHYs_SUPPORTED
  181708. # ifndef PNG_pHYs_SUPPORTED
  181709. # define PNG_pHYs_SUPPORTED
  181710. # endif
  181711. #endif
  181712. #ifndef PNG_NO_WRITE_sBIT
  181713. # define PNG_WRITE_sBIT_SUPPORTED
  181714. # ifndef PNG_sBIT_SUPPORTED
  181715. # define PNG_sBIT_SUPPORTED
  181716. # endif
  181717. #endif
  181718. #ifndef PNG_NO_WRITE_sPLT
  181719. # define PNG_WRITE_sPLT_SUPPORTED
  181720. # ifndef PNG_sPLT_SUPPORTED
  181721. # define PNG_sPLT_SUPPORTED
  181722. # endif
  181723. #endif
  181724. #ifndef PNG_NO_WRITE_sRGB
  181725. # define PNG_WRITE_sRGB_SUPPORTED
  181726. # ifndef PNG_sRGB_SUPPORTED
  181727. # define PNG_sRGB_SUPPORTED
  181728. # endif
  181729. #endif
  181730. #ifndef PNG_NO_WRITE_tEXt
  181731. # define PNG_WRITE_tEXt_SUPPORTED
  181732. # ifndef PNG_tEXt_SUPPORTED
  181733. # define PNG_tEXt_SUPPORTED
  181734. # endif
  181735. #endif
  181736. #ifndef PNG_NO_WRITE_tIME
  181737. # define PNG_WRITE_tIME_SUPPORTED
  181738. # ifndef PNG_tIME_SUPPORTED
  181739. # define PNG_tIME_SUPPORTED
  181740. # endif
  181741. #endif
  181742. #ifndef PNG_NO_WRITE_tRNS
  181743. # define PNG_WRITE_tRNS_SUPPORTED
  181744. # ifndef PNG_tRNS_SUPPORTED
  181745. # define PNG_tRNS_SUPPORTED
  181746. # endif
  181747. #endif
  181748. #ifndef PNG_NO_WRITE_zTXt
  181749. # define PNG_WRITE_zTXt_SUPPORTED
  181750. # ifndef PNG_zTXt_SUPPORTED
  181751. # define PNG_zTXt_SUPPORTED
  181752. # endif
  181753. #endif
  181754. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181755. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181756. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181757. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181758. # endif
  181759. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181760. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181761. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181762. # endif
  181763. # endif
  181764. #endif
  181765. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181766. defined(PNG_WRITE_zTXt_SUPPORTED)
  181767. # define PNG_WRITE_TEXT_SUPPORTED
  181768. # ifndef PNG_TEXT_SUPPORTED
  181769. # define PNG_TEXT_SUPPORTED
  181770. # endif
  181771. #endif
  181772. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181773. /* Turn this off to disable png_read_png() and
  181774. * png_write_png() and leave the row_pointers member
  181775. * out of the info structure.
  181776. */
  181777. #ifndef PNG_NO_INFO_IMAGE
  181778. # define PNG_INFO_IMAGE_SUPPORTED
  181779. #endif
  181780. /* need the time information for reading tIME chunks */
  181781. #if defined(PNG_tIME_SUPPORTED)
  181782. # if !defined(_WIN32_WCE)
  181783. /* "time.h" functions are not supported on WindowsCE */
  181784. # include <time.h>
  181785. # endif
  181786. #endif
  181787. /* Some typedefs to get us started. These should be safe on most of the
  181788. * common platforms. The typedefs should be at least as large as the
  181789. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181790. * don't have to be exactly that size. Some compilers dislike passing
  181791. * unsigned shorts as function parameters, so you may be better off using
  181792. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181793. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181794. */
  181795. typedef unsigned long png_uint_32;
  181796. typedef long png_int_32;
  181797. typedef unsigned short png_uint_16;
  181798. typedef short png_int_16;
  181799. typedef unsigned char png_byte;
  181800. /* This is usually size_t. It is typedef'ed just in case you need it to
  181801. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181802. #ifdef PNG_SIZE_T
  181803. typedef PNG_SIZE_T png_size_t;
  181804. # define png_sizeof(x) png_convert_size(sizeof (x))
  181805. #else
  181806. typedef size_t png_size_t;
  181807. # define png_sizeof(x) sizeof (x)
  181808. #endif
  181809. /* The following is needed for medium model support. It cannot be in the
  181810. * PNG_INTERNAL section. Needs modification for other compilers besides
  181811. * MSC. Model independent support declares all arrays and pointers to be
  181812. * large using the far keyword. The zlib version used must also support
  181813. * model independent data. As of version zlib 1.0.4, the necessary changes
  181814. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181815. * changes that are needed. (Tim Wegner)
  181816. */
  181817. /* Separate compiler dependencies (problem here is that zlib.h always
  181818. defines FAR. (SJT) */
  181819. #ifdef __BORLANDC__
  181820. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181821. # define LDATA 1
  181822. # else
  181823. # define LDATA 0
  181824. # endif
  181825. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181826. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181827. # define PNG_MAX_MALLOC_64K
  181828. # if (LDATA != 1)
  181829. # ifndef FAR
  181830. # define FAR __far
  181831. # endif
  181832. # define USE_FAR_KEYWORD
  181833. # endif /* LDATA != 1 */
  181834. /* Possibly useful for moving data out of default segment.
  181835. * Uncomment it if you want. Could also define FARDATA as
  181836. * const if your compiler supports it. (SJT)
  181837. # define FARDATA FAR
  181838. */
  181839. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181840. #endif /* __BORLANDC__ */
  181841. /* Suggest testing for specific compiler first before testing for
  181842. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181843. * making reliance oncertain keywords suspect. (SJT)
  181844. */
  181845. /* MSC Medium model */
  181846. #if defined(FAR)
  181847. # if defined(M_I86MM)
  181848. # define USE_FAR_KEYWORD
  181849. # define FARDATA FAR
  181850. # include <dos.h>
  181851. # endif
  181852. #endif
  181853. /* SJT: default case */
  181854. #ifndef FAR
  181855. # define FAR
  181856. #endif
  181857. /* At this point FAR is always defined */
  181858. #ifndef FARDATA
  181859. # define FARDATA
  181860. #endif
  181861. /* Typedef for floating-point numbers that are converted
  181862. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181863. typedef png_int_32 png_fixed_point;
  181864. /* Add typedefs for pointers */
  181865. typedef void FAR * png_voidp;
  181866. typedef png_byte FAR * png_bytep;
  181867. typedef png_uint_32 FAR * png_uint_32p;
  181868. typedef png_int_32 FAR * png_int_32p;
  181869. typedef png_uint_16 FAR * png_uint_16p;
  181870. typedef png_int_16 FAR * png_int_16p;
  181871. typedef PNG_CONST char FAR * png_const_charp;
  181872. typedef char FAR * png_charp;
  181873. typedef png_fixed_point FAR * png_fixed_point_p;
  181874. #ifndef PNG_NO_STDIO
  181875. #if defined(_WIN32_WCE)
  181876. typedef HANDLE png_FILE_p;
  181877. #else
  181878. typedef FILE * png_FILE_p;
  181879. #endif
  181880. #endif
  181881. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181882. typedef double FAR * png_doublep;
  181883. #endif
  181884. /* Pointers to pointers; i.e. arrays */
  181885. typedef png_byte FAR * FAR * png_bytepp;
  181886. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181887. typedef png_int_32 FAR * FAR * png_int_32pp;
  181888. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181889. typedef png_int_16 FAR * FAR * png_int_16pp;
  181890. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181891. typedef char FAR * FAR * png_charpp;
  181892. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181893. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181894. typedef double FAR * FAR * png_doublepp;
  181895. #endif
  181896. /* Pointers to pointers to pointers; i.e., pointer to array */
  181897. typedef char FAR * FAR * FAR * png_charppp;
  181898. #if 0
  181899. /* SPC - Is this stuff deprecated? */
  181900. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181901. /* libpng typedefs for types in zlib. If zlib changes
  181902. * or another compression library is used, then change these.
  181903. * Eliminates need to change all the source files.
  181904. */
  181905. typedef charf * png_zcharp;
  181906. typedef charf * FAR * png_zcharpp;
  181907. typedef z_stream FAR * png_zstreamp;
  181908. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181909. /*
  181910. * Define PNG_BUILD_DLL if the module being built is a Windows
  181911. * LIBPNG DLL.
  181912. *
  181913. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181914. * It is equivalent to Microsoft predefined macro _DLL that is
  181915. * automatically defined when you compile using the share
  181916. * version of the CRT (C Run-Time library)
  181917. *
  181918. * The cygwin mods make this behavior a little different:
  181919. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181920. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181921. * -or- if you are building an application that you want to link to the
  181922. * static library.
  181923. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181924. * the other flags is defined.
  181925. */
  181926. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181927. # define PNG_DLL
  181928. #endif
  181929. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181930. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181931. * command-line override
  181932. */
  181933. #if defined(__CYGWIN__)
  181934. # if !defined(PNG_STATIC)
  181935. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181936. # undef PNG_USE_GLOBAL_ARRAYS
  181937. # endif
  181938. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181939. # define PNG_USE_LOCAL_ARRAYS
  181940. # endif
  181941. # else
  181942. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181943. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181944. # undef PNG_USE_GLOBAL_ARRAYS
  181945. # endif
  181946. # endif
  181947. # endif
  181948. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181949. # define PNG_USE_LOCAL_ARRAYS
  181950. # endif
  181951. #endif
  181952. /* Do not use global arrays (helps with building DLL's)
  181953. * They are no longer used in libpng itself, since version 1.0.5c,
  181954. * but might be required for some pre-1.0.5c applications.
  181955. */
  181956. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181957. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181958. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181959. # define PNG_USE_LOCAL_ARRAYS
  181960. # else
  181961. # define PNG_USE_GLOBAL_ARRAYS
  181962. # endif
  181963. #endif
  181964. #if defined(__CYGWIN__)
  181965. # undef PNGAPI
  181966. # define PNGAPI __cdecl
  181967. # undef PNG_IMPEXP
  181968. # define PNG_IMPEXP
  181969. #endif
  181970. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181971. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181972. * Don't ignore those warnings; you must also reset the default calling
  181973. * convention in your compiler to match your PNGAPI, and you must build
  181974. * zlib and your applications the same way you build libpng.
  181975. */
  181976. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181977. # ifndef PNG_NO_MODULEDEF
  181978. # define PNG_NO_MODULEDEF
  181979. # endif
  181980. #endif
  181981. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181982. # define PNG_IMPEXP
  181983. #endif
  181984. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181985. (( defined(_Windows) || defined(_WINDOWS) || \
  181986. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181987. # ifndef PNGAPI
  181988. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181989. # define PNGAPI __cdecl
  181990. # else
  181991. # define PNGAPI _cdecl
  181992. # endif
  181993. # endif
  181994. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181995. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181996. # define PNG_IMPEXP
  181997. # endif
  181998. # if !defined(PNG_IMPEXP)
  181999. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182000. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182001. /* Borland/Microsoft */
  182002. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182003. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182004. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182005. # else
  182006. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182007. # if defined(PNG_BUILD_DLL)
  182008. # define PNG_IMPEXP __export
  182009. # else
  182010. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182011. VC++ */
  182012. # endif /* Exists in Borland C++ for
  182013. C++ classes (== huge) */
  182014. # endif
  182015. # endif
  182016. # if !defined(PNG_IMPEXP)
  182017. # if defined(PNG_BUILD_DLL)
  182018. # define PNG_IMPEXP __declspec(dllexport)
  182019. # else
  182020. # define PNG_IMPEXP __declspec(dllimport)
  182021. # endif
  182022. # endif
  182023. # endif /* PNG_IMPEXP */
  182024. #else /* !(DLL || non-cygwin WINDOWS) */
  182025. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182026. # ifndef PNGAPI
  182027. # define PNGAPI _System
  182028. # endif
  182029. # else
  182030. # if 0 /* ... other platforms, with other meanings */
  182031. # endif
  182032. # endif
  182033. #endif
  182034. #ifndef PNGAPI
  182035. # define PNGAPI
  182036. #endif
  182037. #ifndef PNG_IMPEXP
  182038. # define PNG_IMPEXP
  182039. #endif
  182040. #ifdef PNG_BUILDSYMS
  182041. # ifndef PNG_EXPORT
  182042. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182043. # endif
  182044. # ifdef PNG_USE_GLOBAL_ARRAYS
  182045. # ifndef PNG_EXPORT_VAR
  182046. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182047. # endif
  182048. # endif
  182049. #endif
  182050. #ifndef PNG_EXPORT
  182051. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182052. #endif
  182053. #ifdef PNG_USE_GLOBAL_ARRAYS
  182054. # ifndef PNG_EXPORT_VAR
  182055. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182056. # endif
  182057. #endif
  182058. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182059. * functions that are passed far data must be model independent.
  182060. */
  182061. #ifndef PNG_ABORT
  182062. # define PNG_ABORT() abort()
  182063. #endif
  182064. #ifdef PNG_SETJMP_SUPPORTED
  182065. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182066. #else
  182067. # define png_jmpbuf(png_ptr) \
  182068. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182069. #endif
  182070. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182071. /* use this to make far-to-near assignments */
  182072. # define CHECK 1
  182073. # define NOCHECK 0
  182074. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182075. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182076. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182077. # define png_strcpy _fstrcpy
  182078. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182079. # define png_strlen _fstrlen
  182080. # define png_memcmp _fmemcmp /* SJT: added */
  182081. # define png_memcpy _fmemcpy
  182082. # define png_memset _fmemset
  182083. #else /* use the usual functions */
  182084. # define CVT_PTR(ptr) (ptr)
  182085. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182086. # ifndef PNG_NO_SNPRINTF
  182087. # ifdef _MSC_VER
  182088. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182089. # define png_snprintf2 _snprintf
  182090. # define png_snprintf6 _snprintf
  182091. # else
  182092. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182093. # define png_snprintf2 snprintf
  182094. # define png_snprintf6 snprintf
  182095. # endif
  182096. # else
  182097. /* You don't have or don't want to use snprintf(). Caution: Using
  182098. * sprintf instead of snprintf exposes your application to accidental
  182099. * or malevolent buffer overflows. If you don't have snprintf()
  182100. * as a general rule you should provide one (you can get one from
  182101. * Portable OpenSSH). */
  182102. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182103. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182104. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182105. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182106. # endif
  182107. # define png_strcpy strcpy
  182108. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182109. # define png_strlen strlen
  182110. # define png_memcmp memcmp /* SJT: added */
  182111. # define png_memcpy memcpy
  182112. # define png_memset memset
  182113. #endif
  182114. /* End of memory model independent support */
  182115. /* Just a little check that someone hasn't tried to define something
  182116. * contradictory.
  182117. */
  182118. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182119. # undef PNG_ZBUF_SIZE
  182120. # define PNG_ZBUF_SIZE 65536L
  182121. #endif
  182122. /* Added at libpng-1.2.8 */
  182123. #endif /* PNG_VERSION_INFO_ONLY */
  182124. #endif /* PNGCONF_H */
  182125. /*** End of inlined file: pngconf.h ***/
  182126. #ifdef _MSC_VER
  182127. #pragma warning (disable: 4996 4100)
  182128. #endif
  182129. /*
  182130. * Added at libpng-1.2.8 */
  182131. /* Ref MSDN: Private as priority over Special
  182132. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182133. * procedures. If this value is given, the StringFileInfo block must
  182134. * contain a PrivateBuild string.
  182135. *
  182136. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182137. * standard release procedures but is a variation of the standard
  182138. * file of the same version number. If this value is given, the
  182139. * StringFileInfo block must contain a SpecialBuild string.
  182140. */
  182141. #if defined(PNG_USER_PRIVATEBUILD)
  182142. # define PNG_LIBPNG_BUILD_TYPE \
  182143. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182144. #else
  182145. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182146. # define PNG_LIBPNG_BUILD_TYPE \
  182147. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182148. # else
  182149. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182150. # endif
  182151. #endif
  182152. #ifndef PNG_VERSION_INFO_ONLY
  182153. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182154. #ifdef __cplusplus
  182155. //extern "C" {
  182156. #endif /* __cplusplus */
  182157. /* This file is arranged in several sections. The first section contains
  182158. * structure and type definitions. The second section contains the external
  182159. * library functions, while the third has the internal library functions,
  182160. * which applications aren't expected to use directly.
  182161. */
  182162. #ifndef PNG_NO_TYPECAST_NULL
  182163. #define int_p_NULL (int *)NULL
  182164. #define png_bytep_NULL (png_bytep)NULL
  182165. #define png_bytepp_NULL (png_bytepp)NULL
  182166. #define png_doublep_NULL (png_doublep)NULL
  182167. #define png_error_ptr_NULL (png_error_ptr)NULL
  182168. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182169. #define png_free_ptr_NULL (png_free_ptr)NULL
  182170. #define png_infopp_NULL (png_infopp)NULL
  182171. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182172. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182173. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182174. #define png_structp_NULL (png_structp)NULL
  182175. #define png_uint_16p_NULL (png_uint_16p)NULL
  182176. #define png_voidp_NULL (png_voidp)NULL
  182177. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182178. #else
  182179. #define int_p_NULL NULL
  182180. #define png_bytep_NULL NULL
  182181. #define png_bytepp_NULL NULL
  182182. #define png_doublep_NULL NULL
  182183. #define png_error_ptr_NULL NULL
  182184. #define png_flush_ptr_NULL NULL
  182185. #define png_free_ptr_NULL NULL
  182186. #define png_infopp_NULL NULL
  182187. #define png_malloc_ptr_NULL NULL
  182188. #define png_read_status_ptr_NULL NULL
  182189. #define png_rw_ptr_NULL NULL
  182190. #define png_structp_NULL NULL
  182191. #define png_uint_16p_NULL NULL
  182192. #define png_voidp_NULL NULL
  182193. #define png_write_status_ptr_NULL NULL
  182194. #endif
  182195. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182196. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182197. /* Version information for C files, stored in png.c. This had better match
  182198. * the version above.
  182199. */
  182200. #ifdef PNG_USE_GLOBAL_ARRAYS
  182201. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182202. /* need room for 99.99.99beta99z */
  182203. #else
  182204. #define png_libpng_ver png_get_header_ver(NULL)
  182205. #endif
  182206. #ifdef PNG_USE_GLOBAL_ARRAYS
  182207. /* This was removed in version 1.0.5c */
  182208. /* Structures to facilitate easy interlacing. See png.c for more details */
  182209. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182210. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182211. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182212. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182213. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182214. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182215. /* This isn't currently used. If you need it, see png.c for more details.
  182216. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182217. */
  182218. #endif
  182219. #endif /* PNG_NO_EXTERN */
  182220. /* Three color definitions. The order of the red, green, and blue, (and the
  182221. * exact size) is not important, although the size of the fields need to
  182222. * be png_byte or png_uint_16 (as defined below).
  182223. */
  182224. typedef struct png_color_struct
  182225. {
  182226. png_byte red;
  182227. png_byte green;
  182228. png_byte blue;
  182229. } png_color;
  182230. typedef png_color FAR * png_colorp;
  182231. typedef png_color FAR * FAR * png_colorpp;
  182232. typedef struct png_color_16_struct
  182233. {
  182234. png_byte index; /* used for palette files */
  182235. png_uint_16 red; /* for use in red green blue files */
  182236. png_uint_16 green;
  182237. png_uint_16 blue;
  182238. png_uint_16 gray; /* for use in grayscale files */
  182239. } png_color_16;
  182240. typedef png_color_16 FAR * png_color_16p;
  182241. typedef png_color_16 FAR * FAR * png_color_16pp;
  182242. typedef struct png_color_8_struct
  182243. {
  182244. png_byte red; /* for use in red green blue files */
  182245. png_byte green;
  182246. png_byte blue;
  182247. png_byte gray; /* for use in grayscale files */
  182248. png_byte alpha; /* for alpha channel files */
  182249. } png_color_8;
  182250. typedef png_color_8 FAR * png_color_8p;
  182251. typedef png_color_8 FAR * FAR * png_color_8pp;
  182252. /*
  182253. * The following two structures are used for the in-core representation
  182254. * of sPLT chunks.
  182255. */
  182256. typedef struct png_sPLT_entry_struct
  182257. {
  182258. png_uint_16 red;
  182259. png_uint_16 green;
  182260. png_uint_16 blue;
  182261. png_uint_16 alpha;
  182262. png_uint_16 frequency;
  182263. } png_sPLT_entry;
  182264. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182265. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182266. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182267. * occupy the LSB of their respective members, and the MSB of each member
  182268. * is zero-filled. The frequency member always occupies the full 16 bits.
  182269. */
  182270. typedef struct png_sPLT_struct
  182271. {
  182272. png_charp name; /* palette name */
  182273. png_byte depth; /* depth of palette samples */
  182274. png_sPLT_entryp entries; /* palette entries */
  182275. png_int_32 nentries; /* number of palette entries */
  182276. } png_sPLT_t;
  182277. typedef png_sPLT_t FAR * png_sPLT_tp;
  182278. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182279. #ifdef PNG_TEXT_SUPPORTED
  182280. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182281. * and whether that contents is compressed or not. The "key" field
  182282. * points to a regular zero-terminated C string. The "text", "lang", and
  182283. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182284. * However, the * structure returned by png_get_text() will always contain
  182285. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182286. * so they can be safely used in printf() and other string-handling functions.
  182287. */
  182288. typedef struct png_text_struct
  182289. {
  182290. int compression; /* compression value:
  182291. -1: tEXt, none
  182292. 0: zTXt, deflate
  182293. 1: iTXt, none
  182294. 2: iTXt, deflate */
  182295. png_charp key; /* keyword, 1-79 character description of "text" */
  182296. png_charp text; /* comment, may be an empty string (ie "")
  182297. or a NULL pointer */
  182298. png_size_t text_length; /* length of the text string */
  182299. #ifdef PNG_iTXt_SUPPORTED
  182300. png_size_t itxt_length; /* length of the itxt string */
  182301. png_charp lang; /* language code, 0-79 characters
  182302. or a NULL pointer */
  182303. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182304. chars or a NULL pointer */
  182305. #endif
  182306. } png_text;
  182307. typedef png_text FAR * png_textp;
  182308. typedef png_text FAR * FAR * png_textpp;
  182309. #endif
  182310. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182311. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182312. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182313. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182314. #define PNG_TEXT_COMPRESSION_NONE -1
  182315. #define PNG_TEXT_COMPRESSION_zTXt 0
  182316. #define PNG_ITXT_COMPRESSION_NONE 1
  182317. #define PNG_ITXT_COMPRESSION_zTXt 2
  182318. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182319. /* png_time is a way to hold the time in an machine independent way.
  182320. * Two conversions are provided, both from time_t and struct tm. There
  182321. * is no portable way to convert to either of these structures, as far
  182322. * as I know. If you know of a portable way, send it to me. As a side
  182323. * note - PNG has always been Year 2000 compliant!
  182324. */
  182325. typedef struct png_time_struct
  182326. {
  182327. png_uint_16 year; /* full year, as in, 1995 */
  182328. png_byte month; /* month of year, 1 - 12 */
  182329. png_byte day; /* day of month, 1 - 31 */
  182330. png_byte hour; /* hour of day, 0 - 23 */
  182331. png_byte minute; /* minute of hour, 0 - 59 */
  182332. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182333. } png_time;
  182334. typedef png_time FAR * png_timep;
  182335. typedef png_time FAR * FAR * png_timepp;
  182336. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182337. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182338. * no specific support. The idea is that we can use this to queue
  182339. * up private chunks for output even though the library doesn't actually
  182340. * know about their semantics.
  182341. */
  182342. typedef struct png_unknown_chunk_t
  182343. {
  182344. png_byte name[5];
  182345. png_byte *data;
  182346. png_size_t size;
  182347. /* libpng-using applications should NOT directly modify this byte. */
  182348. png_byte location; /* mode of operation at read time */
  182349. }
  182350. png_unknown_chunk;
  182351. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182352. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182353. #endif
  182354. /* png_info is a structure that holds the information in a PNG file so
  182355. * that the application can find out the characteristics of the image.
  182356. * If you are reading the file, this structure will tell you what is
  182357. * in the PNG file. If you are writing the file, fill in the information
  182358. * you want to put into the PNG file, then call png_write_info().
  182359. * The names chosen should be very close to the PNG specification, so
  182360. * consult that document for information about the meaning of each field.
  182361. *
  182362. * With libpng < 0.95, it was only possible to directly set and read the
  182363. * the values in the png_info_struct, which meant that the contents and
  182364. * order of the values had to remain fixed. With libpng 0.95 and later,
  182365. * however, there are now functions that abstract the contents of
  182366. * png_info_struct from the application, so this makes it easier to use
  182367. * libpng with dynamic libraries, and even makes it possible to use
  182368. * libraries that don't have all of the libpng ancillary chunk-handing
  182369. * functionality.
  182370. *
  182371. * In any case, the order of the parameters in png_info_struct should NOT
  182372. * be changed for as long as possible to keep compatibility with applications
  182373. * that use the old direct-access method with png_info_struct.
  182374. *
  182375. * The following members may have allocated storage attached that should be
  182376. * cleaned up before the structure is discarded: palette, trans, text,
  182377. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182378. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182379. * are automatically freed when the info structure is deallocated, if they were
  182380. * allocated internally by libpng. This behavior can be changed by means
  182381. * of the png_data_freer() function.
  182382. *
  182383. * More allocation details: all the chunk-reading functions that
  182384. * change these members go through the corresponding png_set_*
  182385. * functions. A function to clear these members is available: see
  182386. * png_free_data(). The png_set_* functions do not depend on being
  182387. * able to point info structure members to any of the storage they are
  182388. * passed (they make their own copies), EXCEPT that the png_set_text
  182389. * functions use the same storage passed to them in the text_ptr or
  182390. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182391. * functions do not make their own copies.
  182392. */
  182393. typedef struct png_info_struct
  182394. {
  182395. /* the following are necessary for every PNG file */
  182396. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182397. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182398. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182399. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182400. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182401. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182402. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182403. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182404. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182405. /* The following three should have been named *_method not *_type */
  182406. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182407. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182408. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182409. /* The following is informational only on read, and not used on writes. */
  182410. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182411. png_byte pixel_depth; /* number of bits per pixel */
  182412. png_byte spare_byte; /* to align the data, and for future use */
  182413. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182414. /* The rest of the data is optional. If you are reading, check the
  182415. * valid field to see if the information in these are valid. If you
  182416. * are writing, set the valid field to those chunks you want written,
  182417. * and initialize the appropriate fields below.
  182418. */
  182419. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182420. /* The gAMA chunk describes the gamma characteristics of the system
  182421. * on which the image was created, normally in the range [1.0, 2.5].
  182422. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182423. */
  182424. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182425. #endif
  182426. #if defined(PNG_sRGB_SUPPORTED)
  182427. /* GR-P, 0.96a */
  182428. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182429. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182430. #endif
  182431. #if defined(PNG_TEXT_SUPPORTED)
  182432. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182433. * uncompressed, compressed, and optionally compressed forms, respectively.
  182434. * The data in "text" is an array of pointers to uncompressed,
  182435. * null-terminated C strings. Each chunk has a keyword that describes the
  182436. * textual data contained in that chunk. Keywords are not required to be
  182437. * unique, and the text string may be empty. Any number of text chunks may
  182438. * be in an image.
  182439. */
  182440. int num_text; /* number of comments read/to write */
  182441. int max_text; /* current size of text array */
  182442. png_textp text; /* array of comments read/to write */
  182443. #endif /* PNG_TEXT_SUPPORTED */
  182444. #if defined(PNG_tIME_SUPPORTED)
  182445. /* The tIME chunk holds the last time the displayed image data was
  182446. * modified. See the png_time struct for the contents of this struct.
  182447. */
  182448. png_time mod_time;
  182449. #endif
  182450. #if defined(PNG_sBIT_SUPPORTED)
  182451. /* The sBIT chunk specifies the number of significant high-order bits
  182452. * in the pixel data. Values are in the range [1, bit_depth], and are
  182453. * only specified for the channels in the pixel data. The contents of
  182454. * the low-order bits is not specified. Data is valid if
  182455. * (valid & PNG_INFO_sBIT) is non-zero.
  182456. */
  182457. png_color_8 sig_bit; /* significant bits in color channels */
  182458. #endif
  182459. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182460. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182461. /* The tRNS chunk supplies transparency data for paletted images and
  182462. * other image types that don't need a full alpha channel. There are
  182463. * "num_trans" transparency values for a paletted image, stored in the
  182464. * same order as the palette colors, starting from index 0. Values
  182465. * for the data are in the range [0, 255], ranging from fully transparent
  182466. * to fully opaque, respectively. For non-paletted images, there is a
  182467. * single color specified that should be treated as fully transparent.
  182468. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182469. */
  182470. png_bytep trans; /* transparent values for paletted image */
  182471. png_color_16 trans_values; /* transparent color for non-palette image */
  182472. #endif
  182473. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182474. /* The bKGD chunk gives the suggested image background color if the
  182475. * display program does not have its own background color and the image
  182476. * is needs to composited onto a background before display. The colors
  182477. * in "background" are normally in the same color space/depth as the
  182478. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182479. */
  182480. png_color_16 background;
  182481. #endif
  182482. #if defined(PNG_oFFs_SUPPORTED)
  182483. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182484. * and downwards from the top-left corner of the display, page, or other
  182485. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182486. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182487. */
  182488. png_int_32 x_offset; /* x offset on page */
  182489. png_int_32 y_offset; /* y offset on page */
  182490. png_byte offset_unit_type; /* offset units type */
  182491. #endif
  182492. #if defined(PNG_pHYs_SUPPORTED)
  182493. /* The pHYs chunk gives the physical pixel density of the image for
  182494. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182495. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182496. */
  182497. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182498. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182499. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182500. #endif
  182501. #if defined(PNG_hIST_SUPPORTED)
  182502. /* The hIST chunk contains the relative frequency or importance of the
  182503. * various palette entries, so that a viewer can intelligently select a
  182504. * reduced-color palette, if required. Data is an array of "num_palette"
  182505. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182506. * is non-zero.
  182507. */
  182508. png_uint_16p hist;
  182509. #endif
  182510. #ifdef PNG_cHRM_SUPPORTED
  182511. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182512. * on which the PNG was created. This data allows the viewer to do gamut
  182513. * mapping of the input image to ensure that the viewer sees the same
  182514. * colors in the image as the creator. Values are in the range
  182515. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182516. */
  182517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182518. float x_white;
  182519. float y_white;
  182520. float x_red;
  182521. float y_red;
  182522. float x_green;
  182523. float y_green;
  182524. float x_blue;
  182525. float y_blue;
  182526. #endif
  182527. #endif
  182528. #if defined(PNG_pCAL_SUPPORTED)
  182529. /* The pCAL chunk describes a transformation between the stored pixel
  182530. * values and original physical data values used to create the image.
  182531. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182532. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182533. * (possibly non-linear) transformation function given by "pcal_type"
  182534. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182535. * defines below, and the PNG-Group's PNG extensions document for a
  182536. * complete description of the transformations and how they should be
  182537. * implemented, and for a description of the ASCII parameter strings.
  182538. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182539. */
  182540. png_charp pcal_purpose; /* pCAL chunk description string */
  182541. png_int_32 pcal_X0; /* minimum value */
  182542. png_int_32 pcal_X1; /* maximum value */
  182543. png_charp pcal_units; /* Latin-1 string giving physical units */
  182544. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182545. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182546. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182547. #endif
  182548. /* New members added in libpng-1.0.6 */
  182549. #ifdef PNG_FREE_ME_SUPPORTED
  182550. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182551. #endif
  182552. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182553. /* storage for unknown chunks that the library doesn't recognize. */
  182554. png_unknown_chunkp unknown_chunks;
  182555. png_size_t unknown_chunks_num;
  182556. #endif
  182557. #if defined(PNG_iCCP_SUPPORTED)
  182558. /* iCCP chunk data. */
  182559. png_charp iccp_name; /* profile name */
  182560. png_charp iccp_profile; /* International Color Consortium profile data */
  182561. /* Note to maintainer: should be png_bytep */
  182562. png_uint_32 iccp_proflen; /* ICC profile data length */
  182563. png_byte iccp_compression; /* Always zero */
  182564. #endif
  182565. #if defined(PNG_sPLT_SUPPORTED)
  182566. /* data on sPLT chunks (there may be more than one). */
  182567. png_sPLT_tp splt_palettes;
  182568. png_uint_32 splt_palettes_num;
  182569. #endif
  182570. #if defined(PNG_sCAL_SUPPORTED)
  182571. /* The sCAL chunk describes the actual physical dimensions of the
  182572. * subject matter of the graphic. The chunk contains a unit specification
  182573. * a byte value, and two ASCII strings representing floating-point
  182574. * values. The values are width and height corresponsing to one pixel
  182575. * in the image. This external representation is converted to double
  182576. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182577. */
  182578. png_byte scal_unit; /* unit of physical scale */
  182579. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182580. double scal_pixel_width; /* width of one pixel */
  182581. double scal_pixel_height; /* height of one pixel */
  182582. #endif
  182583. #ifdef PNG_FIXED_POINT_SUPPORTED
  182584. png_charp scal_s_width; /* string containing height */
  182585. png_charp scal_s_height; /* string containing width */
  182586. #endif
  182587. #endif
  182588. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182589. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182590. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182591. png_bytepp row_pointers; /* the image bits */
  182592. #endif
  182593. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182594. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182595. #endif
  182596. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182597. png_fixed_point int_x_white;
  182598. png_fixed_point int_y_white;
  182599. png_fixed_point int_x_red;
  182600. png_fixed_point int_y_red;
  182601. png_fixed_point int_x_green;
  182602. png_fixed_point int_y_green;
  182603. png_fixed_point int_x_blue;
  182604. png_fixed_point int_y_blue;
  182605. #endif
  182606. } png_info;
  182607. typedef png_info FAR * png_infop;
  182608. typedef png_info FAR * FAR * png_infopp;
  182609. /* Maximum positive integer used in PNG is (2^31)-1 */
  182610. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182611. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182612. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182613. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182614. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182615. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182616. #endif
  182617. /* These describe the color_type field in png_info. */
  182618. /* color type masks */
  182619. #define PNG_COLOR_MASK_PALETTE 1
  182620. #define PNG_COLOR_MASK_COLOR 2
  182621. #define PNG_COLOR_MASK_ALPHA 4
  182622. /* color types. Note that not all combinations are legal */
  182623. #define PNG_COLOR_TYPE_GRAY 0
  182624. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182625. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182626. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182627. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182628. /* aliases */
  182629. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182630. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182631. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182632. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182633. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182634. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182635. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182636. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182637. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182638. /* These are for the interlacing type. These values should NOT be changed. */
  182639. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182640. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182641. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182642. /* These are for the oFFs chunk. These values should NOT be changed. */
  182643. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182644. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182645. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182646. /* These are for the pCAL chunk. These values should NOT be changed. */
  182647. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182648. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182649. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182650. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182651. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182652. /* These are for the sCAL chunk. These values should NOT be changed. */
  182653. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182654. #define PNG_SCALE_METER 1 /* meters per pixel */
  182655. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182656. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182657. /* These are for the pHYs chunk. These values should NOT be changed. */
  182658. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182659. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182660. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182661. /* These are for the sRGB chunk. These values should NOT be changed. */
  182662. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182663. #define PNG_sRGB_INTENT_RELATIVE 1
  182664. #define PNG_sRGB_INTENT_SATURATION 2
  182665. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182666. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182667. /* This is for text chunks */
  182668. #define PNG_KEYWORD_MAX_LENGTH 79
  182669. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182670. #define PNG_MAX_PALETTE_LENGTH 256
  182671. /* These determine if an ancillary chunk's data has been successfully read
  182672. * from the PNG header, or if the application has filled in the corresponding
  182673. * data in the info_struct to be written into the output file. The values
  182674. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182675. */
  182676. #define PNG_INFO_gAMA 0x0001
  182677. #define PNG_INFO_sBIT 0x0002
  182678. #define PNG_INFO_cHRM 0x0004
  182679. #define PNG_INFO_PLTE 0x0008
  182680. #define PNG_INFO_tRNS 0x0010
  182681. #define PNG_INFO_bKGD 0x0020
  182682. #define PNG_INFO_hIST 0x0040
  182683. #define PNG_INFO_pHYs 0x0080
  182684. #define PNG_INFO_oFFs 0x0100
  182685. #define PNG_INFO_tIME 0x0200
  182686. #define PNG_INFO_pCAL 0x0400
  182687. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182688. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182689. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182690. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182691. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182692. /* This is used for the transformation routines, as some of them
  182693. * change these values for the row. It also should enable using
  182694. * the routines for other purposes.
  182695. */
  182696. typedef struct png_row_info_struct
  182697. {
  182698. png_uint_32 width; /* width of row */
  182699. png_uint_32 rowbytes; /* number of bytes in row */
  182700. png_byte color_type; /* color type of row */
  182701. png_byte bit_depth; /* bit depth of row */
  182702. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182703. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182704. } png_row_info;
  182705. typedef png_row_info FAR * png_row_infop;
  182706. typedef png_row_info FAR * FAR * png_row_infopp;
  182707. /* These are the function types for the I/O functions and for the functions
  182708. * that allow the user to override the default I/O functions with his or her
  182709. * own. The png_error_ptr type should match that of user-supplied warning
  182710. * and error functions, while the png_rw_ptr type should match that of the
  182711. * user read/write data functions.
  182712. */
  182713. typedef struct png_struct_def png_struct;
  182714. typedef png_struct FAR * png_structp;
  182715. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182716. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182717. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182718. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182719. int));
  182720. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182721. int));
  182722. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182723. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182724. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182725. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182726. png_uint_32, int));
  182727. #endif
  182728. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182729. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182730. defined(PNG_LEGACY_SUPPORTED)
  182731. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182732. png_row_infop, png_bytep));
  182733. #endif
  182734. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182735. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182736. #endif
  182737. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182738. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182739. #endif
  182740. /* Transform masks for the high-level interface */
  182741. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182742. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182743. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182744. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182745. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182746. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182747. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182748. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182749. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182750. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182751. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182752. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182753. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182754. /* Flags for MNG supported features */
  182755. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182756. #define PNG_FLAG_MNG_FILTER_64 0x04
  182757. #define PNG_ALL_MNG_FEATURES 0x05
  182758. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182759. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182760. /* The structure that holds the information to read and write PNG files.
  182761. * The only people who need to care about what is inside of this are the
  182762. * people who will be modifying the library for their own special needs.
  182763. * It should NOT be accessed directly by an application, except to store
  182764. * the jmp_buf.
  182765. */
  182766. struct png_struct_def
  182767. {
  182768. #ifdef PNG_SETJMP_SUPPORTED
  182769. jmp_buf jmpbuf; /* used in png_error */
  182770. #endif
  182771. png_error_ptr error_fn; /* function for printing errors and aborting */
  182772. png_error_ptr warning_fn; /* function for printing warnings */
  182773. png_voidp error_ptr; /* user supplied struct for error functions */
  182774. png_rw_ptr write_data_fn; /* function for writing output data */
  182775. png_rw_ptr read_data_fn; /* function for reading input data */
  182776. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182777. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182778. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182779. #endif
  182780. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182781. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182782. #endif
  182783. /* These were added in libpng-1.0.2 */
  182784. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182785. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182786. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182787. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182788. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182789. png_byte user_transform_channels; /* channels in user transformed pixels */
  182790. #endif
  182791. #endif
  182792. png_uint_32 mode; /* tells us where we are in the PNG file */
  182793. png_uint_32 flags; /* flags indicating various things to libpng */
  182794. png_uint_32 transformations; /* which transformations to perform */
  182795. z_stream zstream; /* pointer to decompression structure (below) */
  182796. png_bytep zbuf; /* buffer for zlib */
  182797. png_size_t zbuf_size; /* size of zbuf */
  182798. int zlib_level; /* holds zlib compression level */
  182799. int zlib_method; /* holds zlib compression method */
  182800. int zlib_window_bits; /* holds zlib compression window bits */
  182801. int zlib_mem_level; /* holds zlib compression memory level */
  182802. int zlib_strategy; /* holds zlib compression strategy */
  182803. png_uint_32 width; /* width of image in pixels */
  182804. png_uint_32 height; /* height of image in pixels */
  182805. png_uint_32 num_rows; /* number of rows in current pass */
  182806. png_uint_32 usr_width; /* width of row at start of write */
  182807. png_uint_32 rowbytes; /* size of row in bytes */
  182808. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182809. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182810. png_uint_32 row_number; /* current row in interlace pass */
  182811. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182812. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182813. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182814. png_bytep up_row; /* buffer to save "up" row when filtering */
  182815. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182816. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182817. png_row_info row_info; /* used for transformation routines */
  182818. png_uint_32 idat_size; /* current IDAT size for read */
  182819. png_uint_32 crc; /* current chunk CRC value */
  182820. png_colorp palette; /* palette from the input file */
  182821. png_uint_16 num_palette; /* number of color entries in palette */
  182822. png_uint_16 num_trans; /* number of transparency values */
  182823. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182824. png_byte compression; /* file compression type (always 0) */
  182825. png_byte filter; /* file filter type (always 0) */
  182826. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182827. png_byte pass; /* current interlace pass (0 - 6) */
  182828. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182829. png_byte color_type; /* color type of file */
  182830. png_byte bit_depth; /* bit depth of file */
  182831. png_byte usr_bit_depth; /* bit depth of users row */
  182832. png_byte pixel_depth; /* number of bits per pixel */
  182833. png_byte channels; /* number of channels in file */
  182834. png_byte usr_channels; /* channels at start of write */
  182835. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182836. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182837. #ifdef PNG_LEGACY_SUPPORTED
  182838. png_byte filler; /* filler byte for pixel expansion */
  182839. #else
  182840. png_uint_16 filler; /* filler bytes for pixel expansion */
  182841. #endif
  182842. #endif
  182843. #if defined(PNG_bKGD_SUPPORTED)
  182844. png_byte background_gamma_type;
  182845. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182846. float background_gamma;
  182847. # endif
  182848. png_color_16 background; /* background color in screen gamma space */
  182849. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182850. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182851. #endif
  182852. #endif /* PNG_bKGD_SUPPORTED */
  182853. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182854. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182855. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182856. png_uint_32 flush_rows; /* number of rows written since last flush */
  182857. #endif
  182858. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182859. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182860. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182861. float gamma; /* file gamma value */
  182862. float screen_gamma; /* screen gamma value (display_exponent) */
  182863. #endif
  182864. #endif
  182865. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182866. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182867. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182868. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182869. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182870. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182871. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182872. #endif
  182873. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182874. png_color_8 sig_bit; /* significant bits in each available channel */
  182875. #endif
  182876. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182877. png_color_8 shift; /* shift for significant bit tranformation */
  182878. #endif
  182879. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182880. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182881. png_bytep trans; /* transparency values for paletted files */
  182882. png_color_16 trans_values; /* transparency values for non-paletted files */
  182883. #endif
  182884. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182885. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182886. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182887. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182888. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182889. png_progressive_end_ptr end_fn; /* called after image is complete */
  182890. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182891. png_bytep save_buffer; /* buffer for previously read data */
  182892. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182893. png_bytep current_buffer; /* buffer for recently used data */
  182894. png_uint_32 push_length; /* size of current input chunk */
  182895. png_uint_32 skip_length; /* bytes to skip in input data */
  182896. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182897. png_size_t save_buffer_max; /* total size of save_buffer */
  182898. png_size_t buffer_size; /* total amount of available input data */
  182899. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182900. int process_mode; /* what push library is currently doing */
  182901. int cur_palette; /* current push library palette index */
  182902. # if defined(PNG_TEXT_SUPPORTED)
  182903. png_size_t current_text_size; /* current size of text input data */
  182904. png_size_t current_text_left; /* how much text left to read in input */
  182905. png_charp current_text; /* current text chunk buffer */
  182906. png_charp current_text_ptr; /* current location in current_text */
  182907. # endif /* PNG_TEXT_SUPPORTED */
  182908. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182909. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182910. /* for the Borland special 64K segment handler */
  182911. png_bytepp offset_table_ptr;
  182912. png_bytep offset_table;
  182913. png_uint_16 offset_table_number;
  182914. png_uint_16 offset_table_count;
  182915. png_uint_16 offset_table_count_free;
  182916. #endif
  182917. #if defined(PNG_READ_DITHER_SUPPORTED)
  182918. png_bytep palette_lookup; /* lookup table for dithering */
  182919. png_bytep dither_index; /* index translation for palette files */
  182920. #endif
  182921. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182922. png_uint_16p hist; /* histogram */
  182923. #endif
  182924. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182925. png_byte heuristic_method; /* heuristic for row filter selection */
  182926. png_byte num_prev_filters; /* number of weights for previous rows */
  182927. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182928. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182929. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182930. png_uint_16p filter_costs; /* relative filter calculation cost */
  182931. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182932. #endif
  182933. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182934. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182935. #endif
  182936. /* New members added in libpng-1.0.6 */
  182937. #ifdef PNG_FREE_ME_SUPPORTED
  182938. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182939. #endif
  182940. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182941. png_voidp user_chunk_ptr;
  182942. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182943. #endif
  182944. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182945. int num_chunk_list;
  182946. png_bytep chunk_list;
  182947. #endif
  182948. /* New members added in libpng-1.0.3 */
  182949. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182950. png_byte rgb_to_gray_status;
  182951. /* These were changed from png_byte in libpng-1.0.6 */
  182952. png_uint_16 rgb_to_gray_red_coeff;
  182953. png_uint_16 rgb_to_gray_green_coeff;
  182954. png_uint_16 rgb_to_gray_blue_coeff;
  182955. #endif
  182956. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182957. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182958. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182959. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182960. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182961. #ifdef PNG_1_0_X
  182962. png_byte mng_features_permitted;
  182963. #else
  182964. png_uint_32 mng_features_permitted;
  182965. #endif /* PNG_1_0_X */
  182966. #endif
  182967. /* New member added in libpng-1.0.7 */
  182968. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182969. png_fixed_point int_gamma;
  182970. #endif
  182971. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182972. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182973. png_byte filter_type;
  182974. #endif
  182975. #if defined(PNG_1_0_X)
  182976. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182977. png_uint_32 row_buf_size;
  182978. #endif
  182979. /* New members added in libpng-1.2.0 */
  182980. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182981. # if !defined(PNG_1_0_X)
  182982. # if defined(PNG_MMX_CODE_SUPPORTED)
  182983. png_byte mmx_bitdepth_threshold;
  182984. png_uint_32 mmx_rowbytes_threshold;
  182985. # endif
  182986. png_uint_32 asm_flags;
  182987. # endif
  182988. #endif
  182989. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182990. #ifdef PNG_USER_MEM_SUPPORTED
  182991. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182992. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182993. png_free_ptr free_fn; /* function for freeing memory */
  182994. #endif
  182995. /* New member added in libpng-1.0.13 and 1.2.0 */
  182996. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182997. #if defined(PNG_READ_DITHER_SUPPORTED)
  182998. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182999. png_bytep dither_sort; /* working sort array */
  183000. png_bytep index_to_palette; /* where the original index currently is */
  183001. /* in the palette */
  183002. png_bytep palette_to_index; /* which original index points to this */
  183003. /* palette color */
  183004. #endif
  183005. /* New members added in libpng-1.0.16 and 1.2.6 */
  183006. png_byte compression_type;
  183007. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183008. png_uint_32 user_width_max;
  183009. png_uint_32 user_height_max;
  183010. #endif
  183011. /* New member added in libpng-1.0.25 and 1.2.17 */
  183012. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183013. /* storage for unknown chunk that the library doesn't recognize. */
  183014. png_unknown_chunk unknown_chunk;
  183015. #endif
  183016. };
  183017. /* This triggers a compiler error in png.c, if png.c and png.h
  183018. * do not agree upon the version number.
  183019. */
  183020. typedef png_structp version_1_2_21;
  183021. typedef png_struct FAR * FAR * png_structpp;
  183022. /* Here are the function definitions most commonly used. This is not
  183023. * the place to find out how to use libpng. See libpng.txt for the
  183024. * full explanation, see example.c for the summary. This just provides
  183025. * a simple one line description of the use of each function.
  183026. */
  183027. /* Returns the version number of the library */
  183028. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183029. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183030. * Handling more than 8 bytes from the beginning of the file is an error.
  183031. */
  183032. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183033. int num_bytes));
  183034. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183035. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183036. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183037. * start > 7 will always fail (ie return non-zero).
  183038. */
  183039. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183040. png_size_t num_to_check));
  183041. /* Simple signature checking function. This is the same as calling
  183042. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183043. */
  183044. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183045. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183046. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183047. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183048. png_error_ptr error_fn, png_error_ptr warn_fn));
  183049. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183050. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183051. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183052. png_error_ptr error_fn, png_error_ptr warn_fn));
  183053. #ifdef PNG_WRITE_SUPPORTED
  183054. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183055. PNGARG((png_structp png_ptr));
  183056. #endif
  183057. #ifdef PNG_WRITE_SUPPORTED
  183058. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183059. PNGARG((png_structp png_ptr, png_uint_32 size));
  183060. #endif
  183061. /* Reset the compression stream */
  183062. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183063. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183064. #ifdef PNG_USER_MEM_SUPPORTED
  183065. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183066. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183067. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183068. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183069. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183070. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183071. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183072. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183073. #endif
  183074. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183075. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183076. png_bytep chunk_name, png_bytep data, png_size_t length));
  183077. /* Write the start of a PNG chunk - length and chunk name. */
  183078. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183079. png_bytep chunk_name, png_uint_32 length));
  183080. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183081. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183082. png_bytep data, png_size_t length));
  183083. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183084. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183085. /* Allocate and initialize the info structure */
  183086. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183087. PNGARG((png_structp png_ptr));
  183088. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183089. /* Initialize the info structure (old interface - DEPRECATED) */
  183090. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183091. #undef png_info_init
  183092. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183093. png_sizeof(png_info));
  183094. #endif
  183095. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183096. png_size_t png_info_struct_size));
  183097. /* Writes all the PNG information before the image. */
  183098. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183099. png_infop info_ptr));
  183100. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183101. png_infop info_ptr));
  183102. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183103. /* read the information before the actual image data. */
  183104. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183105. png_infop info_ptr));
  183106. #endif
  183107. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183108. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183109. PNGARG((png_structp png_ptr, png_timep ptime));
  183110. #endif
  183111. #if !defined(_WIN32_WCE)
  183112. /* "time.h" functions are not supported on WindowsCE */
  183113. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183114. /* convert from a struct tm to png_time */
  183115. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183116. struct tm FAR * ttime));
  183117. /* convert from time_t to png_time. Uses gmtime() */
  183118. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183119. time_t ttime));
  183120. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183121. #endif /* _WIN32_WCE */
  183122. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183123. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183124. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183125. #if !defined(PNG_1_0_X)
  183126. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183127. png_ptr));
  183128. #endif
  183129. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183130. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183131. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183132. /* Deprecated */
  183133. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183134. #endif
  183135. #endif
  183136. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183137. /* Use blue, green, red order for pixels. */
  183138. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183139. #endif
  183140. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183141. /* Expand the grayscale to 24-bit RGB if necessary. */
  183142. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183143. #endif
  183144. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183145. /* Reduce RGB to grayscale. */
  183146. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183147. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183148. int error_action, double red, double green ));
  183149. #endif
  183150. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183151. int error_action, png_fixed_point red, png_fixed_point green ));
  183152. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183153. png_ptr));
  183154. #endif
  183155. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183156. png_colorp palette));
  183157. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183158. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183159. #endif
  183160. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183161. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183162. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183163. #endif
  183164. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183165. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183166. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183167. #endif
  183168. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183169. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183170. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183171. png_uint_32 filler, int flags));
  183172. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183173. #define PNG_FILLER_BEFORE 0
  183174. #define PNG_FILLER_AFTER 1
  183175. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183176. #if !defined(PNG_1_0_X)
  183177. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183178. png_uint_32 filler, int flags));
  183179. #endif
  183180. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183181. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183182. /* Swap bytes in 16-bit depth files. */
  183183. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183184. #endif
  183185. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183186. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183187. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183188. #endif
  183189. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183190. /* Swap packing order of pixels in bytes. */
  183191. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183192. #endif
  183193. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183194. /* Converts files to legal bit depths. */
  183195. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183196. png_color_8p true_bits));
  183197. #endif
  183198. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183199. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183200. /* Have the code handle the interlacing. Returns the number of passes. */
  183201. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183202. #endif
  183203. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183204. /* Invert monochrome files */
  183205. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183206. #endif
  183207. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183208. /* Handle alpha and tRNS by replacing with a background color. */
  183209. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183210. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183211. png_color_16p background_color, int background_gamma_code,
  183212. int need_expand, double background_gamma));
  183213. #endif
  183214. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183215. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183216. #define PNG_BACKGROUND_GAMMA_FILE 2
  183217. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183218. #endif
  183219. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183220. /* strip the second byte of information from a 16-bit depth file. */
  183221. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183222. #endif
  183223. #if defined(PNG_READ_DITHER_SUPPORTED)
  183224. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183225. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183226. png_colorp palette, int num_palette, int maximum_colors,
  183227. png_uint_16p histogram, int full_dither));
  183228. #endif
  183229. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183230. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183231. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183232. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183233. double screen_gamma, double default_file_gamma));
  183234. #endif
  183235. #endif
  183236. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183237. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183238. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183239. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183240. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183241. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183242. int empty_plte_permitted));
  183243. #endif
  183244. #endif
  183245. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183246. /* Set how many lines between output flushes - 0 for no flushing */
  183247. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183248. /* Flush the current PNG output buffer */
  183249. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183250. #endif
  183251. /* optional update palette with requested transformations */
  183252. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183253. /* optional call to update the users info structure */
  183254. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183255. png_infop info_ptr));
  183256. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183257. /* read one or more rows of image data. */
  183258. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183259. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183260. #endif
  183261. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183262. /* read a row of data. */
  183263. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183264. png_bytep row,
  183265. png_bytep display_row));
  183266. #endif
  183267. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183268. /* read the whole image into memory at once. */
  183269. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183270. png_bytepp image));
  183271. #endif
  183272. /* write a row of image data */
  183273. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183274. png_bytep row));
  183275. /* write a few rows of image data */
  183276. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183277. png_bytepp row, png_uint_32 num_rows));
  183278. /* write the image data */
  183279. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183280. png_bytepp image));
  183281. /* writes the end of the PNG file. */
  183282. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183283. png_infop info_ptr));
  183284. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183285. /* read the end of the PNG file. */
  183286. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183287. png_infop info_ptr));
  183288. #endif
  183289. /* free any memory associated with the png_info_struct */
  183290. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183291. png_infopp info_ptr_ptr));
  183292. /* free any memory associated with the png_struct and the png_info_structs */
  183293. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183294. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183295. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183296. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183297. png_infop end_info_ptr));
  183298. /* free any memory associated with the png_struct and the png_info_structs */
  183299. extern PNG_EXPORT(void,png_destroy_write_struct)
  183300. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183301. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183302. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183303. /* set the libpng method of handling chunk CRC errors */
  183304. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183305. int crit_action, int ancil_action));
  183306. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183307. * ancillary and critical chunks, and whether to use the data contained
  183308. * therein. Note that it is impossible to "discard" data in a critical
  183309. * chunk. For versions prior to 0.90, the action was always error/quit,
  183310. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183311. * chunks is warn/discard. These values should NOT be changed.
  183312. *
  183313. * value action:critical action:ancillary
  183314. */
  183315. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183316. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183317. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183318. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183319. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183320. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183321. /* These functions give the user control over the scan-line filtering in
  183322. * libpng and the compression methods used by zlib. These functions are
  183323. * mainly useful for testing, as the defaults should work with most users.
  183324. * Those users who are tight on memory or want faster performance at the
  183325. * expense of compression can modify them. See the compression library
  183326. * header file (zlib.h) for an explination of the compression functions.
  183327. */
  183328. /* set the filtering method(s) used by libpng. Currently, the only valid
  183329. * value for "method" is 0.
  183330. */
  183331. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183332. int filters));
  183333. /* Flags for png_set_filter() to say which filters to use. The flags
  183334. * are chosen so that they don't conflict with real filter types
  183335. * below, in case they are supplied instead of the #defined constants.
  183336. * These values should NOT be changed.
  183337. */
  183338. #define PNG_NO_FILTERS 0x00
  183339. #define PNG_FILTER_NONE 0x08
  183340. #define PNG_FILTER_SUB 0x10
  183341. #define PNG_FILTER_UP 0x20
  183342. #define PNG_FILTER_AVG 0x40
  183343. #define PNG_FILTER_PAETH 0x80
  183344. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183345. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183346. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183347. * These defines should NOT be changed.
  183348. */
  183349. #define PNG_FILTER_VALUE_NONE 0
  183350. #define PNG_FILTER_VALUE_SUB 1
  183351. #define PNG_FILTER_VALUE_UP 2
  183352. #define PNG_FILTER_VALUE_AVG 3
  183353. #define PNG_FILTER_VALUE_PAETH 4
  183354. #define PNG_FILTER_VALUE_LAST 5
  183355. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183356. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183357. * defines, either the default (minimum-sum-of-absolute-differences), or
  183358. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183359. *
  183360. * Weights are factors >= 1.0, indicating how important it is to keep the
  183361. * filter type consistent between rows. Larger numbers mean the current
  183362. * filter is that many times as likely to be the same as the "num_weights"
  183363. * previous filters. This is cumulative for each previous row with a weight.
  183364. * There needs to be "num_weights" values in "filter_weights", or it can be
  183365. * NULL if the weights aren't being specified. Weights have no influence on
  183366. * the selection of the first row filter. Well chosen weights can (in theory)
  183367. * improve the compression for a given image.
  183368. *
  183369. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183370. * filter type. Higher costs indicate more decoding expense, and are
  183371. * therefore less likely to be selected over a filter with lower computational
  183372. * costs. There needs to be a value in "filter_costs" for each valid filter
  183373. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183374. * setting the costs. Costs try to improve the speed of decompression without
  183375. * unduly increasing the compressed image size.
  183376. *
  183377. * A negative weight or cost indicates the default value is to be used, and
  183378. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183379. * The default values for both weights and costs are currently 1.0, but may
  183380. * change if good general weighting/cost heuristics can be found. If both
  183381. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183382. * to the UNWEIGHTED method, but with added encoding time/computation.
  183383. */
  183384. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183385. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183386. int heuristic_method, int num_weights, png_doublep filter_weights,
  183387. png_doublep filter_costs));
  183388. #endif
  183389. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183390. /* Heuristic used for row filter selection. These defines should NOT be
  183391. * changed.
  183392. */
  183393. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183394. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183395. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183396. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183397. /* Set the library compression level. Currently, valid values range from
  183398. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183399. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183400. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183401. * for PNG images, and do considerably fewer caclulations. In the future,
  183402. * these values may not correspond directly to the zlib compression levels.
  183403. */
  183404. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183405. int level));
  183406. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183407. PNGARG((png_structp png_ptr, int mem_level));
  183408. extern PNG_EXPORT(void,png_set_compression_strategy)
  183409. PNGARG((png_structp png_ptr, int strategy));
  183410. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183411. PNGARG((png_structp png_ptr, int window_bits));
  183412. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183413. int method));
  183414. /* These next functions are called for input/output, memory, and error
  183415. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183416. * and call standard C I/O routines such as fread(), fwrite(), and
  183417. * fprintf(). These functions can be made to use other I/O routines
  183418. * at run time for those applications that need to handle I/O in a
  183419. * different manner by calling png_set_???_fn(). See libpng.txt for
  183420. * more information.
  183421. */
  183422. #if !defined(PNG_NO_STDIO)
  183423. /* Initialize the input/output for the PNG file to the default functions. */
  183424. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183425. #endif
  183426. /* Replace the (error and abort), and warning functions with user
  183427. * supplied functions. If no messages are to be printed you must still
  183428. * write and use replacement functions. The replacement error_fn should
  183429. * still do a longjmp to the last setjmp location if you are using this
  183430. * method of error handling. If error_fn or warning_fn is NULL, the
  183431. * default function will be used.
  183432. */
  183433. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183434. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183435. /* Return the user pointer associated with the error functions */
  183436. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183437. /* Replace the default data output functions with a user supplied one(s).
  183438. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183439. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183440. * output_flush_fn will be ignored (and thus can be NULL).
  183441. */
  183442. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183443. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183444. /* Replace the default data input function with a user supplied one. */
  183445. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183446. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183447. /* Return the user pointer associated with the I/O functions */
  183448. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183449. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183450. png_read_status_ptr read_row_fn));
  183451. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183452. png_write_status_ptr write_row_fn));
  183453. #ifdef PNG_USER_MEM_SUPPORTED
  183454. /* Replace the default memory allocation functions with user supplied one(s). */
  183455. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183456. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183457. /* Return the user pointer associated with the memory functions */
  183458. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183459. #endif
  183460. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183461. defined(PNG_LEGACY_SUPPORTED)
  183462. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183463. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183464. #endif
  183465. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183466. defined(PNG_LEGACY_SUPPORTED)
  183467. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183468. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183469. #endif
  183470. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183471. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183472. defined(PNG_LEGACY_SUPPORTED)
  183473. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183474. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183475. int user_transform_channels));
  183476. /* Return the user pointer associated with the user transform functions */
  183477. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183478. PNGARG((png_structp png_ptr));
  183479. #endif
  183480. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183481. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183482. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183483. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183484. png_ptr));
  183485. #endif
  183486. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183487. /* Sets the function callbacks for the push reader, and a pointer to a
  183488. * user-defined structure available to the callback functions.
  183489. */
  183490. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183491. png_voidp progressive_ptr,
  183492. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183493. png_progressive_end_ptr end_fn));
  183494. /* returns the user pointer associated with the push read functions */
  183495. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183496. PNGARG((png_structp png_ptr));
  183497. /* function to be called when data becomes available */
  183498. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183499. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183500. /* function that combines rows. Not very much different than the
  183501. * png_combine_row() call. Is this even used?????
  183502. */
  183503. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183504. png_bytep old_row, png_bytep new_row));
  183505. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183506. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183507. png_uint_32 size));
  183508. #if defined(PNG_1_0_X)
  183509. # define png_malloc_warn png_malloc
  183510. #else
  183511. /* Added at libpng version 1.2.4 */
  183512. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183513. png_uint_32 size));
  183514. #endif
  183515. /* frees a pointer allocated by png_malloc() */
  183516. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183517. #if defined(PNG_1_0_X)
  183518. /* Function to allocate memory for zlib. */
  183519. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183520. uInt size));
  183521. /* Function to free memory for zlib */
  183522. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183523. #endif
  183524. /* Free data that was allocated internally */
  183525. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183526. png_infop info_ptr, png_uint_32 free_me, int num));
  183527. #ifdef PNG_FREE_ME_SUPPORTED
  183528. /* Reassign responsibility for freeing existing data, whether allocated
  183529. * by libpng or by the application */
  183530. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183531. png_infop info_ptr, int freer, png_uint_32 mask));
  183532. #endif
  183533. /* assignments for png_data_freer */
  183534. #define PNG_DESTROY_WILL_FREE_DATA 1
  183535. #define PNG_SET_WILL_FREE_DATA 1
  183536. #define PNG_USER_WILL_FREE_DATA 2
  183537. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183538. #define PNG_FREE_HIST 0x0008
  183539. #define PNG_FREE_ICCP 0x0010
  183540. #define PNG_FREE_SPLT 0x0020
  183541. #define PNG_FREE_ROWS 0x0040
  183542. #define PNG_FREE_PCAL 0x0080
  183543. #define PNG_FREE_SCAL 0x0100
  183544. #define PNG_FREE_UNKN 0x0200
  183545. #define PNG_FREE_LIST 0x0400
  183546. #define PNG_FREE_PLTE 0x1000
  183547. #define PNG_FREE_TRNS 0x2000
  183548. #define PNG_FREE_TEXT 0x4000
  183549. #define PNG_FREE_ALL 0x7fff
  183550. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183551. #ifdef PNG_USER_MEM_SUPPORTED
  183552. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183553. png_uint_32 size));
  183554. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183555. png_voidp ptr));
  183556. #endif
  183557. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183558. png_voidp s1, png_voidp s2, png_uint_32 size));
  183559. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183560. png_voidp s1, int value, png_uint_32 size));
  183561. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183562. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183563. int check));
  183564. #endif /* USE_FAR_KEYWORD */
  183565. #ifndef PNG_NO_ERROR_TEXT
  183566. /* Fatal error in PNG image of libpng - can't continue */
  183567. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183568. png_const_charp error_message));
  183569. /* The same, but the chunk name is prepended to the error string. */
  183570. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183571. png_const_charp error_message));
  183572. #else
  183573. /* Fatal error in PNG image of libpng - can't continue */
  183574. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183575. #endif
  183576. #ifndef PNG_NO_WARNINGS
  183577. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183578. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183579. png_const_charp warning_message));
  183580. #ifdef PNG_READ_SUPPORTED
  183581. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183582. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183583. png_const_charp warning_message));
  183584. #endif /* PNG_READ_SUPPORTED */
  183585. #endif /* PNG_NO_WARNINGS */
  183586. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183587. * Similarly, the png_get_<chunk> calls are used to read values from the
  183588. * png_info_struct, either storing the parameters in the passed variables, or
  183589. * setting pointers into the png_info_struct where the data is stored. The
  183590. * png_get_<chunk> functions return a non-zero value if the data was available
  183591. * in info_ptr, or return zero and do not change any of the parameters if the
  183592. * data was not available.
  183593. *
  183594. * These functions should be used instead of directly accessing png_info
  183595. * to avoid problems with future changes in the size and internal layout of
  183596. * png_info_struct.
  183597. */
  183598. /* Returns "flag" if chunk data is valid in info_ptr. */
  183599. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, png_uint_32 flag));
  183601. /* Returns number of bytes needed to hold a transformed row. */
  183602. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183603. png_infop info_ptr));
  183604. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183605. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183606. returned from png_read_png(). */
  183607. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183608. png_infop info_ptr));
  183609. /* Set row_pointers, which is an array of pointers to scanlines for use
  183610. by png_write_png(). */
  183611. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183612. png_infop info_ptr, png_bytepp row_pointers));
  183613. #endif
  183614. /* Returns number of color channels in image. */
  183615. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183616. png_infop info_ptr));
  183617. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183618. /* Returns image width in pixels. */
  183619. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183620. png_ptr, png_infop info_ptr));
  183621. /* Returns image height in pixels. */
  183622. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183623. png_ptr, png_infop info_ptr));
  183624. /* Returns image bit_depth. */
  183625. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183626. png_ptr, png_infop info_ptr));
  183627. /* Returns image color_type. */
  183628. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183629. png_ptr, png_infop info_ptr));
  183630. /* Returns image filter_type. */
  183631. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183632. png_ptr, png_infop info_ptr));
  183633. /* Returns image interlace_type. */
  183634. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183635. png_ptr, png_infop info_ptr));
  183636. /* Returns image compression_type. */
  183637. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183638. png_ptr, png_infop info_ptr));
  183639. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183640. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183641. png_ptr, png_infop info_ptr));
  183642. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183643. png_ptr, png_infop info_ptr));
  183644. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183645. png_ptr, png_infop info_ptr));
  183646. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183647. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183648. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183649. png_ptr, png_infop info_ptr));
  183650. #endif
  183651. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183652. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183653. png_ptr, png_infop info_ptr));
  183654. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183655. png_ptr, png_infop info_ptr));
  183656. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183657. png_ptr, png_infop info_ptr));
  183658. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183659. png_ptr, png_infop info_ptr));
  183660. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183661. /* Returns pointer to signature string read from PNG header */
  183662. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183663. png_infop info_ptr));
  183664. #if defined(PNG_bKGD_SUPPORTED)
  183665. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183666. png_infop info_ptr, png_color_16p *background));
  183667. #endif
  183668. #if defined(PNG_bKGD_SUPPORTED)
  183669. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183670. png_infop info_ptr, png_color_16p background));
  183671. #endif
  183672. #if defined(PNG_cHRM_SUPPORTED)
  183673. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183674. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183675. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183676. double *red_y, double *green_x, double *green_y, double *blue_x,
  183677. double *blue_y));
  183678. #endif
  183679. #ifdef PNG_FIXED_POINT_SUPPORTED
  183680. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183681. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183682. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183683. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183684. *int_blue_x, png_fixed_point *int_blue_y));
  183685. #endif
  183686. #endif
  183687. #if defined(PNG_cHRM_SUPPORTED)
  183688. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183689. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183690. png_infop info_ptr, double white_x, double white_y, double red_x,
  183691. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183692. #endif
  183693. #ifdef PNG_FIXED_POINT_SUPPORTED
  183694. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183695. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183696. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183697. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183698. png_fixed_point int_blue_y));
  183699. #endif
  183700. #endif
  183701. #if defined(PNG_gAMA_SUPPORTED)
  183702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183703. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183704. png_infop info_ptr, double *file_gamma));
  183705. #endif
  183706. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183707. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183708. #endif
  183709. #if defined(PNG_gAMA_SUPPORTED)
  183710. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183711. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183712. png_infop info_ptr, double file_gamma));
  183713. #endif
  183714. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183715. png_infop info_ptr, png_fixed_point int_file_gamma));
  183716. #endif
  183717. #if defined(PNG_hIST_SUPPORTED)
  183718. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183719. png_infop info_ptr, png_uint_16p *hist));
  183720. #endif
  183721. #if defined(PNG_hIST_SUPPORTED)
  183722. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183723. png_infop info_ptr, png_uint_16p hist));
  183724. #endif
  183725. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183726. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183727. int *bit_depth, int *color_type, int *interlace_method,
  183728. int *compression_method, int *filter_method));
  183729. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183730. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183731. int color_type, int interlace_method, int compression_method,
  183732. int filter_method));
  183733. #if defined(PNG_oFFs_SUPPORTED)
  183734. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183736. int *unit_type));
  183737. #endif
  183738. #if defined(PNG_oFFs_SUPPORTED)
  183739. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183740. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183741. int unit_type));
  183742. #endif
  183743. #if defined(PNG_pCAL_SUPPORTED)
  183744. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183745. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183746. int *type, int *nparams, png_charp *units, png_charpp *params));
  183747. #endif
  183748. #if defined(PNG_pCAL_SUPPORTED)
  183749. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183750. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183751. int type, int nparams, png_charp units, png_charpp params));
  183752. #endif
  183753. #if defined(PNG_pHYs_SUPPORTED)
  183754. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183755. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183756. #endif
  183757. #if defined(PNG_pHYs_SUPPORTED)
  183758. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183759. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183760. #endif
  183761. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183762. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183763. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183764. png_infop info_ptr, png_colorp palette, int num_palette));
  183765. #if defined(PNG_sBIT_SUPPORTED)
  183766. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183767. png_infop info_ptr, png_color_8p *sig_bit));
  183768. #endif
  183769. #if defined(PNG_sBIT_SUPPORTED)
  183770. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183771. png_infop info_ptr, png_color_8p sig_bit));
  183772. #endif
  183773. #if defined(PNG_sRGB_SUPPORTED)
  183774. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183775. png_infop info_ptr, int *intent));
  183776. #endif
  183777. #if defined(PNG_sRGB_SUPPORTED)
  183778. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183779. png_infop info_ptr, int intent));
  183780. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183781. png_infop info_ptr, int intent));
  183782. #endif
  183783. #if defined(PNG_iCCP_SUPPORTED)
  183784. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183785. png_infop info_ptr, png_charpp name, int *compression_type,
  183786. png_charpp profile, png_uint_32 *proflen));
  183787. /* Note to maintainer: profile should be png_bytepp */
  183788. #endif
  183789. #if defined(PNG_iCCP_SUPPORTED)
  183790. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183791. png_infop info_ptr, png_charp name, int compression_type,
  183792. png_charp profile, png_uint_32 proflen));
  183793. /* Note to maintainer: profile should be png_bytep */
  183794. #endif
  183795. #if defined(PNG_sPLT_SUPPORTED)
  183796. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183797. png_infop info_ptr, png_sPLT_tpp entries));
  183798. #endif
  183799. #if defined(PNG_sPLT_SUPPORTED)
  183800. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183801. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183802. #endif
  183803. #if defined(PNG_TEXT_SUPPORTED)
  183804. /* png_get_text also returns the number of text chunks in *num_text */
  183805. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183806. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183807. #endif
  183808. /*
  183809. * Note while png_set_text() will accept a structure whose text,
  183810. * language, and translated keywords are NULL pointers, the structure
  183811. * returned by png_get_text will always contain regular
  183812. * zero-terminated C strings. They might be empty strings but
  183813. * they will never be NULL pointers.
  183814. */
  183815. #if defined(PNG_TEXT_SUPPORTED)
  183816. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183817. png_infop info_ptr, png_textp text_ptr, int num_text));
  183818. #endif
  183819. #if defined(PNG_tIME_SUPPORTED)
  183820. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183821. png_infop info_ptr, png_timep *mod_time));
  183822. #endif
  183823. #if defined(PNG_tIME_SUPPORTED)
  183824. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183825. png_infop info_ptr, png_timep mod_time));
  183826. #endif
  183827. #if defined(PNG_tRNS_SUPPORTED)
  183828. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183829. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183830. png_color_16p *trans_values));
  183831. #endif
  183832. #if defined(PNG_tRNS_SUPPORTED)
  183833. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183834. png_infop info_ptr, png_bytep trans, int num_trans,
  183835. png_color_16p trans_values));
  183836. #endif
  183837. #if defined(PNG_tRNS_SUPPORTED)
  183838. #endif
  183839. #if defined(PNG_sCAL_SUPPORTED)
  183840. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183841. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183842. png_infop info_ptr, int *unit, double *width, double *height));
  183843. #else
  183844. #ifdef PNG_FIXED_POINT_SUPPORTED
  183845. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183846. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183847. #endif
  183848. #endif
  183849. #endif /* PNG_sCAL_SUPPORTED */
  183850. #if defined(PNG_sCAL_SUPPORTED)
  183851. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183852. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183853. png_infop info_ptr, int unit, double width, double height));
  183854. #else
  183855. #ifdef PNG_FIXED_POINT_SUPPORTED
  183856. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183858. #endif
  183859. #endif
  183860. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183861. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183862. /* provide a list of chunks and how they are to be handled, if the built-in
  183863. handling or default unknown chunk handling is not desired. Any chunks not
  183864. listed will be handled in the default manner. The IHDR and IEND chunks
  183865. must not be listed.
  183866. keep = 0: follow default behaviour
  183867. = 1: do not keep
  183868. = 2: keep only if safe-to-copy
  183869. = 3: keep even if unsafe-to-copy
  183870. */
  183871. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183872. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183873. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183874. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183875. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183876. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183877. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183878. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183879. #endif
  183880. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183881. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183882. chunk_name));
  183883. #endif
  183884. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183885. If you need to turn it off for a chunk that your application has freed,
  183886. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183887. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183888. png_infop info_ptr, int mask));
  183889. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183890. /* The "params" pointer is currently not used and is for future expansion. */
  183891. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183892. png_infop info_ptr,
  183893. int transforms,
  183894. png_voidp params));
  183895. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183896. png_infop info_ptr,
  183897. int transforms,
  183898. png_voidp params));
  183899. #endif
  183900. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183901. * numbers for PNG_DEBUG mean more debugging information. This has
  183902. * only been added since version 0.95 so it is not implemented throughout
  183903. * libpng yet, but more support will be added as needed.
  183904. */
  183905. #ifdef PNG_DEBUG
  183906. #if (PNG_DEBUG > 0)
  183907. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183908. #include <crtdbg.h>
  183909. #if (PNG_DEBUG > 1)
  183910. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183911. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183912. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183913. #endif
  183914. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183915. #ifndef PNG_DEBUG_FILE
  183916. #define PNG_DEBUG_FILE stderr
  183917. #endif /* PNG_DEBUG_FILE */
  183918. #if (PNG_DEBUG > 1)
  183919. #define png_debug(l,m) \
  183920. { \
  183921. int num_tabs=l; \
  183922. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183923. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183924. }
  183925. #define png_debug1(l,m,p1) \
  183926. { \
  183927. int num_tabs=l; \
  183928. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183929. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183930. }
  183931. #define png_debug2(l,m,p1,p2) \
  183932. { \
  183933. int num_tabs=l; \
  183934. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183935. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183936. }
  183937. #endif /* (PNG_DEBUG > 1) */
  183938. #endif /* _MSC_VER */
  183939. #endif /* (PNG_DEBUG > 0) */
  183940. #endif /* PNG_DEBUG */
  183941. #ifndef png_debug
  183942. #define png_debug(l, m)
  183943. #endif
  183944. #ifndef png_debug1
  183945. #define png_debug1(l, m, p1)
  183946. #endif
  183947. #ifndef png_debug2
  183948. #define png_debug2(l, m, p1, p2)
  183949. #endif
  183950. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183951. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183952. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183953. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183954. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183955. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183956. png_ptr, png_uint_32 mng_features_permitted));
  183957. #endif
  183958. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183959. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183960. #define PNG_HANDLE_CHUNK_NEVER 1
  183961. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183962. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183963. /* Added to version 1.2.0 */
  183964. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183965. #if defined(PNG_MMX_CODE_SUPPORTED)
  183966. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183967. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183968. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183969. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183970. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183971. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183972. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183973. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183974. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183975. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183976. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183977. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183978. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183979. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183980. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183981. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183982. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183983. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183984. | PNG_MMX_READ_FLAGS \
  183985. | PNG_MMX_WRITE_FLAGS )
  183986. #define PNG_SELECT_READ 1
  183987. #define PNG_SELECT_WRITE 2
  183988. #endif /* PNG_MMX_CODE_SUPPORTED */
  183989. #if !defined(PNG_1_0_X)
  183990. /* pngget.c */
  183991. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183992. PNGARG((int flag_select, int *compilerID));
  183993. /* pngget.c */
  183994. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183995. PNGARG((int flag_select));
  183996. /* pngget.c */
  183997. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183998. PNGARG((png_structp png_ptr));
  183999. /* pngget.c */
  184000. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184001. PNGARG((png_structp png_ptr));
  184002. /* pngget.c */
  184003. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184004. PNGARG((png_structp png_ptr));
  184005. /* pngset.c */
  184006. extern PNG_EXPORT(void,png_set_asm_flags)
  184007. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184008. /* pngset.c */
  184009. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184010. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184011. png_uint_32 mmx_rowbytes_threshold));
  184012. #endif /* PNG_1_0_X */
  184013. #if !defined(PNG_1_0_X)
  184014. /* png.c, pnggccrd.c, or pngvcrd.c */
  184015. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184016. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184017. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184018. * messages before passing them to the error or warning handler. */
  184019. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184020. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184021. png_ptr, png_uint_32 strip_mode));
  184022. #endif
  184023. #endif /* PNG_1_0_X */
  184024. /* Added at libpng-1.2.6 */
  184025. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184026. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184027. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184028. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184029. png_ptr));
  184030. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184031. png_ptr));
  184032. #endif
  184033. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184034. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184035. /* With these routines we avoid an integer divide, which will be slower on
  184036. * most machines. However, it does take more operations than the corresponding
  184037. * divide method, so it may be slower on a few RISC systems. There are two
  184038. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184039. *
  184040. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184041. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184042. * standard method.
  184043. *
  184044. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184045. */
  184046. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184047. # define png_composite(composite, fg, alpha, bg) \
  184048. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184049. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184050. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184051. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184052. # define png_composite_16(composite, fg, alpha, bg) \
  184053. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184054. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184055. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184056. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184057. #else /* standard method using integer division */
  184058. # define png_composite(composite, fg, alpha, bg) \
  184059. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184060. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184061. (png_uint_16)127) / 255)
  184062. # define png_composite_16(composite, fg, alpha, bg) \
  184063. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184064. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184065. (png_uint_32)32767) / (png_uint_32)65535L)
  184066. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184067. /* Inline macros to do direct reads of bytes from the input buffer. These
  184068. * require that you are using an architecture that uses PNG byte ordering
  184069. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184070. * in big-endian mode and 680x0 are the only ones that will support this.
  184071. * The x86 line of processors definitely do not. The png_get_int_32()
  184072. * routine also assumes we are using two's complement format for negative
  184073. * values, which is almost certainly true.
  184074. */
  184075. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184076. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184077. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184078. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184079. #else
  184080. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184081. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184082. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184083. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184084. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184085. PNGARG((png_structp png_ptr, png_bytep buf));
  184086. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184087. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184088. */
  184089. extern PNG_EXPORT(void,png_save_uint_32)
  184090. PNGARG((png_bytep buf, png_uint_32 i));
  184091. extern PNG_EXPORT(void,png_save_int_32)
  184092. PNGARG((png_bytep buf, png_int_32 i));
  184093. /* Place a 16-bit number into a buffer in PNG byte order.
  184094. * The parameter is declared unsigned int, not png_uint_16,
  184095. * just to avoid potential problems on pre-ANSI C compilers.
  184096. */
  184097. extern PNG_EXPORT(void,png_save_uint_16)
  184098. PNGARG((png_bytep buf, unsigned int i));
  184099. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184100. /* ************************************************************************* */
  184101. /* These next functions are used internally in the code. They generally
  184102. * shouldn't be used unless you are writing code to add or replace some
  184103. * functionality in libpng. More information about most functions can
  184104. * be found in the files where the functions are located.
  184105. */
  184106. /* Various modes of operation, that are visible to applications because
  184107. * they are used for unknown chunk location.
  184108. */
  184109. #define PNG_HAVE_IHDR 0x01
  184110. #define PNG_HAVE_PLTE 0x02
  184111. #define PNG_HAVE_IDAT 0x04
  184112. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184113. #define PNG_HAVE_IEND 0x10
  184114. #if defined(PNG_INTERNAL)
  184115. /* More modes of operation. Note that after an init, mode is set to
  184116. * zero automatically when the structure is created.
  184117. */
  184118. #define PNG_HAVE_gAMA 0x20
  184119. #define PNG_HAVE_cHRM 0x40
  184120. #define PNG_HAVE_sRGB 0x80
  184121. #define PNG_HAVE_CHUNK_HEADER 0x100
  184122. #define PNG_WROTE_tIME 0x200
  184123. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184124. #define PNG_BACKGROUND_IS_GRAY 0x800
  184125. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184126. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184127. /* flags for the transformations the PNG library does on the image data */
  184128. #define PNG_BGR 0x0001
  184129. #define PNG_INTERLACE 0x0002
  184130. #define PNG_PACK 0x0004
  184131. #define PNG_SHIFT 0x0008
  184132. #define PNG_SWAP_BYTES 0x0010
  184133. #define PNG_INVERT_MONO 0x0020
  184134. #define PNG_DITHER 0x0040
  184135. #define PNG_BACKGROUND 0x0080
  184136. #define PNG_BACKGROUND_EXPAND 0x0100
  184137. /* 0x0200 unused */
  184138. #define PNG_16_TO_8 0x0400
  184139. #define PNG_RGBA 0x0800
  184140. #define PNG_EXPAND 0x1000
  184141. #define PNG_GAMMA 0x2000
  184142. #define PNG_GRAY_TO_RGB 0x4000
  184143. #define PNG_FILLER 0x8000L
  184144. #define PNG_PACKSWAP 0x10000L
  184145. #define PNG_SWAP_ALPHA 0x20000L
  184146. #define PNG_STRIP_ALPHA 0x40000L
  184147. #define PNG_INVERT_ALPHA 0x80000L
  184148. #define PNG_USER_TRANSFORM 0x100000L
  184149. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184150. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184151. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184152. /* 0x800000L Unused */
  184153. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184154. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184155. /* 0x4000000L unused */
  184156. /* 0x8000000L unused */
  184157. /* 0x10000000L unused */
  184158. /* 0x20000000L unused */
  184159. /* 0x40000000L unused */
  184160. /* flags for png_create_struct */
  184161. #define PNG_STRUCT_PNG 0x0001
  184162. #define PNG_STRUCT_INFO 0x0002
  184163. /* Scaling factor for filter heuristic weighting calculations */
  184164. #define PNG_WEIGHT_SHIFT 8
  184165. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184166. #define PNG_COST_SHIFT 3
  184167. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184168. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184169. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184170. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184171. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184172. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184173. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184174. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184175. #define PNG_FLAG_ROW_INIT 0x0040
  184176. #define PNG_FLAG_FILLER_AFTER 0x0080
  184177. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184178. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184179. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184180. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184181. #define PNG_FLAG_FREE_PLTE 0x1000
  184182. #define PNG_FLAG_FREE_TRNS 0x2000
  184183. #define PNG_FLAG_FREE_HIST 0x4000
  184184. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184185. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184186. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184187. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184188. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184189. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184190. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184191. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184192. /* 0x800000L unused */
  184193. /* 0x1000000L unused */
  184194. /* 0x2000000L unused */
  184195. /* 0x4000000L unused */
  184196. /* 0x8000000L unused */
  184197. /* 0x10000000L unused */
  184198. /* 0x20000000L unused */
  184199. /* 0x40000000L unused */
  184200. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184201. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184202. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184203. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184204. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184205. PNG_FLAG_CRC_CRITICAL_MASK)
  184206. /* save typing and make code easier to understand */
  184207. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184208. abs((int)((c1).green) - (int)((c2).green)) + \
  184209. abs((int)((c1).blue) - (int)((c2).blue)))
  184210. /* Added to libpng-1.2.6 JB */
  184211. #define PNG_ROWBYTES(pixel_bits, width) \
  184212. ((pixel_bits) >= 8 ? \
  184213. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184214. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184215. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184216. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184217. "ideal" and "delta" should be constants, normally simple
  184218. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184219. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184220. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184221. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184222. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184223. /* place to hold the signature string for a PNG file. */
  184224. #ifdef PNG_USE_GLOBAL_ARRAYS
  184225. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184226. #else
  184227. #endif
  184228. #endif /* PNG_NO_EXTERN */
  184229. /* Constant strings for known chunk types. If you need to add a chunk,
  184230. * define the name here, and add an invocation of the macro in png.c and
  184231. * wherever it's needed.
  184232. */
  184233. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184234. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184235. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184236. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184237. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184238. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184239. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184240. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184241. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184242. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184243. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184244. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184245. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184246. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184247. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184248. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184249. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184250. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184251. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184252. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184253. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184254. #ifdef PNG_USE_GLOBAL_ARRAYS
  184255. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184256. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184257. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184258. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184259. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184260. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184261. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184262. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184263. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184264. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184265. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184266. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184267. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184268. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184269. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184270. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184271. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184272. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184273. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184274. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184275. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184276. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184277. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184278. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184279. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184280. */
  184281. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184282. #undef png_read_init
  184283. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184284. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184285. #endif
  184286. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184287. png_const_charp user_png_ver, png_size_t png_struct_size));
  184288. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184289. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184290. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184291. png_info_size));
  184292. #endif
  184293. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184294. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184295. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184296. */
  184297. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184298. #undef png_write_init
  184299. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184300. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184301. #endif
  184302. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184303. png_const_charp user_png_ver, png_size_t png_struct_size));
  184304. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184305. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184306. png_info_size));
  184307. /* Allocate memory for an internal libpng struct */
  184308. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184309. /* Free memory from internal libpng struct */
  184310. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184311. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184312. malloc_fn, png_voidp mem_ptr));
  184313. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184314. png_free_ptr free_fn, png_voidp mem_ptr));
  184315. /* Free any memory that info_ptr points to and reset struct. */
  184316. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184317. png_infop info_ptr));
  184318. #ifndef PNG_1_0_X
  184319. /* Function to allocate memory for zlib. */
  184320. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184321. /* Function to free memory for zlib */
  184322. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184323. #ifdef PNG_SIZE_T
  184324. /* Function to convert a sizeof an item to png_sizeof item */
  184325. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184326. #endif
  184327. /* Next four functions are used internally as callbacks. PNGAPI is required
  184328. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184329. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184330. png_bytep data, png_size_t length));
  184331. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184332. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184333. png_bytep buffer, png_size_t length));
  184334. #endif
  184335. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184336. png_bytep data, png_size_t length));
  184337. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184338. #if !defined(PNG_NO_STDIO)
  184339. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184340. #endif
  184341. #endif
  184342. #else /* PNG_1_0_X */
  184343. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184344. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184345. png_bytep buffer, png_size_t length));
  184346. #endif
  184347. #endif /* PNG_1_0_X */
  184348. /* Reset the CRC variable */
  184349. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184350. /* Write the "data" buffer to whatever output you are using. */
  184351. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184352. png_size_t length));
  184353. /* Read data from whatever input you are using into the "data" buffer */
  184354. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184355. png_size_t length));
  184356. /* Read bytes into buf, and update png_ptr->crc */
  184357. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184358. png_size_t length));
  184359. /* Decompress data in a chunk that uses compression */
  184360. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184361. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184362. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184363. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184364. png_size_t prefix_length, png_size_t *data_length));
  184365. #endif
  184366. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184367. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184368. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184369. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184370. /* Calculate the CRC over a section of data. Note that we are only
  184371. * passing a maximum of 64K on systems that have this as a memory limit,
  184372. * since this is the maximum buffer size we can specify.
  184373. */
  184374. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184375. png_size_t length));
  184376. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184377. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184378. #endif
  184379. /* simple function to write the signature */
  184380. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184381. /* write various chunks */
  184382. /* Write the IHDR chunk, and update the png_struct with the necessary
  184383. * information.
  184384. */
  184385. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184386. png_uint_32 height,
  184387. int bit_depth, int color_type, int compression_method, int filter_method,
  184388. int interlace_method));
  184389. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184390. png_uint_32 num_pal));
  184391. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184392. png_size_t length));
  184393. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184394. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184395. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184396. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184397. #endif
  184398. #ifdef PNG_FIXED_POINT_SUPPORTED
  184399. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184400. file_gamma));
  184401. #endif
  184402. #endif
  184403. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184404. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184405. int color_type));
  184406. #endif
  184407. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184408. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184409. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184410. double white_x, double white_y,
  184411. double red_x, double red_y, double green_x, double green_y,
  184412. double blue_x, double blue_y));
  184413. #endif
  184414. #ifdef PNG_FIXED_POINT_SUPPORTED
  184415. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184416. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184417. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184418. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184419. png_fixed_point int_blue_y));
  184420. #endif
  184421. #endif
  184422. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184423. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184424. int intent));
  184425. #endif
  184426. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184427. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184428. png_charp name, int compression_type,
  184429. png_charp profile, int proflen));
  184430. /* Note to maintainer: profile should be png_bytep */
  184431. #endif
  184432. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184433. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184434. png_sPLT_tp palette));
  184435. #endif
  184436. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184437. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184438. png_color_16p values, int number, int color_type));
  184439. #endif
  184440. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184441. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184442. png_color_16p values, int color_type));
  184443. #endif
  184444. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184445. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184446. int num_hist));
  184447. #endif
  184448. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184449. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184450. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184451. png_charp key, png_charpp new_key));
  184452. #endif
  184453. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184454. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184455. png_charp text, png_size_t text_len));
  184456. #endif
  184457. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184458. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184459. png_charp text, png_size_t text_len, int compression));
  184460. #endif
  184461. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184462. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184463. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184464. png_charp text));
  184465. #endif
  184466. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184467. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184468. png_infop info_ptr, png_textp text_ptr, int num_text));
  184469. #endif
  184470. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184471. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184472. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184473. #endif
  184474. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184475. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184476. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184477. png_charp units, png_charpp params));
  184478. #endif
  184479. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184480. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184481. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184482. int unit_type));
  184483. #endif
  184484. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184485. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184486. png_timep mod_time));
  184487. #endif
  184488. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184489. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184490. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184491. int unit, double width, double height));
  184492. #else
  184493. #ifdef PNG_FIXED_POINT_SUPPORTED
  184494. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184495. int unit, png_charp width, png_charp height));
  184496. #endif
  184497. #endif
  184498. #endif
  184499. /* Called when finished processing a row of data */
  184500. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184501. /* Internal use only. Called before first row of data */
  184502. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184503. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184504. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184505. #endif
  184506. /* combine a row of data, dealing with alpha, etc. if requested */
  184507. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184508. int mask));
  184509. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184510. /* expand an interlaced row */
  184511. /* OLD pre-1.0.9 interface:
  184512. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184513. png_bytep row, int pass, png_uint_32 transformations));
  184514. */
  184515. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184516. #endif
  184517. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184518. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184519. /* grab pixels out of a row for an interlaced pass */
  184520. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184521. png_bytep row, int pass));
  184522. #endif
  184523. /* unfilter a row */
  184524. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184525. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184526. /* Choose the best filter to use and filter the row data */
  184527. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184528. png_row_infop row_info));
  184529. /* Write out the filtered row. */
  184530. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184531. png_bytep filtered_row));
  184532. /* finish a row while reading, dealing with interlacing passes, etc. */
  184533. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184534. /* initialize the row buffers, etc. */
  184535. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184536. /* optional call to update the users info structure */
  184537. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184538. png_infop info_ptr));
  184539. /* these are the functions that do the transformations */
  184540. #if defined(PNG_READ_FILLER_SUPPORTED)
  184541. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184542. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184543. #endif
  184544. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184545. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184546. png_bytep row));
  184547. #endif
  184548. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184549. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184550. png_bytep row));
  184551. #endif
  184552. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184553. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184554. png_bytep row));
  184555. #endif
  184556. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184557. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184558. png_bytep row));
  184559. #endif
  184560. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184561. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184562. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184563. png_bytep row, png_uint_32 flags));
  184564. #endif
  184565. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184566. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184567. #endif
  184568. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184569. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184570. #endif
  184571. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184572. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184573. row_info, png_bytep row));
  184574. #endif
  184575. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184576. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184577. png_bytep row));
  184578. #endif
  184579. #if defined(PNG_READ_PACK_SUPPORTED)
  184580. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184581. #endif
  184582. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184583. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184584. png_color_8p sig_bits));
  184585. #endif
  184586. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184587. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184588. #endif
  184589. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184590. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184591. #endif
  184592. #if defined(PNG_READ_DITHER_SUPPORTED)
  184593. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184594. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184595. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184596. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184597. png_colorp palette, int num_palette));
  184598. # endif
  184599. #endif
  184600. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184601. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184602. #endif
  184603. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184604. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184605. png_bytep row, png_uint_32 bit_depth));
  184606. #endif
  184607. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184608. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184609. png_color_8p bit_depth));
  184610. #endif
  184611. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184613. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184614. png_color_16p trans_values, png_color_16p background,
  184615. png_color_16p background_1,
  184616. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184617. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184618. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184619. #else
  184620. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184621. png_color_16p trans_values, png_color_16p background));
  184622. #endif
  184623. #endif
  184624. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184625. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184626. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184627. int gamma_shift));
  184628. #endif
  184629. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184630. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184631. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184632. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184633. png_bytep row, png_color_16p trans_value));
  184634. #endif
  184635. /* The following decodes the appropriate chunks, and does error correction,
  184636. * then calls the appropriate callback for the chunk if it is valid.
  184637. */
  184638. /* decode the IHDR chunk */
  184639. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184640. png_uint_32 length));
  184641. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184642. png_uint_32 length));
  184643. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184644. png_uint_32 length));
  184645. #if defined(PNG_READ_bKGD_SUPPORTED)
  184646. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184647. png_uint_32 length));
  184648. #endif
  184649. #if defined(PNG_READ_cHRM_SUPPORTED)
  184650. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184651. png_uint_32 length));
  184652. #endif
  184653. #if defined(PNG_READ_gAMA_SUPPORTED)
  184654. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184655. png_uint_32 length));
  184656. #endif
  184657. #if defined(PNG_READ_hIST_SUPPORTED)
  184658. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184659. png_uint_32 length));
  184660. #endif
  184661. #if defined(PNG_READ_iCCP_SUPPORTED)
  184662. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184663. png_uint_32 length));
  184664. #endif /* PNG_READ_iCCP_SUPPORTED */
  184665. #if defined(PNG_READ_iTXt_SUPPORTED)
  184666. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184667. png_uint_32 length));
  184668. #endif
  184669. #if defined(PNG_READ_oFFs_SUPPORTED)
  184670. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184671. png_uint_32 length));
  184672. #endif
  184673. #if defined(PNG_READ_pCAL_SUPPORTED)
  184674. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184675. png_uint_32 length));
  184676. #endif
  184677. #if defined(PNG_READ_pHYs_SUPPORTED)
  184678. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184679. png_uint_32 length));
  184680. #endif
  184681. #if defined(PNG_READ_sBIT_SUPPORTED)
  184682. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184683. png_uint_32 length));
  184684. #endif
  184685. #if defined(PNG_READ_sCAL_SUPPORTED)
  184686. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184687. png_uint_32 length));
  184688. #endif
  184689. #if defined(PNG_READ_sPLT_SUPPORTED)
  184690. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184691. png_uint_32 length));
  184692. #endif /* PNG_READ_sPLT_SUPPORTED */
  184693. #if defined(PNG_READ_sRGB_SUPPORTED)
  184694. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184695. png_uint_32 length));
  184696. #endif
  184697. #if defined(PNG_READ_tEXt_SUPPORTED)
  184698. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184699. png_uint_32 length));
  184700. #endif
  184701. #if defined(PNG_READ_tIME_SUPPORTED)
  184702. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184703. png_uint_32 length));
  184704. #endif
  184705. #if defined(PNG_READ_tRNS_SUPPORTED)
  184706. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184707. png_uint_32 length));
  184708. #endif
  184709. #if defined(PNG_READ_zTXt_SUPPORTED)
  184710. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184711. png_uint_32 length));
  184712. #endif
  184713. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184714. png_infop info_ptr, png_uint_32 length));
  184715. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184716. png_bytep chunk_name));
  184717. /* handle the transformations for reading and writing */
  184718. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184719. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184720. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184721. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184722. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184723. png_infop info_ptr));
  184724. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184725. png_infop info_ptr));
  184726. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184727. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184728. png_uint_32 length));
  184729. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184730. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184731. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184732. png_bytep buffer, png_size_t buffer_length));
  184733. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184734. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184735. png_bytep buffer, png_size_t buffer_length));
  184736. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184737. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184738. png_infop info_ptr, png_uint_32 length));
  184739. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184740. png_infop info_ptr));
  184741. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184742. png_infop info_ptr));
  184743. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184744. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184745. png_infop info_ptr));
  184746. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184747. png_infop info_ptr));
  184748. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184749. #if defined(PNG_READ_tEXt_SUPPORTED)
  184750. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184751. png_infop info_ptr, png_uint_32 length));
  184752. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184753. png_infop info_ptr));
  184754. #endif
  184755. #if defined(PNG_READ_zTXt_SUPPORTED)
  184756. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184757. png_infop info_ptr, png_uint_32 length));
  184758. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184759. png_infop info_ptr));
  184760. #endif
  184761. #if defined(PNG_READ_iTXt_SUPPORTED)
  184762. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184763. png_infop info_ptr, png_uint_32 length));
  184764. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184765. png_infop info_ptr));
  184766. #endif
  184767. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184768. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184769. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184770. png_bytep row));
  184771. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184772. png_bytep row));
  184773. #endif
  184774. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184775. #if defined(PNG_MMX_CODE_SUPPORTED)
  184776. /* png.c */ /* PRIVATE */
  184777. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184778. #endif
  184779. #endif
  184780. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184781. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184782. png_infop info_ptr));
  184783. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184784. png_infop info_ptr));
  184785. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184786. png_infop info_ptr));
  184787. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184788. png_infop info_ptr));
  184789. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184790. png_infop info_ptr));
  184791. #if defined(PNG_pHYs_SUPPORTED)
  184792. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184793. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184794. #endif /* PNG_pHYs_SUPPORTED */
  184795. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184796. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184797. #endif /* PNG_INTERNAL */
  184798. #ifdef __cplusplus
  184799. //}
  184800. #endif
  184801. #endif /* PNG_VERSION_INFO_ONLY */
  184802. /* do not put anything past this line */
  184803. #endif /* PNG_H */
  184804. /*** End of inlined file: png.h ***/
  184805. #define PNG_NO_EXTERN
  184806. /*** Start of inlined file: png.c ***/
  184807. /* png.c - location for general purpose libpng functions
  184808. *
  184809. * Last changed in libpng 1.2.21 [October 4, 2007]
  184810. * For conditions of distribution and use, see copyright notice in png.h
  184811. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184812. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184813. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184814. */
  184815. #define PNG_INTERNAL
  184816. #define PNG_NO_EXTERN
  184817. /* Generate a compiler error if there is an old png.h in the search path. */
  184818. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184819. /* Version information for C files. This had better match the version
  184820. * string defined in png.h. */
  184821. #ifdef PNG_USE_GLOBAL_ARRAYS
  184822. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184823. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184824. #ifdef PNG_READ_SUPPORTED
  184825. /* png_sig was changed to a function in version 1.0.5c */
  184826. /* Place to hold the signature string for a PNG file. */
  184827. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184828. #endif /* PNG_READ_SUPPORTED */
  184829. /* Invoke global declarations for constant strings for known chunk types */
  184830. PNG_IHDR;
  184831. PNG_IDAT;
  184832. PNG_IEND;
  184833. PNG_PLTE;
  184834. PNG_bKGD;
  184835. PNG_cHRM;
  184836. PNG_gAMA;
  184837. PNG_hIST;
  184838. PNG_iCCP;
  184839. PNG_iTXt;
  184840. PNG_oFFs;
  184841. PNG_pCAL;
  184842. PNG_sCAL;
  184843. PNG_pHYs;
  184844. PNG_sBIT;
  184845. PNG_sPLT;
  184846. PNG_sRGB;
  184847. PNG_tEXt;
  184848. PNG_tIME;
  184849. PNG_tRNS;
  184850. PNG_zTXt;
  184851. #ifdef PNG_READ_SUPPORTED
  184852. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184853. /* start of interlace block */
  184854. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184855. /* offset to next interlace block */
  184856. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184857. /* start of interlace block in the y direction */
  184858. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184859. /* offset to next interlace block in the y direction */
  184860. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184861. /* Height of interlace block. This is not currently used - if you need
  184862. * it, uncomment it here and in png.h
  184863. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184864. */
  184865. /* Mask to determine which pixels are valid in a pass */
  184866. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184867. /* Mask to determine which pixels to overwrite while displaying */
  184868. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184869. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184870. #endif /* PNG_READ_SUPPORTED */
  184871. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184872. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184873. * of the PNG file signature. If the PNG data is embedded into another
  184874. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184875. * or write any of the magic bytes before it starts on the IHDR.
  184876. */
  184877. #ifdef PNG_READ_SUPPORTED
  184878. void PNGAPI
  184879. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184880. {
  184881. if(png_ptr == NULL) return;
  184882. png_debug(1, "in png_set_sig_bytes\n");
  184883. if (num_bytes > 8)
  184884. png_error(png_ptr, "Too many bytes for PNG signature.");
  184885. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184886. }
  184887. /* Checks whether the supplied bytes match the PNG signature. We allow
  184888. * checking less than the full 8-byte signature so that those apps that
  184889. * already read the first few bytes of a file to determine the file type
  184890. * can simply check the remaining bytes for extra assurance. Returns
  184891. * an integer less than, equal to, or greater than zero if sig is found,
  184892. * respectively, to be less than, to match, or be greater than the correct
  184893. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184894. */
  184895. int PNGAPI
  184896. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184897. {
  184898. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184899. if (num_to_check > 8)
  184900. num_to_check = 8;
  184901. else if (num_to_check < 1)
  184902. return (-1);
  184903. if (start > 7)
  184904. return (-1);
  184905. if (start + num_to_check > 8)
  184906. num_to_check = 8 - start;
  184907. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184908. }
  184909. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184910. /* (Obsolete) function to check signature bytes. It does not allow one
  184911. * to check a partial signature. This function might be removed in the
  184912. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184913. */
  184914. int PNGAPI
  184915. png_check_sig(png_bytep sig, int num)
  184916. {
  184917. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184918. }
  184919. #endif
  184920. #endif /* PNG_READ_SUPPORTED */
  184921. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184922. /* Function to allocate memory for zlib and clear it to 0. */
  184923. #ifdef PNG_1_0_X
  184924. voidpf PNGAPI
  184925. #else
  184926. voidpf /* private */
  184927. #endif
  184928. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184929. {
  184930. png_voidp ptr;
  184931. png_structp p=(png_structp)png_ptr;
  184932. png_uint_32 save_flags=p->flags;
  184933. png_uint_32 num_bytes;
  184934. if(png_ptr == NULL) return (NULL);
  184935. if (items > PNG_UINT_32_MAX/size)
  184936. {
  184937. png_warning (p, "Potential overflow in png_zalloc()");
  184938. return (NULL);
  184939. }
  184940. num_bytes = (png_uint_32)items * size;
  184941. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184942. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184943. p->flags=save_flags;
  184944. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184945. if (ptr == NULL)
  184946. return ((voidpf)ptr);
  184947. if (num_bytes > (png_uint_32)0x8000L)
  184948. {
  184949. png_memset(ptr, 0, (png_size_t)0x8000L);
  184950. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184951. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184952. }
  184953. else
  184954. {
  184955. png_memset(ptr, 0, (png_size_t)num_bytes);
  184956. }
  184957. #endif
  184958. return ((voidpf)ptr);
  184959. }
  184960. /* function to free memory for zlib */
  184961. #ifdef PNG_1_0_X
  184962. void PNGAPI
  184963. #else
  184964. void /* private */
  184965. #endif
  184966. png_zfree(voidpf png_ptr, voidpf ptr)
  184967. {
  184968. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184969. }
  184970. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184971. * in case CRC is > 32 bits to leave the top bits 0.
  184972. */
  184973. void /* PRIVATE */
  184974. png_reset_crc(png_structp png_ptr)
  184975. {
  184976. png_ptr->crc = crc32(0, Z_NULL, 0);
  184977. }
  184978. /* Calculate the CRC over a section of data. We can only pass as
  184979. * much data to this routine as the largest single buffer size. We
  184980. * also check that this data will actually be used before going to the
  184981. * trouble of calculating it.
  184982. */
  184983. void /* PRIVATE */
  184984. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184985. {
  184986. int need_crc = 1;
  184987. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184988. {
  184989. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184990. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184991. need_crc = 0;
  184992. }
  184993. else /* critical */
  184994. {
  184995. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184996. need_crc = 0;
  184997. }
  184998. if (need_crc)
  184999. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185000. }
  185001. /* Allocate the memory for an info_struct for the application. We don't
  185002. * really need the png_ptr, but it could potentially be useful in the
  185003. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185004. * and png_info_init() so that applications that want to use a shared
  185005. * libpng don't have to be recompiled if png_info changes size.
  185006. */
  185007. png_infop PNGAPI
  185008. png_create_info_struct(png_structp png_ptr)
  185009. {
  185010. png_infop info_ptr;
  185011. png_debug(1, "in png_create_info_struct\n");
  185012. if(png_ptr == NULL) return (NULL);
  185013. #ifdef PNG_USER_MEM_SUPPORTED
  185014. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185015. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185016. #else
  185017. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185018. #endif
  185019. if (info_ptr != NULL)
  185020. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185021. return (info_ptr);
  185022. }
  185023. /* This function frees the memory associated with a single info struct.
  185024. * Normally, one would use either png_destroy_read_struct() or
  185025. * png_destroy_write_struct() to free an info struct, but this may be
  185026. * useful for some applications.
  185027. */
  185028. void PNGAPI
  185029. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185030. {
  185031. png_infop info_ptr = NULL;
  185032. if(png_ptr == NULL) return;
  185033. png_debug(1, "in png_destroy_info_struct\n");
  185034. if (info_ptr_ptr != NULL)
  185035. info_ptr = *info_ptr_ptr;
  185036. if (info_ptr != NULL)
  185037. {
  185038. png_info_destroy(png_ptr, info_ptr);
  185039. #ifdef PNG_USER_MEM_SUPPORTED
  185040. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185041. png_ptr->mem_ptr);
  185042. #else
  185043. png_destroy_struct((png_voidp)info_ptr);
  185044. #endif
  185045. *info_ptr_ptr = NULL;
  185046. }
  185047. }
  185048. /* Initialize the info structure. This is now an internal function (0.89)
  185049. * and applications using it are urged to use png_create_info_struct()
  185050. * instead.
  185051. */
  185052. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185053. #undef png_info_init
  185054. void PNGAPI
  185055. png_info_init(png_infop info_ptr)
  185056. {
  185057. /* We only come here via pre-1.0.12-compiled applications */
  185058. png_info_init_3(&info_ptr, 0);
  185059. }
  185060. #endif
  185061. void PNGAPI
  185062. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185063. {
  185064. png_infop info_ptr = *ptr_ptr;
  185065. if(info_ptr == NULL) return;
  185066. png_debug(1, "in png_info_init_3\n");
  185067. if(png_sizeof(png_info) > png_info_struct_size)
  185068. {
  185069. png_destroy_struct(info_ptr);
  185070. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185071. *ptr_ptr = info_ptr;
  185072. }
  185073. /* set everything to 0 */
  185074. png_memset(info_ptr, 0, png_sizeof (png_info));
  185075. }
  185076. #ifdef PNG_FREE_ME_SUPPORTED
  185077. void PNGAPI
  185078. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185079. int freer, png_uint_32 mask)
  185080. {
  185081. png_debug(1, "in png_data_freer\n");
  185082. if (png_ptr == NULL || info_ptr == NULL)
  185083. return;
  185084. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185085. info_ptr->free_me |= mask;
  185086. else if(freer == PNG_USER_WILL_FREE_DATA)
  185087. info_ptr->free_me &= ~mask;
  185088. else
  185089. png_warning(png_ptr,
  185090. "Unknown freer parameter in png_data_freer.");
  185091. }
  185092. #endif
  185093. void PNGAPI
  185094. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185095. int num)
  185096. {
  185097. png_debug(1, "in png_free_data\n");
  185098. if (png_ptr == NULL || info_ptr == NULL)
  185099. return;
  185100. #if defined(PNG_TEXT_SUPPORTED)
  185101. /* free text item num or (if num == -1) all text items */
  185102. #ifdef PNG_FREE_ME_SUPPORTED
  185103. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185104. #else
  185105. if (mask & PNG_FREE_TEXT)
  185106. #endif
  185107. {
  185108. if (num != -1)
  185109. {
  185110. if (info_ptr->text && info_ptr->text[num].key)
  185111. {
  185112. png_free(png_ptr, info_ptr->text[num].key);
  185113. info_ptr->text[num].key = NULL;
  185114. }
  185115. }
  185116. else
  185117. {
  185118. int i;
  185119. for (i = 0; i < info_ptr->num_text; i++)
  185120. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185121. png_free(png_ptr, info_ptr->text);
  185122. info_ptr->text = NULL;
  185123. info_ptr->num_text=0;
  185124. }
  185125. }
  185126. #endif
  185127. #if defined(PNG_tRNS_SUPPORTED)
  185128. /* free any tRNS entry */
  185129. #ifdef PNG_FREE_ME_SUPPORTED
  185130. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185131. #else
  185132. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185133. #endif
  185134. {
  185135. png_free(png_ptr, info_ptr->trans);
  185136. info_ptr->valid &= ~PNG_INFO_tRNS;
  185137. #ifndef PNG_FREE_ME_SUPPORTED
  185138. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185139. #endif
  185140. info_ptr->trans = NULL;
  185141. }
  185142. #endif
  185143. #if defined(PNG_sCAL_SUPPORTED)
  185144. /* free any sCAL entry */
  185145. #ifdef PNG_FREE_ME_SUPPORTED
  185146. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185147. #else
  185148. if (mask & PNG_FREE_SCAL)
  185149. #endif
  185150. {
  185151. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185152. png_free(png_ptr, info_ptr->scal_s_width);
  185153. png_free(png_ptr, info_ptr->scal_s_height);
  185154. info_ptr->scal_s_width = NULL;
  185155. info_ptr->scal_s_height = NULL;
  185156. #endif
  185157. info_ptr->valid &= ~PNG_INFO_sCAL;
  185158. }
  185159. #endif
  185160. #if defined(PNG_pCAL_SUPPORTED)
  185161. /* free any pCAL entry */
  185162. #ifdef PNG_FREE_ME_SUPPORTED
  185163. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185164. #else
  185165. if (mask & PNG_FREE_PCAL)
  185166. #endif
  185167. {
  185168. png_free(png_ptr, info_ptr->pcal_purpose);
  185169. png_free(png_ptr, info_ptr->pcal_units);
  185170. info_ptr->pcal_purpose = NULL;
  185171. info_ptr->pcal_units = NULL;
  185172. if (info_ptr->pcal_params != NULL)
  185173. {
  185174. int i;
  185175. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185176. {
  185177. png_free(png_ptr, info_ptr->pcal_params[i]);
  185178. info_ptr->pcal_params[i]=NULL;
  185179. }
  185180. png_free(png_ptr, info_ptr->pcal_params);
  185181. info_ptr->pcal_params = NULL;
  185182. }
  185183. info_ptr->valid &= ~PNG_INFO_pCAL;
  185184. }
  185185. #endif
  185186. #if defined(PNG_iCCP_SUPPORTED)
  185187. /* free any iCCP entry */
  185188. #ifdef PNG_FREE_ME_SUPPORTED
  185189. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185190. #else
  185191. if (mask & PNG_FREE_ICCP)
  185192. #endif
  185193. {
  185194. png_free(png_ptr, info_ptr->iccp_name);
  185195. png_free(png_ptr, info_ptr->iccp_profile);
  185196. info_ptr->iccp_name = NULL;
  185197. info_ptr->iccp_profile = NULL;
  185198. info_ptr->valid &= ~PNG_INFO_iCCP;
  185199. }
  185200. #endif
  185201. #if defined(PNG_sPLT_SUPPORTED)
  185202. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185203. #ifdef PNG_FREE_ME_SUPPORTED
  185204. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185205. #else
  185206. if (mask & PNG_FREE_SPLT)
  185207. #endif
  185208. {
  185209. if (num != -1)
  185210. {
  185211. if(info_ptr->splt_palettes)
  185212. {
  185213. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185214. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185215. info_ptr->splt_palettes[num].name = NULL;
  185216. info_ptr->splt_palettes[num].entries = NULL;
  185217. }
  185218. }
  185219. else
  185220. {
  185221. if(info_ptr->splt_palettes_num)
  185222. {
  185223. int i;
  185224. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185225. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185226. png_free(png_ptr, info_ptr->splt_palettes);
  185227. info_ptr->splt_palettes = NULL;
  185228. info_ptr->splt_palettes_num = 0;
  185229. }
  185230. info_ptr->valid &= ~PNG_INFO_sPLT;
  185231. }
  185232. }
  185233. #endif
  185234. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185235. if(png_ptr->unknown_chunk.data)
  185236. {
  185237. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185238. png_ptr->unknown_chunk.data = NULL;
  185239. }
  185240. #ifdef PNG_FREE_ME_SUPPORTED
  185241. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185242. #else
  185243. if (mask & PNG_FREE_UNKN)
  185244. #endif
  185245. {
  185246. if (num != -1)
  185247. {
  185248. if(info_ptr->unknown_chunks)
  185249. {
  185250. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185251. info_ptr->unknown_chunks[num].data = NULL;
  185252. }
  185253. }
  185254. else
  185255. {
  185256. int i;
  185257. if(info_ptr->unknown_chunks_num)
  185258. {
  185259. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185260. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185261. png_free(png_ptr, info_ptr->unknown_chunks);
  185262. info_ptr->unknown_chunks = NULL;
  185263. info_ptr->unknown_chunks_num = 0;
  185264. }
  185265. }
  185266. }
  185267. #endif
  185268. #if defined(PNG_hIST_SUPPORTED)
  185269. /* free any hIST entry */
  185270. #ifdef PNG_FREE_ME_SUPPORTED
  185271. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185272. #else
  185273. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185274. #endif
  185275. {
  185276. png_free(png_ptr, info_ptr->hist);
  185277. info_ptr->hist = NULL;
  185278. info_ptr->valid &= ~PNG_INFO_hIST;
  185279. #ifndef PNG_FREE_ME_SUPPORTED
  185280. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185281. #endif
  185282. }
  185283. #endif
  185284. /* free any PLTE entry that was internally allocated */
  185285. #ifdef PNG_FREE_ME_SUPPORTED
  185286. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185287. #else
  185288. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185289. #endif
  185290. {
  185291. png_zfree(png_ptr, info_ptr->palette);
  185292. info_ptr->palette = NULL;
  185293. info_ptr->valid &= ~PNG_INFO_PLTE;
  185294. #ifndef PNG_FREE_ME_SUPPORTED
  185295. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185296. #endif
  185297. info_ptr->num_palette = 0;
  185298. }
  185299. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185300. /* free any image bits attached to the info structure */
  185301. #ifdef PNG_FREE_ME_SUPPORTED
  185302. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185303. #else
  185304. if (mask & PNG_FREE_ROWS)
  185305. #endif
  185306. {
  185307. if(info_ptr->row_pointers)
  185308. {
  185309. int row;
  185310. for (row = 0; row < (int)info_ptr->height; row++)
  185311. {
  185312. png_free(png_ptr, info_ptr->row_pointers[row]);
  185313. info_ptr->row_pointers[row]=NULL;
  185314. }
  185315. png_free(png_ptr, info_ptr->row_pointers);
  185316. info_ptr->row_pointers=NULL;
  185317. }
  185318. info_ptr->valid &= ~PNG_INFO_IDAT;
  185319. }
  185320. #endif
  185321. #ifdef PNG_FREE_ME_SUPPORTED
  185322. if(num == -1)
  185323. info_ptr->free_me &= ~mask;
  185324. else
  185325. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185326. #endif
  185327. }
  185328. /* This is an internal routine to free any memory that the info struct is
  185329. * pointing to before re-using it or freeing the struct itself. Recall
  185330. * that png_free() checks for NULL pointers for us.
  185331. */
  185332. void /* PRIVATE */
  185333. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185334. {
  185335. png_debug(1, "in png_info_destroy\n");
  185336. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185337. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185338. if (png_ptr->num_chunk_list)
  185339. {
  185340. png_free(png_ptr, png_ptr->chunk_list);
  185341. png_ptr->chunk_list=NULL;
  185342. png_ptr->num_chunk_list=0;
  185343. }
  185344. #endif
  185345. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185346. }
  185347. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185348. /* This function returns a pointer to the io_ptr associated with the user
  185349. * functions. The application should free any memory associated with this
  185350. * pointer before png_write_destroy() or png_read_destroy() are called.
  185351. */
  185352. png_voidp PNGAPI
  185353. png_get_io_ptr(png_structp png_ptr)
  185354. {
  185355. if(png_ptr == NULL) return (NULL);
  185356. return (png_ptr->io_ptr);
  185357. }
  185358. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185359. #if !defined(PNG_NO_STDIO)
  185360. /* Initialize the default input/output functions for the PNG file. If you
  185361. * use your own read or write routines, you can call either png_set_read_fn()
  185362. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185363. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185364. * necessarily available.
  185365. */
  185366. void PNGAPI
  185367. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185368. {
  185369. png_debug(1, "in png_init_io\n");
  185370. if(png_ptr == NULL) return;
  185371. png_ptr->io_ptr = (png_voidp)fp;
  185372. }
  185373. #endif
  185374. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185375. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185376. * a "Creation Time" or other text-based time string.
  185377. */
  185378. png_charp PNGAPI
  185379. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185380. {
  185381. static PNG_CONST char short_months[12][4] =
  185382. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185383. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185384. if(png_ptr == NULL) return (NULL);
  185385. if (png_ptr->time_buffer == NULL)
  185386. {
  185387. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185388. png_sizeof(char)));
  185389. }
  185390. #if defined(_WIN32_WCE)
  185391. {
  185392. wchar_t time_buf[29];
  185393. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185394. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185395. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185396. ptime->second % 61);
  185397. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185398. NULL, NULL);
  185399. }
  185400. #else
  185401. #ifdef USE_FAR_KEYWORD
  185402. {
  185403. char near_time_buf[29];
  185404. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185405. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185406. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185407. ptime->second % 61);
  185408. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185409. 29*png_sizeof(char));
  185410. }
  185411. #else
  185412. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185413. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185414. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185415. ptime->second % 61);
  185416. #endif
  185417. #endif /* _WIN32_WCE */
  185418. return ((png_charp)png_ptr->time_buffer);
  185419. }
  185420. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185421. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185422. png_charp PNGAPI
  185423. png_get_copyright(png_structp png_ptr)
  185424. {
  185425. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185426. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185427. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185428. Copyright (c) 1996-1997 Andreas Dilger\n\
  185429. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185430. }
  185431. /* The following return the library version as a short string in the
  185432. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185433. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185434. * is defined in png.h.
  185435. * Note: now there is no difference between png_get_libpng_ver() and
  185436. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185437. * it is guaranteed that png.c uses the correct version of png.h.
  185438. */
  185439. png_charp PNGAPI
  185440. png_get_libpng_ver(png_structp png_ptr)
  185441. {
  185442. /* Version of *.c files used when building libpng */
  185443. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185444. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185445. }
  185446. png_charp PNGAPI
  185447. png_get_header_ver(png_structp png_ptr)
  185448. {
  185449. /* Version of *.h files used when building libpng */
  185450. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185451. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185452. }
  185453. png_charp PNGAPI
  185454. png_get_header_version(png_structp png_ptr)
  185455. {
  185456. /* Returns longer string containing both version and date */
  185457. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185458. return ((png_charp) PNG_HEADER_VERSION_STRING
  185459. #ifndef PNG_READ_SUPPORTED
  185460. " (NO READ SUPPORT)"
  185461. #endif
  185462. "\n");
  185463. }
  185464. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185465. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185466. int PNGAPI
  185467. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185468. {
  185469. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185470. int i;
  185471. png_bytep p;
  185472. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185473. return 0;
  185474. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185475. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185476. if (!png_memcmp(chunk_name, p, 4))
  185477. return ((int)*(p+4));
  185478. return 0;
  185479. }
  185480. #endif
  185481. /* This function, added to libpng-1.0.6g, is untested. */
  185482. int PNGAPI
  185483. png_reset_zstream(png_structp png_ptr)
  185484. {
  185485. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185486. return (inflateReset(&png_ptr->zstream));
  185487. }
  185488. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185489. /* This function was added to libpng-1.0.7 */
  185490. png_uint_32 PNGAPI
  185491. png_access_version_number(void)
  185492. {
  185493. /* Version of *.c files used when building libpng */
  185494. return((png_uint_32) PNG_LIBPNG_VER);
  185495. }
  185496. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185497. #if !defined(PNG_1_0_X)
  185498. /* this function was added to libpng 1.2.0 */
  185499. int PNGAPI
  185500. png_mmx_support(void)
  185501. {
  185502. /* obsolete, to be removed from libpng-1.4.0 */
  185503. return -1;
  185504. }
  185505. #endif /* PNG_1_0_X */
  185506. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185507. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185508. #ifdef PNG_SIZE_T
  185509. /* Added at libpng version 1.2.6 */
  185510. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185511. png_size_t PNGAPI
  185512. png_convert_size(size_t size)
  185513. {
  185514. if (size > (png_size_t)-1)
  185515. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185516. return ((png_size_t)size);
  185517. }
  185518. #endif /* PNG_SIZE_T */
  185519. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185520. /*** End of inlined file: png.c ***/
  185521. /*** Start of inlined file: pngerror.c ***/
  185522. /* pngerror.c - stub functions for i/o and memory allocation
  185523. *
  185524. * Last changed in libpng 1.2.20 October 4, 2007
  185525. * For conditions of distribution and use, see copyright notice in png.h
  185526. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185527. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185528. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185529. *
  185530. * This file provides a location for all error handling. Users who
  185531. * need special error handling are expected to write replacement functions
  185532. * and use png_set_error_fn() to use those functions. See the instructions
  185533. * at each function.
  185534. */
  185535. #define PNG_INTERNAL
  185536. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185537. static void /* PRIVATE */
  185538. png_default_error PNGARG((png_structp png_ptr,
  185539. png_const_charp error_message));
  185540. #ifndef PNG_NO_WARNINGS
  185541. static void /* PRIVATE */
  185542. png_default_warning PNGARG((png_structp png_ptr,
  185543. png_const_charp warning_message));
  185544. #endif /* PNG_NO_WARNINGS */
  185545. /* This function is called whenever there is a fatal error. This function
  185546. * should not be changed. If there is a need to handle errors differently,
  185547. * you should supply a replacement error function and use png_set_error_fn()
  185548. * to replace the error function at run-time.
  185549. */
  185550. #ifndef PNG_NO_ERROR_TEXT
  185551. void PNGAPI
  185552. png_error(png_structp png_ptr, png_const_charp error_message)
  185553. {
  185554. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185555. char msg[16];
  185556. if (png_ptr != NULL)
  185557. {
  185558. if (png_ptr->flags&
  185559. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185560. {
  185561. if (*error_message == '#')
  185562. {
  185563. int offset;
  185564. for (offset=1; offset<15; offset++)
  185565. if (*(error_message+offset) == ' ')
  185566. break;
  185567. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185568. {
  185569. int i;
  185570. for (i=0; i<offset-1; i++)
  185571. msg[i]=error_message[i+1];
  185572. msg[i]='\0';
  185573. error_message=msg;
  185574. }
  185575. else
  185576. error_message+=offset;
  185577. }
  185578. else
  185579. {
  185580. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185581. {
  185582. msg[0]='0';
  185583. msg[1]='\0';
  185584. error_message=msg;
  185585. }
  185586. }
  185587. }
  185588. }
  185589. #endif
  185590. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185591. (*(png_ptr->error_fn))(png_ptr, error_message);
  185592. /* If the custom handler doesn't exist, or if it returns,
  185593. use the default handler, which will not return. */
  185594. png_default_error(png_ptr, error_message);
  185595. }
  185596. #else
  185597. void PNGAPI
  185598. png_err(png_structp png_ptr)
  185599. {
  185600. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185601. (*(png_ptr->error_fn))(png_ptr, '\0');
  185602. /* If the custom handler doesn't exist, or if it returns,
  185603. use the default handler, which will not return. */
  185604. png_default_error(png_ptr, '\0');
  185605. }
  185606. #endif /* PNG_NO_ERROR_TEXT */
  185607. #ifndef PNG_NO_WARNINGS
  185608. /* This function is called whenever there is a non-fatal error. This function
  185609. * should not be changed. If there is a need to handle warnings differently,
  185610. * you should supply a replacement warning function and use
  185611. * png_set_error_fn() to replace the warning function at run-time.
  185612. */
  185613. void PNGAPI
  185614. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185615. {
  185616. int offset = 0;
  185617. if (png_ptr != NULL)
  185618. {
  185619. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185620. if (png_ptr->flags&
  185621. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185622. #endif
  185623. {
  185624. if (*warning_message == '#')
  185625. {
  185626. for (offset=1; offset<15; offset++)
  185627. if (*(warning_message+offset) == ' ')
  185628. break;
  185629. }
  185630. }
  185631. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185632. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185633. }
  185634. else
  185635. png_default_warning(png_ptr, warning_message+offset);
  185636. }
  185637. #endif /* PNG_NO_WARNINGS */
  185638. /* These utilities are used internally to build an error message that relates
  185639. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185640. * this is used to prefix the message. The message is limited in length
  185641. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185642. * if the character is invalid.
  185643. */
  185644. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185645. /*static PNG_CONST char png_digit[16] = {
  185646. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185647. 'A', 'B', 'C', 'D', 'E', 'F'
  185648. };*/
  185649. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185650. static void /* PRIVATE */
  185651. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185652. error_message)
  185653. {
  185654. int iout = 0, iin = 0;
  185655. while (iin < 4)
  185656. {
  185657. int c = png_ptr->chunk_name[iin++];
  185658. if (isnonalpha(c))
  185659. {
  185660. buffer[iout++] = '[';
  185661. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185662. buffer[iout++] = png_digit[c & 0x0f];
  185663. buffer[iout++] = ']';
  185664. }
  185665. else
  185666. {
  185667. buffer[iout++] = (png_byte)c;
  185668. }
  185669. }
  185670. if (error_message == NULL)
  185671. buffer[iout] = 0;
  185672. else
  185673. {
  185674. buffer[iout++] = ':';
  185675. buffer[iout++] = ' ';
  185676. png_strncpy(buffer+iout, error_message, 63);
  185677. buffer[iout+63] = 0;
  185678. }
  185679. }
  185680. #ifdef PNG_READ_SUPPORTED
  185681. void PNGAPI
  185682. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185683. {
  185684. char msg[18+64];
  185685. if (png_ptr == NULL)
  185686. png_error(png_ptr, error_message);
  185687. else
  185688. {
  185689. png_format_buffer(png_ptr, msg, error_message);
  185690. png_error(png_ptr, msg);
  185691. }
  185692. }
  185693. #endif /* PNG_READ_SUPPORTED */
  185694. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185695. #ifndef PNG_NO_WARNINGS
  185696. void PNGAPI
  185697. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185698. {
  185699. char msg[18+64];
  185700. if (png_ptr == NULL)
  185701. png_warning(png_ptr, warning_message);
  185702. else
  185703. {
  185704. png_format_buffer(png_ptr, msg, warning_message);
  185705. png_warning(png_ptr, msg);
  185706. }
  185707. }
  185708. #endif /* PNG_NO_WARNINGS */
  185709. /* This is the default error handling function. Note that replacements for
  185710. * this function MUST NOT RETURN, or the program will likely crash. This
  185711. * function is used by default, or if the program supplies NULL for the
  185712. * error function pointer in png_set_error_fn().
  185713. */
  185714. static void /* PRIVATE */
  185715. png_default_error(png_structp, png_const_charp error_message)
  185716. {
  185717. #ifndef PNG_NO_CONSOLE_IO
  185718. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185719. if (*error_message == '#')
  185720. {
  185721. int offset;
  185722. char error_number[16];
  185723. for (offset=0; offset<15; offset++)
  185724. {
  185725. error_number[offset] = *(error_message+offset+1);
  185726. if (*(error_message+offset) == ' ')
  185727. break;
  185728. }
  185729. if((offset > 1) && (offset < 15))
  185730. {
  185731. error_number[offset-1]='\0';
  185732. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185733. error_message+offset);
  185734. }
  185735. else
  185736. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185737. }
  185738. else
  185739. #endif
  185740. fprintf(stderr, "libpng error: %s\n", error_message);
  185741. #endif
  185742. #ifdef PNG_SETJMP_SUPPORTED
  185743. if (png_ptr)
  185744. {
  185745. # ifdef USE_FAR_KEYWORD
  185746. {
  185747. jmp_buf jmpbuf;
  185748. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185749. longjmp(jmpbuf, 1);
  185750. }
  185751. # else
  185752. longjmp(png_ptr->jmpbuf, 1);
  185753. # endif
  185754. }
  185755. #else
  185756. PNG_ABORT();
  185757. #endif
  185758. #ifdef PNG_NO_CONSOLE_IO
  185759. error_message = error_message; /* make compiler happy */
  185760. #endif
  185761. }
  185762. #ifndef PNG_NO_WARNINGS
  185763. /* This function is called when there is a warning, but the library thinks
  185764. * it can continue anyway. Replacement functions don't have to do anything
  185765. * here if you don't want them to. In the default configuration, png_ptr is
  185766. * not used, but it is passed in case it may be useful.
  185767. */
  185768. static void /* PRIVATE */
  185769. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185770. {
  185771. #ifndef PNG_NO_CONSOLE_IO
  185772. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185773. if (*warning_message == '#')
  185774. {
  185775. int offset;
  185776. char warning_number[16];
  185777. for (offset=0; offset<15; offset++)
  185778. {
  185779. warning_number[offset]=*(warning_message+offset+1);
  185780. if (*(warning_message+offset) == ' ')
  185781. break;
  185782. }
  185783. if((offset > 1) && (offset < 15))
  185784. {
  185785. warning_number[offset-1]='\0';
  185786. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185787. warning_message+offset);
  185788. }
  185789. else
  185790. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185791. }
  185792. else
  185793. # endif
  185794. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185795. #else
  185796. warning_message = warning_message; /* make compiler happy */
  185797. #endif
  185798. png_ptr = png_ptr; /* make compiler happy */
  185799. }
  185800. #endif /* PNG_NO_WARNINGS */
  185801. /* This function is called when the application wants to use another method
  185802. * of handling errors and warnings. Note that the error function MUST NOT
  185803. * return to the calling routine or serious problems will occur. The return
  185804. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185805. */
  185806. void PNGAPI
  185807. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185808. png_error_ptr error_fn, png_error_ptr warning_fn)
  185809. {
  185810. if (png_ptr == NULL)
  185811. return;
  185812. png_ptr->error_ptr = error_ptr;
  185813. png_ptr->error_fn = error_fn;
  185814. png_ptr->warning_fn = warning_fn;
  185815. }
  185816. /* This function returns a pointer to the error_ptr associated with the user
  185817. * functions. The application should free any memory associated with this
  185818. * pointer before png_write_destroy and png_read_destroy are called.
  185819. */
  185820. png_voidp PNGAPI
  185821. png_get_error_ptr(png_structp png_ptr)
  185822. {
  185823. if (png_ptr == NULL)
  185824. return NULL;
  185825. return ((png_voidp)png_ptr->error_ptr);
  185826. }
  185827. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185828. void PNGAPI
  185829. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185830. {
  185831. if(png_ptr != NULL)
  185832. {
  185833. png_ptr->flags &=
  185834. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185835. }
  185836. }
  185837. #endif
  185838. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185839. /*** End of inlined file: pngerror.c ***/
  185840. /*** Start of inlined file: pngget.c ***/
  185841. /* pngget.c - retrieval of values from info struct
  185842. *
  185843. * Last changed in libpng 1.2.15 January 5, 2007
  185844. * For conditions of distribution and use, see copyright notice in png.h
  185845. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185846. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185847. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185848. */
  185849. #define PNG_INTERNAL
  185850. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185851. png_uint_32 PNGAPI
  185852. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185853. {
  185854. if (png_ptr != NULL && info_ptr != NULL)
  185855. return(info_ptr->valid & flag);
  185856. else
  185857. return(0);
  185858. }
  185859. png_uint_32 PNGAPI
  185860. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185861. {
  185862. if (png_ptr != NULL && info_ptr != NULL)
  185863. return(info_ptr->rowbytes);
  185864. else
  185865. return(0);
  185866. }
  185867. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185868. png_bytepp PNGAPI
  185869. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185870. {
  185871. if (png_ptr != NULL && info_ptr != NULL)
  185872. return(info_ptr->row_pointers);
  185873. else
  185874. return(0);
  185875. }
  185876. #endif
  185877. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185878. /* easy access to info, added in libpng-0.99 */
  185879. png_uint_32 PNGAPI
  185880. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185881. {
  185882. if (png_ptr != NULL && info_ptr != NULL)
  185883. {
  185884. return info_ptr->width;
  185885. }
  185886. return (0);
  185887. }
  185888. png_uint_32 PNGAPI
  185889. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185890. {
  185891. if (png_ptr != NULL && info_ptr != NULL)
  185892. {
  185893. return info_ptr->height;
  185894. }
  185895. return (0);
  185896. }
  185897. png_byte PNGAPI
  185898. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185899. {
  185900. if (png_ptr != NULL && info_ptr != NULL)
  185901. {
  185902. return info_ptr->bit_depth;
  185903. }
  185904. return (0);
  185905. }
  185906. png_byte PNGAPI
  185907. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185908. {
  185909. if (png_ptr != NULL && info_ptr != NULL)
  185910. {
  185911. return info_ptr->color_type;
  185912. }
  185913. return (0);
  185914. }
  185915. png_byte PNGAPI
  185916. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185917. {
  185918. if (png_ptr != NULL && info_ptr != NULL)
  185919. {
  185920. return info_ptr->filter_type;
  185921. }
  185922. return (0);
  185923. }
  185924. png_byte PNGAPI
  185925. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185926. {
  185927. if (png_ptr != NULL && info_ptr != NULL)
  185928. {
  185929. return info_ptr->interlace_type;
  185930. }
  185931. return (0);
  185932. }
  185933. png_byte PNGAPI
  185934. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185935. {
  185936. if (png_ptr != NULL && info_ptr != NULL)
  185937. {
  185938. return info_ptr->compression_type;
  185939. }
  185940. return (0);
  185941. }
  185942. png_uint_32 PNGAPI
  185943. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185944. {
  185945. if (png_ptr != NULL && info_ptr != NULL)
  185946. #if defined(PNG_pHYs_SUPPORTED)
  185947. if (info_ptr->valid & PNG_INFO_pHYs)
  185948. {
  185949. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185950. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185951. return (0);
  185952. else return (info_ptr->x_pixels_per_unit);
  185953. }
  185954. #else
  185955. return (0);
  185956. #endif
  185957. return (0);
  185958. }
  185959. png_uint_32 PNGAPI
  185960. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185961. {
  185962. if (png_ptr != NULL && info_ptr != NULL)
  185963. #if defined(PNG_pHYs_SUPPORTED)
  185964. if (info_ptr->valid & PNG_INFO_pHYs)
  185965. {
  185966. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185967. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185968. return (0);
  185969. else return (info_ptr->y_pixels_per_unit);
  185970. }
  185971. #else
  185972. return (0);
  185973. #endif
  185974. return (0);
  185975. }
  185976. png_uint_32 PNGAPI
  185977. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185978. {
  185979. if (png_ptr != NULL && info_ptr != NULL)
  185980. #if defined(PNG_pHYs_SUPPORTED)
  185981. if (info_ptr->valid & PNG_INFO_pHYs)
  185982. {
  185983. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185984. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185985. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185986. return (0);
  185987. else return (info_ptr->x_pixels_per_unit);
  185988. }
  185989. #else
  185990. return (0);
  185991. #endif
  185992. return (0);
  185993. }
  185994. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185995. float PNGAPI
  185996. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185997. {
  185998. if (png_ptr != NULL && info_ptr != NULL)
  185999. #if defined(PNG_pHYs_SUPPORTED)
  186000. if (info_ptr->valid & PNG_INFO_pHYs)
  186001. {
  186002. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186003. if (info_ptr->x_pixels_per_unit == 0)
  186004. return ((float)0.0);
  186005. else
  186006. return ((float)((float)info_ptr->y_pixels_per_unit
  186007. /(float)info_ptr->x_pixels_per_unit));
  186008. }
  186009. #else
  186010. return (0.0);
  186011. #endif
  186012. return ((float)0.0);
  186013. }
  186014. #endif
  186015. png_int_32 PNGAPI
  186016. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186017. {
  186018. if (png_ptr != NULL && info_ptr != NULL)
  186019. #if defined(PNG_oFFs_SUPPORTED)
  186020. if (info_ptr->valid & PNG_INFO_oFFs)
  186021. {
  186022. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186023. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186024. return (0);
  186025. else return (info_ptr->x_offset);
  186026. }
  186027. #else
  186028. return (0);
  186029. #endif
  186030. return (0);
  186031. }
  186032. png_int_32 PNGAPI
  186033. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186034. {
  186035. if (png_ptr != NULL && info_ptr != NULL)
  186036. #if defined(PNG_oFFs_SUPPORTED)
  186037. if (info_ptr->valid & PNG_INFO_oFFs)
  186038. {
  186039. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186040. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186041. return (0);
  186042. else return (info_ptr->y_offset);
  186043. }
  186044. #else
  186045. return (0);
  186046. #endif
  186047. return (0);
  186048. }
  186049. png_int_32 PNGAPI
  186050. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186051. {
  186052. if (png_ptr != NULL && info_ptr != NULL)
  186053. #if defined(PNG_oFFs_SUPPORTED)
  186054. if (info_ptr->valid & PNG_INFO_oFFs)
  186055. {
  186056. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186057. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186058. return (0);
  186059. else return (info_ptr->x_offset);
  186060. }
  186061. #else
  186062. return (0);
  186063. #endif
  186064. return (0);
  186065. }
  186066. png_int_32 PNGAPI
  186067. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186068. {
  186069. if (png_ptr != NULL && info_ptr != NULL)
  186070. #if defined(PNG_oFFs_SUPPORTED)
  186071. if (info_ptr->valid & PNG_INFO_oFFs)
  186072. {
  186073. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186074. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186075. return (0);
  186076. else return (info_ptr->y_offset);
  186077. }
  186078. #else
  186079. return (0);
  186080. #endif
  186081. return (0);
  186082. }
  186083. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186084. png_uint_32 PNGAPI
  186085. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186086. {
  186087. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186088. *.0254 +.5));
  186089. }
  186090. png_uint_32 PNGAPI
  186091. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186092. {
  186093. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186094. *.0254 +.5));
  186095. }
  186096. png_uint_32 PNGAPI
  186097. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186098. {
  186099. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186100. *.0254 +.5));
  186101. }
  186102. float PNGAPI
  186103. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186104. {
  186105. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186106. *.00003937);
  186107. }
  186108. float PNGAPI
  186109. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186110. {
  186111. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186112. *.00003937);
  186113. }
  186114. #if defined(PNG_pHYs_SUPPORTED)
  186115. png_uint_32 PNGAPI
  186116. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186117. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186118. {
  186119. png_uint_32 retval = 0;
  186120. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186121. {
  186122. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186123. if (res_x != NULL)
  186124. {
  186125. *res_x = info_ptr->x_pixels_per_unit;
  186126. retval |= PNG_INFO_pHYs;
  186127. }
  186128. if (res_y != NULL)
  186129. {
  186130. *res_y = info_ptr->y_pixels_per_unit;
  186131. retval |= PNG_INFO_pHYs;
  186132. }
  186133. if (unit_type != NULL)
  186134. {
  186135. *unit_type = (int)info_ptr->phys_unit_type;
  186136. retval |= PNG_INFO_pHYs;
  186137. if(*unit_type == 1)
  186138. {
  186139. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186140. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186141. }
  186142. }
  186143. }
  186144. return (retval);
  186145. }
  186146. #endif /* PNG_pHYs_SUPPORTED */
  186147. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186148. /* png_get_channels really belongs in here, too, but it's been around longer */
  186149. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186150. png_byte PNGAPI
  186151. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186152. {
  186153. if (png_ptr != NULL && info_ptr != NULL)
  186154. return(info_ptr->channels);
  186155. else
  186156. return (0);
  186157. }
  186158. png_bytep PNGAPI
  186159. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186160. {
  186161. if (png_ptr != NULL && info_ptr != NULL)
  186162. return(info_ptr->signature);
  186163. else
  186164. return (NULL);
  186165. }
  186166. #if defined(PNG_bKGD_SUPPORTED)
  186167. png_uint_32 PNGAPI
  186168. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186169. png_color_16p *background)
  186170. {
  186171. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186172. && background != NULL)
  186173. {
  186174. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186175. *background = &(info_ptr->background);
  186176. return (PNG_INFO_bKGD);
  186177. }
  186178. return (0);
  186179. }
  186180. #endif
  186181. #if defined(PNG_cHRM_SUPPORTED)
  186182. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186183. png_uint_32 PNGAPI
  186184. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186185. double *white_x, double *white_y, double *red_x, double *red_y,
  186186. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186187. {
  186188. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186189. {
  186190. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186191. if (white_x != NULL)
  186192. *white_x = (double)info_ptr->x_white;
  186193. if (white_y != NULL)
  186194. *white_y = (double)info_ptr->y_white;
  186195. if (red_x != NULL)
  186196. *red_x = (double)info_ptr->x_red;
  186197. if (red_y != NULL)
  186198. *red_y = (double)info_ptr->y_red;
  186199. if (green_x != NULL)
  186200. *green_x = (double)info_ptr->x_green;
  186201. if (green_y != NULL)
  186202. *green_y = (double)info_ptr->y_green;
  186203. if (blue_x != NULL)
  186204. *blue_x = (double)info_ptr->x_blue;
  186205. if (blue_y != NULL)
  186206. *blue_y = (double)info_ptr->y_blue;
  186207. return (PNG_INFO_cHRM);
  186208. }
  186209. return (0);
  186210. }
  186211. #endif
  186212. #ifdef PNG_FIXED_POINT_SUPPORTED
  186213. png_uint_32 PNGAPI
  186214. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186215. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186216. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186217. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186218. {
  186219. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186220. {
  186221. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186222. if (white_x != NULL)
  186223. *white_x = info_ptr->int_x_white;
  186224. if (white_y != NULL)
  186225. *white_y = info_ptr->int_y_white;
  186226. if (red_x != NULL)
  186227. *red_x = info_ptr->int_x_red;
  186228. if (red_y != NULL)
  186229. *red_y = info_ptr->int_y_red;
  186230. if (green_x != NULL)
  186231. *green_x = info_ptr->int_x_green;
  186232. if (green_y != NULL)
  186233. *green_y = info_ptr->int_y_green;
  186234. if (blue_x != NULL)
  186235. *blue_x = info_ptr->int_x_blue;
  186236. if (blue_y != NULL)
  186237. *blue_y = info_ptr->int_y_blue;
  186238. return (PNG_INFO_cHRM);
  186239. }
  186240. return (0);
  186241. }
  186242. #endif
  186243. #endif
  186244. #if defined(PNG_gAMA_SUPPORTED)
  186245. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186246. png_uint_32 PNGAPI
  186247. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186248. {
  186249. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186250. && file_gamma != NULL)
  186251. {
  186252. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186253. *file_gamma = (double)info_ptr->gamma;
  186254. return (PNG_INFO_gAMA);
  186255. }
  186256. return (0);
  186257. }
  186258. #endif
  186259. #ifdef PNG_FIXED_POINT_SUPPORTED
  186260. png_uint_32 PNGAPI
  186261. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186262. png_fixed_point *int_file_gamma)
  186263. {
  186264. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186265. && int_file_gamma != NULL)
  186266. {
  186267. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186268. *int_file_gamma = info_ptr->int_gamma;
  186269. return (PNG_INFO_gAMA);
  186270. }
  186271. return (0);
  186272. }
  186273. #endif
  186274. #endif
  186275. #if defined(PNG_sRGB_SUPPORTED)
  186276. png_uint_32 PNGAPI
  186277. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186278. {
  186279. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186280. && file_srgb_intent != NULL)
  186281. {
  186282. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186283. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186284. return (PNG_INFO_sRGB);
  186285. }
  186286. return (0);
  186287. }
  186288. #endif
  186289. #if defined(PNG_iCCP_SUPPORTED)
  186290. png_uint_32 PNGAPI
  186291. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186292. png_charpp name, int *compression_type,
  186293. png_charpp profile, png_uint_32 *proflen)
  186294. {
  186295. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186296. && name != NULL && profile != NULL && proflen != NULL)
  186297. {
  186298. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186299. *name = info_ptr->iccp_name;
  186300. *profile = info_ptr->iccp_profile;
  186301. /* compression_type is a dummy so the API won't have to change
  186302. if we introduce multiple compression types later. */
  186303. *proflen = (int)info_ptr->iccp_proflen;
  186304. *compression_type = (int)info_ptr->iccp_compression;
  186305. return (PNG_INFO_iCCP);
  186306. }
  186307. return (0);
  186308. }
  186309. #endif
  186310. #if defined(PNG_sPLT_SUPPORTED)
  186311. png_uint_32 PNGAPI
  186312. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186313. png_sPLT_tpp spalettes)
  186314. {
  186315. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186316. {
  186317. *spalettes = info_ptr->splt_palettes;
  186318. return ((png_uint_32)info_ptr->splt_palettes_num);
  186319. }
  186320. return (0);
  186321. }
  186322. #endif
  186323. #if defined(PNG_hIST_SUPPORTED)
  186324. png_uint_32 PNGAPI
  186325. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186326. {
  186327. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186328. && hist != NULL)
  186329. {
  186330. png_debug1(1, "in %s retrieval function\n", "hIST");
  186331. *hist = info_ptr->hist;
  186332. return (PNG_INFO_hIST);
  186333. }
  186334. return (0);
  186335. }
  186336. #endif
  186337. png_uint_32 PNGAPI
  186338. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186339. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186340. int *color_type, int *interlace_type, int *compression_type,
  186341. int *filter_type)
  186342. {
  186343. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186344. bit_depth != NULL && color_type != NULL)
  186345. {
  186346. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186347. *width = info_ptr->width;
  186348. *height = info_ptr->height;
  186349. *bit_depth = info_ptr->bit_depth;
  186350. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186351. png_error(png_ptr, "Invalid bit depth");
  186352. *color_type = info_ptr->color_type;
  186353. if (info_ptr->color_type > 6)
  186354. png_error(png_ptr, "Invalid color type");
  186355. if (compression_type != NULL)
  186356. *compression_type = info_ptr->compression_type;
  186357. if (filter_type != NULL)
  186358. *filter_type = info_ptr->filter_type;
  186359. if (interlace_type != NULL)
  186360. *interlace_type = info_ptr->interlace_type;
  186361. /* check for potential overflow of rowbytes */
  186362. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186363. png_error(png_ptr, "Invalid image width");
  186364. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186365. png_error(png_ptr, "Invalid image height");
  186366. if (info_ptr->width > (PNG_UINT_32_MAX
  186367. >> 3) /* 8-byte RGBA pixels */
  186368. - 64 /* bigrowbuf hack */
  186369. - 1 /* filter byte */
  186370. - 7*8 /* rounding of width to multiple of 8 pixels */
  186371. - 8) /* extra max_pixel_depth pad */
  186372. {
  186373. png_warning(png_ptr,
  186374. "Width too large for libpng to process image data.");
  186375. }
  186376. return (1);
  186377. }
  186378. return (0);
  186379. }
  186380. #if defined(PNG_oFFs_SUPPORTED)
  186381. png_uint_32 PNGAPI
  186382. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186383. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186384. {
  186385. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186386. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186387. {
  186388. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186389. *offset_x = info_ptr->x_offset;
  186390. *offset_y = info_ptr->y_offset;
  186391. *unit_type = (int)info_ptr->offset_unit_type;
  186392. return (PNG_INFO_oFFs);
  186393. }
  186394. return (0);
  186395. }
  186396. #endif
  186397. #if defined(PNG_pCAL_SUPPORTED)
  186398. png_uint_32 PNGAPI
  186399. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186400. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186401. png_charp *units, png_charpp *params)
  186402. {
  186403. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186404. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186405. nparams != NULL && units != NULL && params != NULL)
  186406. {
  186407. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186408. *purpose = info_ptr->pcal_purpose;
  186409. *X0 = info_ptr->pcal_X0;
  186410. *X1 = info_ptr->pcal_X1;
  186411. *type = (int)info_ptr->pcal_type;
  186412. *nparams = (int)info_ptr->pcal_nparams;
  186413. *units = info_ptr->pcal_units;
  186414. *params = info_ptr->pcal_params;
  186415. return (PNG_INFO_pCAL);
  186416. }
  186417. return (0);
  186418. }
  186419. #endif
  186420. #if defined(PNG_sCAL_SUPPORTED)
  186421. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186422. png_uint_32 PNGAPI
  186423. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186424. int *unit, double *width, double *height)
  186425. {
  186426. if (png_ptr != NULL && info_ptr != NULL &&
  186427. (info_ptr->valid & PNG_INFO_sCAL))
  186428. {
  186429. *unit = info_ptr->scal_unit;
  186430. *width = info_ptr->scal_pixel_width;
  186431. *height = info_ptr->scal_pixel_height;
  186432. return (PNG_INFO_sCAL);
  186433. }
  186434. return(0);
  186435. }
  186436. #else
  186437. #ifdef PNG_FIXED_POINT_SUPPORTED
  186438. png_uint_32 PNGAPI
  186439. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186440. int *unit, png_charpp width, png_charpp height)
  186441. {
  186442. if (png_ptr != NULL && info_ptr != NULL &&
  186443. (info_ptr->valid & PNG_INFO_sCAL))
  186444. {
  186445. *unit = info_ptr->scal_unit;
  186446. *width = info_ptr->scal_s_width;
  186447. *height = info_ptr->scal_s_height;
  186448. return (PNG_INFO_sCAL);
  186449. }
  186450. return(0);
  186451. }
  186452. #endif
  186453. #endif
  186454. #endif
  186455. #if defined(PNG_pHYs_SUPPORTED)
  186456. png_uint_32 PNGAPI
  186457. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186458. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186459. {
  186460. png_uint_32 retval = 0;
  186461. if (png_ptr != NULL && info_ptr != NULL &&
  186462. (info_ptr->valid & PNG_INFO_pHYs))
  186463. {
  186464. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186465. if (res_x != NULL)
  186466. {
  186467. *res_x = info_ptr->x_pixels_per_unit;
  186468. retval |= PNG_INFO_pHYs;
  186469. }
  186470. if (res_y != NULL)
  186471. {
  186472. *res_y = info_ptr->y_pixels_per_unit;
  186473. retval |= PNG_INFO_pHYs;
  186474. }
  186475. if (unit_type != NULL)
  186476. {
  186477. *unit_type = (int)info_ptr->phys_unit_type;
  186478. retval |= PNG_INFO_pHYs;
  186479. }
  186480. }
  186481. return (retval);
  186482. }
  186483. #endif
  186484. png_uint_32 PNGAPI
  186485. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186486. int *num_palette)
  186487. {
  186488. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186489. && palette != NULL)
  186490. {
  186491. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186492. *palette = info_ptr->palette;
  186493. *num_palette = info_ptr->num_palette;
  186494. png_debug1(3, "num_palette = %d\n", *num_palette);
  186495. return (PNG_INFO_PLTE);
  186496. }
  186497. return (0);
  186498. }
  186499. #if defined(PNG_sBIT_SUPPORTED)
  186500. png_uint_32 PNGAPI
  186501. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186502. {
  186503. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186504. && sig_bit != NULL)
  186505. {
  186506. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186507. *sig_bit = &(info_ptr->sig_bit);
  186508. return (PNG_INFO_sBIT);
  186509. }
  186510. return (0);
  186511. }
  186512. #endif
  186513. #if defined(PNG_TEXT_SUPPORTED)
  186514. png_uint_32 PNGAPI
  186515. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186516. int *num_text)
  186517. {
  186518. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186519. {
  186520. png_debug1(1, "in %s retrieval function\n",
  186521. (png_ptr->chunk_name[0] == '\0' ? "text"
  186522. : (png_const_charp)png_ptr->chunk_name));
  186523. if (text_ptr != NULL)
  186524. *text_ptr = info_ptr->text;
  186525. if (num_text != NULL)
  186526. *num_text = info_ptr->num_text;
  186527. return ((png_uint_32)info_ptr->num_text);
  186528. }
  186529. if (num_text != NULL)
  186530. *num_text = 0;
  186531. return(0);
  186532. }
  186533. #endif
  186534. #if defined(PNG_tIME_SUPPORTED)
  186535. png_uint_32 PNGAPI
  186536. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186537. {
  186538. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186539. && mod_time != NULL)
  186540. {
  186541. png_debug1(1, "in %s retrieval function\n", "tIME");
  186542. *mod_time = &(info_ptr->mod_time);
  186543. return (PNG_INFO_tIME);
  186544. }
  186545. return (0);
  186546. }
  186547. #endif
  186548. #if defined(PNG_tRNS_SUPPORTED)
  186549. png_uint_32 PNGAPI
  186550. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186551. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186552. {
  186553. png_uint_32 retval = 0;
  186554. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186555. {
  186556. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186557. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186558. {
  186559. if (trans != NULL)
  186560. {
  186561. *trans = info_ptr->trans;
  186562. retval |= PNG_INFO_tRNS;
  186563. }
  186564. if (trans_values != NULL)
  186565. *trans_values = &(info_ptr->trans_values);
  186566. }
  186567. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186568. {
  186569. if (trans_values != NULL)
  186570. {
  186571. *trans_values = &(info_ptr->trans_values);
  186572. retval |= PNG_INFO_tRNS;
  186573. }
  186574. if(trans != NULL)
  186575. *trans = NULL;
  186576. }
  186577. if(num_trans != NULL)
  186578. {
  186579. *num_trans = info_ptr->num_trans;
  186580. retval |= PNG_INFO_tRNS;
  186581. }
  186582. }
  186583. return (retval);
  186584. }
  186585. #endif
  186586. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186587. png_uint_32 PNGAPI
  186588. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186589. png_unknown_chunkpp unknowns)
  186590. {
  186591. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186592. {
  186593. *unknowns = info_ptr->unknown_chunks;
  186594. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186595. }
  186596. return (0);
  186597. }
  186598. #endif
  186599. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186600. png_byte PNGAPI
  186601. png_get_rgb_to_gray_status (png_structp png_ptr)
  186602. {
  186603. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186604. }
  186605. #endif
  186606. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186607. png_voidp PNGAPI
  186608. png_get_user_chunk_ptr(png_structp png_ptr)
  186609. {
  186610. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186611. }
  186612. #endif
  186613. #ifdef PNG_WRITE_SUPPORTED
  186614. png_uint_32 PNGAPI
  186615. png_get_compression_buffer_size(png_structp png_ptr)
  186616. {
  186617. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186618. }
  186619. #endif
  186620. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186621. #ifndef PNG_1_0_X
  186622. /* this function was added to libpng 1.2.0 and should exist by default */
  186623. png_uint_32 PNGAPI
  186624. png_get_asm_flags (png_structp png_ptr)
  186625. {
  186626. /* obsolete, to be removed from libpng-1.4.0 */
  186627. return (png_ptr? 0L: 0L);
  186628. }
  186629. /* this function was added to libpng 1.2.0 and should exist by default */
  186630. png_uint_32 PNGAPI
  186631. png_get_asm_flagmask (int flag_select)
  186632. {
  186633. /* obsolete, to be removed from libpng-1.4.0 */
  186634. flag_select=flag_select;
  186635. return 0L;
  186636. }
  186637. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186638. /* this function was added to libpng 1.2.0 */
  186639. png_uint_32 PNGAPI
  186640. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186641. {
  186642. /* obsolete, to be removed from libpng-1.4.0 */
  186643. flag_select=flag_select;
  186644. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186645. return 0L;
  186646. }
  186647. /* this function was added to libpng 1.2.0 */
  186648. png_byte PNGAPI
  186649. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186650. {
  186651. /* obsolete, to be removed from libpng-1.4.0 */
  186652. return (png_ptr? 0: 0);
  186653. }
  186654. /* this function was added to libpng 1.2.0 */
  186655. png_uint_32 PNGAPI
  186656. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186657. {
  186658. /* obsolete, to be removed from libpng-1.4.0 */
  186659. return (png_ptr? 0L: 0L);
  186660. }
  186661. #endif /* ?PNG_1_0_X */
  186662. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186663. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186664. /* these functions were added to libpng 1.2.6 */
  186665. png_uint_32 PNGAPI
  186666. png_get_user_width_max (png_structp png_ptr)
  186667. {
  186668. return (png_ptr? png_ptr->user_width_max : 0);
  186669. }
  186670. png_uint_32 PNGAPI
  186671. png_get_user_height_max (png_structp png_ptr)
  186672. {
  186673. return (png_ptr? png_ptr->user_height_max : 0);
  186674. }
  186675. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186676. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186677. /*** End of inlined file: pngget.c ***/
  186678. /*** Start of inlined file: pngmem.c ***/
  186679. /* pngmem.c - stub functions for memory allocation
  186680. *
  186681. * Last changed in libpng 1.2.13 November 13, 2006
  186682. * For conditions of distribution and use, see copyright notice in png.h
  186683. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186684. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186685. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186686. *
  186687. * This file provides a location for all memory allocation. Users who
  186688. * need special memory handling are expected to supply replacement
  186689. * functions for png_malloc() and png_free(), and to use
  186690. * png_create_read_struct_2() and png_create_write_struct_2() to
  186691. * identify the replacement functions.
  186692. */
  186693. #define PNG_INTERNAL
  186694. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186695. /* Borland DOS special memory handler */
  186696. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186697. /* if you change this, be sure to change the one in png.h also */
  186698. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186699. by a single call to calloc() if this is thought to improve performance. */
  186700. png_voidp /* PRIVATE */
  186701. png_create_struct(int type)
  186702. {
  186703. #ifdef PNG_USER_MEM_SUPPORTED
  186704. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186705. }
  186706. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186707. png_voidp /* PRIVATE */
  186708. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186709. {
  186710. #endif /* PNG_USER_MEM_SUPPORTED */
  186711. png_size_t size;
  186712. png_voidp struct_ptr;
  186713. if (type == PNG_STRUCT_INFO)
  186714. size = png_sizeof(png_info);
  186715. else if (type == PNG_STRUCT_PNG)
  186716. size = png_sizeof(png_struct);
  186717. else
  186718. return (png_get_copyright(NULL));
  186719. #ifdef PNG_USER_MEM_SUPPORTED
  186720. if(malloc_fn != NULL)
  186721. {
  186722. png_struct dummy_struct;
  186723. png_structp png_ptr = &dummy_struct;
  186724. png_ptr->mem_ptr=mem_ptr;
  186725. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186726. }
  186727. else
  186728. #endif /* PNG_USER_MEM_SUPPORTED */
  186729. struct_ptr = (png_voidp)farmalloc(size);
  186730. if (struct_ptr != NULL)
  186731. png_memset(struct_ptr, 0, size);
  186732. return (struct_ptr);
  186733. }
  186734. /* Free memory allocated by a png_create_struct() call */
  186735. void /* PRIVATE */
  186736. png_destroy_struct(png_voidp struct_ptr)
  186737. {
  186738. #ifdef PNG_USER_MEM_SUPPORTED
  186739. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186740. }
  186741. /* Free memory allocated by a png_create_struct() call */
  186742. void /* PRIVATE */
  186743. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186744. png_voidp mem_ptr)
  186745. {
  186746. #endif
  186747. if (struct_ptr != NULL)
  186748. {
  186749. #ifdef PNG_USER_MEM_SUPPORTED
  186750. if(free_fn != NULL)
  186751. {
  186752. png_struct dummy_struct;
  186753. png_structp png_ptr = &dummy_struct;
  186754. png_ptr->mem_ptr=mem_ptr;
  186755. (*(free_fn))(png_ptr, struct_ptr);
  186756. return;
  186757. }
  186758. #endif /* PNG_USER_MEM_SUPPORTED */
  186759. farfree (struct_ptr);
  186760. }
  186761. }
  186762. /* Allocate memory. For reasonable files, size should never exceed
  186763. * 64K. However, zlib may allocate more then 64K if you don't tell
  186764. * it not to. See zconf.h and png.h for more information. zlib does
  186765. * need to allocate exactly 64K, so whatever you call here must
  186766. * have the ability to do that.
  186767. *
  186768. * Borland seems to have a problem in DOS mode for exactly 64K.
  186769. * It gives you a segment with an offset of 8 (perhaps to store its
  186770. * memory stuff). zlib doesn't like this at all, so we have to
  186771. * detect and deal with it. This code should not be needed in
  186772. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186773. * been updated by Alexander Lehmann for version 0.89 to waste less
  186774. * memory.
  186775. *
  186776. * Note that we can't use png_size_t for the "size" declaration,
  186777. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186778. * result, we would be truncating potentially larger memory requests
  186779. * (which should cause a fatal error) and introducing major problems.
  186780. */
  186781. png_voidp PNGAPI
  186782. png_malloc(png_structp png_ptr, png_uint_32 size)
  186783. {
  186784. png_voidp ret;
  186785. if (png_ptr == NULL || size == 0)
  186786. return (NULL);
  186787. #ifdef PNG_USER_MEM_SUPPORTED
  186788. if(png_ptr->malloc_fn != NULL)
  186789. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186790. else
  186791. ret = (png_malloc_default(png_ptr, size));
  186792. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186793. png_error(png_ptr, "Out of memory!");
  186794. return (ret);
  186795. }
  186796. png_voidp PNGAPI
  186797. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186798. {
  186799. png_voidp ret;
  186800. #endif /* PNG_USER_MEM_SUPPORTED */
  186801. if (png_ptr == NULL || size == 0)
  186802. return (NULL);
  186803. #ifdef PNG_MAX_MALLOC_64K
  186804. if (size > (png_uint_32)65536L)
  186805. {
  186806. png_warning(png_ptr, "Cannot Allocate > 64K");
  186807. ret = NULL;
  186808. }
  186809. else
  186810. #endif
  186811. if (size != (size_t)size)
  186812. ret = NULL;
  186813. else if (size == (png_uint_32)65536L)
  186814. {
  186815. if (png_ptr->offset_table == NULL)
  186816. {
  186817. /* try to see if we need to do any of this fancy stuff */
  186818. ret = farmalloc(size);
  186819. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186820. {
  186821. int num_blocks;
  186822. png_uint_32 total_size;
  186823. png_bytep table;
  186824. int i;
  186825. png_byte huge * hptr;
  186826. if (ret != NULL)
  186827. {
  186828. farfree(ret);
  186829. ret = NULL;
  186830. }
  186831. if(png_ptr->zlib_window_bits > 14)
  186832. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186833. else
  186834. num_blocks = 1;
  186835. if (png_ptr->zlib_mem_level >= 7)
  186836. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186837. else
  186838. num_blocks++;
  186839. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186840. table = farmalloc(total_size);
  186841. if (table == NULL)
  186842. {
  186843. #ifndef PNG_USER_MEM_SUPPORTED
  186844. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186845. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186846. else
  186847. png_warning(png_ptr, "Out Of Memory.");
  186848. #endif
  186849. return (NULL);
  186850. }
  186851. if ((png_size_t)table & 0xfff0)
  186852. {
  186853. #ifndef PNG_USER_MEM_SUPPORTED
  186854. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186855. png_error(png_ptr,
  186856. "Farmalloc didn't return normalized pointer");
  186857. else
  186858. png_warning(png_ptr,
  186859. "Farmalloc didn't return normalized pointer");
  186860. #endif
  186861. return (NULL);
  186862. }
  186863. png_ptr->offset_table = table;
  186864. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186865. png_sizeof (png_bytep));
  186866. if (png_ptr->offset_table_ptr == NULL)
  186867. {
  186868. #ifndef PNG_USER_MEM_SUPPORTED
  186869. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186870. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186871. else
  186872. png_warning(png_ptr, "Out Of memory.");
  186873. #endif
  186874. return (NULL);
  186875. }
  186876. hptr = (png_byte huge *)table;
  186877. if ((png_size_t)hptr & 0xf)
  186878. {
  186879. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186880. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186881. }
  186882. for (i = 0; i < num_blocks; i++)
  186883. {
  186884. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186885. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186886. }
  186887. png_ptr->offset_table_number = num_blocks;
  186888. png_ptr->offset_table_count = 0;
  186889. png_ptr->offset_table_count_free = 0;
  186890. }
  186891. }
  186892. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186893. {
  186894. #ifndef PNG_USER_MEM_SUPPORTED
  186895. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186896. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186897. else
  186898. png_warning(png_ptr, "Out of Memory.");
  186899. #endif
  186900. return (NULL);
  186901. }
  186902. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186903. }
  186904. else
  186905. ret = farmalloc(size);
  186906. #ifndef PNG_USER_MEM_SUPPORTED
  186907. if (ret == NULL)
  186908. {
  186909. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186910. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186911. else
  186912. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186913. }
  186914. #endif
  186915. return (ret);
  186916. }
  186917. /* free a pointer allocated by png_malloc(). In the default
  186918. configuration, png_ptr is not used, but is passed in case it
  186919. is needed. If ptr is NULL, return without taking any action. */
  186920. void PNGAPI
  186921. png_free(png_structp png_ptr, png_voidp ptr)
  186922. {
  186923. if (png_ptr == NULL || ptr == NULL)
  186924. return;
  186925. #ifdef PNG_USER_MEM_SUPPORTED
  186926. if (png_ptr->free_fn != NULL)
  186927. {
  186928. (*(png_ptr->free_fn))(png_ptr, ptr);
  186929. return;
  186930. }
  186931. else png_free_default(png_ptr, ptr);
  186932. }
  186933. void PNGAPI
  186934. png_free_default(png_structp png_ptr, png_voidp ptr)
  186935. {
  186936. #endif /* PNG_USER_MEM_SUPPORTED */
  186937. if(png_ptr == NULL) return;
  186938. if (png_ptr->offset_table != NULL)
  186939. {
  186940. int i;
  186941. for (i = 0; i < png_ptr->offset_table_count; i++)
  186942. {
  186943. if (ptr == png_ptr->offset_table_ptr[i])
  186944. {
  186945. ptr = NULL;
  186946. png_ptr->offset_table_count_free++;
  186947. break;
  186948. }
  186949. }
  186950. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186951. {
  186952. farfree(png_ptr->offset_table);
  186953. farfree(png_ptr->offset_table_ptr);
  186954. png_ptr->offset_table = NULL;
  186955. png_ptr->offset_table_ptr = NULL;
  186956. }
  186957. }
  186958. if (ptr != NULL)
  186959. {
  186960. farfree(ptr);
  186961. }
  186962. }
  186963. #else /* Not the Borland DOS special memory handler */
  186964. /* Allocate memory for a png_struct or a png_info. The malloc and
  186965. memset can be replaced by a single call to calloc() if this is thought
  186966. to improve performance noticably. */
  186967. png_voidp /* PRIVATE */
  186968. png_create_struct(int type)
  186969. {
  186970. #ifdef PNG_USER_MEM_SUPPORTED
  186971. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186972. }
  186973. /* Allocate memory for a png_struct or a png_info. The malloc and
  186974. memset can be replaced by a single call to calloc() if this is thought
  186975. to improve performance noticably. */
  186976. png_voidp /* PRIVATE */
  186977. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186978. {
  186979. #endif /* PNG_USER_MEM_SUPPORTED */
  186980. png_size_t size;
  186981. png_voidp struct_ptr;
  186982. if (type == PNG_STRUCT_INFO)
  186983. size = png_sizeof(png_info);
  186984. else if (type == PNG_STRUCT_PNG)
  186985. size = png_sizeof(png_struct);
  186986. else
  186987. return (NULL);
  186988. #ifdef PNG_USER_MEM_SUPPORTED
  186989. if(malloc_fn != NULL)
  186990. {
  186991. png_struct dummy_struct;
  186992. png_structp png_ptr = &dummy_struct;
  186993. png_ptr->mem_ptr=mem_ptr;
  186994. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186995. if (struct_ptr != NULL)
  186996. png_memset(struct_ptr, 0, size);
  186997. return (struct_ptr);
  186998. }
  186999. #endif /* PNG_USER_MEM_SUPPORTED */
  187000. #if defined(__TURBOC__) && !defined(__FLAT__)
  187001. struct_ptr = (png_voidp)farmalloc(size);
  187002. #else
  187003. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187004. struct_ptr = (png_voidp)halloc(size,1);
  187005. # else
  187006. struct_ptr = (png_voidp)malloc(size);
  187007. # endif
  187008. #endif
  187009. if (struct_ptr != NULL)
  187010. png_memset(struct_ptr, 0, size);
  187011. return (struct_ptr);
  187012. }
  187013. /* Free memory allocated by a png_create_struct() call */
  187014. void /* PRIVATE */
  187015. png_destroy_struct(png_voidp struct_ptr)
  187016. {
  187017. #ifdef PNG_USER_MEM_SUPPORTED
  187018. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187019. }
  187020. /* Free memory allocated by a png_create_struct() call */
  187021. void /* PRIVATE */
  187022. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187023. png_voidp mem_ptr)
  187024. {
  187025. #endif /* PNG_USER_MEM_SUPPORTED */
  187026. if (struct_ptr != NULL)
  187027. {
  187028. #ifdef PNG_USER_MEM_SUPPORTED
  187029. if(free_fn != NULL)
  187030. {
  187031. png_struct dummy_struct;
  187032. png_structp png_ptr = &dummy_struct;
  187033. png_ptr->mem_ptr=mem_ptr;
  187034. (*(free_fn))(png_ptr, struct_ptr);
  187035. return;
  187036. }
  187037. #endif /* PNG_USER_MEM_SUPPORTED */
  187038. #if defined(__TURBOC__) && !defined(__FLAT__)
  187039. farfree(struct_ptr);
  187040. #else
  187041. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187042. hfree(struct_ptr);
  187043. # else
  187044. free(struct_ptr);
  187045. # endif
  187046. #endif
  187047. }
  187048. }
  187049. /* Allocate memory. For reasonable files, size should never exceed
  187050. 64K. However, zlib may allocate more then 64K if you don't tell
  187051. it not to. See zconf.h and png.h for more information. zlib does
  187052. need to allocate exactly 64K, so whatever you call here must
  187053. have the ability to do that. */
  187054. png_voidp PNGAPI
  187055. png_malloc(png_structp png_ptr, png_uint_32 size)
  187056. {
  187057. png_voidp ret;
  187058. #ifdef PNG_USER_MEM_SUPPORTED
  187059. if (png_ptr == NULL || size == 0)
  187060. return (NULL);
  187061. if(png_ptr->malloc_fn != NULL)
  187062. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187063. else
  187064. ret = (png_malloc_default(png_ptr, size));
  187065. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187066. png_error(png_ptr, "Out of Memory!");
  187067. return (ret);
  187068. }
  187069. png_voidp PNGAPI
  187070. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187071. {
  187072. png_voidp ret;
  187073. #endif /* PNG_USER_MEM_SUPPORTED */
  187074. if (png_ptr == NULL || size == 0)
  187075. return (NULL);
  187076. #ifdef PNG_MAX_MALLOC_64K
  187077. if (size > (png_uint_32)65536L)
  187078. {
  187079. #ifndef PNG_USER_MEM_SUPPORTED
  187080. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187081. png_error(png_ptr, "Cannot Allocate > 64K");
  187082. else
  187083. #endif
  187084. return NULL;
  187085. }
  187086. #endif
  187087. /* Check for overflow */
  187088. #if defined(__TURBOC__) && !defined(__FLAT__)
  187089. if (size != (unsigned long)size)
  187090. ret = NULL;
  187091. else
  187092. ret = farmalloc(size);
  187093. #else
  187094. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187095. if (size != (unsigned long)size)
  187096. ret = NULL;
  187097. else
  187098. ret = halloc(size, 1);
  187099. # else
  187100. if (size != (size_t)size)
  187101. ret = NULL;
  187102. else
  187103. ret = malloc((size_t)size);
  187104. # endif
  187105. #endif
  187106. #ifndef PNG_USER_MEM_SUPPORTED
  187107. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187108. png_error(png_ptr, "Out of Memory");
  187109. #endif
  187110. return (ret);
  187111. }
  187112. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187113. without taking any action. */
  187114. void PNGAPI
  187115. png_free(png_structp png_ptr, png_voidp ptr)
  187116. {
  187117. if (png_ptr == NULL || ptr == NULL)
  187118. return;
  187119. #ifdef PNG_USER_MEM_SUPPORTED
  187120. if (png_ptr->free_fn != NULL)
  187121. {
  187122. (*(png_ptr->free_fn))(png_ptr, ptr);
  187123. return;
  187124. }
  187125. else png_free_default(png_ptr, ptr);
  187126. }
  187127. void PNGAPI
  187128. png_free_default(png_structp png_ptr, png_voidp ptr)
  187129. {
  187130. if (png_ptr == NULL || ptr == NULL)
  187131. return;
  187132. #endif /* PNG_USER_MEM_SUPPORTED */
  187133. #if defined(__TURBOC__) && !defined(__FLAT__)
  187134. farfree(ptr);
  187135. #else
  187136. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187137. hfree(ptr);
  187138. # else
  187139. free(ptr);
  187140. # endif
  187141. #endif
  187142. }
  187143. #endif /* Not Borland DOS special memory handler */
  187144. #if defined(PNG_1_0_X)
  187145. # define png_malloc_warn png_malloc
  187146. #else
  187147. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187148. * function will set up png_malloc() to issue a png_warning and return NULL
  187149. * instead of issuing a png_error, if it fails to allocate the requested
  187150. * memory.
  187151. */
  187152. png_voidp PNGAPI
  187153. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187154. {
  187155. png_voidp ptr;
  187156. png_uint_32 save_flags;
  187157. if(png_ptr == NULL) return (NULL);
  187158. save_flags=png_ptr->flags;
  187159. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187160. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187161. png_ptr->flags=save_flags;
  187162. return(ptr);
  187163. }
  187164. #endif
  187165. png_voidp PNGAPI
  187166. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187167. png_uint_32 length)
  187168. {
  187169. png_size_t size;
  187170. size = (png_size_t)length;
  187171. if ((png_uint_32)size != length)
  187172. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187173. return(png_memcpy (s1, s2, size));
  187174. }
  187175. png_voidp PNGAPI
  187176. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187177. png_uint_32 length)
  187178. {
  187179. png_size_t size;
  187180. size = (png_size_t)length;
  187181. if ((png_uint_32)size != length)
  187182. png_error(png_ptr,"Overflow in png_memset_check.");
  187183. return (png_memset (s1, value, size));
  187184. }
  187185. #ifdef PNG_USER_MEM_SUPPORTED
  187186. /* This function is called when the application wants to use another method
  187187. * of allocating and freeing memory.
  187188. */
  187189. void PNGAPI
  187190. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187191. malloc_fn, png_free_ptr free_fn)
  187192. {
  187193. if(png_ptr != NULL) {
  187194. png_ptr->mem_ptr = mem_ptr;
  187195. png_ptr->malloc_fn = malloc_fn;
  187196. png_ptr->free_fn = free_fn;
  187197. }
  187198. }
  187199. /* This function returns a pointer to the mem_ptr associated with the user
  187200. * functions. The application should free any memory associated with this
  187201. * pointer before png_write_destroy and png_read_destroy are called.
  187202. */
  187203. png_voidp PNGAPI
  187204. png_get_mem_ptr(png_structp png_ptr)
  187205. {
  187206. if(png_ptr == NULL) return (NULL);
  187207. return ((png_voidp)png_ptr->mem_ptr);
  187208. }
  187209. #endif /* PNG_USER_MEM_SUPPORTED */
  187210. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187211. /*** End of inlined file: pngmem.c ***/
  187212. /*** Start of inlined file: pngread.c ***/
  187213. /* pngread.c - read a PNG file
  187214. *
  187215. * Last changed in libpng 1.2.20 September 7, 2007
  187216. * For conditions of distribution and use, see copyright notice in png.h
  187217. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187218. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187219. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187220. *
  187221. * This file contains routines that an application calls directly to
  187222. * read a PNG file or stream.
  187223. */
  187224. #define PNG_INTERNAL
  187225. #if defined(PNG_READ_SUPPORTED)
  187226. /* Create a PNG structure for reading, and allocate any memory needed. */
  187227. png_structp PNGAPI
  187228. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187229. png_error_ptr error_fn, png_error_ptr warn_fn)
  187230. {
  187231. #ifdef PNG_USER_MEM_SUPPORTED
  187232. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187233. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187234. }
  187235. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187236. png_structp PNGAPI
  187237. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187238. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187239. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187240. {
  187241. #endif /* PNG_USER_MEM_SUPPORTED */
  187242. png_structp png_ptr;
  187243. #ifdef PNG_SETJMP_SUPPORTED
  187244. #ifdef USE_FAR_KEYWORD
  187245. jmp_buf jmpbuf;
  187246. #endif
  187247. #endif
  187248. int i;
  187249. png_debug(1, "in png_create_read_struct\n");
  187250. #ifdef PNG_USER_MEM_SUPPORTED
  187251. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187252. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187253. #else
  187254. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187255. #endif
  187256. if (png_ptr == NULL)
  187257. return (NULL);
  187258. /* added at libpng-1.2.6 */
  187259. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187260. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187261. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187262. #endif
  187263. #ifdef PNG_SETJMP_SUPPORTED
  187264. #ifdef USE_FAR_KEYWORD
  187265. if (setjmp(jmpbuf))
  187266. #else
  187267. if (setjmp(png_ptr->jmpbuf))
  187268. #endif
  187269. {
  187270. png_free(png_ptr, png_ptr->zbuf);
  187271. png_ptr->zbuf=NULL;
  187272. #ifdef PNG_USER_MEM_SUPPORTED
  187273. png_destroy_struct_2((png_voidp)png_ptr,
  187274. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187275. #else
  187276. png_destroy_struct((png_voidp)png_ptr);
  187277. #endif
  187278. return (NULL);
  187279. }
  187280. #ifdef USE_FAR_KEYWORD
  187281. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187282. #endif
  187283. #endif
  187284. #ifdef PNG_USER_MEM_SUPPORTED
  187285. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187286. #endif
  187287. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187288. i=0;
  187289. do
  187290. {
  187291. if(user_png_ver[i] != png_libpng_ver[i])
  187292. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187293. } while (png_libpng_ver[i++]);
  187294. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187295. {
  187296. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187297. * we must recompile any applications that use any older library version.
  187298. * For versions after libpng 1.0, we will be compatible, so we need
  187299. * only check the first digit.
  187300. */
  187301. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187302. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187303. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187304. {
  187305. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187306. char msg[80];
  187307. if (user_png_ver)
  187308. {
  187309. png_snprintf(msg, 80,
  187310. "Application was compiled with png.h from libpng-%.20s",
  187311. user_png_ver);
  187312. png_warning(png_ptr, msg);
  187313. }
  187314. png_snprintf(msg, 80,
  187315. "Application is running with png.c from libpng-%.20s",
  187316. png_libpng_ver);
  187317. png_warning(png_ptr, msg);
  187318. #endif
  187319. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187320. png_ptr->flags=0;
  187321. #endif
  187322. png_error(png_ptr,
  187323. "Incompatible libpng version in application and library");
  187324. }
  187325. }
  187326. /* initialize zbuf - compression buffer */
  187327. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187328. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187329. (png_uint_32)png_ptr->zbuf_size);
  187330. png_ptr->zstream.zalloc = png_zalloc;
  187331. png_ptr->zstream.zfree = png_zfree;
  187332. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187333. switch (inflateInit(&png_ptr->zstream))
  187334. {
  187335. case Z_OK: /* Do nothing */ break;
  187336. case Z_MEM_ERROR:
  187337. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187338. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187339. default: png_error(png_ptr, "Unknown zlib error");
  187340. }
  187341. png_ptr->zstream.next_out = png_ptr->zbuf;
  187342. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187343. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187344. #ifdef PNG_SETJMP_SUPPORTED
  187345. /* Applications that neglect to set up their own setjmp() and then encounter
  187346. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187347. abort instead of returning. */
  187348. #ifdef USE_FAR_KEYWORD
  187349. if (setjmp(jmpbuf))
  187350. PNG_ABORT();
  187351. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187352. #else
  187353. if (setjmp(png_ptr->jmpbuf))
  187354. PNG_ABORT();
  187355. #endif
  187356. #endif
  187357. return (png_ptr);
  187358. }
  187359. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187360. /* Initialize PNG structure for reading, and allocate any memory needed.
  187361. This interface is deprecated in favour of the png_create_read_struct(),
  187362. and it will disappear as of libpng-1.3.0. */
  187363. #undef png_read_init
  187364. void PNGAPI
  187365. png_read_init(png_structp png_ptr)
  187366. {
  187367. /* We only come here via pre-1.0.7-compiled applications */
  187368. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187369. }
  187370. void PNGAPI
  187371. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187372. png_size_t png_struct_size, png_size_t png_info_size)
  187373. {
  187374. /* We only come here via pre-1.0.12-compiled applications */
  187375. if(png_ptr == NULL) return;
  187376. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187377. if(png_sizeof(png_struct) > png_struct_size ||
  187378. png_sizeof(png_info) > png_info_size)
  187379. {
  187380. char msg[80];
  187381. png_ptr->warning_fn=NULL;
  187382. if (user_png_ver)
  187383. {
  187384. png_snprintf(msg, 80,
  187385. "Application was compiled with png.h from libpng-%.20s",
  187386. user_png_ver);
  187387. png_warning(png_ptr, msg);
  187388. }
  187389. png_snprintf(msg, 80,
  187390. "Application is running with png.c from libpng-%.20s",
  187391. png_libpng_ver);
  187392. png_warning(png_ptr, msg);
  187393. }
  187394. #endif
  187395. if(png_sizeof(png_struct) > png_struct_size)
  187396. {
  187397. png_ptr->error_fn=NULL;
  187398. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187399. png_ptr->flags=0;
  187400. #endif
  187401. png_error(png_ptr,
  187402. "The png struct allocated by the application for reading is too small.");
  187403. }
  187404. if(png_sizeof(png_info) > png_info_size)
  187405. {
  187406. png_ptr->error_fn=NULL;
  187407. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187408. png_ptr->flags=0;
  187409. #endif
  187410. png_error(png_ptr,
  187411. "The info struct allocated by application for reading is too small.");
  187412. }
  187413. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187414. }
  187415. #endif /* PNG_1_0_X || PNG_1_2_X */
  187416. void PNGAPI
  187417. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187418. png_size_t png_struct_size)
  187419. {
  187420. #ifdef PNG_SETJMP_SUPPORTED
  187421. jmp_buf tmp_jmp; /* to save current jump buffer */
  187422. #endif
  187423. int i=0;
  187424. png_structp png_ptr=*ptr_ptr;
  187425. if(png_ptr == NULL) return;
  187426. do
  187427. {
  187428. if(user_png_ver[i] != png_libpng_ver[i])
  187429. {
  187430. #ifdef PNG_LEGACY_SUPPORTED
  187431. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187432. #else
  187433. png_ptr->warning_fn=NULL;
  187434. png_warning(png_ptr,
  187435. "Application uses deprecated png_read_init() and should be recompiled.");
  187436. break;
  187437. #endif
  187438. }
  187439. } while (png_libpng_ver[i++]);
  187440. png_debug(1, "in png_read_init_3\n");
  187441. #ifdef PNG_SETJMP_SUPPORTED
  187442. /* save jump buffer and error functions */
  187443. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187444. #endif
  187445. if(png_sizeof(png_struct) > png_struct_size)
  187446. {
  187447. png_destroy_struct(png_ptr);
  187448. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187449. png_ptr = *ptr_ptr;
  187450. }
  187451. /* reset all variables to 0 */
  187452. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187453. #ifdef PNG_SETJMP_SUPPORTED
  187454. /* restore jump buffer */
  187455. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187456. #endif
  187457. /* added at libpng-1.2.6 */
  187458. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187459. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187460. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187461. #endif
  187462. /* initialize zbuf - compression buffer */
  187463. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187464. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187465. (png_uint_32)png_ptr->zbuf_size);
  187466. png_ptr->zstream.zalloc = png_zalloc;
  187467. png_ptr->zstream.zfree = png_zfree;
  187468. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187469. switch (inflateInit(&png_ptr->zstream))
  187470. {
  187471. case Z_OK: /* Do nothing */ break;
  187472. case Z_MEM_ERROR:
  187473. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187474. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187475. default: png_error(png_ptr, "Unknown zlib error");
  187476. }
  187477. png_ptr->zstream.next_out = png_ptr->zbuf;
  187478. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187479. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187480. }
  187481. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187482. /* Read the information before the actual image data. This has been
  187483. * changed in v0.90 to allow reading a file that already has the magic
  187484. * bytes read from the stream. You can tell libpng how many bytes have
  187485. * been read from the beginning of the stream (up to the maximum of 8)
  187486. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187487. * here. The application can then have access to the signature bytes we
  187488. * read if it is determined that this isn't a valid PNG file.
  187489. */
  187490. void PNGAPI
  187491. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187492. {
  187493. if(png_ptr == NULL) return;
  187494. png_debug(1, "in png_read_info\n");
  187495. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187496. if (png_ptr->sig_bytes < 8)
  187497. {
  187498. png_size_t num_checked = png_ptr->sig_bytes,
  187499. num_to_check = 8 - num_checked;
  187500. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187501. png_ptr->sig_bytes = 8;
  187502. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187503. {
  187504. if (num_checked < 4 &&
  187505. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187506. png_error(png_ptr, "Not a PNG file");
  187507. else
  187508. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187509. }
  187510. if (num_checked < 3)
  187511. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187512. }
  187513. for(;;)
  187514. {
  187515. #ifdef PNG_USE_LOCAL_ARRAYS
  187516. PNG_CONST PNG_IHDR;
  187517. PNG_CONST PNG_IDAT;
  187518. PNG_CONST PNG_IEND;
  187519. PNG_CONST PNG_PLTE;
  187520. #if defined(PNG_READ_bKGD_SUPPORTED)
  187521. PNG_CONST PNG_bKGD;
  187522. #endif
  187523. #if defined(PNG_READ_cHRM_SUPPORTED)
  187524. PNG_CONST PNG_cHRM;
  187525. #endif
  187526. #if defined(PNG_READ_gAMA_SUPPORTED)
  187527. PNG_CONST PNG_gAMA;
  187528. #endif
  187529. #if defined(PNG_READ_hIST_SUPPORTED)
  187530. PNG_CONST PNG_hIST;
  187531. #endif
  187532. #if defined(PNG_READ_iCCP_SUPPORTED)
  187533. PNG_CONST PNG_iCCP;
  187534. #endif
  187535. #if defined(PNG_READ_iTXt_SUPPORTED)
  187536. PNG_CONST PNG_iTXt;
  187537. #endif
  187538. #if defined(PNG_READ_oFFs_SUPPORTED)
  187539. PNG_CONST PNG_oFFs;
  187540. #endif
  187541. #if defined(PNG_READ_pCAL_SUPPORTED)
  187542. PNG_CONST PNG_pCAL;
  187543. #endif
  187544. #if defined(PNG_READ_pHYs_SUPPORTED)
  187545. PNG_CONST PNG_pHYs;
  187546. #endif
  187547. #if defined(PNG_READ_sBIT_SUPPORTED)
  187548. PNG_CONST PNG_sBIT;
  187549. #endif
  187550. #if defined(PNG_READ_sCAL_SUPPORTED)
  187551. PNG_CONST PNG_sCAL;
  187552. #endif
  187553. #if defined(PNG_READ_sPLT_SUPPORTED)
  187554. PNG_CONST PNG_sPLT;
  187555. #endif
  187556. #if defined(PNG_READ_sRGB_SUPPORTED)
  187557. PNG_CONST PNG_sRGB;
  187558. #endif
  187559. #if defined(PNG_READ_tEXt_SUPPORTED)
  187560. PNG_CONST PNG_tEXt;
  187561. #endif
  187562. #if defined(PNG_READ_tIME_SUPPORTED)
  187563. PNG_CONST PNG_tIME;
  187564. #endif
  187565. #if defined(PNG_READ_tRNS_SUPPORTED)
  187566. PNG_CONST PNG_tRNS;
  187567. #endif
  187568. #if defined(PNG_READ_zTXt_SUPPORTED)
  187569. PNG_CONST PNG_zTXt;
  187570. #endif
  187571. #endif /* PNG_USE_LOCAL_ARRAYS */
  187572. png_byte chunk_length[4];
  187573. png_uint_32 length;
  187574. png_read_data(png_ptr, chunk_length, 4);
  187575. length = png_get_uint_31(png_ptr,chunk_length);
  187576. png_reset_crc(png_ptr);
  187577. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187578. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187579. length);
  187580. /* This should be a binary subdivision search or a hash for
  187581. * matching the chunk name rather than a linear search.
  187582. */
  187583. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187584. if(png_ptr->mode & PNG_AFTER_IDAT)
  187585. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187586. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187587. png_handle_IHDR(png_ptr, info_ptr, length);
  187588. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187589. png_handle_IEND(png_ptr, info_ptr, length);
  187590. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187591. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187592. {
  187593. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187594. png_ptr->mode |= PNG_HAVE_IDAT;
  187595. png_handle_unknown(png_ptr, info_ptr, length);
  187596. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187597. png_ptr->mode |= PNG_HAVE_PLTE;
  187598. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187599. {
  187600. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187601. png_error(png_ptr, "Missing IHDR before IDAT");
  187602. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187603. !(png_ptr->mode & PNG_HAVE_PLTE))
  187604. png_error(png_ptr, "Missing PLTE before IDAT");
  187605. break;
  187606. }
  187607. }
  187608. #endif
  187609. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187610. png_handle_PLTE(png_ptr, info_ptr, length);
  187611. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187612. {
  187613. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187614. png_error(png_ptr, "Missing IHDR before IDAT");
  187615. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187616. !(png_ptr->mode & PNG_HAVE_PLTE))
  187617. png_error(png_ptr, "Missing PLTE before IDAT");
  187618. png_ptr->idat_size = length;
  187619. png_ptr->mode |= PNG_HAVE_IDAT;
  187620. break;
  187621. }
  187622. #if defined(PNG_READ_bKGD_SUPPORTED)
  187623. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187624. png_handle_bKGD(png_ptr, info_ptr, length);
  187625. #endif
  187626. #if defined(PNG_READ_cHRM_SUPPORTED)
  187627. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187628. png_handle_cHRM(png_ptr, info_ptr, length);
  187629. #endif
  187630. #if defined(PNG_READ_gAMA_SUPPORTED)
  187631. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187632. png_handle_gAMA(png_ptr, info_ptr, length);
  187633. #endif
  187634. #if defined(PNG_READ_hIST_SUPPORTED)
  187635. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187636. png_handle_hIST(png_ptr, info_ptr, length);
  187637. #endif
  187638. #if defined(PNG_READ_oFFs_SUPPORTED)
  187639. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187640. png_handle_oFFs(png_ptr, info_ptr, length);
  187641. #endif
  187642. #if defined(PNG_READ_pCAL_SUPPORTED)
  187643. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187644. png_handle_pCAL(png_ptr, info_ptr, length);
  187645. #endif
  187646. #if defined(PNG_READ_sCAL_SUPPORTED)
  187647. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187648. png_handle_sCAL(png_ptr, info_ptr, length);
  187649. #endif
  187650. #if defined(PNG_READ_pHYs_SUPPORTED)
  187651. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187652. png_handle_pHYs(png_ptr, info_ptr, length);
  187653. #endif
  187654. #if defined(PNG_READ_sBIT_SUPPORTED)
  187655. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187656. png_handle_sBIT(png_ptr, info_ptr, length);
  187657. #endif
  187658. #if defined(PNG_READ_sRGB_SUPPORTED)
  187659. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187660. png_handle_sRGB(png_ptr, info_ptr, length);
  187661. #endif
  187662. #if defined(PNG_READ_iCCP_SUPPORTED)
  187663. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187664. png_handle_iCCP(png_ptr, info_ptr, length);
  187665. #endif
  187666. #if defined(PNG_READ_sPLT_SUPPORTED)
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187668. png_handle_sPLT(png_ptr, info_ptr, length);
  187669. #endif
  187670. #if defined(PNG_READ_tEXt_SUPPORTED)
  187671. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187672. png_handle_tEXt(png_ptr, info_ptr, length);
  187673. #endif
  187674. #if defined(PNG_READ_tIME_SUPPORTED)
  187675. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187676. png_handle_tIME(png_ptr, info_ptr, length);
  187677. #endif
  187678. #if defined(PNG_READ_tRNS_SUPPORTED)
  187679. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187680. png_handle_tRNS(png_ptr, info_ptr, length);
  187681. #endif
  187682. #if defined(PNG_READ_zTXt_SUPPORTED)
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187684. png_handle_zTXt(png_ptr, info_ptr, length);
  187685. #endif
  187686. #if defined(PNG_READ_iTXt_SUPPORTED)
  187687. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187688. png_handle_iTXt(png_ptr, info_ptr, length);
  187689. #endif
  187690. else
  187691. png_handle_unknown(png_ptr, info_ptr, length);
  187692. }
  187693. }
  187694. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187695. /* optional call to update the users info_ptr structure */
  187696. void PNGAPI
  187697. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187698. {
  187699. png_debug(1, "in png_read_update_info\n");
  187700. if(png_ptr == NULL) return;
  187701. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187702. png_read_start_row(png_ptr);
  187703. else
  187704. png_warning(png_ptr,
  187705. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187706. png_read_transform_info(png_ptr, info_ptr);
  187707. }
  187708. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187709. /* Initialize palette, background, etc, after transformations
  187710. * are set, but before any reading takes place. This allows
  187711. * the user to obtain a gamma-corrected palette, for example.
  187712. * If the user doesn't call this, we will do it ourselves.
  187713. */
  187714. void PNGAPI
  187715. png_start_read_image(png_structp png_ptr)
  187716. {
  187717. png_debug(1, "in png_start_read_image\n");
  187718. if(png_ptr == NULL) return;
  187719. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187720. png_read_start_row(png_ptr);
  187721. }
  187722. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187723. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187724. void PNGAPI
  187725. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187726. {
  187727. #ifdef PNG_USE_LOCAL_ARRAYS
  187728. PNG_CONST PNG_IDAT;
  187729. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187730. 0xff};
  187731. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187732. #endif
  187733. int ret;
  187734. if(png_ptr == NULL) return;
  187735. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187736. png_ptr->row_number, png_ptr->pass);
  187737. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187738. png_read_start_row(png_ptr);
  187739. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187740. {
  187741. /* check for transforms that have been set but were defined out */
  187742. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187743. if (png_ptr->transformations & PNG_INVERT_MONO)
  187744. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187745. #endif
  187746. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187747. if (png_ptr->transformations & PNG_FILLER)
  187748. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187749. #endif
  187750. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187751. if (png_ptr->transformations & PNG_PACKSWAP)
  187752. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187753. #endif
  187754. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187755. if (png_ptr->transformations & PNG_PACK)
  187756. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187757. #endif
  187758. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187759. if (png_ptr->transformations & PNG_SHIFT)
  187760. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187761. #endif
  187762. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187763. if (png_ptr->transformations & PNG_BGR)
  187764. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187765. #endif
  187766. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187767. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187768. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187769. #endif
  187770. }
  187771. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187772. /* if interlaced and we do not need a new row, combine row and return */
  187773. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187774. {
  187775. switch (png_ptr->pass)
  187776. {
  187777. case 0:
  187778. if (png_ptr->row_number & 0x07)
  187779. {
  187780. if (dsp_row != NULL)
  187781. png_combine_row(png_ptr, dsp_row,
  187782. png_pass_dsp_mask[png_ptr->pass]);
  187783. png_read_finish_row(png_ptr);
  187784. return;
  187785. }
  187786. break;
  187787. case 1:
  187788. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187789. {
  187790. if (dsp_row != NULL)
  187791. png_combine_row(png_ptr, dsp_row,
  187792. png_pass_dsp_mask[png_ptr->pass]);
  187793. png_read_finish_row(png_ptr);
  187794. return;
  187795. }
  187796. break;
  187797. case 2:
  187798. if ((png_ptr->row_number & 0x07) != 4)
  187799. {
  187800. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187801. png_combine_row(png_ptr, dsp_row,
  187802. png_pass_dsp_mask[png_ptr->pass]);
  187803. png_read_finish_row(png_ptr);
  187804. return;
  187805. }
  187806. break;
  187807. case 3:
  187808. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187809. {
  187810. if (dsp_row != NULL)
  187811. png_combine_row(png_ptr, dsp_row,
  187812. png_pass_dsp_mask[png_ptr->pass]);
  187813. png_read_finish_row(png_ptr);
  187814. return;
  187815. }
  187816. break;
  187817. case 4:
  187818. if ((png_ptr->row_number & 3) != 2)
  187819. {
  187820. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187821. png_combine_row(png_ptr, dsp_row,
  187822. png_pass_dsp_mask[png_ptr->pass]);
  187823. png_read_finish_row(png_ptr);
  187824. return;
  187825. }
  187826. break;
  187827. case 5:
  187828. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187829. {
  187830. if (dsp_row != NULL)
  187831. png_combine_row(png_ptr, dsp_row,
  187832. png_pass_dsp_mask[png_ptr->pass]);
  187833. png_read_finish_row(png_ptr);
  187834. return;
  187835. }
  187836. break;
  187837. case 6:
  187838. if (!(png_ptr->row_number & 1))
  187839. {
  187840. png_read_finish_row(png_ptr);
  187841. return;
  187842. }
  187843. break;
  187844. }
  187845. }
  187846. #endif
  187847. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187848. png_error(png_ptr, "Invalid attempt to read row data");
  187849. png_ptr->zstream.next_out = png_ptr->row_buf;
  187850. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187851. do
  187852. {
  187853. if (!(png_ptr->zstream.avail_in))
  187854. {
  187855. while (!png_ptr->idat_size)
  187856. {
  187857. png_byte chunk_length[4];
  187858. png_crc_finish(png_ptr, 0);
  187859. png_read_data(png_ptr, chunk_length, 4);
  187860. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187861. png_reset_crc(png_ptr);
  187862. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187863. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187864. png_error(png_ptr, "Not enough image data");
  187865. }
  187866. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187867. png_ptr->zstream.next_in = png_ptr->zbuf;
  187868. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187869. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187870. png_crc_read(png_ptr, png_ptr->zbuf,
  187871. (png_size_t)png_ptr->zstream.avail_in);
  187872. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187873. }
  187874. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187875. if (ret == Z_STREAM_END)
  187876. {
  187877. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187878. png_ptr->idat_size)
  187879. png_error(png_ptr, "Extra compressed data");
  187880. png_ptr->mode |= PNG_AFTER_IDAT;
  187881. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187882. break;
  187883. }
  187884. if (ret != Z_OK)
  187885. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187886. "Decompression error");
  187887. } while (png_ptr->zstream.avail_out);
  187888. png_ptr->row_info.color_type = png_ptr->color_type;
  187889. png_ptr->row_info.width = png_ptr->iwidth;
  187890. png_ptr->row_info.channels = png_ptr->channels;
  187891. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187892. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187893. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187894. png_ptr->row_info.width);
  187895. if(png_ptr->row_buf[0])
  187896. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187897. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187898. (int)(png_ptr->row_buf[0]));
  187899. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187900. png_ptr->rowbytes + 1);
  187901. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187902. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187903. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187904. {
  187905. /* Intrapixel differencing */
  187906. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187907. }
  187908. #endif
  187909. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187910. png_do_read_transformations(png_ptr);
  187911. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187912. /* blow up interlaced rows to full size */
  187913. if (png_ptr->interlaced &&
  187914. (png_ptr->transformations & PNG_INTERLACE))
  187915. {
  187916. if (png_ptr->pass < 6)
  187917. /* old interface (pre-1.0.9):
  187918. png_do_read_interlace(&(png_ptr->row_info),
  187919. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187920. */
  187921. png_do_read_interlace(png_ptr);
  187922. if (dsp_row != NULL)
  187923. png_combine_row(png_ptr, dsp_row,
  187924. png_pass_dsp_mask[png_ptr->pass]);
  187925. if (row != NULL)
  187926. png_combine_row(png_ptr, row,
  187927. png_pass_mask[png_ptr->pass]);
  187928. }
  187929. else
  187930. #endif
  187931. {
  187932. if (row != NULL)
  187933. png_combine_row(png_ptr, row, 0xff);
  187934. if (dsp_row != NULL)
  187935. png_combine_row(png_ptr, dsp_row, 0xff);
  187936. }
  187937. png_read_finish_row(png_ptr);
  187938. if (png_ptr->read_row_fn != NULL)
  187939. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187940. }
  187941. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187942. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187943. /* Read one or more rows of image data. If the image is interlaced,
  187944. * and png_set_interlace_handling() has been called, the rows need to
  187945. * contain the contents of the rows from the previous pass. If the
  187946. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187947. * called, the rows contents must be initialized to the contents of the
  187948. * screen.
  187949. *
  187950. * "row" holds the actual image, and pixels are placed in it
  187951. * as they arrive. If the image is displayed after each pass, it will
  187952. * appear to "sparkle" in. "display_row" can be used to display a
  187953. * "chunky" progressive image, with finer detail added as it becomes
  187954. * available. If you do not want this "chunky" display, you may pass
  187955. * NULL for display_row. If you do not want the sparkle display, and
  187956. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187957. * If you have called png_handle_alpha(), and the image has either an
  187958. * alpha channel or a transparency chunk, you must provide a buffer for
  187959. * rows. In this case, you do not have to provide a display_row buffer
  187960. * also, but you may. If the image is not interlaced, or if you have
  187961. * not called png_set_interlace_handling(), the display_row buffer will
  187962. * be ignored, so pass NULL to it.
  187963. *
  187964. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187965. */
  187966. void PNGAPI
  187967. png_read_rows(png_structp png_ptr, png_bytepp row,
  187968. png_bytepp display_row, png_uint_32 num_rows)
  187969. {
  187970. png_uint_32 i;
  187971. png_bytepp rp;
  187972. png_bytepp dp;
  187973. png_debug(1, "in png_read_rows\n");
  187974. if(png_ptr == NULL) return;
  187975. rp = row;
  187976. dp = display_row;
  187977. if (rp != NULL && dp != NULL)
  187978. for (i = 0; i < num_rows; i++)
  187979. {
  187980. png_bytep rptr = *rp++;
  187981. png_bytep dptr = *dp++;
  187982. png_read_row(png_ptr, rptr, dptr);
  187983. }
  187984. else if(rp != NULL)
  187985. for (i = 0; i < num_rows; i++)
  187986. {
  187987. png_bytep rptr = *rp;
  187988. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187989. rp++;
  187990. }
  187991. else if(dp != NULL)
  187992. for (i = 0; i < num_rows; i++)
  187993. {
  187994. png_bytep dptr = *dp;
  187995. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187996. dp++;
  187997. }
  187998. }
  187999. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188000. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188001. /* Read the entire image. If the image has an alpha channel or a tRNS
  188002. * chunk, and you have called png_handle_alpha()[*], you will need to
  188003. * initialize the image to the current image that PNG will be overlaying.
  188004. * We set the num_rows again here, in case it was incorrectly set in
  188005. * png_read_start_row() by a call to png_read_update_info() or
  188006. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188007. * prior to either of these functions like it should have been. You can
  188008. * only call this function once. If you desire to have an image for
  188009. * each pass of a interlaced image, use png_read_rows() instead.
  188010. *
  188011. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188012. */
  188013. void PNGAPI
  188014. png_read_image(png_structp png_ptr, png_bytepp image)
  188015. {
  188016. png_uint_32 i,image_height;
  188017. int pass, j;
  188018. png_bytepp rp;
  188019. png_debug(1, "in png_read_image\n");
  188020. if(png_ptr == NULL) return;
  188021. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188022. pass = png_set_interlace_handling(png_ptr);
  188023. #else
  188024. if (png_ptr->interlaced)
  188025. png_error(png_ptr,
  188026. "Cannot read interlaced image -- interlace handler disabled.");
  188027. pass = 1;
  188028. #endif
  188029. image_height=png_ptr->height;
  188030. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188031. for (j = 0; j < pass; j++)
  188032. {
  188033. rp = image;
  188034. for (i = 0; i < image_height; i++)
  188035. {
  188036. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188037. rp++;
  188038. }
  188039. }
  188040. }
  188041. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188042. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188043. /* Read the end of the PNG file. Will not read past the end of the
  188044. * file, will verify the end is accurate, and will read any comments
  188045. * or time information at the end of the file, if info is not NULL.
  188046. */
  188047. void PNGAPI
  188048. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188049. {
  188050. png_byte chunk_length[4];
  188051. png_uint_32 length;
  188052. png_debug(1, "in png_read_end\n");
  188053. if(png_ptr == NULL) return;
  188054. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188055. do
  188056. {
  188057. #ifdef PNG_USE_LOCAL_ARRAYS
  188058. PNG_CONST PNG_IHDR;
  188059. PNG_CONST PNG_IDAT;
  188060. PNG_CONST PNG_IEND;
  188061. PNG_CONST PNG_PLTE;
  188062. #if defined(PNG_READ_bKGD_SUPPORTED)
  188063. PNG_CONST PNG_bKGD;
  188064. #endif
  188065. #if defined(PNG_READ_cHRM_SUPPORTED)
  188066. PNG_CONST PNG_cHRM;
  188067. #endif
  188068. #if defined(PNG_READ_gAMA_SUPPORTED)
  188069. PNG_CONST PNG_gAMA;
  188070. #endif
  188071. #if defined(PNG_READ_hIST_SUPPORTED)
  188072. PNG_CONST PNG_hIST;
  188073. #endif
  188074. #if defined(PNG_READ_iCCP_SUPPORTED)
  188075. PNG_CONST PNG_iCCP;
  188076. #endif
  188077. #if defined(PNG_READ_iTXt_SUPPORTED)
  188078. PNG_CONST PNG_iTXt;
  188079. #endif
  188080. #if defined(PNG_READ_oFFs_SUPPORTED)
  188081. PNG_CONST PNG_oFFs;
  188082. #endif
  188083. #if defined(PNG_READ_pCAL_SUPPORTED)
  188084. PNG_CONST PNG_pCAL;
  188085. #endif
  188086. #if defined(PNG_READ_pHYs_SUPPORTED)
  188087. PNG_CONST PNG_pHYs;
  188088. #endif
  188089. #if defined(PNG_READ_sBIT_SUPPORTED)
  188090. PNG_CONST PNG_sBIT;
  188091. #endif
  188092. #if defined(PNG_READ_sCAL_SUPPORTED)
  188093. PNG_CONST PNG_sCAL;
  188094. #endif
  188095. #if defined(PNG_READ_sPLT_SUPPORTED)
  188096. PNG_CONST PNG_sPLT;
  188097. #endif
  188098. #if defined(PNG_READ_sRGB_SUPPORTED)
  188099. PNG_CONST PNG_sRGB;
  188100. #endif
  188101. #if defined(PNG_READ_tEXt_SUPPORTED)
  188102. PNG_CONST PNG_tEXt;
  188103. #endif
  188104. #if defined(PNG_READ_tIME_SUPPORTED)
  188105. PNG_CONST PNG_tIME;
  188106. #endif
  188107. #if defined(PNG_READ_tRNS_SUPPORTED)
  188108. PNG_CONST PNG_tRNS;
  188109. #endif
  188110. #if defined(PNG_READ_zTXt_SUPPORTED)
  188111. PNG_CONST PNG_zTXt;
  188112. #endif
  188113. #endif /* PNG_USE_LOCAL_ARRAYS */
  188114. png_read_data(png_ptr, chunk_length, 4);
  188115. length = png_get_uint_31(png_ptr,chunk_length);
  188116. png_reset_crc(png_ptr);
  188117. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188118. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188119. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188120. png_handle_IHDR(png_ptr, info_ptr, length);
  188121. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188122. png_handle_IEND(png_ptr, info_ptr, length);
  188123. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188124. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188125. {
  188126. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188127. {
  188128. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188129. png_error(png_ptr, "Too many IDAT's found");
  188130. }
  188131. png_handle_unknown(png_ptr, info_ptr, length);
  188132. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188133. png_ptr->mode |= PNG_HAVE_PLTE;
  188134. }
  188135. #endif
  188136. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188137. {
  188138. /* Zero length IDATs are legal after the last IDAT has been
  188139. * read, but not after other chunks have been read.
  188140. */
  188141. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188142. png_error(png_ptr, "Too many IDAT's found");
  188143. png_crc_finish(png_ptr, length);
  188144. }
  188145. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188146. png_handle_PLTE(png_ptr, info_ptr, length);
  188147. #if defined(PNG_READ_bKGD_SUPPORTED)
  188148. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188149. png_handle_bKGD(png_ptr, info_ptr, length);
  188150. #endif
  188151. #if defined(PNG_READ_cHRM_SUPPORTED)
  188152. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188153. png_handle_cHRM(png_ptr, info_ptr, length);
  188154. #endif
  188155. #if defined(PNG_READ_gAMA_SUPPORTED)
  188156. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188157. png_handle_gAMA(png_ptr, info_ptr, length);
  188158. #endif
  188159. #if defined(PNG_READ_hIST_SUPPORTED)
  188160. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188161. png_handle_hIST(png_ptr, info_ptr, length);
  188162. #endif
  188163. #if defined(PNG_READ_oFFs_SUPPORTED)
  188164. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188165. png_handle_oFFs(png_ptr, info_ptr, length);
  188166. #endif
  188167. #if defined(PNG_READ_pCAL_SUPPORTED)
  188168. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188169. png_handle_pCAL(png_ptr, info_ptr, length);
  188170. #endif
  188171. #if defined(PNG_READ_sCAL_SUPPORTED)
  188172. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188173. png_handle_sCAL(png_ptr, info_ptr, length);
  188174. #endif
  188175. #if defined(PNG_READ_pHYs_SUPPORTED)
  188176. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188177. png_handle_pHYs(png_ptr, info_ptr, length);
  188178. #endif
  188179. #if defined(PNG_READ_sBIT_SUPPORTED)
  188180. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188181. png_handle_sBIT(png_ptr, info_ptr, length);
  188182. #endif
  188183. #if defined(PNG_READ_sRGB_SUPPORTED)
  188184. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188185. png_handle_sRGB(png_ptr, info_ptr, length);
  188186. #endif
  188187. #if defined(PNG_READ_iCCP_SUPPORTED)
  188188. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188189. png_handle_iCCP(png_ptr, info_ptr, length);
  188190. #endif
  188191. #if defined(PNG_READ_sPLT_SUPPORTED)
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188193. png_handle_sPLT(png_ptr, info_ptr, length);
  188194. #endif
  188195. #if defined(PNG_READ_tEXt_SUPPORTED)
  188196. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188197. png_handle_tEXt(png_ptr, info_ptr, length);
  188198. #endif
  188199. #if defined(PNG_READ_tIME_SUPPORTED)
  188200. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188201. png_handle_tIME(png_ptr, info_ptr, length);
  188202. #endif
  188203. #if defined(PNG_READ_tRNS_SUPPORTED)
  188204. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188205. png_handle_tRNS(png_ptr, info_ptr, length);
  188206. #endif
  188207. #if defined(PNG_READ_zTXt_SUPPORTED)
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188209. png_handle_zTXt(png_ptr, info_ptr, length);
  188210. #endif
  188211. #if defined(PNG_READ_iTXt_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188213. png_handle_iTXt(png_ptr, info_ptr, length);
  188214. #endif
  188215. else
  188216. png_handle_unknown(png_ptr, info_ptr, length);
  188217. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188218. }
  188219. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188220. /* free all memory used by the read */
  188221. void PNGAPI
  188222. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188223. png_infopp end_info_ptr_ptr)
  188224. {
  188225. png_structp png_ptr = NULL;
  188226. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188227. #ifdef PNG_USER_MEM_SUPPORTED
  188228. png_free_ptr free_fn;
  188229. png_voidp mem_ptr;
  188230. #endif
  188231. png_debug(1, "in png_destroy_read_struct\n");
  188232. if (png_ptr_ptr != NULL)
  188233. png_ptr = *png_ptr_ptr;
  188234. if (info_ptr_ptr != NULL)
  188235. info_ptr = *info_ptr_ptr;
  188236. if (end_info_ptr_ptr != NULL)
  188237. end_info_ptr = *end_info_ptr_ptr;
  188238. #ifdef PNG_USER_MEM_SUPPORTED
  188239. free_fn = png_ptr->free_fn;
  188240. mem_ptr = png_ptr->mem_ptr;
  188241. #endif
  188242. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188243. if (info_ptr != NULL)
  188244. {
  188245. #if defined(PNG_TEXT_SUPPORTED)
  188246. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188247. #endif
  188248. #ifdef PNG_USER_MEM_SUPPORTED
  188249. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188250. (png_voidp)mem_ptr);
  188251. #else
  188252. png_destroy_struct((png_voidp)info_ptr);
  188253. #endif
  188254. *info_ptr_ptr = NULL;
  188255. }
  188256. if (end_info_ptr != NULL)
  188257. {
  188258. #if defined(PNG_READ_TEXT_SUPPORTED)
  188259. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188260. #endif
  188261. #ifdef PNG_USER_MEM_SUPPORTED
  188262. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188263. (png_voidp)mem_ptr);
  188264. #else
  188265. png_destroy_struct((png_voidp)end_info_ptr);
  188266. #endif
  188267. *end_info_ptr_ptr = NULL;
  188268. }
  188269. if (png_ptr != NULL)
  188270. {
  188271. #ifdef PNG_USER_MEM_SUPPORTED
  188272. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188273. (png_voidp)mem_ptr);
  188274. #else
  188275. png_destroy_struct((png_voidp)png_ptr);
  188276. #endif
  188277. *png_ptr_ptr = NULL;
  188278. }
  188279. }
  188280. /* free all memory used by the read (old method) */
  188281. void /* PRIVATE */
  188282. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188283. {
  188284. #ifdef PNG_SETJMP_SUPPORTED
  188285. jmp_buf tmp_jmp;
  188286. #endif
  188287. png_error_ptr error_fn;
  188288. png_error_ptr warning_fn;
  188289. png_voidp error_ptr;
  188290. #ifdef PNG_USER_MEM_SUPPORTED
  188291. png_free_ptr free_fn;
  188292. #endif
  188293. png_debug(1, "in png_read_destroy\n");
  188294. if (info_ptr != NULL)
  188295. png_info_destroy(png_ptr, info_ptr);
  188296. if (end_info_ptr != NULL)
  188297. png_info_destroy(png_ptr, end_info_ptr);
  188298. png_free(png_ptr, png_ptr->zbuf);
  188299. png_free(png_ptr, png_ptr->big_row_buf);
  188300. png_free(png_ptr, png_ptr->prev_row);
  188301. #if defined(PNG_READ_DITHER_SUPPORTED)
  188302. png_free(png_ptr, png_ptr->palette_lookup);
  188303. png_free(png_ptr, png_ptr->dither_index);
  188304. #endif
  188305. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188306. png_free(png_ptr, png_ptr->gamma_table);
  188307. #endif
  188308. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188309. png_free(png_ptr, png_ptr->gamma_from_1);
  188310. png_free(png_ptr, png_ptr->gamma_to_1);
  188311. #endif
  188312. #ifdef PNG_FREE_ME_SUPPORTED
  188313. if (png_ptr->free_me & PNG_FREE_PLTE)
  188314. png_zfree(png_ptr, png_ptr->palette);
  188315. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188316. #else
  188317. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188318. png_zfree(png_ptr, png_ptr->palette);
  188319. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188320. #endif
  188321. #if defined(PNG_tRNS_SUPPORTED) || \
  188322. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188323. #ifdef PNG_FREE_ME_SUPPORTED
  188324. if (png_ptr->free_me & PNG_FREE_TRNS)
  188325. png_free(png_ptr, png_ptr->trans);
  188326. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188327. #else
  188328. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188329. png_free(png_ptr, png_ptr->trans);
  188330. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188331. #endif
  188332. #endif
  188333. #if defined(PNG_READ_hIST_SUPPORTED)
  188334. #ifdef PNG_FREE_ME_SUPPORTED
  188335. if (png_ptr->free_me & PNG_FREE_HIST)
  188336. png_free(png_ptr, png_ptr->hist);
  188337. png_ptr->free_me &= ~PNG_FREE_HIST;
  188338. #else
  188339. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188340. png_free(png_ptr, png_ptr->hist);
  188341. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188342. #endif
  188343. #endif
  188344. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188345. if (png_ptr->gamma_16_table != NULL)
  188346. {
  188347. int i;
  188348. int istop = (1 << (8 - png_ptr->gamma_shift));
  188349. for (i = 0; i < istop; i++)
  188350. {
  188351. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188352. }
  188353. png_free(png_ptr, png_ptr->gamma_16_table);
  188354. }
  188355. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188356. if (png_ptr->gamma_16_from_1 != NULL)
  188357. {
  188358. int i;
  188359. int istop = (1 << (8 - png_ptr->gamma_shift));
  188360. for (i = 0; i < istop; i++)
  188361. {
  188362. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188363. }
  188364. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188365. }
  188366. if (png_ptr->gamma_16_to_1 != NULL)
  188367. {
  188368. int i;
  188369. int istop = (1 << (8 - png_ptr->gamma_shift));
  188370. for (i = 0; i < istop; i++)
  188371. {
  188372. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188373. }
  188374. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188375. }
  188376. #endif
  188377. #endif
  188378. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188379. png_free(png_ptr, png_ptr->time_buffer);
  188380. #endif
  188381. inflateEnd(&png_ptr->zstream);
  188382. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188383. png_free(png_ptr, png_ptr->save_buffer);
  188384. #endif
  188385. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188386. #ifdef PNG_TEXT_SUPPORTED
  188387. png_free(png_ptr, png_ptr->current_text);
  188388. #endif /* PNG_TEXT_SUPPORTED */
  188389. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188390. /* Save the important info out of the png_struct, in case it is
  188391. * being used again.
  188392. */
  188393. #ifdef PNG_SETJMP_SUPPORTED
  188394. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188395. #endif
  188396. error_fn = png_ptr->error_fn;
  188397. warning_fn = png_ptr->warning_fn;
  188398. error_ptr = png_ptr->error_ptr;
  188399. #ifdef PNG_USER_MEM_SUPPORTED
  188400. free_fn = png_ptr->free_fn;
  188401. #endif
  188402. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188403. png_ptr->error_fn = error_fn;
  188404. png_ptr->warning_fn = warning_fn;
  188405. png_ptr->error_ptr = error_ptr;
  188406. #ifdef PNG_USER_MEM_SUPPORTED
  188407. png_ptr->free_fn = free_fn;
  188408. #endif
  188409. #ifdef PNG_SETJMP_SUPPORTED
  188410. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188411. #endif
  188412. }
  188413. void PNGAPI
  188414. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188415. {
  188416. if(png_ptr == NULL) return;
  188417. png_ptr->read_row_fn = read_row_fn;
  188418. }
  188419. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188420. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188421. void PNGAPI
  188422. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188423. int transforms,
  188424. voidp params)
  188425. {
  188426. int row;
  188427. if(png_ptr == NULL) return;
  188428. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188429. /* invert the alpha channel from opacity to transparency
  188430. */
  188431. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188432. png_set_invert_alpha(png_ptr);
  188433. #endif
  188434. /* png_read_info() gives us all of the information from the
  188435. * PNG file before the first IDAT (image data chunk).
  188436. */
  188437. png_read_info(png_ptr, info_ptr);
  188438. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188439. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188440. /* -------------- image transformations start here ------------------- */
  188441. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188442. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188443. */
  188444. if (transforms & PNG_TRANSFORM_STRIP_16)
  188445. png_set_strip_16(png_ptr);
  188446. #endif
  188447. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188448. /* Strip alpha bytes from the input data without combining with
  188449. * the background (not recommended).
  188450. */
  188451. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188452. png_set_strip_alpha(png_ptr);
  188453. #endif
  188454. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188455. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188456. * byte into separate bytes (useful for paletted and grayscale images).
  188457. */
  188458. if (transforms & PNG_TRANSFORM_PACKING)
  188459. png_set_packing(png_ptr);
  188460. #endif
  188461. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188462. /* Change the order of packed pixels to least significant bit first
  188463. * (not useful if you are using png_set_packing).
  188464. */
  188465. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188466. png_set_packswap(png_ptr);
  188467. #endif
  188468. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188469. /* Expand paletted colors into true RGB triplets
  188470. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188471. * Expand paletted or RGB images with transparency to full alpha
  188472. * channels so the data will be available as RGBA quartets.
  188473. */
  188474. if (transforms & PNG_TRANSFORM_EXPAND)
  188475. if ((png_ptr->bit_depth < 8) ||
  188476. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188477. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188478. png_set_expand(png_ptr);
  188479. #endif
  188480. /* We don't handle background color or gamma transformation or dithering.
  188481. */
  188482. #if defined(PNG_READ_INVERT_SUPPORTED)
  188483. /* invert monochrome files to have 0 as white and 1 as black
  188484. */
  188485. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188486. png_set_invert_mono(png_ptr);
  188487. #endif
  188488. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188489. /* If you want to shift the pixel values from the range [0,255] or
  188490. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188491. * colors were originally in:
  188492. */
  188493. if ((transforms & PNG_TRANSFORM_SHIFT)
  188494. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188495. {
  188496. png_color_8p sig_bit;
  188497. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188498. png_set_shift(png_ptr, sig_bit);
  188499. }
  188500. #endif
  188501. #if defined(PNG_READ_BGR_SUPPORTED)
  188502. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188503. */
  188504. if (transforms & PNG_TRANSFORM_BGR)
  188505. png_set_bgr(png_ptr);
  188506. #endif
  188507. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188508. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188509. */
  188510. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188511. png_set_swap_alpha(png_ptr);
  188512. #endif
  188513. #if defined(PNG_READ_SWAP_SUPPORTED)
  188514. /* swap bytes of 16 bit files to least significant byte first
  188515. */
  188516. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188517. png_set_swap(png_ptr);
  188518. #endif
  188519. /* We don't handle adding filler bytes */
  188520. /* Optional call to gamma correct and add the background to the palette
  188521. * and update info structure. REQUIRED if you are expecting libpng to
  188522. * update the palette for you (i.e., you selected such a transform above).
  188523. */
  188524. png_read_update_info(png_ptr, info_ptr);
  188525. /* -------------- image transformations end here ------------------- */
  188526. #ifdef PNG_FREE_ME_SUPPORTED
  188527. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188528. #endif
  188529. if(info_ptr->row_pointers == NULL)
  188530. {
  188531. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188532. info_ptr->height * png_sizeof(png_bytep));
  188533. #ifdef PNG_FREE_ME_SUPPORTED
  188534. info_ptr->free_me |= PNG_FREE_ROWS;
  188535. #endif
  188536. for (row = 0; row < (int)info_ptr->height; row++)
  188537. {
  188538. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188539. png_get_rowbytes(png_ptr, info_ptr));
  188540. }
  188541. }
  188542. png_read_image(png_ptr, info_ptr->row_pointers);
  188543. info_ptr->valid |= PNG_INFO_IDAT;
  188544. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188545. png_read_end(png_ptr, info_ptr);
  188546. transforms = transforms; /* quiet compiler warnings */
  188547. params = params;
  188548. }
  188549. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188550. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188551. #endif /* PNG_READ_SUPPORTED */
  188552. /*** End of inlined file: pngread.c ***/
  188553. /*** Start of inlined file: pngpread.c ***/
  188554. /* pngpread.c - read a png file in push mode
  188555. *
  188556. * Last changed in libpng 1.2.21 October 4, 2007
  188557. * For conditions of distribution and use, see copyright notice in png.h
  188558. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188559. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188560. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188561. */
  188562. #define PNG_INTERNAL
  188563. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188564. /* push model modes */
  188565. #define PNG_READ_SIG_MODE 0
  188566. #define PNG_READ_CHUNK_MODE 1
  188567. #define PNG_READ_IDAT_MODE 2
  188568. #define PNG_SKIP_MODE 3
  188569. #define PNG_READ_tEXt_MODE 4
  188570. #define PNG_READ_zTXt_MODE 5
  188571. #define PNG_READ_DONE_MODE 6
  188572. #define PNG_READ_iTXt_MODE 7
  188573. #define PNG_ERROR_MODE 8
  188574. void PNGAPI
  188575. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188576. png_bytep buffer, png_size_t buffer_size)
  188577. {
  188578. if(png_ptr == NULL) return;
  188579. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188580. while (png_ptr->buffer_size)
  188581. {
  188582. png_process_some_data(png_ptr, info_ptr);
  188583. }
  188584. }
  188585. /* What we do with the incoming data depends on what we were previously
  188586. * doing before we ran out of data...
  188587. */
  188588. void /* PRIVATE */
  188589. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188590. {
  188591. if(png_ptr == NULL) return;
  188592. switch (png_ptr->process_mode)
  188593. {
  188594. case PNG_READ_SIG_MODE:
  188595. {
  188596. png_push_read_sig(png_ptr, info_ptr);
  188597. break;
  188598. }
  188599. case PNG_READ_CHUNK_MODE:
  188600. {
  188601. png_push_read_chunk(png_ptr, info_ptr);
  188602. break;
  188603. }
  188604. case PNG_READ_IDAT_MODE:
  188605. {
  188606. png_push_read_IDAT(png_ptr);
  188607. break;
  188608. }
  188609. #if defined(PNG_READ_tEXt_SUPPORTED)
  188610. case PNG_READ_tEXt_MODE:
  188611. {
  188612. png_push_read_tEXt(png_ptr, info_ptr);
  188613. break;
  188614. }
  188615. #endif
  188616. #if defined(PNG_READ_zTXt_SUPPORTED)
  188617. case PNG_READ_zTXt_MODE:
  188618. {
  188619. png_push_read_zTXt(png_ptr, info_ptr);
  188620. break;
  188621. }
  188622. #endif
  188623. #if defined(PNG_READ_iTXt_SUPPORTED)
  188624. case PNG_READ_iTXt_MODE:
  188625. {
  188626. png_push_read_iTXt(png_ptr, info_ptr);
  188627. break;
  188628. }
  188629. #endif
  188630. case PNG_SKIP_MODE:
  188631. {
  188632. png_push_crc_finish(png_ptr);
  188633. break;
  188634. }
  188635. default:
  188636. {
  188637. png_ptr->buffer_size = 0;
  188638. break;
  188639. }
  188640. }
  188641. }
  188642. /* Read any remaining signature bytes from the stream and compare them with
  188643. * the correct PNG signature. It is possible that this routine is called
  188644. * with bytes already read from the signature, either because they have been
  188645. * checked by the calling application, or because of multiple calls to this
  188646. * routine.
  188647. */
  188648. void /* PRIVATE */
  188649. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188650. {
  188651. png_size_t num_checked = png_ptr->sig_bytes,
  188652. num_to_check = 8 - num_checked;
  188653. if (png_ptr->buffer_size < num_to_check)
  188654. {
  188655. num_to_check = png_ptr->buffer_size;
  188656. }
  188657. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188658. num_to_check);
  188659. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188660. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188661. {
  188662. if (num_checked < 4 &&
  188663. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188664. png_error(png_ptr, "Not a PNG file");
  188665. else
  188666. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188667. }
  188668. else
  188669. {
  188670. if (png_ptr->sig_bytes >= 8)
  188671. {
  188672. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188673. }
  188674. }
  188675. }
  188676. void /* PRIVATE */
  188677. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188678. {
  188679. #ifdef PNG_USE_LOCAL_ARRAYS
  188680. PNG_CONST PNG_IHDR;
  188681. PNG_CONST PNG_IDAT;
  188682. PNG_CONST PNG_IEND;
  188683. PNG_CONST PNG_PLTE;
  188684. #if defined(PNG_READ_bKGD_SUPPORTED)
  188685. PNG_CONST PNG_bKGD;
  188686. #endif
  188687. #if defined(PNG_READ_cHRM_SUPPORTED)
  188688. PNG_CONST PNG_cHRM;
  188689. #endif
  188690. #if defined(PNG_READ_gAMA_SUPPORTED)
  188691. PNG_CONST PNG_gAMA;
  188692. #endif
  188693. #if defined(PNG_READ_hIST_SUPPORTED)
  188694. PNG_CONST PNG_hIST;
  188695. #endif
  188696. #if defined(PNG_READ_iCCP_SUPPORTED)
  188697. PNG_CONST PNG_iCCP;
  188698. #endif
  188699. #if defined(PNG_READ_iTXt_SUPPORTED)
  188700. PNG_CONST PNG_iTXt;
  188701. #endif
  188702. #if defined(PNG_READ_oFFs_SUPPORTED)
  188703. PNG_CONST PNG_oFFs;
  188704. #endif
  188705. #if defined(PNG_READ_pCAL_SUPPORTED)
  188706. PNG_CONST PNG_pCAL;
  188707. #endif
  188708. #if defined(PNG_READ_pHYs_SUPPORTED)
  188709. PNG_CONST PNG_pHYs;
  188710. #endif
  188711. #if defined(PNG_READ_sBIT_SUPPORTED)
  188712. PNG_CONST PNG_sBIT;
  188713. #endif
  188714. #if defined(PNG_READ_sCAL_SUPPORTED)
  188715. PNG_CONST PNG_sCAL;
  188716. #endif
  188717. #if defined(PNG_READ_sRGB_SUPPORTED)
  188718. PNG_CONST PNG_sRGB;
  188719. #endif
  188720. #if defined(PNG_READ_sPLT_SUPPORTED)
  188721. PNG_CONST PNG_sPLT;
  188722. #endif
  188723. #if defined(PNG_READ_tEXt_SUPPORTED)
  188724. PNG_CONST PNG_tEXt;
  188725. #endif
  188726. #if defined(PNG_READ_tIME_SUPPORTED)
  188727. PNG_CONST PNG_tIME;
  188728. #endif
  188729. #if defined(PNG_READ_tRNS_SUPPORTED)
  188730. PNG_CONST PNG_tRNS;
  188731. #endif
  188732. #if defined(PNG_READ_zTXt_SUPPORTED)
  188733. PNG_CONST PNG_zTXt;
  188734. #endif
  188735. #endif /* PNG_USE_LOCAL_ARRAYS */
  188736. /* First we make sure we have enough data for the 4 byte chunk name
  188737. * and the 4 byte chunk length before proceeding with decoding the
  188738. * chunk data. To fully decode each of these chunks, we also make
  188739. * sure we have enough data in the buffer for the 4 byte CRC at the
  188740. * end of every chunk (except IDAT, which is handled separately).
  188741. */
  188742. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188743. {
  188744. png_byte chunk_length[4];
  188745. if (png_ptr->buffer_size < 8)
  188746. {
  188747. png_push_save_buffer(png_ptr);
  188748. return;
  188749. }
  188750. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188751. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188752. png_reset_crc(png_ptr);
  188753. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188754. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188755. }
  188756. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188757. if(png_ptr->mode & PNG_AFTER_IDAT)
  188758. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188759. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188760. {
  188761. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188762. {
  188763. png_push_save_buffer(png_ptr);
  188764. return;
  188765. }
  188766. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188767. }
  188768. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188769. {
  188770. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188771. {
  188772. png_push_save_buffer(png_ptr);
  188773. return;
  188774. }
  188775. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188776. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188777. png_push_have_end(png_ptr, info_ptr);
  188778. }
  188779. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188780. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188781. {
  188782. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188783. {
  188784. png_push_save_buffer(png_ptr);
  188785. return;
  188786. }
  188787. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188788. png_ptr->mode |= PNG_HAVE_IDAT;
  188789. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188790. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188791. png_ptr->mode |= PNG_HAVE_PLTE;
  188792. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188793. {
  188794. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188795. png_error(png_ptr, "Missing IHDR before IDAT");
  188796. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188797. !(png_ptr->mode & PNG_HAVE_PLTE))
  188798. png_error(png_ptr, "Missing PLTE before IDAT");
  188799. }
  188800. }
  188801. #endif
  188802. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188803. {
  188804. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188805. {
  188806. png_push_save_buffer(png_ptr);
  188807. return;
  188808. }
  188809. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188810. }
  188811. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188812. {
  188813. /* If we reach an IDAT chunk, this means we have read all of the
  188814. * header chunks, and we can start reading the image (or if this
  188815. * is called after the image has been read - we have an error).
  188816. */
  188817. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188818. png_error(png_ptr, "Missing IHDR before IDAT");
  188819. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188820. !(png_ptr->mode & PNG_HAVE_PLTE))
  188821. png_error(png_ptr, "Missing PLTE before IDAT");
  188822. if (png_ptr->mode & PNG_HAVE_IDAT)
  188823. {
  188824. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188825. if (png_ptr->push_length == 0)
  188826. return;
  188827. if (png_ptr->mode & PNG_AFTER_IDAT)
  188828. png_error(png_ptr, "Too many IDAT's found");
  188829. }
  188830. png_ptr->idat_size = png_ptr->push_length;
  188831. png_ptr->mode |= PNG_HAVE_IDAT;
  188832. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188833. png_push_have_info(png_ptr, info_ptr);
  188834. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188835. png_ptr->zstream.next_out = png_ptr->row_buf;
  188836. return;
  188837. }
  188838. #if defined(PNG_READ_gAMA_SUPPORTED)
  188839. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188840. {
  188841. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188842. {
  188843. png_push_save_buffer(png_ptr);
  188844. return;
  188845. }
  188846. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188847. }
  188848. #endif
  188849. #if defined(PNG_READ_sBIT_SUPPORTED)
  188850. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188851. {
  188852. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188853. {
  188854. png_push_save_buffer(png_ptr);
  188855. return;
  188856. }
  188857. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188858. }
  188859. #endif
  188860. #if defined(PNG_READ_cHRM_SUPPORTED)
  188861. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188862. {
  188863. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188864. {
  188865. png_push_save_buffer(png_ptr);
  188866. return;
  188867. }
  188868. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188869. }
  188870. #endif
  188871. #if defined(PNG_READ_sRGB_SUPPORTED)
  188872. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188873. {
  188874. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188875. {
  188876. png_push_save_buffer(png_ptr);
  188877. return;
  188878. }
  188879. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188880. }
  188881. #endif
  188882. #if defined(PNG_READ_iCCP_SUPPORTED)
  188883. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188884. {
  188885. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188886. {
  188887. png_push_save_buffer(png_ptr);
  188888. return;
  188889. }
  188890. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188891. }
  188892. #endif
  188893. #if defined(PNG_READ_sPLT_SUPPORTED)
  188894. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188895. {
  188896. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188897. {
  188898. png_push_save_buffer(png_ptr);
  188899. return;
  188900. }
  188901. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188902. }
  188903. #endif
  188904. #if defined(PNG_READ_tRNS_SUPPORTED)
  188905. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188906. {
  188907. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188908. {
  188909. png_push_save_buffer(png_ptr);
  188910. return;
  188911. }
  188912. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188913. }
  188914. #endif
  188915. #if defined(PNG_READ_bKGD_SUPPORTED)
  188916. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188917. {
  188918. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188919. {
  188920. png_push_save_buffer(png_ptr);
  188921. return;
  188922. }
  188923. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188924. }
  188925. #endif
  188926. #if defined(PNG_READ_hIST_SUPPORTED)
  188927. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188928. {
  188929. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188930. {
  188931. png_push_save_buffer(png_ptr);
  188932. return;
  188933. }
  188934. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188935. }
  188936. #endif
  188937. #if defined(PNG_READ_pHYs_SUPPORTED)
  188938. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188939. {
  188940. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188941. {
  188942. png_push_save_buffer(png_ptr);
  188943. return;
  188944. }
  188945. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188946. }
  188947. #endif
  188948. #if defined(PNG_READ_oFFs_SUPPORTED)
  188949. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188950. {
  188951. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188952. {
  188953. png_push_save_buffer(png_ptr);
  188954. return;
  188955. }
  188956. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188957. }
  188958. #endif
  188959. #if defined(PNG_READ_pCAL_SUPPORTED)
  188960. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188961. {
  188962. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188963. {
  188964. png_push_save_buffer(png_ptr);
  188965. return;
  188966. }
  188967. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188968. }
  188969. #endif
  188970. #if defined(PNG_READ_sCAL_SUPPORTED)
  188971. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188972. {
  188973. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188974. {
  188975. png_push_save_buffer(png_ptr);
  188976. return;
  188977. }
  188978. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188979. }
  188980. #endif
  188981. #if defined(PNG_READ_tIME_SUPPORTED)
  188982. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188983. {
  188984. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188985. {
  188986. png_push_save_buffer(png_ptr);
  188987. return;
  188988. }
  188989. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188990. }
  188991. #endif
  188992. #if defined(PNG_READ_tEXt_SUPPORTED)
  188993. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188994. {
  188995. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188996. {
  188997. png_push_save_buffer(png_ptr);
  188998. return;
  188999. }
  189000. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189001. }
  189002. #endif
  189003. #if defined(PNG_READ_zTXt_SUPPORTED)
  189004. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189005. {
  189006. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189007. {
  189008. png_push_save_buffer(png_ptr);
  189009. return;
  189010. }
  189011. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189012. }
  189013. #endif
  189014. #if defined(PNG_READ_iTXt_SUPPORTED)
  189015. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189016. {
  189017. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189018. {
  189019. png_push_save_buffer(png_ptr);
  189020. return;
  189021. }
  189022. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189023. }
  189024. #endif
  189025. else
  189026. {
  189027. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189028. {
  189029. png_push_save_buffer(png_ptr);
  189030. return;
  189031. }
  189032. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189033. }
  189034. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189035. }
  189036. void /* PRIVATE */
  189037. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189038. {
  189039. png_ptr->process_mode = PNG_SKIP_MODE;
  189040. png_ptr->skip_length = skip;
  189041. }
  189042. void /* PRIVATE */
  189043. png_push_crc_finish(png_structp png_ptr)
  189044. {
  189045. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189046. {
  189047. png_size_t save_size;
  189048. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189049. save_size = (png_size_t)png_ptr->skip_length;
  189050. else
  189051. save_size = png_ptr->save_buffer_size;
  189052. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189053. png_ptr->skip_length -= save_size;
  189054. png_ptr->buffer_size -= save_size;
  189055. png_ptr->save_buffer_size -= save_size;
  189056. png_ptr->save_buffer_ptr += save_size;
  189057. }
  189058. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189059. {
  189060. png_size_t save_size;
  189061. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189062. save_size = (png_size_t)png_ptr->skip_length;
  189063. else
  189064. save_size = png_ptr->current_buffer_size;
  189065. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189066. png_ptr->skip_length -= save_size;
  189067. png_ptr->buffer_size -= save_size;
  189068. png_ptr->current_buffer_size -= save_size;
  189069. png_ptr->current_buffer_ptr += save_size;
  189070. }
  189071. if (!png_ptr->skip_length)
  189072. {
  189073. if (png_ptr->buffer_size < 4)
  189074. {
  189075. png_push_save_buffer(png_ptr);
  189076. return;
  189077. }
  189078. png_crc_finish(png_ptr, 0);
  189079. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189080. }
  189081. }
  189082. void PNGAPI
  189083. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189084. {
  189085. png_bytep ptr;
  189086. if(png_ptr == NULL) return;
  189087. ptr = buffer;
  189088. if (png_ptr->save_buffer_size)
  189089. {
  189090. png_size_t save_size;
  189091. if (length < png_ptr->save_buffer_size)
  189092. save_size = length;
  189093. else
  189094. save_size = png_ptr->save_buffer_size;
  189095. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189096. length -= save_size;
  189097. ptr += save_size;
  189098. png_ptr->buffer_size -= save_size;
  189099. png_ptr->save_buffer_size -= save_size;
  189100. png_ptr->save_buffer_ptr += save_size;
  189101. }
  189102. if (length && png_ptr->current_buffer_size)
  189103. {
  189104. png_size_t save_size;
  189105. if (length < png_ptr->current_buffer_size)
  189106. save_size = length;
  189107. else
  189108. save_size = png_ptr->current_buffer_size;
  189109. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189110. png_ptr->buffer_size -= save_size;
  189111. png_ptr->current_buffer_size -= save_size;
  189112. png_ptr->current_buffer_ptr += save_size;
  189113. }
  189114. }
  189115. void /* PRIVATE */
  189116. png_push_save_buffer(png_structp png_ptr)
  189117. {
  189118. if (png_ptr->save_buffer_size)
  189119. {
  189120. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189121. {
  189122. png_size_t i,istop;
  189123. png_bytep sp;
  189124. png_bytep dp;
  189125. istop = png_ptr->save_buffer_size;
  189126. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189127. i < istop; i++, sp++, dp++)
  189128. {
  189129. *dp = *sp;
  189130. }
  189131. }
  189132. }
  189133. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189134. png_ptr->save_buffer_max)
  189135. {
  189136. png_size_t new_max;
  189137. png_bytep old_buffer;
  189138. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189139. (png_ptr->current_buffer_size + 256))
  189140. {
  189141. png_error(png_ptr, "Potential overflow of save_buffer");
  189142. }
  189143. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189144. old_buffer = png_ptr->save_buffer;
  189145. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189146. (png_uint_32)new_max);
  189147. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189148. png_free(png_ptr, old_buffer);
  189149. png_ptr->save_buffer_max = new_max;
  189150. }
  189151. if (png_ptr->current_buffer_size)
  189152. {
  189153. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189154. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189155. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189156. png_ptr->current_buffer_size = 0;
  189157. }
  189158. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189159. png_ptr->buffer_size = 0;
  189160. }
  189161. void /* PRIVATE */
  189162. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189163. png_size_t buffer_length)
  189164. {
  189165. png_ptr->current_buffer = buffer;
  189166. png_ptr->current_buffer_size = buffer_length;
  189167. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189168. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189169. }
  189170. void /* PRIVATE */
  189171. png_push_read_IDAT(png_structp png_ptr)
  189172. {
  189173. #ifdef PNG_USE_LOCAL_ARRAYS
  189174. PNG_CONST PNG_IDAT;
  189175. #endif
  189176. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189177. {
  189178. png_byte chunk_length[4];
  189179. if (png_ptr->buffer_size < 8)
  189180. {
  189181. png_push_save_buffer(png_ptr);
  189182. return;
  189183. }
  189184. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189185. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189186. png_reset_crc(png_ptr);
  189187. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189188. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189189. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189190. {
  189191. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189192. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189193. png_error(png_ptr, "Not enough compressed data");
  189194. return;
  189195. }
  189196. png_ptr->idat_size = png_ptr->push_length;
  189197. }
  189198. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189199. {
  189200. png_size_t save_size;
  189201. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189202. {
  189203. save_size = (png_size_t)png_ptr->idat_size;
  189204. /* check for overflow */
  189205. if((png_uint_32)save_size != png_ptr->idat_size)
  189206. png_error(png_ptr, "save_size overflowed in pngpread");
  189207. }
  189208. else
  189209. save_size = png_ptr->save_buffer_size;
  189210. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189211. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189212. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189213. png_ptr->idat_size -= save_size;
  189214. png_ptr->buffer_size -= save_size;
  189215. png_ptr->save_buffer_size -= save_size;
  189216. png_ptr->save_buffer_ptr += save_size;
  189217. }
  189218. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189219. {
  189220. png_size_t save_size;
  189221. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189222. {
  189223. save_size = (png_size_t)png_ptr->idat_size;
  189224. /* check for overflow */
  189225. if((png_uint_32)save_size != png_ptr->idat_size)
  189226. png_error(png_ptr, "save_size overflowed in pngpread");
  189227. }
  189228. else
  189229. save_size = png_ptr->current_buffer_size;
  189230. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189231. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189232. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189233. png_ptr->idat_size -= save_size;
  189234. png_ptr->buffer_size -= save_size;
  189235. png_ptr->current_buffer_size -= save_size;
  189236. png_ptr->current_buffer_ptr += save_size;
  189237. }
  189238. if (!png_ptr->idat_size)
  189239. {
  189240. if (png_ptr->buffer_size < 4)
  189241. {
  189242. png_push_save_buffer(png_ptr);
  189243. return;
  189244. }
  189245. png_crc_finish(png_ptr, 0);
  189246. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189247. png_ptr->mode |= PNG_AFTER_IDAT;
  189248. }
  189249. }
  189250. void /* PRIVATE */
  189251. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189252. png_size_t buffer_length)
  189253. {
  189254. int ret;
  189255. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189256. png_error(png_ptr, "Extra compression data");
  189257. png_ptr->zstream.next_in = buffer;
  189258. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189259. for(;;)
  189260. {
  189261. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189262. if (ret != Z_OK)
  189263. {
  189264. if (ret == Z_STREAM_END)
  189265. {
  189266. if (png_ptr->zstream.avail_in)
  189267. png_error(png_ptr, "Extra compressed data");
  189268. if (!(png_ptr->zstream.avail_out))
  189269. {
  189270. png_push_process_row(png_ptr);
  189271. }
  189272. png_ptr->mode |= PNG_AFTER_IDAT;
  189273. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189274. break;
  189275. }
  189276. else if (ret == Z_BUF_ERROR)
  189277. break;
  189278. else
  189279. png_error(png_ptr, "Decompression Error");
  189280. }
  189281. if (!(png_ptr->zstream.avail_out))
  189282. {
  189283. if ((
  189284. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189285. png_ptr->interlaced && png_ptr->pass > 6) ||
  189286. (!png_ptr->interlaced &&
  189287. #endif
  189288. png_ptr->row_number == png_ptr->num_rows))
  189289. {
  189290. if (png_ptr->zstream.avail_in)
  189291. {
  189292. png_warning(png_ptr, "Too much data in IDAT chunks");
  189293. }
  189294. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189295. break;
  189296. }
  189297. png_push_process_row(png_ptr);
  189298. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189299. png_ptr->zstream.next_out = png_ptr->row_buf;
  189300. }
  189301. else
  189302. break;
  189303. }
  189304. }
  189305. void /* PRIVATE */
  189306. png_push_process_row(png_structp png_ptr)
  189307. {
  189308. png_ptr->row_info.color_type = png_ptr->color_type;
  189309. png_ptr->row_info.width = png_ptr->iwidth;
  189310. png_ptr->row_info.channels = png_ptr->channels;
  189311. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189312. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189313. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189314. png_ptr->row_info.width);
  189315. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189316. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189317. (int)(png_ptr->row_buf[0]));
  189318. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189319. png_ptr->rowbytes + 1);
  189320. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189321. png_do_read_transformations(png_ptr);
  189322. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189323. /* blow up interlaced rows to full size */
  189324. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189325. {
  189326. if (png_ptr->pass < 6)
  189327. /* old interface (pre-1.0.9):
  189328. png_do_read_interlace(&(png_ptr->row_info),
  189329. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189330. */
  189331. png_do_read_interlace(png_ptr);
  189332. switch (png_ptr->pass)
  189333. {
  189334. case 0:
  189335. {
  189336. int i;
  189337. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189338. {
  189339. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189340. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189341. }
  189342. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189343. {
  189344. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189345. {
  189346. png_push_have_row(png_ptr, png_bytep_NULL);
  189347. png_read_push_finish_row(png_ptr);
  189348. }
  189349. }
  189350. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189351. {
  189352. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189353. {
  189354. png_push_have_row(png_ptr, png_bytep_NULL);
  189355. png_read_push_finish_row(png_ptr);
  189356. }
  189357. }
  189358. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189359. {
  189360. png_push_have_row(png_ptr, png_bytep_NULL);
  189361. png_read_push_finish_row(png_ptr);
  189362. }
  189363. break;
  189364. }
  189365. case 1:
  189366. {
  189367. int i;
  189368. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189369. {
  189370. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189371. png_read_push_finish_row(png_ptr);
  189372. }
  189373. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189374. {
  189375. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189376. {
  189377. png_push_have_row(png_ptr, png_bytep_NULL);
  189378. png_read_push_finish_row(png_ptr);
  189379. }
  189380. }
  189381. break;
  189382. }
  189383. case 2:
  189384. {
  189385. int i;
  189386. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189387. {
  189388. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189389. png_read_push_finish_row(png_ptr);
  189390. }
  189391. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189392. {
  189393. png_push_have_row(png_ptr, png_bytep_NULL);
  189394. png_read_push_finish_row(png_ptr);
  189395. }
  189396. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189397. {
  189398. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189399. {
  189400. png_push_have_row(png_ptr, png_bytep_NULL);
  189401. png_read_push_finish_row(png_ptr);
  189402. }
  189403. }
  189404. break;
  189405. }
  189406. case 3:
  189407. {
  189408. int i;
  189409. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189410. {
  189411. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189412. png_read_push_finish_row(png_ptr);
  189413. }
  189414. if (png_ptr->pass == 4) /* skip top two generated rows */
  189415. {
  189416. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189417. {
  189418. png_push_have_row(png_ptr, png_bytep_NULL);
  189419. png_read_push_finish_row(png_ptr);
  189420. }
  189421. }
  189422. break;
  189423. }
  189424. case 4:
  189425. {
  189426. int i;
  189427. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189428. {
  189429. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189430. png_read_push_finish_row(png_ptr);
  189431. }
  189432. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189433. {
  189434. png_push_have_row(png_ptr, png_bytep_NULL);
  189435. png_read_push_finish_row(png_ptr);
  189436. }
  189437. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189438. {
  189439. png_push_have_row(png_ptr, png_bytep_NULL);
  189440. png_read_push_finish_row(png_ptr);
  189441. }
  189442. break;
  189443. }
  189444. case 5:
  189445. {
  189446. int i;
  189447. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189448. {
  189449. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189450. png_read_push_finish_row(png_ptr);
  189451. }
  189452. if (png_ptr->pass == 6) /* skip top generated row */
  189453. {
  189454. png_push_have_row(png_ptr, png_bytep_NULL);
  189455. png_read_push_finish_row(png_ptr);
  189456. }
  189457. break;
  189458. }
  189459. case 6:
  189460. {
  189461. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189462. png_read_push_finish_row(png_ptr);
  189463. if (png_ptr->pass != 6)
  189464. break;
  189465. png_push_have_row(png_ptr, png_bytep_NULL);
  189466. png_read_push_finish_row(png_ptr);
  189467. }
  189468. }
  189469. }
  189470. else
  189471. #endif
  189472. {
  189473. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189474. png_read_push_finish_row(png_ptr);
  189475. }
  189476. }
  189477. void /* PRIVATE */
  189478. png_read_push_finish_row(png_structp png_ptr)
  189479. {
  189480. #ifdef PNG_USE_LOCAL_ARRAYS
  189481. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189482. /* start of interlace block */
  189483. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189484. /* offset to next interlace block */
  189485. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189486. /* start of interlace block in the y direction */
  189487. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189488. /* offset to next interlace block in the y direction */
  189489. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189490. /* Height of interlace block. This is not currently used - if you need
  189491. * it, uncomment it here and in png.h
  189492. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189493. */
  189494. #endif
  189495. png_ptr->row_number++;
  189496. if (png_ptr->row_number < png_ptr->num_rows)
  189497. return;
  189498. if (png_ptr->interlaced)
  189499. {
  189500. png_ptr->row_number = 0;
  189501. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189502. png_ptr->rowbytes + 1);
  189503. do
  189504. {
  189505. png_ptr->pass++;
  189506. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189507. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189508. (png_ptr->pass == 5 && png_ptr->width < 2))
  189509. png_ptr->pass++;
  189510. if (png_ptr->pass > 7)
  189511. png_ptr->pass--;
  189512. if (png_ptr->pass >= 7)
  189513. break;
  189514. png_ptr->iwidth = (png_ptr->width +
  189515. png_pass_inc[png_ptr->pass] - 1 -
  189516. png_pass_start[png_ptr->pass]) /
  189517. png_pass_inc[png_ptr->pass];
  189518. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189519. png_ptr->iwidth) + 1;
  189520. if (png_ptr->transformations & PNG_INTERLACE)
  189521. break;
  189522. png_ptr->num_rows = (png_ptr->height +
  189523. png_pass_yinc[png_ptr->pass] - 1 -
  189524. png_pass_ystart[png_ptr->pass]) /
  189525. png_pass_yinc[png_ptr->pass];
  189526. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189527. }
  189528. }
  189529. #if defined(PNG_READ_tEXt_SUPPORTED)
  189530. void /* PRIVATE */
  189531. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189532. length)
  189533. {
  189534. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189535. {
  189536. png_error(png_ptr, "Out of place tEXt");
  189537. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189538. }
  189539. #ifdef PNG_MAX_MALLOC_64K
  189540. png_ptr->skip_length = 0; /* This may not be necessary */
  189541. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189542. {
  189543. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189544. png_ptr->skip_length = length - (png_uint_32)65535L;
  189545. length = (png_uint_32)65535L;
  189546. }
  189547. #endif
  189548. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189549. (png_uint_32)(length+1));
  189550. png_ptr->current_text[length] = '\0';
  189551. png_ptr->current_text_ptr = png_ptr->current_text;
  189552. png_ptr->current_text_size = (png_size_t)length;
  189553. png_ptr->current_text_left = (png_size_t)length;
  189554. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189555. }
  189556. void /* PRIVATE */
  189557. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189558. {
  189559. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189560. {
  189561. png_size_t text_size;
  189562. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189563. text_size = png_ptr->buffer_size;
  189564. else
  189565. text_size = png_ptr->current_text_left;
  189566. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189567. png_ptr->current_text_left -= text_size;
  189568. png_ptr->current_text_ptr += text_size;
  189569. }
  189570. if (!(png_ptr->current_text_left))
  189571. {
  189572. png_textp text_ptr;
  189573. png_charp text;
  189574. png_charp key;
  189575. int ret;
  189576. if (png_ptr->buffer_size < 4)
  189577. {
  189578. png_push_save_buffer(png_ptr);
  189579. return;
  189580. }
  189581. png_push_crc_finish(png_ptr);
  189582. #if defined(PNG_MAX_MALLOC_64K)
  189583. if (png_ptr->skip_length)
  189584. return;
  189585. #endif
  189586. key = png_ptr->current_text;
  189587. for (text = key; *text; text++)
  189588. /* empty loop */ ;
  189589. if (text < key + png_ptr->current_text_size)
  189590. text++;
  189591. text_ptr = (png_textp)png_malloc(png_ptr,
  189592. (png_uint_32)png_sizeof(png_text));
  189593. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189594. text_ptr->key = key;
  189595. #ifdef PNG_iTXt_SUPPORTED
  189596. text_ptr->lang = NULL;
  189597. text_ptr->lang_key = NULL;
  189598. #endif
  189599. text_ptr->text = text;
  189600. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189601. png_free(png_ptr, key);
  189602. png_free(png_ptr, text_ptr);
  189603. png_ptr->current_text = NULL;
  189604. if (ret)
  189605. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189606. }
  189607. }
  189608. #endif
  189609. #if defined(PNG_READ_zTXt_SUPPORTED)
  189610. void /* PRIVATE */
  189611. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189612. length)
  189613. {
  189614. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189615. {
  189616. png_error(png_ptr, "Out of place zTXt");
  189617. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189618. }
  189619. #ifdef PNG_MAX_MALLOC_64K
  189620. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189621. * to be able to store the uncompressed data. Actually, the threshold
  189622. * is probably around 32K, but it isn't as definite as 64K is.
  189623. */
  189624. if (length > (png_uint_32)65535L)
  189625. {
  189626. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189627. png_push_crc_skip(png_ptr, length);
  189628. return;
  189629. }
  189630. #endif
  189631. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189632. (png_uint_32)(length+1));
  189633. png_ptr->current_text[length] = '\0';
  189634. png_ptr->current_text_ptr = png_ptr->current_text;
  189635. png_ptr->current_text_size = (png_size_t)length;
  189636. png_ptr->current_text_left = (png_size_t)length;
  189637. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189638. }
  189639. void /* PRIVATE */
  189640. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189641. {
  189642. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189643. {
  189644. png_size_t text_size;
  189645. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189646. text_size = png_ptr->buffer_size;
  189647. else
  189648. text_size = png_ptr->current_text_left;
  189649. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189650. png_ptr->current_text_left -= text_size;
  189651. png_ptr->current_text_ptr += text_size;
  189652. }
  189653. if (!(png_ptr->current_text_left))
  189654. {
  189655. png_textp text_ptr;
  189656. png_charp text;
  189657. png_charp key;
  189658. int ret;
  189659. png_size_t text_size, key_size;
  189660. if (png_ptr->buffer_size < 4)
  189661. {
  189662. png_push_save_buffer(png_ptr);
  189663. return;
  189664. }
  189665. png_push_crc_finish(png_ptr);
  189666. key = png_ptr->current_text;
  189667. for (text = key; *text; text++)
  189668. /* empty loop */ ;
  189669. /* zTXt can't have zero text */
  189670. if (text >= key + png_ptr->current_text_size)
  189671. {
  189672. png_ptr->current_text = NULL;
  189673. png_free(png_ptr, key);
  189674. return;
  189675. }
  189676. text++;
  189677. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189678. {
  189679. png_ptr->current_text = NULL;
  189680. png_free(png_ptr, key);
  189681. return;
  189682. }
  189683. text++;
  189684. png_ptr->zstream.next_in = (png_bytep )text;
  189685. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189686. (text - key));
  189687. png_ptr->zstream.next_out = png_ptr->zbuf;
  189688. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189689. key_size = text - key;
  189690. text_size = 0;
  189691. text = NULL;
  189692. ret = Z_STREAM_END;
  189693. while (png_ptr->zstream.avail_in)
  189694. {
  189695. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189696. if (ret != Z_OK && ret != Z_STREAM_END)
  189697. {
  189698. inflateReset(&png_ptr->zstream);
  189699. png_ptr->zstream.avail_in = 0;
  189700. png_ptr->current_text = NULL;
  189701. png_free(png_ptr, key);
  189702. png_free(png_ptr, text);
  189703. return;
  189704. }
  189705. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189706. {
  189707. if (text == NULL)
  189708. {
  189709. text = (png_charp)png_malloc(png_ptr,
  189710. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189711. + key_size + 1));
  189712. png_memcpy(text + key_size, png_ptr->zbuf,
  189713. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189714. png_memcpy(text, key, key_size);
  189715. text_size = key_size + png_ptr->zbuf_size -
  189716. png_ptr->zstream.avail_out;
  189717. *(text + text_size) = '\0';
  189718. }
  189719. else
  189720. {
  189721. png_charp tmp;
  189722. tmp = text;
  189723. text = (png_charp)png_malloc(png_ptr, text_size +
  189724. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189725. + 1));
  189726. png_memcpy(text, tmp, text_size);
  189727. png_free(png_ptr, tmp);
  189728. png_memcpy(text + text_size, png_ptr->zbuf,
  189729. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189730. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189731. *(text + text_size) = '\0';
  189732. }
  189733. if (ret != Z_STREAM_END)
  189734. {
  189735. png_ptr->zstream.next_out = png_ptr->zbuf;
  189736. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189737. }
  189738. }
  189739. else
  189740. {
  189741. break;
  189742. }
  189743. if (ret == Z_STREAM_END)
  189744. break;
  189745. }
  189746. inflateReset(&png_ptr->zstream);
  189747. png_ptr->zstream.avail_in = 0;
  189748. if (ret != Z_STREAM_END)
  189749. {
  189750. png_ptr->current_text = NULL;
  189751. png_free(png_ptr, key);
  189752. png_free(png_ptr, text);
  189753. return;
  189754. }
  189755. png_ptr->current_text = NULL;
  189756. png_free(png_ptr, key);
  189757. key = text;
  189758. text += key_size;
  189759. text_ptr = (png_textp)png_malloc(png_ptr,
  189760. (png_uint_32)png_sizeof(png_text));
  189761. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189762. text_ptr->key = key;
  189763. #ifdef PNG_iTXt_SUPPORTED
  189764. text_ptr->lang = NULL;
  189765. text_ptr->lang_key = NULL;
  189766. #endif
  189767. text_ptr->text = text;
  189768. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189769. png_free(png_ptr, key);
  189770. png_free(png_ptr, text_ptr);
  189771. if (ret)
  189772. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189773. }
  189774. }
  189775. #endif
  189776. #if defined(PNG_READ_iTXt_SUPPORTED)
  189777. void /* PRIVATE */
  189778. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189779. length)
  189780. {
  189781. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189782. {
  189783. png_error(png_ptr, "Out of place iTXt");
  189784. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189785. }
  189786. #ifdef PNG_MAX_MALLOC_64K
  189787. png_ptr->skip_length = 0; /* This may not be necessary */
  189788. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189789. {
  189790. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189791. png_ptr->skip_length = length - (png_uint_32)65535L;
  189792. length = (png_uint_32)65535L;
  189793. }
  189794. #endif
  189795. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189796. (png_uint_32)(length+1));
  189797. png_ptr->current_text[length] = '\0';
  189798. png_ptr->current_text_ptr = png_ptr->current_text;
  189799. png_ptr->current_text_size = (png_size_t)length;
  189800. png_ptr->current_text_left = (png_size_t)length;
  189801. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189802. }
  189803. void /* PRIVATE */
  189804. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189805. {
  189806. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189807. {
  189808. png_size_t text_size;
  189809. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189810. text_size = png_ptr->buffer_size;
  189811. else
  189812. text_size = png_ptr->current_text_left;
  189813. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189814. png_ptr->current_text_left -= text_size;
  189815. png_ptr->current_text_ptr += text_size;
  189816. }
  189817. if (!(png_ptr->current_text_left))
  189818. {
  189819. png_textp text_ptr;
  189820. png_charp key;
  189821. int comp_flag;
  189822. png_charp lang;
  189823. png_charp lang_key;
  189824. png_charp text;
  189825. int ret;
  189826. if (png_ptr->buffer_size < 4)
  189827. {
  189828. png_push_save_buffer(png_ptr);
  189829. return;
  189830. }
  189831. png_push_crc_finish(png_ptr);
  189832. #if defined(PNG_MAX_MALLOC_64K)
  189833. if (png_ptr->skip_length)
  189834. return;
  189835. #endif
  189836. key = png_ptr->current_text;
  189837. for (lang = key; *lang; lang++)
  189838. /* empty loop */ ;
  189839. if (lang < key + png_ptr->current_text_size - 3)
  189840. lang++;
  189841. comp_flag = *lang++;
  189842. lang++; /* skip comp_type, always zero */
  189843. for (lang_key = lang; *lang_key; lang_key++)
  189844. /* empty loop */ ;
  189845. lang_key++; /* skip NUL separator */
  189846. text=lang_key;
  189847. if (lang_key < key + png_ptr->current_text_size - 1)
  189848. {
  189849. for (; *text; text++)
  189850. /* empty loop */ ;
  189851. }
  189852. if (text < key + png_ptr->current_text_size)
  189853. text++;
  189854. text_ptr = (png_textp)png_malloc(png_ptr,
  189855. (png_uint_32)png_sizeof(png_text));
  189856. text_ptr->compression = comp_flag + 2;
  189857. text_ptr->key = key;
  189858. text_ptr->lang = lang;
  189859. text_ptr->lang_key = lang_key;
  189860. text_ptr->text = text;
  189861. text_ptr->text_length = 0;
  189862. text_ptr->itxt_length = png_strlen(text);
  189863. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189864. png_ptr->current_text = NULL;
  189865. png_free(png_ptr, text_ptr);
  189866. if (ret)
  189867. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189868. }
  189869. }
  189870. #endif
  189871. /* This function is called when we haven't found a handler for this
  189872. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189873. * name or a critical chunk), the chunk is (currently) silently ignored.
  189874. */
  189875. void /* PRIVATE */
  189876. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189877. length)
  189878. {
  189879. png_uint_32 skip=0;
  189880. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189881. if (!(png_ptr->chunk_name[0] & 0x20))
  189882. {
  189883. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189884. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189885. PNG_HANDLE_CHUNK_ALWAYS
  189886. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189887. && png_ptr->read_user_chunk_fn == NULL
  189888. #endif
  189889. )
  189890. #endif
  189891. png_chunk_error(png_ptr, "unknown critical chunk");
  189892. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189893. }
  189894. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189895. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189896. {
  189897. #ifdef PNG_MAX_MALLOC_64K
  189898. if (length > (png_uint_32)65535L)
  189899. {
  189900. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189901. skip = length - (png_uint_32)65535L;
  189902. length = (png_uint_32)65535L;
  189903. }
  189904. #endif
  189905. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189906. (png_charp)png_ptr->chunk_name, 5);
  189907. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189908. png_ptr->unknown_chunk.size = (png_size_t)length;
  189909. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189910. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189911. if(png_ptr->read_user_chunk_fn != NULL)
  189912. {
  189913. /* callback to user unknown chunk handler */
  189914. int ret;
  189915. ret = (*(png_ptr->read_user_chunk_fn))
  189916. (png_ptr, &png_ptr->unknown_chunk);
  189917. if (ret < 0)
  189918. png_chunk_error(png_ptr, "error in user chunk");
  189919. if (ret == 0)
  189920. {
  189921. if (!(png_ptr->chunk_name[0] & 0x20))
  189922. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189923. PNG_HANDLE_CHUNK_ALWAYS)
  189924. png_chunk_error(png_ptr, "unknown critical chunk");
  189925. png_set_unknown_chunks(png_ptr, info_ptr,
  189926. &png_ptr->unknown_chunk, 1);
  189927. }
  189928. }
  189929. #else
  189930. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189931. #endif
  189932. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189933. png_ptr->unknown_chunk.data = NULL;
  189934. }
  189935. else
  189936. #endif
  189937. skip=length;
  189938. png_push_crc_skip(png_ptr, skip);
  189939. }
  189940. void /* PRIVATE */
  189941. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189942. {
  189943. if (png_ptr->info_fn != NULL)
  189944. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189945. }
  189946. void /* PRIVATE */
  189947. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189948. {
  189949. if (png_ptr->end_fn != NULL)
  189950. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189951. }
  189952. void /* PRIVATE */
  189953. png_push_have_row(png_structp png_ptr, png_bytep row)
  189954. {
  189955. if (png_ptr->row_fn != NULL)
  189956. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189957. (int)png_ptr->pass);
  189958. }
  189959. void PNGAPI
  189960. png_progressive_combine_row (png_structp png_ptr,
  189961. png_bytep old_row, png_bytep new_row)
  189962. {
  189963. #ifdef PNG_USE_LOCAL_ARRAYS
  189964. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189965. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189966. #endif
  189967. if(png_ptr == NULL) return;
  189968. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189969. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189970. }
  189971. void PNGAPI
  189972. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189973. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189974. png_progressive_end_ptr end_fn)
  189975. {
  189976. if(png_ptr == NULL) return;
  189977. png_ptr->info_fn = info_fn;
  189978. png_ptr->row_fn = row_fn;
  189979. png_ptr->end_fn = end_fn;
  189980. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189981. }
  189982. png_voidp PNGAPI
  189983. png_get_progressive_ptr(png_structp png_ptr)
  189984. {
  189985. if(png_ptr == NULL) return (NULL);
  189986. return png_ptr->io_ptr;
  189987. }
  189988. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189989. /*** End of inlined file: pngpread.c ***/
  189990. /*** Start of inlined file: pngrio.c ***/
  189991. /* pngrio.c - functions for data input
  189992. *
  189993. * Last changed in libpng 1.2.13 November 13, 2006
  189994. * For conditions of distribution and use, see copyright notice in png.h
  189995. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189996. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189997. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189998. *
  189999. * This file provides a location for all input. Users who need
  190000. * special handling are expected to write a function that has the same
  190001. * arguments as this and performs a similar function, but that possibly
  190002. * has a different input method. Note that you shouldn't change this
  190003. * function, but rather write a replacement function and then make
  190004. * libpng use it at run time with png_set_read_fn(...).
  190005. */
  190006. #define PNG_INTERNAL
  190007. #if defined(PNG_READ_SUPPORTED)
  190008. /* Read the data from whatever input you are using. The default routine
  190009. reads from a file pointer. Note that this routine sometimes gets called
  190010. with very small lengths, so you should implement some kind of simple
  190011. buffering if you are using unbuffered reads. This should never be asked
  190012. to read more then 64K on a 16 bit machine. */
  190013. void /* PRIVATE */
  190014. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190015. {
  190016. png_debug1(4,"reading %d bytes\n", (int)length);
  190017. if (png_ptr->read_data_fn != NULL)
  190018. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190019. else
  190020. png_error(png_ptr, "Call to NULL read function");
  190021. }
  190022. #if !defined(PNG_NO_STDIO)
  190023. /* This is the function that does the actual reading of data. If you are
  190024. not reading from a standard C stream, you should create a replacement
  190025. read_data function and use it at run time with png_set_read_fn(), rather
  190026. than changing the library. */
  190027. #ifndef USE_FAR_KEYWORD
  190028. void PNGAPI
  190029. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190030. {
  190031. png_size_t check;
  190032. if(png_ptr == NULL) return;
  190033. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190034. * instead of an int, which is what fread() actually returns.
  190035. */
  190036. #if defined(_WIN32_WCE)
  190037. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190038. check = 0;
  190039. #else
  190040. check = (png_size_t)fread(data, (png_size_t)1, length,
  190041. (png_FILE_p)png_ptr->io_ptr);
  190042. #endif
  190043. if (check != length)
  190044. png_error(png_ptr, "Read Error");
  190045. }
  190046. #else
  190047. /* this is the model-independent version. Since the standard I/O library
  190048. can't handle far buffers in the medium and small models, we have to copy
  190049. the data.
  190050. */
  190051. #define NEAR_BUF_SIZE 1024
  190052. #define MIN(a,b) (a <= b ? a : b)
  190053. static void PNGAPI
  190054. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190055. {
  190056. int check;
  190057. png_byte *n_data;
  190058. png_FILE_p io_ptr;
  190059. if(png_ptr == NULL) return;
  190060. /* Check if data really is near. If so, use usual code. */
  190061. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190062. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190063. if ((png_bytep)n_data == data)
  190064. {
  190065. #if defined(_WIN32_WCE)
  190066. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190067. check = 0;
  190068. #else
  190069. check = fread(n_data, 1, length, io_ptr);
  190070. #endif
  190071. }
  190072. else
  190073. {
  190074. png_byte buf[NEAR_BUF_SIZE];
  190075. png_size_t read, remaining, err;
  190076. check = 0;
  190077. remaining = length;
  190078. do
  190079. {
  190080. read = MIN(NEAR_BUF_SIZE, remaining);
  190081. #if defined(_WIN32_WCE)
  190082. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190083. err = 0;
  190084. #else
  190085. err = fread(buf, (png_size_t)1, read, io_ptr);
  190086. #endif
  190087. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190088. if(err != read)
  190089. break;
  190090. else
  190091. check += err;
  190092. data += read;
  190093. remaining -= read;
  190094. }
  190095. while (remaining != 0);
  190096. }
  190097. if ((png_uint_32)check != (png_uint_32)length)
  190098. png_error(png_ptr, "read Error");
  190099. }
  190100. #endif
  190101. #endif
  190102. /* This function allows the application to supply a new input function
  190103. for libpng if standard C streams aren't being used.
  190104. This function takes as its arguments:
  190105. png_ptr - pointer to a png input data structure
  190106. io_ptr - pointer to user supplied structure containing info about
  190107. the input functions. May be NULL.
  190108. read_data_fn - pointer to a new input function that takes as its
  190109. arguments a pointer to a png_struct, a pointer to
  190110. a location where input data can be stored, and a 32-bit
  190111. unsigned int that is the number of bytes to be read.
  190112. To exit and output any fatal error messages the new write
  190113. function should call png_error(png_ptr, "Error msg"). */
  190114. void PNGAPI
  190115. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190116. png_rw_ptr read_data_fn)
  190117. {
  190118. if(png_ptr == NULL) return;
  190119. png_ptr->io_ptr = io_ptr;
  190120. #if !defined(PNG_NO_STDIO)
  190121. if (read_data_fn != NULL)
  190122. png_ptr->read_data_fn = read_data_fn;
  190123. else
  190124. png_ptr->read_data_fn = png_default_read_data;
  190125. #else
  190126. png_ptr->read_data_fn = read_data_fn;
  190127. #endif
  190128. /* It is an error to write to a read device */
  190129. if (png_ptr->write_data_fn != NULL)
  190130. {
  190131. png_ptr->write_data_fn = NULL;
  190132. png_warning(png_ptr,
  190133. "It's an error to set both read_data_fn and write_data_fn in the ");
  190134. png_warning(png_ptr,
  190135. "same structure. Resetting write_data_fn to NULL.");
  190136. }
  190137. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190138. png_ptr->output_flush_fn = NULL;
  190139. #endif
  190140. }
  190141. #endif /* PNG_READ_SUPPORTED */
  190142. /*** End of inlined file: pngrio.c ***/
  190143. /*** Start of inlined file: pngrtran.c ***/
  190144. /* pngrtran.c - transforms the data in a row for PNG readers
  190145. *
  190146. * Last changed in libpng 1.2.21 [October 4, 2007]
  190147. * For conditions of distribution and use, see copyright notice in png.h
  190148. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190149. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190150. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190151. *
  190152. * This file contains functions optionally called by an application
  190153. * in order to tell libpng how to handle data when reading a PNG.
  190154. * Transformations that are used in both reading and writing are
  190155. * in pngtrans.c.
  190156. */
  190157. #define PNG_INTERNAL
  190158. #if defined(PNG_READ_SUPPORTED)
  190159. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190160. void PNGAPI
  190161. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190162. {
  190163. png_debug(1, "in png_set_crc_action\n");
  190164. /* Tell libpng how we react to CRC errors in critical chunks */
  190165. if(png_ptr == NULL) return;
  190166. switch (crit_action)
  190167. {
  190168. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190169. break;
  190170. case PNG_CRC_WARN_USE: /* warn/use data */
  190171. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190172. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190173. break;
  190174. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190175. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190176. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190177. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190178. break;
  190179. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190180. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190181. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190182. case PNG_CRC_DEFAULT:
  190183. default:
  190184. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190185. break;
  190186. }
  190187. switch (ancil_action)
  190188. {
  190189. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190190. break;
  190191. case PNG_CRC_WARN_USE: /* warn/use data */
  190192. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190193. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190194. break;
  190195. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190196. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190197. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190198. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190199. break;
  190200. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190201. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190202. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190203. break;
  190204. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190205. case PNG_CRC_DEFAULT:
  190206. default:
  190207. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190208. break;
  190209. }
  190210. }
  190211. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190212. defined(PNG_FLOATING_POINT_SUPPORTED)
  190213. /* handle alpha and tRNS via a background color */
  190214. void PNGAPI
  190215. png_set_background(png_structp png_ptr,
  190216. png_color_16p background_color, int background_gamma_code,
  190217. int need_expand, double background_gamma)
  190218. {
  190219. png_debug(1, "in png_set_background\n");
  190220. if(png_ptr == NULL) return;
  190221. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190222. {
  190223. png_warning(png_ptr, "Application must supply a known background gamma");
  190224. return;
  190225. }
  190226. png_ptr->transformations |= PNG_BACKGROUND;
  190227. png_memcpy(&(png_ptr->background), background_color,
  190228. png_sizeof(png_color_16));
  190229. png_ptr->background_gamma = (float)background_gamma;
  190230. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190231. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190232. }
  190233. #endif
  190234. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190235. /* strip 16 bit depth files to 8 bit depth */
  190236. void PNGAPI
  190237. png_set_strip_16(png_structp png_ptr)
  190238. {
  190239. png_debug(1, "in png_set_strip_16\n");
  190240. if(png_ptr == NULL) return;
  190241. png_ptr->transformations |= PNG_16_TO_8;
  190242. }
  190243. #endif
  190244. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190245. void PNGAPI
  190246. png_set_strip_alpha(png_structp png_ptr)
  190247. {
  190248. png_debug(1, "in png_set_strip_alpha\n");
  190249. if(png_ptr == NULL) return;
  190250. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190251. }
  190252. #endif
  190253. #if defined(PNG_READ_DITHER_SUPPORTED)
  190254. /* Dither file to 8 bit. Supply a palette, the current number
  190255. * of elements in the palette, the maximum number of elements
  190256. * allowed, and a histogram if possible. If the current number
  190257. * of colors is greater then the maximum number, the palette will be
  190258. * modified to fit in the maximum number. "full_dither" indicates
  190259. * whether we need a dithering cube set up for RGB images, or if we
  190260. * simply are reducing the number of colors in a paletted image.
  190261. */
  190262. typedef struct png_dsort_struct
  190263. {
  190264. struct png_dsort_struct FAR * next;
  190265. png_byte left;
  190266. png_byte right;
  190267. } png_dsort;
  190268. typedef png_dsort FAR * png_dsortp;
  190269. typedef png_dsort FAR * FAR * png_dsortpp;
  190270. void PNGAPI
  190271. png_set_dither(png_structp png_ptr, png_colorp palette,
  190272. int num_palette, int maximum_colors, png_uint_16p histogram,
  190273. int full_dither)
  190274. {
  190275. png_debug(1, "in png_set_dither\n");
  190276. if(png_ptr == NULL) return;
  190277. png_ptr->transformations |= PNG_DITHER;
  190278. if (!full_dither)
  190279. {
  190280. int i;
  190281. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190282. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190283. for (i = 0; i < num_palette; i++)
  190284. png_ptr->dither_index[i] = (png_byte)i;
  190285. }
  190286. if (num_palette > maximum_colors)
  190287. {
  190288. if (histogram != NULL)
  190289. {
  190290. /* This is easy enough, just throw out the least used colors.
  190291. Perhaps not the best solution, but good enough. */
  190292. int i;
  190293. /* initialize an array to sort colors */
  190294. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190295. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190296. /* initialize the dither_sort array */
  190297. for (i = 0; i < num_palette; i++)
  190298. png_ptr->dither_sort[i] = (png_byte)i;
  190299. /* Find the least used palette entries by starting a
  190300. bubble sort, and running it until we have sorted
  190301. out enough colors. Note that we don't care about
  190302. sorting all the colors, just finding which are
  190303. least used. */
  190304. for (i = num_palette - 1; i >= maximum_colors; i--)
  190305. {
  190306. int done; /* to stop early if the list is pre-sorted */
  190307. int j;
  190308. done = 1;
  190309. for (j = 0; j < i; j++)
  190310. {
  190311. if (histogram[png_ptr->dither_sort[j]]
  190312. < histogram[png_ptr->dither_sort[j + 1]])
  190313. {
  190314. png_byte t;
  190315. t = png_ptr->dither_sort[j];
  190316. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190317. png_ptr->dither_sort[j + 1] = t;
  190318. done = 0;
  190319. }
  190320. }
  190321. if (done)
  190322. break;
  190323. }
  190324. /* swap the palette around, and set up a table, if necessary */
  190325. if (full_dither)
  190326. {
  190327. int j = num_palette;
  190328. /* put all the useful colors within the max, but don't
  190329. move the others */
  190330. for (i = 0; i < maximum_colors; i++)
  190331. {
  190332. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190333. {
  190334. do
  190335. j--;
  190336. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190337. palette[i] = palette[j];
  190338. }
  190339. }
  190340. }
  190341. else
  190342. {
  190343. int j = num_palette;
  190344. /* move all the used colors inside the max limit, and
  190345. develop a translation table */
  190346. for (i = 0; i < maximum_colors; i++)
  190347. {
  190348. /* only move the colors we need to */
  190349. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190350. {
  190351. png_color tmp_color;
  190352. do
  190353. j--;
  190354. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190355. tmp_color = palette[j];
  190356. palette[j] = palette[i];
  190357. palette[i] = tmp_color;
  190358. /* indicate where the color went */
  190359. png_ptr->dither_index[j] = (png_byte)i;
  190360. png_ptr->dither_index[i] = (png_byte)j;
  190361. }
  190362. }
  190363. /* find closest color for those colors we are not using */
  190364. for (i = 0; i < num_palette; i++)
  190365. {
  190366. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190367. {
  190368. int min_d, k, min_k, d_index;
  190369. /* find the closest color to one we threw out */
  190370. d_index = png_ptr->dither_index[i];
  190371. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190372. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190373. {
  190374. int d;
  190375. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190376. if (d < min_d)
  190377. {
  190378. min_d = d;
  190379. min_k = k;
  190380. }
  190381. }
  190382. /* point to closest color */
  190383. png_ptr->dither_index[i] = (png_byte)min_k;
  190384. }
  190385. }
  190386. }
  190387. png_free(png_ptr, png_ptr->dither_sort);
  190388. png_ptr->dither_sort=NULL;
  190389. }
  190390. else
  190391. {
  190392. /* This is much harder to do simply (and quickly). Perhaps
  190393. we need to go through a median cut routine, but those
  190394. don't always behave themselves with only a few colors
  190395. as input. So we will just find the closest two colors,
  190396. and throw out one of them (chosen somewhat randomly).
  190397. [We don't understand this at all, so if someone wants to
  190398. work on improving it, be our guest - AED, GRP]
  190399. */
  190400. int i;
  190401. int max_d;
  190402. int num_new_palette;
  190403. png_dsortp t;
  190404. png_dsortpp hash;
  190405. t=NULL;
  190406. /* initialize palette index arrays */
  190407. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190408. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190409. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190410. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190411. /* initialize the sort array */
  190412. for (i = 0; i < num_palette; i++)
  190413. {
  190414. png_ptr->index_to_palette[i] = (png_byte)i;
  190415. png_ptr->palette_to_index[i] = (png_byte)i;
  190416. }
  190417. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190418. png_sizeof (png_dsortp)));
  190419. for (i = 0; i < 769; i++)
  190420. hash[i] = NULL;
  190421. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190422. num_new_palette = num_palette;
  190423. /* initial wild guess at how far apart the farthest pixel
  190424. pair we will be eliminating will be. Larger
  190425. numbers mean more areas will be allocated, Smaller
  190426. numbers run the risk of not saving enough data, and
  190427. having to do this all over again.
  190428. I have not done extensive checking on this number.
  190429. */
  190430. max_d = 96;
  190431. while (num_new_palette > maximum_colors)
  190432. {
  190433. for (i = 0; i < num_new_palette - 1; i++)
  190434. {
  190435. int j;
  190436. for (j = i + 1; j < num_new_palette; j++)
  190437. {
  190438. int d;
  190439. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190440. if (d <= max_d)
  190441. {
  190442. t = (png_dsortp)png_malloc_warn(png_ptr,
  190443. (png_uint_32)(png_sizeof(png_dsort)));
  190444. if (t == NULL)
  190445. break;
  190446. t->next = hash[d];
  190447. t->left = (png_byte)i;
  190448. t->right = (png_byte)j;
  190449. hash[d] = t;
  190450. }
  190451. }
  190452. if (t == NULL)
  190453. break;
  190454. }
  190455. if (t != NULL)
  190456. for (i = 0; i <= max_d; i++)
  190457. {
  190458. if (hash[i] != NULL)
  190459. {
  190460. png_dsortp p;
  190461. for (p = hash[i]; p; p = p->next)
  190462. {
  190463. if ((int)png_ptr->index_to_palette[p->left]
  190464. < num_new_palette &&
  190465. (int)png_ptr->index_to_palette[p->right]
  190466. < num_new_palette)
  190467. {
  190468. int j, next_j;
  190469. if (num_new_palette & 0x01)
  190470. {
  190471. j = p->left;
  190472. next_j = p->right;
  190473. }
  190474. else
  190475. {
  190476. j = p->right;
  190477. next_j = p->left;
  190478. }
  190479. num_new_palette--;
  190480. palette[png_ptr->index_to_palette[j]]
  190481. = palette[num_new_palette];
  190482. if (!full_dither)
  190483. {
  190484. int k;
  190485. for (k = 0; k < num_palette; k++)
  190486. {
  190487. if (png_ptr->dither_index[k] ==
  190488. png_ptr->index_to_palette[j])
  190489. png_ptr->dither_index[k] =
  190490. png_ptr->index_to_palette[next_j];
  190491. if ((int)png_ptr->dither_index[k] ==
  190492. num_new_palette)
  190493. png_ptr->dither_index[k] =
  190494. png_ptr->index_to_palette[j];
  190495. }
  190496. }
  190497. png_ptr->index_to_palette[png_ptr->palette_to_index
  190498. [num_new_palette]] = png_ptr->index_to_palette[j];
  190499. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190500. = png_ptr->palette_to_index[num_new_palette];
  190501. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190502. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190503. }
  190504. if (num_new_palette <= maximum_colors)
  190505. break;
  190506. }
  190507. if (num_new_palette <= maximum_colors)
  190508. break;
  190509. }
  190510. }
  190511. for (i = 0; i < 769; i++)
  190512. {
  190513. if (hash[i] != NULL)
  190514. {
  190515. png_dsortp p = hash[i];
  190516. while (p)
  190517. {
  190518. t = p->next;
  190519. png_free(png_ptr, p);
  190520. p = t;
  190521. }
  190522. }
  190523. hash[i] = 0;
  190524. }
  190525. max_d += 96;
  190526. }
  190527. png_free(png_ptr, hash);
  190528. png_free(png_ptr, png_ptr->palette_to_index);
  190529. png_free(png_ptr, png_ptr->index_to_palette);
  190530. png_ptr->palette_to_index=NULL;
  190531. png_ptr->index_to_palette=NULL;
  190532. }
  190533. num_palette = maximum_colors;
  190534. }
  190535. if (png_ptr->palette == NULL)
  190536. {
  190537. png_ptr->palette = palette;
  190538. }
  190539. png_ptr->num_palette = (png_uint_16)num_palette;
  190540. if (full_dither)
  190541. {
  190542. int i;
  190543. png_bytep distance;
  190544. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190545. PNG_DITHER_BLUE_BITS;
  190546. int num_red = (1 << PNG_DITHER_RED_BITS);
  190547. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190548. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190549. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190550. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190551. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190552. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190553. png_sizeof (png_byte));
  190554. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190555. png_sizeof(png_byte)));
  190556. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190557. for (i = 0; i < num_palette; i++)
  190558. {
  190559. int ir, ig, ib;
  190560. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190561. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190562. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190563. for (ir = 0; ir < num_red; ir++)
  190564. {
  190565. /* int dr = abs(ir - r); */
  190566. int dr = ((ir > r) ? ir - r : r - ir);
  190567. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190568. for (ig = 0; ig < num_green; ig++)
  190569. {
  190570. /* int dg = abs(ig - g); */
  190571. int dg = ((ig > g) ? ig - g : g - ig);
  190572. int dt = dr + dg;
  190573. int dm = ((dr > dg) ? dr : dg);
  190574. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190575. for (ib = 0; ib < num_blue; ib++)
  190576. {
  190577. int d_index = index_g | ib;
  190578. /* int db = abs(ib - b); */
  190579. int db = ((ib > b) ? ib - b : b - ib);
  190580. int dmax = ((dm > db) ? dm : db);
  190581. int d = dmax + dt + db;
  190582. if (d < (int)distance[d_index])
  190583. {
  190584. distance[d_index] = (png_byte)d;
  190585. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190586. }
  190587. }
  190588. }
  190589. }
  190590. }
  190591. png_free(png_ptr, distance);
  190592. }
  190593. }
  190594. #endif
  190595. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190596. /* Transform the image from the file_gamma to the screen_gamma. We
  190597. * only do transformations on images where the file_gamma and screen_gamma
  190598. * are not close reciprocals, otherwise it slows things down slightly, and
  190599. * also needlessly introduces small errors.
  190600. *
  190601. * We will turn off gamma transformation later if no semitransparent entries
  190602. * are present in the tRNS array for palette images. We can't do it here
  190603. * because we don't necessarily have the tRNS chunk yet.
  190604. */
  190605. void PNGAPI
  190606. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190607. {
  190608. png_debug(1, "in png_set_gamma\n");
  190609. if(png_ptr == NULL) return;
  190610. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190611. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190612. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190613. png_ptr->transformations |= PNG_GAMMA;
  190614. png_ptr->gamma = (float)file_gamma;
  190615. png_ptr->screen_gamma = (float)scrn_gamma;
  190616. }
  190617. #endif
  190618. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190619. /* Expand paletted images to RGB, expand grayscale images of
  190620. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190621. * to alpha channels.
  190622. */
  190623. void PNGAPI
  190624. png_set_expand(png_structp png_ptr)
  190625. {
  190626. png_debug(1, "in png_set_expand\n");
  190627. if(png_ptr == NULL) return;
  190628. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190629. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190630. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190631. #endif
  190632. }
  190633. /* GRR 19990627: the following three functions currently are identical
  190634. * to png_set_expand(). However, it is entirely reasonable that someone
  190635. * might wish to expand an indexed image to RGB but *not* expand a single,
  190636. * fully transparent palette entry to a full alpha channel--perhaps instead
  190637. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190638. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190639. * IOW, a future version of the library may make the transformations flag
  190640. * a bit more fine-grained, with separate bits for each of these three
  190641. * functions.
  190642. *
  190643. * More to the point, these functions make it obvious what libpng will be
  190644. * doing, whereas "expand" can (and does) mean any number of things.
  190645. *
  190646. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190647. * to expand only the sample depth but not to expand the tRNS to alpha.
  190648. */
  190649. /* Expand paletted images to RGB. */
  190650. void PNGAPI
  190651. png_set_palette_to_rgb(png_structp png_ptr)
  190652. {
  190653. png_debug(1, "in png_set_palette_to_rgb\n");
  190654. if(png_ptr == NULL) return;
  190655. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190656. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190657. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190658. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190659. #endif
  190660. }
  190661. #if !defined(PNG_1_0_X)
  190662. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190663. void PNGAPI
  190664. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190665. {
  190666. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190667. if(png_ptr == NULL) return;
  190668. png_ptr->transformations |= PNG_EXPAND;
  190669. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190670. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190671. #endif
  190672. }
  190673. #endif
  190674. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190675. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190676. /* Deprecated as of libpng-1.2.9 */
  190677. void PNGAPI
  190678. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190679. {
  190680. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190681. if(png_ptr == NULL) return;
  190682. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190683. }
  190684. #endif
  190685. /* Expand tRNS chunks to alpha channels. */
  190686. void PNGAPI
  190687. png_set_tRNS_to_alpha(png_structp png_ptr)
  190688. {
  190689. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190690. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190691. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190692. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190693. #endif
  190694. }
  190695. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190696. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190697. void PNGAPI
  190698. png_set_gray_to_rgb(png_structp png_ptr)
  190699. {
  190700. png_debug(1, "in png_set_gray_to_rgb\n");
  190701. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190702. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190703. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190704. #endif
  190705. }
  190706. #endif
  190707. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190708. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190709. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190710. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190711. */
  190712. void PNGAPI
  190713. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190714. double green)
  190715. {
  190716. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190717. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190718. if(png_ptr == NULL) return;
  190719. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190720. }
  190721. #endif
  190722. void PNGAPI
  190723. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190724. png_fixed_point red, png_fixed_point green)
  190725. {
  190726. png_debug(1, "in png_set_rgb_to_gray\n");
  190727. if(png_ptr == NULL) return;
  190728. switch(error_action)
  190729. {
  190730. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190731. break;
  190732. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190733. break;
  190734. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190735. }
  190736. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190737. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190738. png_ptr->transformations |= PNG_EXPAND;
  190739. #else
  190740. {
  190741. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190742. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190743. }
  190744. #endif
  190745. {
  190746. png_uint_16 red_int, green_int;
  190747. if(red < 0 || green < 0)
  190748. {
  190749. red_int = 6968; /* .212671 * 32768 + .5 */
  190750. green_int = 23434; /* .715160 * 32768 + .5 */
  190751. }
  190752. else if(red + green < 100000L)
  190753. {
  190754. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190755. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190756. }
  190757. else
  190758. {
  190759. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190760. red_int = 6968;
  190761. green_int = 23434;
  190762. }
  190763. png_ptr->rgb_to_gray_red_coeff = red_int;
  190764. png_ptr->rgb_to_gray_green_coeff = green_int;
  190765. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190766. }
  190767. }
  190768. #endif
  190769. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190770. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190771. defined(PNG_LEGACY_SUPPORTED)
  190772. void PNGAPI
  190773. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190774. read_user_transform_fn)
  190775. {
  190776. png_debug(1, "in png_set_read_user_transform_fn\n");
  190777. if(png_ptr == NULL) return;
  190778. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190779. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190780. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190781. #endif
  190782. #ifdef PNG_LEGACY_SUPPORTED
  190783. if(read_user_transform_fn)
  190784. png_warning(png_ptr,
  190785. "This version of libpng does not support user transforms");
  190786. #endif
  190787. }
  190788. #endif
  190789. /* Initialize everything needed for the read. This includes modifying
  190790. * the palette.
  190791. */
  190792. void /* PRIVATE */
  190793. png_init_read_transformations(png_structp png_ptr)
  190794. {
  190795. png_debug(1, "in png_init_read_transformations\n");
  190796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190797. if(png_ptr != NULL)
  190798. #endif
  190799. {
  190800. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190801. || defined(PNG_READ_GAMMA_SUPPORTED)
  190802. int color_type = png_ptr->color_type;
  190803. #endif
  190804. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190805. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190806. /* Detect gray background and attempt to enable optimization
  190807. * for gray --> RGB case */
  190808. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190809. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190810. * background color might actually be gray yet not be flagged as such.
  190811. * This is not a problem for the current code, which uses
  190812. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190813. * png_do_gray_to_rgb() transformation.
  190814. */
  190815. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190816. !(color_type & PNG_COLOR_MASK_COLOR))
  190817. {
  190818. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190819. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190820. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190821. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190822. png_ptr->background.red == png_ptr->background.green &&
  190823. png_ptr->background.red == png_ptr->background.blue)
  190824. {
  190825. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190826. png_ptr->background.gray = png_ptr->background.red;
  190827. }
  190828. #endif
  190829. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190830. (png_ptr->transformations & PNG_EXPAND))
  190831. {
  190832. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190833. {
  190834. /* expand background and tRNS chunks */
  190835. switch (png_ptr->bit_depth)
  190836. {
  190837. case 1:
  190838. png_ptr->background.gray *= (png_uint_16)0xff;
  190839. png_ptr->background.red = png_ptr->background.green
  190840. = png_ptr->background.blue = png_ptr->background.gray;
  190841. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190842. {
  190843. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190844. png_ptr->trans_values.red = png_ptr->trans_values.green
  190845. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190846. }
  190847. break;
  190848. case 2:
  190849. png_ptr->background.gray *= (png_uint_16)0x55;
  190850. png_ptr->background.red = png_ptr->background.green
  190851. = png_ptr->background.blue = png_ptr->background.gray;
  190852. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190853. {
  190854. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190855. png_ptr->trans_values.red = png_ptr->trans_values.green
  190856. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190857. }
  190858. break;
  190859. case 4:
  190860. png_ptr->background.gray *= (png_uint_16)0x11;
  190861. png_ptr->background.red = png_ptr->background.green
  190862. = png_ptr->background.blue = png_ptr->background.gray;
  190863. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190864. {
  190865. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190866. png_ptr->trans_values.red = png_ptr->trans_values.green
  190867. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190868. }
  190869. break;
  190870. case 8:
  190871. case 16:
  190872. png_ptr->background.red = png_ptr->background.green
  190873. = png_ptr->background.blue = png_ptr->background.gray;
  190874. break;
  190875. }
  190876. }
  190877. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190878. {
  190879. png_ptr->background.red =
  190880. png_ptr->palette[png_ptr->background.index].red;
  190881. png_ptr->background.green =
  190882. png_ptr->palette[png_ptr->background.index].green;
  190883. png_ptr->background.blue =
  190884. png_ptr->palette[png_ptr->background.index].blue;
  190885. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190886. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190887. {
  190888. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190889. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190890. #endif
  190891. {
  190892. /* invert the alpha channel (in tRNS) unless the pixels are
  190893. going to be expanded, in which case leave it for later */
  190894. int i,istop;
  190895. istop=(int)png_ptr->num_trans;
  190896. for (i=0; i<istop; i++)
  190897. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190898. }
  190899. }
  190900. #endif
  190901. }
  190902. }
  190903. #endif
  190904. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190905. png_ptr->background_1 = png_ptr->background;
  190906. #endif
  190907. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190908. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190909. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190910. < PNG_GAMMA_THRESHOLD))
  190911. {
  190912. int i,k;
  190913. k=0;
  190914. for (i=0; i<png_ptr->num_trans; i++)
  190915. {
  190916. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190917. k=1; /* partial transparency is present */
  190918. }
  190919. if (k == 0)
  190920. png_ptr->transformations &= (~PNG_GAMMA);
  190921. }
  190922. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190923. png_ptr->gamma != 0.0)
  190924. {
  190925. png_build_gamma_table(png_ptr);
  190926. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190927. if (png_ptr->transformations & PNG_BACKGROUND)
  190928. {
  190929. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190930. {
  190931. /* could skip if no transparency and
  190932. */
  190933. png_color back, back_1;
  190934. png_colorp palette = png_ptr->palette;
  190935. int num_palette = png_ptr->num_palette;
  190936. int i;
  190937. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190938. {
  190939. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190940. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190941. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190942. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190943. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190944. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190945. }
  190946. else
  190947. {
  190948. double g, gs;
  190949. switch (png_ptr->background_gamma_type)
  190950. {
  190951. case PNG_BACKGROUND_GAMMA_SCREEN:
  190952. g = (png_ptr->screen_gamma);
  190953. gs = 1.0;
  190954. break;
  190955. case PNG_BACKGROUND_GAMMA_FILE:
  190956. g = 1.0 / (png_ptr->gamma);
  190957. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190958. break;
  190959. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190960. g = 1.0 / (png_ptr->background_gamma);
  190961. gs = 1.0 / (png_ptr->background_gamma *
  190962. png_ptr->screen_gamma);
  190963. break;
  190964. default:
  190965. g = 1.0; /* back_1 */
  190966. gs = 1.0; /* back */
  190967. }
  190968. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190969. {
  190970. back.red = (png_byte)png_ptr->background.red;
  190971. back.green = (png_byte)png_ptr->background.green;
  190972. back.blue = (png_byte)png_ptr->background.blue;
  190973. }
  190974. else
  190975. {
  190976. back.red = (png_byte)(pow(
  190977. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190978. back.green = (png_byte)(pow(
  190979. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190980. back.blue = (png_byte)(pow(
  190981. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190982. }
  190983. back_1.red = (png_byte)(pow(
  190984. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190985. back_1.green = (png_byte)(pow(
  190986. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190987. back_1.blue = (png_byte)(pow(
  190988. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190989. }
  190990. for (i = 0; i < num_palette; i++)
  190991. {
  190992. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190993. {
  190994. if (png_ptr->trans[i] == 0)
  190995. {
  190996. palette[i] = back;
  190997. }
  190998. else /* if (png_ptr->trans[i] != 0xff) */
  190999. {
  191000. png_byte v, w;
  191001. v = png_ptr->gamma_to_1[palette[i].red];
  191002. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191003. palette[i].red = png_ptr->gamma_from_1[w];
  191004. v = png_ptr->gamma_to_1[palette[i].green];
  191005. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191006. palette[i].green = png_ptr->gamma_from_1[w];
  191007. v = png_ptr->gamma_to_1[palette[i].blue];
  191008. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191009. palette[i].blue = png_ptr->gamma_from_1[w];
  191010. }
  191011. }
  191012. else
  191013. {
  191014. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191015. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191016. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191017. }
  191018. }
  191019. }
  191020. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191021. else
  191022. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191023. {
  191024. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191025. double g = 1.0;
  191026. double gs = 1.0;
  191027. switch (png_ptr->background_gamma_type)
  191028. {
  191029. case PNG_BACKGROUND_GAMMA_SCREEN:
  191030. g = (png_ptr->screen_gamma);
  191031. gs = 1.0;
  191032. break;
  191033. case PNG_BACKGROUND_GAMMA_FILE:
  191034. g = 1.0 / (png_ptr->gamma);
  191035. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191036. break;
  191037. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191038. g = 1.0 / (png_ptr->background_gamma);
  191039. gs = 1.0 / (png_ptr->background_gamma *
  191040. png_ptr->screen_gamma);
  191041. break;
  191042. }
  191043. png_ptr->background_1.gray = (png_uint_16)(pow(
  191044. (double)png_ptr->background.gray / m, g) * m + .5);
  191045. png_ptr->background.gray = (png_uint_16)(pow(
  191046. (double)png_ptr->background.gray / m, gs) * m + .5);
  191047. if ((png_ptr->background.red != png_ptr->background.green) ||
  191048. (png_ptr->background.red != png_ptr->background.blue) ||
  191049. (png_ptr->background.red != png_ptr->background.gray))
  191050. {
  191051. /* RGB or RGBA with color background */
  191052. png_ptr->background_1.red = (png_uint_16)(pow(
  191053. (double)png_ptr->background.red / m, g) * m + .5);
  191054. png_ptr->background_1.green = (png_uint_16)(pow(
  191055. (double)png_ptr->background.green / m, g) * m + .5);
  191056. png_ptr->background_1.blue = (png_uint_16)(pow(
  191057. (double)png_ptr->background.blue / m, g) * m + .5);
  191058. png_ptr->background.red = (png_uint_16)(pow(
  191059. (double)png_ptr->background.red / m, gs) * m + .5);
  191060. png_ptr->background.green = (png_uint_16)(pow(
  191061. (double)png_ptr->background.green / m, gs) * m + .5);
  191062. png_ptr->background.blue = (png_uint_16)(pow(
  191063. (double)png_ptr->background.blue / m, gs) * m + .5);
  191064. }
  191065. else
  191066. {
  191067. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191068. png_ptr->background_1.red = png_ptr->background_1.green
  191069. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191070. png_ptr->background.red = png_ptr->background.green
  191071. = png_ptr->background.blue = png_ptr->background.gray;
  191072. }
  191073. }
  191074. }
  191075. else
  191076. /* transformation does not include PNG_BACKGROUND */
  191077. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191078. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191079. {
  191080. png_colorp palette = png_ptr->palette;
  191081. int num_palette = png_ptr->num_palette;
  191082. int i;
  191083. for (i = 0; i < num_palette; i++)
  191084. {
  191085. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191086. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191087. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191088. }
  191089. }
  191090. }
  191091. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191092. else
  191093. #endif
  191094. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191095. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191096. /* No GAMMA transformation */
  191097. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191098. (color_type == PNG_COLOR_TYPE_PALETTE))
  191099. {
  191100. int i;
  191101. int istop = (int)png_ptr->num_trans;
  191102. png_color back;
  191103. png_colorp palette = png_ptr->palette;
  191104. back.red = (png_byte)png_ptr->background.red;
  191105. back.green = (png_byte)png_ptr->background.green;
  191106. back.blue = (png_byte)png_ptr->background.blue;
  191107. for (i = 0; i < istop; i++)
  191108. {
  191109. if (png_ptr->trans[i] == 0)
  191110. {
  191111. palette[i] = back;
  191112. }
  191113. else if (png_ptr->trans[i] != 0xff)
  191114. {
  191115. /* The png_composite() macro is defined in png.h */
  191116. png_composite(palette[i].red, palette[i].red,
  191117. png_ptr->trans[i], back.red);
  191118. png_composite(palette[i].green, palette[i].green,
  191119. png_ptr->trans[i], back.green);
  191120. png_composite(palette[i].blue, palette[i].blue,
  191121. png_ptr->trans[i], back.blue);
  191122. }
  191123. }
  191124. }
  191125. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191126. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191127. if ((png_ptr->transformations & PNG_SHIFT) &&
  191128. (color_type == PNG_COLOR_TYPE_PALETTE))
  191129. {
  191130. png_uint_16 i;
  191131. png_uint_16 istop = png_ptr->num_palette;
  191132. int sr = 8 - png_ptr->sig_bit.red;
  191133. int sg = 8 - png_ptr->sig_bit.green;
  191134. int sb = 8 - png_ptr->sig_bit.blue;
  191135. if (sr < 0 || sr > 8)
  191136. sr = 0;
  191137. if (sg < 0 || sg > 8)
  191138. sg = 0;
  191139. if (sb < 0 || sb > 8)
  191140. sb = 0;
  191141. for (i = 0; i < istop; i++)
  191142. {
  191143. png_ptr->palette[i].red >>= sr;
  191144. png_ptr->palette[i].green >>= sg;
  191145. png_ptr->palette[i].blue >>= sb;
  191146. }
  191147. }
  191148. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191149. }
  191150. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191151. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191152. if(png_ptr)
  191153. return;
  191154. #endif
  191155. }
  191156. /* Modify the info structure to reflect the transformations. The
  191157. * info should be updated so a PNG file could be written with it,
  191158. * assuming the transformations result in valid PNG data.
  191159. */
  191160. void /* PRIVATE */
  191161. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191162. {
  191163. png_debug(1, "in png_read_transform_info\n");
  191164. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191165. if (png_ptr->transformations & PNG_EXPAND)
  191166. {
  191167. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191168. {
  191169. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191170. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191171. else
  191172. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191173. info_ptr->bit_depth = 8;
  191174. info_ptr->num_trans = 0;
  191175. }
  191176. else
  191177. {
  191178. if (png_ptr->num_trans)
  191179. {
  191180. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191181. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191182. else
  191183. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191184. }
  191185. if (info_ptr->bit_depth < 8)
  191186. info_ptr->bit_depth = 8;
  191187. info_ptr->num_trans = 0;
  191188. }
  191189. }
  191190. #endif
  191191. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191192. if (png_ptr->transformations & PNG_BACKGROUND)
  191193. {
  191194. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191195. info_ptr->num_trans = 0;
  191196. info_ptr->background = png_ptr->background;
  191197. }
  191198. #endif
  191199. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191200. if (png_ptr->transformations & PNG_GAMMA)
  191201. {
  191202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191203. info_ptr->gamma = png_ptr->gamma;
  191204. #endif
  191205. #ifdef PNG_FIXED_POINT_SUPPORTED
  191206. info_ptr->int_gamma = png_ptr->int_gamma;
  191207. #endif
  191208. }
  191209. #endif
  191210. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191211. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191212. info_ptr->bit_depth = 8;
  191213. #endif
  191214. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191215. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191216. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191217. #endif
  191218. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191219. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191220. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191221. #endif
  191222. #if defined(PNG_READ_DITHER_SUPPORTED)
  191223. if (png_ptr->transformations & PNG_DITHER)
  191224. {
  191225. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191226. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191227. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191228. {
  191229. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191230. }
  191231. }
  191232. #endif
  191233. #if defined(PNG_READ_PACK_SUPPORTED)
  191234. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191235. info_ptr->bit_depth = 8;
  191236. #endif
  191237. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191238. info_ptr->channels = 1;
  191239. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191240. info_ptr->channels = 3;
  191241. else
  191242. info_ptr->channels = 1;
  191243. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191244. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191245. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191246. #endif
  191247. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191248. info_ptr->channels++;
  191249. #if defined(PNG_READ_FILLER_SUPPORTED)
  191250. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191251. if ((png_ptr->transformations & PNG_FILLER) &&
  191252. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191253. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191254. {
  191255. info_ptr->channels++;
  191256. /* if adding a true alpha channel not just filler */
  191257. #if !defined(PNG_1_0_X)
  191258. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191259. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191260. #endif
  191261. }
  191262. #endif
  191263. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191264. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191265. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191266. {
  191267. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191268. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191269. if(info_ptr->channels < png_ptr->user_transform_channels)
  191270. info_ptr->channels = png_ptr->user_transform_channels;
  191271. }
  191272. #endif
  191273. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191274. info_ptr->bit_depth);
  191275. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191276. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191277. if(png_ptr)
  191278. return;
  191279. #endif
  191280. }
  191281. /* Transform the row. The order of transformations is significant,
  191282. * and is very touchy. If you add a transformation, take care to
  191283. * decide how it fits in with the other transformations here.
  191284. */
  191285. void /* PRIVATE */
  191286. png_do_read_transformations(png_structp png_ptr)
  191287. {
  191288. png_debug(1, "in png_do_read_transformations\n");
  191289. if (png_ptr->row_buf == NULL)
  191290. {
  191291. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191292. char msg[50];
  191293. png_snprintf2(msg, 50,
  191294. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191295. png_ptr->pass);
  191296. png_error(png_ptr, msg);
  191297. #else
  191298. png_error(png_ptr, "NULL row buffer");
  191299. #endif
  191300. }
  191301. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191302. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191303. /* Application has failed to call either png_read_start_image()
  191304. * or png_read_update_info() after setting transforms that expand
  191305. * pixels. This check added to libpng-1.2.19 */
  191306. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191307. png_error(png_ptr, "Uninitialized row");
  191308. #else
  191309. png_warning(png_ptr, "Uninitialized row");
  191310. #endif
  191311. #endif
  191312. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191313. if (png_ptr->transformations & PNG_EXPAND)
  191314. {
  191315. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191316. {
  191317. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191318. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191319. }
  191320. else
  191321. {
  191322. if (png_ptr->num_trans &&
  191323. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191324. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191325. &(png_ptr->trans_values));
  191326. else
  191327. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191328. NULL);
  191329. }
  191330. }
  191331. #endif
  191332. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191333. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191334. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191335. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191336. #endif
  191337. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191338. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191339. {
  191340. int rgb_error =
  191341. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191342. if(rgb_error)
  191343. {
  191344. png_ptr->rgb_to_gray_status=1;
  191345. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191346. PNG_RGB_TO_GRAY_WARN)
  191347. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191348. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191349. PNG_RGB_TO_GRAY_ERR)
  191350. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191351. }
  191352. }
  191353. #endif
  191354. /*
  191355. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191356. In most cases, the "simple transparency" should be done prior to doing
  191357. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191358. pixel is transparent. You would also need to make sure that the
  191359. transparency information is upgraded to RGB.
  191360. To summarize, the current flow is:
  191361. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191362. with background "in place" if transparent,
  191363. convert to RGB if necessary
  191364. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191365. convert to RGB if necessary
  191366. To support RGB backgrounds for gray images we need:
  191367. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191368. 3 or 6 bytes and composite with background
  191369. "in place" if transparent (3x compare/pixel
  191370. compared to doing composite with gray bkgrnd)
  191371. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191372. remove alpha bytes (3x float operations/pixel
  191373. compared with composite on gray background)
  191374. Greg's change will do this. The reason it wasn't done before is for
  191375. performance, as this increases the per-pixel operations. If we would check
  191376. in advance if the background was gray or RGB, and position the gray-to-RGB
  191377. transform appropriately, then it would save a lot of work/time.
  191378. */
  191379. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191380. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191381. * for performance reasons */
  191382. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191383. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191384. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191385. #endif
  191386. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191387. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191388. ((png_ptr->num_trans != 0 ) ||
  191389. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191390. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191391. &(png_ptr->trans_values), &(png_ptr->background)
  191392. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191393. , &(png_ptr->background_1),
  191394. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191395. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191396. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191397. png_ptr->gamma_shift
  191398. #endif
  191399. );
  191400. #endif
  191401. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191402. if ((png_ptr->transformations & PNG_GAMMA) &&
  191403. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191404. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191405. ((png_ptr->num_trans != 0) ||
  191406. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191407. #endif
  191408. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191409. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191410. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191411. png_ptr->gamma_shift);
  191412. #endif
  191413. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191414. if (png_ptr->transformations & PNG_16_TO_8)
  191415. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191416. #endif
  191417. #if defined(PNG_READ_DITHER_SUPPORTED)
  191418. if (png_ptr->transformations & PNG_DITHER)
  191419. {
  191420. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191421. png_ptr->palette_lookup, png_ptr->dither_index);
  191422. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191423. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191424. }
  191425. #endif
  191426. #if defined(PNG_READ_INVERT_SUPPORTED)
  191427. if (png_ptr->transformations & PNG_INVERT_MONO)
  191428. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191429. #endif
  191430. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191431. if (png_ptr->transformations & PNG_SHIFT)
  191432. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191433. &(png_ptr->shift));
  191434. #endif
  191435. #if defined(PNG_READ_PACK_SUPPORTED)
  191436. if (png_ptr->transformations & PNG_PACK)
  191437. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191438. #endif
  191439. #if defined(PNG_READ_BGR_SUPPORTED)
  191440. if (png_ptr->transformations & PNG_BGR)
  191441. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191442. #endif
  191443. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191444. if (png_ptr->transformations & PNG_PACKSWAP)
  191445. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191446. #endif
  191447. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191448. /* if gray -> RGB, do so now only if we did not do so above */
  191449. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191450. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191451. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191452. #endif
  191453. #if defined(PNG_READ_FILLER_SUPPORTED)
  191454. if (png_ptr->transformations & PNG_FILLER)
  191455. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191456. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191457. #endif
  191458. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191459. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191460. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191461. #endif
  191462. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191463. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191464. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191465. #endif
  191466. #if defined(PNG_READ_SWAP_SUPPORTED)
  191467. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191468. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191469. #endif
  191470. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191471. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191472. {
  191473. if(png_ptr->read_user_transform_fn != NULL)
  191474. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191475. (png_ptr, /* png_ptr */
  191476. &(png_ptr->row_info), /* row_info: */
  191477. /* png_uint_32 width; width of row */
  191478. /* png_uint_32 rowbytes; number of bytes in row */
  191479. /* png_byte color_type; color type of pixels */
  191480. /* png_byte bit_depth; bit depth of samples */
  191481. /* png_byte channels; number of channels (1-4) */
  191482. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191483. png_ptr->row_buf + 1); /* start of pixel data for row */
  191484. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191485. if(png_ptr->user_transform_depth)
  191486. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191487. if(png_ptr->user_transform_channels)
  191488. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191489. #endif
  191490. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191491. png_ptr->row_info.channels);
  191492. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191493. png_ptr->row_info.width);
  191494. }
  191495. #endif
  191496. }
  191497. #if defined(PNG_READ_PACK_SUPPORTED)
  191498. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191499. * without changing the actual values. Thus, if you had a row with
  191500. * a bit depth of 1, you would end up with bytes that only contained
  191501. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191502. * png_do_shift() after this.
  191503. */
  191504. void /* PRIVATE */
  191505. png_do_unpack(png_row_infop row_info, png_bytep row)
  191506. {
  191507. png_debug(1, "in png_do_unpack\n");
  191508. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191509. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191510. #else
  191511. if (row_info->bit_depth < 8)
  191512. #endif
  191513. {
  191514. png_uint_32 i;
  191515. png_uint_32 row_width=row_info->width;
  191516. switch (row_info->bit_depth)
  191517. {
  191518. case 1:
  191519. {
  191520. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191521. png_bytep dp = row + (png_size_t)row_width - 1;
  191522. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191523. for (i = 0; i < row_width; i++)
  191524. {
  191525. *dp = (png_byte)((*sp >> shift) & 0x01);
  191526. if (shift == 7)
  191527. {
  191528. shift = 0;
  191529. sp--;
  191530. }
  191531. else
  191532. shift++;
  191533. dp--;
  191534. }
  191535. break;
  191536. }
  191537. case 2:
  191538. {
  191539. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191540. png_bytep dp = row + (png_size_t)row_width - 1;
  191541. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191542. for (i = 0; i < row_width; i++)
  191543. {
  191544. *dp = (png_byte)((*sp >> shift) & 0x03);
  191545. if (shift == 6)
  191546. {
  191547. shift = 0;
  191548. sp--;
  191549. }
  191550. else
  191551. shift += 2;
  191552. dp--;
  191553. }
  191554. break;
  191555. }
  191556. case 4:
  191557. {
  191558. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191559. png_bytep dp = row + (png_size_t)row_width - 1;
  191560. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191561. for (i = 0; i < row_width; i++)
  191562. {
  191563. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191564. if (shift == 4)
  191565. {
  191566. shift = 0;
  191567. sp--;
  191568. }
  191569. else
  191570. shift = 4;
  191571. dp--;
  191572. }
  191573. break;
  191574. }
  191575. }
  191576. row_info->bit_depth = 8;
  191577. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191578. row_info->rowbytes = row_width * row_info->channels;
  191579. }
  191580. }
  191581. #endif
  191582. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191583. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191584. * pixels back to their significant bits values. Thus, if you have
  191585. * a row of bit depth 8, but only 5 are significant, this will shift
  191586. * the values back to 0 through 31.
  191587. */
  191588. void /* PRIVATE */
  191589. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191590. {
  191591. png_debug(1, "in png_do_unshift\n");
  191592. if (
  191593. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191594. row != NULL && row_info != NULL && sig_bits != NULL &&
  191595. #endif
  191596. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191597. {
  191598. int shift[4];
  191599. int channels = 0;
  191600. int c;
  191601. png_uint_16 value = 0;
  191602. png_uint_32 row_width = row_info->width;
  191603. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191604. {
  191605. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191606. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191607. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191608. }
  191609. else
  191610. {
  191611. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191612. }
  191613. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191614. {
  191615. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191616. }
  191617. for (c = 0; c < channels; c++)
  191618. {
  191619. if (shift[c] <= 0)
  191620. shift[c] = 0;
  191621. else
  191622. value = 1;
  191623. }
  191624. if (!value)
  191625. return;
  191626. switch (row_info->bit_depth)
  191627. {
  191628. case 2:
  191629. {
  191630. png_bytep bp;
  191631. png_uint_32 i;
  191632. png_uint_32 istop = row_info->rowbytes;
  191633. for (bp = row, i = 0; i < istop; i++)
  191634. {
  191635. *bp >>= 1;
  191636. *bp++ &= 0x55;
  191637. }
  191638. break;
  191639. }
  191640. case 4:
  191641. {
  191642. png_bytep bp = row;
  191643. png_uint_32 i;
  191644. png_uint_32 istop = row_info->rowbytes;
  191645. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191646. (png_byte)((int)0xf >> shift[0]));
  191647. for (i = 0; i < istop; i++)
  191648. {
  191649. *bp >>= shift[0];
  191650. *bp++ &= mask;
  191651. }
  191652. break;
  191653. }
  191654. case 8:
  191655. {
  191656. png_bytep bp = row;
  191657. png_uint_32 i;
  191658. png_uint_32 istop = row_width * channels;
  191659. for (i = 0; i < istop; i++)
  191660. {
  191661. *bp++ >>= shift[i%channels];
  191662. }
  191663. break;
  191664. }
  191665. case 16:
  191666. {
  191667. png_bytep bp = row;
  191668. png_uint_32 i;
  191669. png_uint_32 istop = channels * row_width;
  191670. for (i = 0; i < istop; i++)
  191671. {
  191672. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191673. value >>= shift[i%channels];
  191674. *bp++ = (png_byte)(value >> 8);
  191675. *bp++ = (png_byte)(value & 0xff);
  191676. }
  191677. break;
  191678. }
  191679. }
  191680. }
  191681. }
  191682. #endif
  191683. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191684. /* chop rows of bit depth 16 down to 8 */
  191685. void /* PRIVATE */
  191686. png_do_chop(png_row_infop row_info, png_bytep row)
  191687. {
  191688. png_debug(1, "in png_do_chop\n");
  191689. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191690. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191691. #else
  191692. if (row_info->bit_depth == 16)
  191693. #endif
  191694. {
  191695. png_bytep sp = row;
  191696. png_bytep dp = row;
  191697. png_uint_32 i;
  191698. png_uint_32 istop = row_info->width * row_info->channels;
  191699. for (i = 0; i<istop; i++, sp += 2, dp++)
  191700. {
  191701. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191702. /* This does a more accurate scaling of the 16-bit color
  191703. * value, rather than a simple low-byte truncation.
  191704. *
  191705. * What the ideal calculation should be:
  191706. * *dp = (((((png_uint_32)(*sp) << 8) |
  191707. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191708. *
  191709. * GRR: no, I think this is what it really should be:
  191710. * *dp = (((((png_uint_32)(*sp) << 8) |
  191711. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191712. *
  191713. * GRR: here's the exact calculation with shifts:
  191714. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191715. * *dp = (temp - (temp >> 8)) >> 8;
  191716. *
  191717. * Approximate calculation with shift/add instead of multiply/divide:
  191718. * *dp = ((((png_uint_32)(*sp) << 8) |
  191719. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191720. *
  191721. * What we actually do to avoid extra shifting and conversion:
  191722. */
  191723. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191724. #else
  191725. /* Simply discard the low order byte */
  191726. *dp = *sp;
  191727. #endif
  191728. }
  191729. row_info->bit_depth = 8;
  191730. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191731. row_info->rowbytes = row_info->width * row_info->channels;
  191732. }
  191733. }
  191734. #endif
  191735. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191736. void /* PRIVATE */
  191737. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191738. {
  191739. png_debug(1, "in png_do_read_swap_alpha\n");
  191740. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191741. if (row != NULL && row_info != NULL)
  191742. #endif
  191743. {
  191744. png_uint_32 row_width = row_info->width;
  191745. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191746. {
  191747. /* This converts from RGBA to ARGB */
  191748. if (row_info->bit_depth == 8)
  191749. {
  191750. png_bytep sp = row + row_info->rowbytes;
  191751. png_bytep dp = sp;
  191752. png_byte save;
  191753. png_uint_32 i;
  191754. for (i = 0; i < row_width; i++)
  191755. {
  191756. save = *(--sp);
  191757. *(--dp) = *(--sp);
  191758. *(--dp) = *(--sp);
  191759. *(--dp) = *(--sp);
  191760. *(--dp) = save;
  191761. }
  191762. }
  191763. /* This converts from RRGGBBAA to AARRGGBB */
  191764. else
  191765. {
  191766. png_bytep sp = row + row_info->rowbytes;
  191767. png_bytep dp = sp;
  191768. png_byte save[2];
  191769. png_uint_32 i;
  191770. for (i = 0; i < row_width; i++)
  191771. {
  191772. save[0] = *(--sp);
  191773. save[1] = *(--sp);
  191774. *(--dp) = *(--sp);
  191775. *(--dp) = *(--sp);
  191776. *(--dp) = *(--sp);
  191777. *(--dp) = *(--sp);
  191778. *(--dp) = *(--sp);
  191779. *(--dp) = *(--sp);
  191780. *(--dp) = save[0];
  191781. *(--dp) = save[1];
  191782. }
  191783. }
  191784. }
  191785. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191786. {
  191787. /* This converts from GA to AG */
  191788. if (row_info->bit_depth == 8)
  191789. {
  191790. png_bytep sp = row + row_info->rowbytes;
  191791. png_bytep dp = sp;
  191792. png_byte save;
  191793. png_uint_32 i;
  191794. for (i = 0; i < row_width; i++)
  191795. {
  191796. save = *(--sp);
  191797. *(--dp) = *(--sp);
  191798. *(--dp) = save;
  191799. }
  191800. }
  191801. /* This converts from GGAA to AAGG */
  191802. else
  191803. {
  191804. png_bytep sp = row + row_info->rowbytes;
  191805. png_bytep dp = sp;
  191806. png_byte save[2];
  191807. png_uint_32 i;
  191808. for (i = 0; i < row_width; i++)
  191809. {
  191810. save[0] = *(--sp);
  191811. save[1] = *(--sp);
  191812. *(--dp) = *(--sp);
  191813. *(--dp) = *(--sp);
  191814. *(--dp) = save[0];
  191815. *(--dp) = save[1];
  191816. }
  191817. }
  191818. }
  191819. }
  191820. }
  191821. #endif
  191822. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191823. void /* PRIVATE */
  191824. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191825. {
  191826. png_debug(1, "in png_do_read_invert_alpha\n");
  191827. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191828. if (row != NULL && row_info != NULL)
  191829. #endif
  191830. {
  191831. png_uint_32 row_width = row_info->width;
  191832. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191833. {
  191834. /* This inverts the alpha channel in RGBA */
  191835. if (row_info->bit_depth == 8)
  191836. {
  191837. png_bytep sp = row + row_info->rowbytes;
  191838. png_bytep dp = sp;
  191839. png_uint_32 i;
  191840. for (i = 0; i < row_width; i++)
  191841. {
  191842. *(--dp) = (png_byte)(255 - *(--sp));
  191843. /* This does nothing:
  191844. *(--dp) = *(--sp);
  191845. *(--dp) = *(--sp);
  191846. *(--dp) = *(--sp);
  191847. We can replace it with:
  191848. */
  191849. sp-=3;
  191850. dp=sp;
  191851. }
  191852. }
  191853. /* This inverts the alpha channel in RRGGBBAA */
  191854. else
  191855. {
  191856. png_bytep sp = row + row_info->rowbytes;
  191857. png_bytep dp = sp;
  191858. png_uint_32 i;
  191859. for (i = 0; i < row_width; i++)
  191860. {
  191861. *(--dp) = (png_byte)(255 - *(--sp));
  191862. *(--dp) = (png_byte)(255 - *(--sp));
  191863. /* This does nothing:
  191864. *(--dp) = *(--sp);
  191865. *(--dp) = *(--sp);
  191866. *(--dp) = *(--sp);
  191867. *(--dp) = *(--sp);
  191868. *(--dp) = *(--sp);
  191869. *(--dp) = *(--sp);
  191870. We can replace it with:
  191871. */
  191872. sp-=6;
  191873. dp=sp;
  191874. }
  191875. }
  191876. }
  191877. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191878. {
  191879. /* This inverts the alpha channel in GA */
  191880. if (row_info->bit_depth == 8)
  191881. {
  191882. png_bytep sp = row + row_info->rowbytes;
  191883. png_bytep dp = sp;
  191884. png_uint_32 i;
  191885. for (i = 0; i < row_width; i++)
  191886. {
  191887. *(--dp) = (png_byte)(255 - *(--sp));
  191888. *(--dp) = *(--sp);
  191889. }
  191890. }
  191891. /* This inverts the alpha channel in GGAA */
  191892. else
  191893. {
  191894. png_bytep sp = row + row_info->rowbytes;
  191895. png_bytep dp = sp;
  191896. png_uint_32 i;
  191897. for (i = 0; i < row_width; i++)
  191898. {
  191899. *(--dp) = (png_byte)(255 - *(--sp));
  191900. *(--dp) = (png_byte)(255 - *(--sp));
  191901. /*
  191902. *(--dp) = *(--sp);
  191903. *(--dp) = *(--sp);
  191904. */
  191905. sp-=2;
  191906. dp=sp;
  191907. }
  191908. }
  191909. }
  191910. }
  191911. }
  191912. #endif
  191913. #if defined(PNG_READ_FILLER_SUPPORTED)
  191914. /* Add filler channel if we have RGB color */
  191915. void /* PRIVATE */
  191916. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191917. png_uint_32 filler, png_uint_32 flags)
  191918. {
  191919. png_uint_32 i;
  191920. png_uint_32 row_width = row_info->width;
  191921. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191922. png_byte lo_filler = (png_byte)(filler & 0xff);
  191923. png_debug(1, "in png_do_read_filler\n");
  191924. if (
  191925. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191926. row != NULL && row_info != NULL &&
  191927. #endif
  191928. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191929. {
  191930. if(row_info->bit_depth == 8)
  191931. {
  191932. /* This changes the data from G to GX */
  191933. if (flags & PNG_FLAG_FILLER_AFTER)
  191934. {
  191935. png_bytep sp = row + (png_size_t)row_width;
  191936. png_bytep dp = sp + (png_size_t)row_width;
  191937. for (i = 1; i < row_width; i++)
  191938. {
  191939. *(--dp) = lo_filler;
  191940. *(--dp) = *(--sp);
  191941. }
  191942. *(--dp) = lo_filler;
  191943. row_info->channels = 2;
  191944. row_info->pixel_depth = 16;
  191945. row_info->rowbytes = row_width * 2;
  191946. }
  191947. /* This changes the data from G to XG */
  191948. else
  191949. {
  191950. png_bytep sp = row + (png_size_t)row_width;
  191951. png_bytep dp = sp + (png_size_t)row_width;
  191952. for (i = 0; i < row_width; i++)
  191953. {
  191954. *(--dp) = *(--sp);
  191955. *(--dp) = lo_filler;
  191956. }
  191957. row_info->channels = 2;
  191958. row_info->pixel_depth = 16;
  191959. row_info->rowbytes = row_width * 2;
  191960. }
  191961. }
  191962. else if(row_info->bit_depth == 16)
  191963. {
  191964. /* This changes the data from GG to GGXX */
  191965. if (flags & PNG_FLAG_FILLER_AFTER)
  191966. {
  191967. png_bytep sp = row + (png_size_t)row_width * 2;
  191968. png_bytep dp = sp + (png_size_t)row_width * 2;
  191969. for (i = 1; i < row_width; i++)
  191970. {
  191971. *(--dp) = hi_filler;
  191972. *(--dp) = lo_filler;
  191973. *(--dp) = *(--sp);
  191974. *(--dp) = *(--sp);
  191975. }
  191976. *(--dp) = hi_filler;
  191977. *(--dp) = lo_filler;
  191978. row_info->channels = 2;
  191979. row_info->pixel_depth = 32;
  191980. row_info->rowbytes = row_width * 4;
  191981. }
  191982. /* This changes the data from GG to XXGG */
  191983. else
  191984. {
  191985. png_bytep sp = row + (png_size_t)row_width * 2;
  191986. png_bytep dp = sp + (png_size_t)row_width * 2;
  191987. for (i = 0; i < row_width; i++)
  191988. {
  191989. *(--dp) = *(--sp);
  191990. *(--dp) = *(--sp);
  191991. *(--dp) = hi_filler;
  191992. *(--dp) = lo_filler;
  191993. }
  191994. row_info->channels = 2;
  191995. row_info->pixel_depth = 32;
  191996. row_info->rowbytes = row_width * 4;
  191997. }
  191998. }
  191999. } /* COLOR_TYPE == GRAY */
  192000. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192001. {
  192002. if(row_info->bit_depth == 8)
  192003. {
  192004. /* This changes the data from RGB to RGBX */
  192005. if (flags & PNG_FLAG_FILLER_AFTER)
  192006. {
  192007. png_bytep sp = row + (png_size_t)row_width * 3;
  192008. png_bytep dp = sp + (png_size_t)row_width;
  192009. for (i = 1; i < row_width; i++)
  192010. {
  192011. *(--dp) = lo_filler;
  192012. *(--dp) = *(--sp);
  192013. *(--dp) = *(--sp);
  192014. *(--dp) = *(--sp);
  192015. }
  192016. *(--dp) = lo_filler;
  192017. row_info->channels = 4;
  192018. row_info->pixel_depth = 32;
  192019. row_info->rowbytes = row_width * 4;
  192020. }
  192021. /* This changes the data from RGB to XRGB */
  192022. else
  192023. {
  192024. png_bytep sp = row + (png_size_t)row_width * 3;
  192025. png_bytep dp = sp + (png_size_t)row_width;
  192026. for (i = 0; i < row_width; i++)
  192027. {
  192028. *(--dp) = *(--sp);
  192029. *(--dp) = *(--sp);
  192030. *(--dp) = *(--sp);
  192031. *(--dp) = lo_filler;
  192032. }
  192033. row_info->channels = 4;
  192034. row_info->pixel_depth = 32;
  192035. row_info->rowbytes = row_width * 4;
  192036. }
  192037. }
  192038. else if(row_info->bit_depth == 16)
  192039. {
  192040. /* This changes the data from RRGGBB to RRGGBBXX */
  192041. if (flags & PNG_FLAG_FILLER_AFTER)
  192042. {
  192043. png_bytep sp = row + (png_size_t)row_width * 6;
  192044. png_bytep dp = sp + (png_size_t)row_width * 2;
  192045. for (i = 1; i < row_width; i++)
  192046. {
  192047. *(--dp) = hi_filler;
  192048. *(--dp) = lo_filler;
  192049. *(--dp) = *(--sp);
  192050. *(--dp) = *(--sp);
  192051. *(--dp) = *(--sp);
  192052. *(--dp) = *(--sp);
  192053. *(--dp) = *(--sp);
  192054. *(--dp) = *(--sp);
  192055. }
  192056. *(--dp) = hi_filler;
  192057. *(--dp) = lo_filler;
  192058. row_info->channels = 4;
  192059. row_info->pixel_depth = 64;
  192060. row_info->rowbytes = row_width * 8;
  192061. }
  192062. /* This changes the data from RRGGBB to XXRRGGBB */
  192063. else
  192064. {
  192065. png_bytep sp = row + (png_size_t)row_width * 6;
  192066. png_bytep dp = sp + (png_size_t)row_width * 2;
  192067. for (i = 0; i < row_width; i++)
  192068. {
  192069. *(--dp) = *(--sp);
  192070. *(--dp) = *(--sp);
  192071. *(--dp) = *(--sp);
  192072. *(--dp) = *(--sp);
  192073. *(--dp) = *(--sp);
  192074. *(--dp) = *(--sp);
  192075. *(--dp) = hi_filler;
  192076. *(--dp) = lo_filler;
  192077. }
  192078. row_info->channels = 4;
  192079. row_info->pixel_depth = 64;
  192080. row_info->rowbytes = row_width * 8;
  192081. }
  192082. }
  192083. } /* COLOR_TYPE == RGB */
  192084. }
  192085. #endif
  192086. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192087. /* expand grayscale files to RGB, with or without alpha */
  192088. void /* PRIVATE */
  192089. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192090. {
  192091. png_uint_32 i;
  192092. png_uint_32 row_width = row_info->width;
  192093. png_debug(1, "in png_do_gray_to_rgb\n");
  192094. if (row_info->bit_depth >= 8 &&
  192095. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192096. row != NULL && row_info != NULL &&
  192097. #endif
  192098. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192099. {
  192100. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192101. {
  192102. if (row_info->bit_depth == 8)
  192103. {
  192104. png_bytep sp = row + (png_size_t)row_width - 1;
  192105. png_bytep dp = sp + (png_size_t)row_width * 2;
  192106. for (i = 0; i < row_width; i++)
  192107. {
  192108. *(dp--) = *sp;
  192109. *(dp--) = *sp;
  192110. *(dp--) = *(sp--);
  192111. }
  192112. }
  192113. else
  192114. {
  192115. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192116. png_bytep dp = sp + (png_size_t)row_width * 4;
  192117. for (i = 0; i < row_width; i++)
  192118. {
  192119. *(dp--) = *sp;
  192120. *(dp--) = *(sp - 1);
  192121. *(dp--) = *sp;
  192122. *(dp--) = *(sp - 1);
  192123. *(dp--) = *(sp--);
  192124. *(dp--) = *(sp--);
  192125. }
  192126. }
  192127. }
  192128. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192129. {
  192130. if (row_info->bit_depth == 8)
  192131. {
  192132. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192133. png_bytep dp = sp + (png_size_t)row_width * 2;
  192134. for (i = 0; i < row_width; i++)
  192135. {
  192136. *(dp--) = *(sp--);
  192137. *(dp--) = *sp;
  192138. *(dp--) = *sp;
  192139. *(dp--) = *(sp--);
  192140. }
  192141. }
  192142. else
  192143. {
  192144. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192145. png_bytep dp = sp + (png_size_t)row_width * 4;
  192146. for (i = 0; i < row_width; i++)
  192147. {
  192148. *(dp--) = *(sp--);
  192149. *(dp--) = *(sp--);
  192150. *(dp--) = *sp;
  192151. *(dp--) = *(sp - 1);
  192152. *(dp--) = *sp;
  192153. *(dp--) = *(sp - 1);
  192154. *(dp--) = *(sp--);
  192155. *(dp--) = *(sp--);
  192156. }
  192157. }
  192158. }
  192159. row_info->channels += (png_byte)2;
  192160. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192161. row_info->pixel_depth = (png_byte)(row_info->channels *
  192162. row_info->bit_depth);
  192163. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192164. }
  192165. }
  192166. #endif
  192167. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192168. /* reduce RGB files to grayscale, with or without alpha
  192169. * using the equation given in Poynton's ColorFAQ at
  192170. * <http://www.inforamp.net/~poynton/>
  192171. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192172. *
  192173. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192174. *
  192175. * We approximate this with
  192176. *
  192177. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192178. *
  192179. * which can be expressed with integers as
  192180. *
  192181. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192182. *
  192183. * The calculation is to be done in a linear colorspace.
  192184. *
  192185. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192186. */
  192187. int /* PRIVATE */
  192188. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192189. {
  192190. png_uint_32 i;
  192191. png_uint_32 row_width = row_info->width;
  192192. int rgb_error = 0;
  192193. png_debug(1, "in png_do_rgb_to_gray\n");
  192194. if (
  192195. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192196. row != NULL && row_info != NULL &&
  192197. #endif
  192198. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192199. {
  192200. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192201. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192202. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192203. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192204. {
  192205. if (row_info->bit_depth == 8)
  192206. {
  192207. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192208. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192209. {
  192210. png_bytep sp = row;
  192211. png_bytep dp = row;
  192212. for (i = 0; i < row_width; i++)
  192213. {
  192214. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192215. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192216. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192217. if(red != green || red != blue)
  192218. {
  192219. rgb_error |= 1;
  192220. *(dp++) = png_ptr->gamma_from_1[
  192221. (rc*red+gc*green+bc*blue)>>15];
  192222. }
  192223. else
  192224. *(dp++) = *(sp-1);
  192225. }
  192226. }
  192227. else
  192228. #endif
  192229. {
  192230. png_bytep sp = row;
  192231. png_bytep dp = row;
  192232. for (i = 0; i < row_width; i++)
  192233. {
  192234. png_byte red = *(sp++);
  192235. png_byte green = *(sp++);
  192236. png_byte blue = *(sp++);
  192237. if(red != green || red != blue)
  192238. {
  192239. rgb_error |= 1;
  192240. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192241. }
  192242. else
  192243. *(dp++) = *(sp-1);
  192244. }
  192245. }
  192246. }
  192247. else /* RGB bit_depth == 16 */
  192248. {
  192249. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192250. if (png_ptr->gamma_16_to_1 != NULL &&
  192251. png_ptr->gamma_16_from_1 != NULL)
  192252. {
  192253. png_bytep sp = row;
  192254. png_bytep dp = row;
  192255. for (i = 0; i < row_width; i++)
  192256. {
  192257. png_uint_16 red, green, blue, w;
  192258. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192259. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192260. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192261. if(red == green && red == blue)
  192262. w = red;
  192263. else
  192264. {
  192265. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192266. png_ptr->gamma_shift][red>>8];
  192267. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192268. png_ptr->gamma_shift][green>>8];
  192269. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192270. png_ptr->gamma_shift][blue>>8];
  192271. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192272. + bc*blue_1)>>15);
  192273. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192274. png_ptr->gamma_shift][gray16 >> 8];
  192275. rgb_error |= 1;
  192276. }
  192277. *(dp++) = (png_byte)((w>>8) & 0xff);
  192278. *(dp++) = (png_byte)(w & 0xff);
  192279. }
  192280. }
  192281. else
  192282. #endif
  192283. {
  192284. png_bytep sp = row;
  192285. png_bytep dp = row;
  192286. for (i = 0; i < row_width; i++)
  192287. {
  192288. png_uint_16 red, green, blue, gray16;
  192289. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192290. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192291. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192292. if(red != green || red != blue)
  192293. rgb_error |= 1;
  192294. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192295. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192296. *(dp++) = (png_byte)(gray16 & 0xff);
  192297. }
  192298. }
  192299. }
  192300. }
  192301. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192302. {
  192303. if (row_info->bit_depth == 8)
  192304. {
  192305. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192306. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192307. {
  192308. png_bytep sp = row;
  192309. png_bytep dp = row;
  192310. for (i = 0; i < row_width; i++)
  192311. {
  192312. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192313. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192314. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192315. if(red != green || red != blue)
  192316. rgb_error |= 1;
  192317. *(dp++) = png_ptr->gamma_from_1
  192318. [(rc*red + gc*green + bc*blue)>>15];
  192319. *(dp++) = *(sp++); /* alpha */
  192320. }
  192321. }
  192322. else
  192323. #endif
  192324. {
  192325. png_bytep sp = row;
  192326. png_bytep dp = row;
  192327. for (i = 0; i < row_width; i++)
  192328. {
  192329. png_byte red = *(sp++);
  192330. png_byte green = *(sp++);
  192331. png_byte blue = *(sp++);
  192332. if(red != green || red != blue)
  192333. rgb_error |= 1;
  192334. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192335. *(dp++) = *(sp++); /* alpha */
  192336. }
  192337. }
  192338. }
  192339. else /* RGBA bit_depth == 16 */
  192340. {
  192341. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192342. if (png_ptr->gamma_16_to_1 != NULL &&
  192343. png_ptr->gamma_16_from_1 != NULL)
  192344. {
  192345. png_bytep sp = row;
  192346. png_bytep dp = row;
  192347. for (i = 0; i < row_width; i++)
  192348. {
  192349. png_uint_16 red, green, blue, w;
  192350. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192351. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192352. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192353. if(red == green && red == blue)
  192354. w = red;
  192355. else
  192356. {
  192357. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192358. png_ptr->gamma_shift][red>>8];
  192359. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192360. png_ptr->gamma_shift][green>>8];
  192361. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192362. png_ptr->gamma_shift][blue>>8];
  192363. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192364. + gc * green_1 + bc * blue_1)>>15);
  192365. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192366. png_ptr->gamma_shift][gray16 >> 8];
  192367. rgb_error |= 1;
  192368. }
  192369. *(dp++) = (png_byte)((w>>8) & 0xff);
  192370. *(dp++) = (png_byte)(w & 0xff);
  192371. *(dp++) = *(sp++); /* alpha */
  192372. *(dp++) = *(sp++);
  192373. }
  192374. }
  192375. else
  192376. #endif
  192377. {
  192378. png_bytep sp = row;
  192379. png_bytep dp = row;
  192380. for (i = 0; i < row_width; i++)
  192381. {
  192382. png_uint_16 red, green, blue, gray16;
  192383. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192384. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192385. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192386. if(red != green || red != blue)
  192387. rgb_error |= 1;
  192388. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192389. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192390. *(dp++) = (png_byte)(gray16 & 0xff);
  192391. *(dp++) = *(sp++); /* alpha */
  192392. *(dp++) = *(sp++);
  192393. }
  192394. }
  192395. }
  192396. }
  192397. row_info->channels -= (png_byte)2;
  192398. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192399. row_info->pixel_depth = (png_byte)(row_info->channels *
  192400. row_info->bit_depth);
  192401. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192402. }
  192403. return rgb_error;
  192404. }
  192405. #endif
  192406. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192407. * large of png_color. This lets grayscale images be treated as
  192408. * paletted. Most useful for gamma correction and simplification
  192409. * of code.
  192410. */
  192411. void PNGAPI
  192412. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192413. {
  192414. int num_palette;
  192415. int color_inc;
  192416. int i;
  192417. int v;
  192418. png_debug(1, "in png_do_build_grayscale_palette\n");
  192419. if (palette == NULL)
  192420. return;
  192421. switch (bit_depth)
  192422. {
  192423. case 1:
  192424. num_palette = 2;
  192425. color_inc = 0xff;
  192426. break;
  192427. case 2:
  192428. num_palette = 4;
  192429. color_inc = 0x55;
  192430. break;
  192431. case 4:
  192432. num_palette = 16;
  192433. color_inc = 0x11;
  192434. break;
  192435. case 8:
  192436. num_palette = 256;
  192437. color_inc = 1;
  192438. break;
  192439. default:
  192440. num_palette = 0;
  192441. color_inc = 0;
  192442. break;
  192443. }
  192444. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192445. {
  192446. palette[i].red = (png_byte)v;
  192447. palette[i].green = (png_byte)v;
  192448. palette[i].blue = (png_byte)v;
  192449. }
  192450. }
  192451. /* This function is currently unused. Do we really need it? */
  192452. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192453. void /* PRIVATE */
  192454. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192455. int num_palette)
  192456. {
  192457. png_debug(1, "in png_correct_palette\n");
  192458. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192459. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192460. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192461. {
  192462. png_color back, back_1;
  192463. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192464. {
  192465. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192466. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192467. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192468. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192469. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192470. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192471. }
  192472. else
  192473. {
  192474. double g;
  192475. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192476. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192477. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192478. {
  192479. back.red = png_ptr->background.red;
  192480. back.green = png_ptr->background.green;
  192481. back.blue = png_ptr->background.blue;
  192482. }
  192483. else
  192484. {
  192485. back.red =
  192486. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192487. 255.0 + 0.5);
  192488. back.green =
  192489. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192490. 255.0 + 0.5);
  192491. back.blue =
  192492. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192493. 255.0 + 0.5);
  192494. }
  192495. g = 1.0 / png_ptr->background_gamma;
  192496. back_1.red =
  192497. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192498. 255.0 + 0.5);
  192499. back_1.green =
  192500. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192501. 255.0 + 0.5);
  192502. back_1.blue =
  192503. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192504. 255.0 + 0.5);
  192505. }
  192506. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192507. {
  192508. png_uint_32 i;
  192509. for (i = 0; i < (png_uint_32)num_palette; i++)
  192510. {
  192511. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192512. {
  192513. palette[i] = back;
  192514. }
  192515. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192516. {
  192517. png_byte v, w;
  192518. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192519. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192520. palette[i].red = png_ptr->gamma_from_1[w];
  192521. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192522. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192523. palette[i].green = png_ptr->gamma_from_1[w];
  192524. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192525. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192526. palette[i].blue = png_ptr->gamma_from_1[w];
  192527. }
  192528. else
  192529. {
  192530. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192531. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192532. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192533. }
  192534. }
  192535. }
  192536. else
  192537. {
  192538. int i;
  192539. for (i = 0; i < num_palette; i++)
  192540. {
  192541. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192542. {
  192543. palette[i] = back;
  192544. }
  192545. else
  192546. {
  192547. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192548. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192549. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192550. }
  192551. }
  192552. }
  192553. }
  192554. else
  192555. #endif
  192556. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192557. if (png_ptr->transformations & PNG_GAMMA)
  192558. {
  192559. int i;
  192560. for (i = 0; i < num_palette; i++)
  192561. {
  192562. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192563. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192564. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192565. }
  192566. }
  192567. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192568. else
  192569. #endif
  192570. #endif
  192571. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192572. if (png_ptr->transformations & PNG_BACKGROUND)
  192573. {
  192574. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192575. {
  192576. png_color back;
  192577. back.red = (png_byte)png_ptr->background.red;
  192578. back.green = (png_byte)png_ptr->background.green;
  192579. back.blue = (png_byte)png_ptr->background.blue;
  192580. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192581. {
  192582. if (png_ptr->trans[i] == 0)
  192583. {
  192584. palette[i].red = back.red;
  192585. palette[i].green = back.green;
  192586. palette[i].blue = back.blue;
  192587. }
  192588. else if (png_ptr->trans[i] != 0xff)
  192589. {
  192590. png_composite(palette[i].red, png_ptr->palette[i].red,
  192591. png_ptr->trans[i], back.red);
  192592. png_composite(palette[i].green, png_ptr->palette[i].green,
  192593. png_ptr->trans[i], back.green);
  192594. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192595. png_ptr->trans[i], back.blue);
  192596. }
  192597. }
  192598. }
  192599. else /* assume grayscale palette (what else could it be?) */
  192600. {
  192601. int i;
  192602. for (i = 0; i < num_palette; i++)
  192603. {
  192604. if (i == (png_byte)png_ptr->trans_values.gray)
  192605. {
  192606. palette[i].red = (png_byte)png_ptr->background.red;
  192607. palette[i].green = (png_byte)png_ptr->background.green;
  192608. palette[i].blue = (png_byte)png_ptr->background.blue;
  192609. }
  192610. }
  192611. }
  192612. }
  192613. #endif
  192614. }
  192615. #endif
  192616. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192617. /* Replace any alpha or transparency with the supplied background color.
  192618. * "background" is already in the screen gamma, while "background_1" is
  192619. * at a gamma of 1.0. Paletted files have already been taken care of.
  192620. */
  192621. void /* PRIVATE */
  192622. png_do_background(png_row_infop row_info, png_bytep row,
  192623. png_color_16p trans_values, png_color_16p background
  192624. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192625. , png_color_16p background_1,
  192626. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192627. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192628. png_uint_16pp gamma_16_to_1, int gamma_shift
  192629. #endif
  192630. )
  192631. {
  192632. png_bytep sp, dp;
  192633. png_uint_32 i;
  192634. png_uint_32 row_width=row_info->width;
  192635. int shift;
  192636. png_debug(1, "in png_do_background\n");
  192637. if (background != NULL &&
  192638. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192639. row != NULL && row_info != NULL &&
  192640. #endif
  192641. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192642. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192643. {
  192644. switch (row_info->color_type)
  192645. {
  192646. case PNG_COLOR_TYPE_GRAY:
  192647. {
  192648. switch (row_info->bit_depth)
  192649. {
  192650. case 1:
  192651. {
  192652. sp = row;
  192653. shift = 7;
  192654. for (i = 0; i < row_width; i++)
  192655. {
  192656. if ((png_uint_16)((*sp >> shift) & 0x01)
  192657. == trans_values->gray)
  192658. {
  192659. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192660. *sp |= (png_byte)(background->gray << shift);
  192661. }
  192662. if (!shift)
  192663. {
  192664. shift = 7;
  192665. sp++;
  192666. }
  192667. else
  192668. shift--;
  192669. }
  192670. break;
  192671. }
  192672. case 2:
  192673. {
  192674. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192675. if (gamma_table != NULL)
  192676. {
  192677. sp = row;
  192678. shift = 6;
  192679. for (i = 0; i < row_width; i++)
  192680. {
  192681. if ((png_uint_16)((*sp >> shift) & 0x03)
  192682. == trans_values->gray)
  192683. {
  192684. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192685. *sp |= (png_byte)(background->gray << shift);
  192686. }
  192687. else
  192688. {
  192689. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192690. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192691. (p << 4) | (p << 6)] >> 6) & 0x03);
  192692. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192693. *sp |= (png_byte)(g << shift);
  192694. }
  192695. if (!shift)
  192696. {
  192697. shift = 6;
  192698. sp++;
  192699. }
  192700. else
  192701. shift -= 2;
  192702. }
  192703. }
  192704. else
  192705. #endif
  192706. {
  192707. sp = row;
  192708. shift = 6;
  192709. for (i = 0; i < row_width; i++)
  192710. {
  192711. if ((png_uint_16)((*sp >> shift) & 0x03)
  192712. == trans_values->gray)
  192713. {
  192714. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192715. *sp |= (png_byte)(background->gray << shift);
  192716. }
  192717. if (!shift)
  192718. {
  192719. shift = 6;
  192720. sp++;
  192721. }
  192722. else
  192723. shift -= 2;
  192724. }
  192725. }
  192726. break;
  192727. }
  192728. case 4:
  192729. {
  192730. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192731. if (gamma_table != NULL)
  192732. {
  192733. sp = row;
  192734. shift = 4;
  192735. for (i = 0; i < row_width; i++)
  192736. {
  192737. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192738. == trans_values->gray)
  192739. {
  192740. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192741. *sp |= (png_byte)(background->gray << shift);
  192742. }
  192743. else
  192744. {
  192745. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192746. png_byte g = (png_byte)((gamma_table[p |
  192747. (p << 4)] >> 4) & 0x0f);
  192748. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192749. *sp |= (png_byte)(g << shift);
  192750. }
  192751. if (!shift)
  192752. {
  192753. shift = 4;
  192754. sp++;
  192755. }
  192756. else
  192757. shift -= 4;
  192758. }
  192759. }
  192760. else
  192761. #endif
  192762. {
  192763. sp = row;
  192764. shift = 4;
  192765. for (i = 0; i < row_width; i++)
  192766. {
  192767. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192768. == trans_values->gray)
  192769. {
  192770. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192771. *sp |= (png_byte)(background->gray << shift);
  192772. }
  192773. if (!shift)
  192774. {
  192775. shift = 4;
  192776. sp++;
  192777. }
  192778. else
  192779. shift -= 4;
  192780. }
  192781. }
  192782. break;
  192783. }
  192784. case 8:
  192785. {
  192786. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192787. if (gamma_table != NULL)
  192788. {
  192789. sp = row;
  192790. for (i = 0; i < row_width; i++, sp++)
  192791. {
  192792. if (*sp == trans_values->gray)
  192793. {
  192794. *sp = (png_byte)background->gray;
  192795. }
  192796. else
  192797. {
  192798. *sp = gamma_table[*sp];
  192799. }
  192800. }
  192801. }
  192802. else
  192803. #endif
  192804. {
  192805. sp = row;
  192806. for (i = 0; i < row_width; i++, sp++)
  192807. {
  192808. if (*sp == trans_values->gray)
  192809. {
  192810. *sp = (png_byte)background->gray;
  192811. }
  192812. }
  192813. }
  192814. break;
  192815. }
  192816. case 16:
  192817. {
  192818. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192819. if (gamma_16 != NULL)
  192820. {
  192821. sp = row;
  192822. for (i = 0; i < row_width; i++, sp += 2)
  192823. {
  192824. png_uint_16 v;
  192825. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192826. if (v == trans_values->gray)
  192827. {
  192828. /* background is already in screen gamma */
  192829. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192830. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192831. }
  192832. else
  192833. {
  192834. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192835. *sp = (png_byte)((v >> 8) & 0xff);
  192836. *(sp + 1) = (png_byte)(v & 0xff);
  192837. }
  192838. }
  192839. }
  192840. else
  192841. #endif
  192842. {
  192843. sp = row;
  192844. for (i = 0; i < row_width; i++, sp += 2)
  192845. {
  192846. png_uint_16 v;
  192847. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192848. if (v == trans_values->gray)
  192849. {
  192850. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192851. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192852. }
  192853. }
  192854. }
  192855. break;
  192856. }
  192857. }
  192858. break;
  192859. }
  192860. case PNG_COLOR_TYPE_RGB:
  192861. {
  192862. if (row_info->bit_depth == 8)
  192863. {
  192864. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192865. if (gamma_table != NULL)
  192866. {
  192867. sp = row;
  192868. for (i = 0; i < row_width; i++, sp += 3)
  192869. {
  192870. if (*sp == trans_values->red &&
  192871. *(sp + 1) == trans_values->green &&
  192872. *(sp + 2) == trans_values->blue)
  192873. {
  192874. *sp = (png_byte)background->red;
  192875. *(sp + 1) = (png_byte)background->green;
  192876. *(sp + 2) = (png_byte)background->blue;
  192877. }
  192878. else
  192879. {
  192880. *sp = gamma_table[*sp];
  192881. *(sp + 1) = gamma_table[*(sp + 1)];
  192882. *(sp + 2) = gamma_table[*(sp + 2)];
  192883. }
  192884. }
  192885. }
  192886. else
  192887. #endif
  192888. {
  192889. sp = row;
  192890. for (i = 0; i < row_width; i++, sp += 3)
  192891. {
  192892. if (*sp == trans_values->red &&
  192893. *(sp + 1) == trans_values->green &&
  192894. *(sp + 2) == trans_values->blue)
  192895. {
  192896. *sp = (png_byte)background->red;
  192897. *(sp + 1) = (png_byte)background->green;
  192898. *(sp + 2) = (png_byte)background->blue;
  192899. }
  192900. }
  192901. }
  192902. }
  192903. else /* if (row_info->bit_depth == 16) */
  192904. {
  192905. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192906. if (gamma_16 != NULL)
  192907. {
  192908. sp = row;
  192909. for (i = 0; i < row_width; i++, sp += 6)
  192910. {
  192911. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192912. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192913. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192914. if (r == trans_values->red && g == trans_values->green &&
  192915. b == trans_values->blue)
  192916. {
  192917. /* background is already in screen gamma */
  192918. *sp = (png_byte)((background->red >> 8) & 0xff);
  192919. *(sp + 1) = (png_byte)(background->red & 0xff);
  192920. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192921. *(sp + 3) = (png_byte)(background->green & 0xff);
  192922. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192923. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192924. }
  192925. else
  192926. {
  192927. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192928. *sp = (png_byte)((v >> 8) & 0xff);
  192929. *(sp + 1) = (png_byte)(v & 0xff);
  192930. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192931. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192932. *(sp + 3) = (png_byte)(v & 0xff);
  192933. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192934. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192935. *(sp + 5) = (png_byte)(v & 0xff);
  192936. }
  192937. }
  192938. }
  192939. else
  192940. #endif
  192941. {
  192942. sp = row;
  192943. for (i = 0; i < row_width; i++, sp += 6)
  192944. {
  192945. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192946. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192947. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192948. if (r == trans_values->red && g == trans_values->green &&
  192949. b == trans_values->blue)
  192950. {
  192951. *sp = (png_byte)((background->red >> 8) & 0xff);
  192952. *(sp + 1) = (png_byte)(background->red & 0xff);
  192953. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192954. *(sp + 3) = (png_byte)(background->green & 0xff);
  192955. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192956. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192957. }
  192958. }
  192959. }
  192960. }
  192961. break;
  192962. }
  192963. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192964. {
  192965. if (row_info->bit_depth == 8)
  192966. {
  192967. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192968. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192969. gamma_table != NULL)
  192970. {
  192971. sp = row;
  192972. dp = row;
  192973. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192974. {
  192975. png_uint_16 a = *(sp + 1);
  192976. if (a == 0xff)
  192977. {
  192978. *dp = gamma_table[*sp];
  192979. }
  192980. else if (a == 0)
  192981. {
  192982. /* background is already in screen gamma */
  192983. *dp = (png_byte)background->gray;
  192984. }
  192985. else
  192986. {
  192987. png_byte v, w;
  192988. v = gamma_to_1[*sp];
  192989. png_composite(w, v, a, background_1->gray);
  192990. *dp = gamma_from_1[w];
  192991. }
  192992. }
  192993. }
  192994. else
  192995. #endif
  192996. {
  192997. sp = row;
  192998. dp = row;
  192999. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193000. {
  193001. png_byte a = *(sp + 1);
  193002. if (a == 0xff)
  193003. {
  193004. *dp = *sp;
  193005. }
  193006. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193007. else if (a == 0)
  193008. {
  193009. *dp = (png_byte)background->gray;
  193010. }
  193011. else
  193012. {
  193013. png_composite(*dp, *sp, a, background_1->gray);
  193014. }
  193015. #else
  193016. *dp = (png_byte)background->gray;
  193017. #endif
  193018. }
  193019. }
  193020. }
  193021. else /* if (png_ptr->bit_depth == 16) */
  193022. {
  193023. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193024. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193025. gamma_16_to_1 != NULL)
  193026. {
  193027. sp = row;
  193028. dp = row;
  193029. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193030. {
  193031. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193032. if (a == (png_uint_16)0xffff)
  193033. {
  193034. png_uint_16 v;
  193035. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193036. *dp = (png_byte)((v >> 8) & 0xff);
  193037. *(dp + 1) = (png_byte)(v & 0xff);
  193038. }
  193039. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193040. else if (a == 0)
  193041. #else
  193042. else
  193043. #endif
  193044. {
  193045. /* background is already in screen gamma */
  193046. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193047. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193048. }
  193049. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193050. else
  193051. {
  193052. png_uint_16 g, v, w;
  193053. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193054. png_composite_16(v, g, a, background_1->gray);
  193055. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193056. *dp = (png_byte)((w >> 8) & 0xff);
  193057. *(dp + 1) = (png_byte)(w & 0xff);
  193058. }
  193059. #endif
  193060. }
  193061. }
  193062. else
  193063. #endif
  193064. {
  193065. sp = row;
  193066. dp = row;
  193067. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193068. {
  193069. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193070. if (a == (png_uint_16)0xffff)
  193071. {
  193072. png_memcpy(dp, sp, 2);
  193073. }
  193074. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193075. else if (a == 0)
  193076. #else
  193077. else
  193078. #endif
  193079. {
  193080. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193081. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193082. }
  193083. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193084. else
  193085. {
  193086. png_uint_16 g, v;
  193087. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193088. png_composite_16(v, g, a, background_1->gray);
  193089. *dp = (png_byte)((v >> 8) & 0xff);
  193090. *(dp + 1) = (png_byte)(v & 0xff);
  193091. }
  193092. #endif
  193093. }
  193094. }
  193095. }
  193096. break;
  193097. }
  193098. case PNG_COLOR_TYPE_RGB_ALPHA:
  193099. {
  193100. if (row_info->bit_depth == 8)
  193101. {
  193102. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193103. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193104. gamma_table != NULL)
  193105. {
  193106. sp = row;
  193107. dp = row;
  193108. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193109. {
  193110. png_byte a = *(sp + 3);
  193111. if (a == 0xff)
  193112. {
  193113. *dp = gamma_table[*sp];
  193114. *(dp + 1) = gamma_table[*(sp + 1)];
  193115. *(dp + 2) = gamma_table[*(sp + 2)];
  193116. }
  193117. else if (a == 0)
  193118. {
  193119. /* background is already in screen gamma */
  193120. *dp = (png_byte)background->red;
  193121. *(dp + 1) = (png_byte)background->green;
  193122. *(dp + 2) = (png_byte)background->blue;
  193123. }
  193124. else
  193125. {
  193126. png_byte v, w;
  193127. v = gamma_to_1[*sp];
  193128. png_composite(w, v, a, background_1->red);
  193129. *dp = gamma_from_1[w];
  193130. v = gamma_to_1[*(sp + 1)];
  193131. png_composite(w, v, a, background_1->green);
  193132. *(dp + 1) = gamma_from_1[w];
  193133. v = gamma_to_1[*(sp + 2)];
  193134. png_composite(w, v, a, background_1->blue);
  193135. *(dp + 2) = gamma_from_1[w];
  193136. }
  193137. }
  193138. }
  193139. else
  193140. #endif
  193141. {
  193142. sp = row;
  193143. dp = row;
  193144. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193145. {
  193146. png_byte a = *(sp + 3);
  193147. if (a == 0xff)
  193148. {
  193149. *dp = *sp;
  193150. *(dp + 1) = *(sp + 1);
  193151. *(dp + 2) = *(sp + 2);
  193152. }
  193153. else if (a == 0)
  193154. {
  193155. *dp = (png_byte)background->red;
  193156. *(dp + 1) = (png_byte)background->green;
  193157. *(dp + 2) = (png_byte)background->blue;
  193158. }
  193159. else
  193160. {
  193161. png_composite(*dp, *sp, a, background->red);
  193162. png_composite(*(dp + 1), *(sp + 1), a,
  193163. background->green);
  193164. png_composite(*(dp + 2), *(sp + 2), a,
  193165. background->blue);
  193166. }
  193167. }
  193168. }
  193169. }
  193170. else /* if (row_info->bit_depth == 16) */
  193171. {
  193172. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193173. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193174. gamma_16_to_1 != NULL)
  193175. {
  193176. sp = row;
  193177. dp = row;
  193178. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193179. {
  193180. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193181. << 8) + (png_uint_16)(*(sp + 7)));
  193182. if (a == (png_uint_16)0xffff)
  193183. {
  193184. png_uint_16 v;
  193185. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193186. *dp = (png_byte)((v >> 8) & 0xff);
  193187. *(dp + 1) = (png_byte)(v & 0xff);
  193188. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193189. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193190. *(dp + 3) = (png_byte)(v & 0xff);
  193191. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193192. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193193. *(dp + 5) = (png_byte)(v & 0xff);
  193194. }
  193195. else if (a == 0)
  193196. {
  193197. /* background is already in screen gamma */
  193198. *dp = (png_byte)((background->red >> 8) & 0xff);
  193199. *(dp + 1) = (png_byte)(background->red & 0xff);
  193200. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193201. *(dp + 3) = (png_byte)(background->green & 0xff);
  193202. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193203. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193204. }
  193205. else
  193206. {
  193207. png_uint_16 v, w, x;
  193208. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193209. png_composite_16(w, v, a, background_1->red);
  193210. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193211. *dp = (png_byte)((x >> 8) & 0xff);
  193212. *(dp + 1) = (png_byte)(x & 0xff);
  193213. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193214. png_composite_16(w, v, a, background_1->green);
  193215. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193216. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193217. *(dp + 3) = (png_byte)(x & 0xff);
  193218. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193219. png_composite_16(w, v, a, background_1->blue);
  193220. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193221. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193222. *(dp + 5) = (png_byte)(x & 0xff);
  193223. }
  193224. }
  193225. }
  193226. else
  193227. #endif
  193228. {
  193229. sp = row;
  193230. dp = row;
  193231. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193232. {
  193233. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193234. << 8) + (png_uint_16)(*(sp + 7)));
  193235. if (a == (png_uint_16)0xffff)
  193236. {
  193237. png_memcpy(dp, sp, 6);
  193238. }
  193239. else if (a == 0)
  193240. {
  193241. *dp = (png_byte)((background->red >> 8) & 0xff);
  193242. *(dp + 1) = (png_byte)(background->red & 0xff);
  193243. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193244. *(dp + 3) = (png_byte)(background->green & 0xff);
  193245. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193246. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193247. }
  193248. else
  193249. {
  193250. png_uint_16 v;
  193251. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193252. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193253. + *(sp + 3));
  193254. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193255. + *(sp + 5));
  193256. png_composite_16(v, r, a, background->red);
  193257. *dp = (png_byte)((v >> 8) & 0xff);
  193258. *(dp + 1) = (png_byte)(v & 0xff);
  193259. png_composite_16(v, g, a, background->green);
  193260. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193261. *(dp + 3) = (png_byte)(v & 0xff);
  193262. png_composite_16(v, b, a, background->blue);
  193263. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193264. *(dp + 5) = (png_byte)(v & 0xff);
  193265. }
  193266. }
  193267. }
  193268. }
  193269. break;
  193270. }
  193271. }
  193272. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193273. {
  193274. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193275. row_info->channels--;
  193276. row_info->pixel_depth = (png_byte)(row_info->channels *
  193277. row_info->bit_depth);
  193278. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193279. }
  193280. }
  193281. }
  193282. #endif
  193283. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193284. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193285. * you do this after you deal with the transparency issue on grayscale
  193286. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193287. * is 16, use gamma_16_table and gamma_shift. Build these with
  193288. * build_gamma_table().
  193289. */
  193290. void /* PRIVATE */
  193291. png_do_gamma(png_row_infop row_info, png_bytep row,
  193292. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193293. int gamma_shift)
  193294. {
  193295. png_bytep sp;
  193296. png_uint_32 i;
  193297. png_uint_32 row_width=row_info->width;
  193298. png_debug(1, "in png_do_gamma\n");
  193299. if (
  193300. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193301. row != NULL && row_info != NULL &&
  193302. #endif
  193303. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193304. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193305. {
  193306. switch (row_info->color_type)
  193307. {
  193308. case PNG_COLOR_TYPE_RGB:
  193309. {
  193310. if (row_info->bit_depth == 8)
  193311. {
  193312. sp = row;
  193313. for (i = 0; i < row_width; i++)
  193314. {
  193315. *sp = gamma_table[*sp];
  193316. sp++;
  193317. *sp = gamma_table[*sp];
  193318. sp++;
  193319. *sp = gamma_table[*sp];
  193320. sp++;
  193321. }
  193322. }
  193323. else /* if (row_info->bit_depth == 16) */
  193324. {
  193325. sp = row;
  193326. for (i = 0; i < row_width; i++)
  193327. {
  193328. png_uint_16 v;
  193329. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193330. *sp = (png_byte)((v >> 8) & 0xff);
  193331. *(sp + 1) = (png_byte)(v & 0xff);
  193332. sp += 2;
  193333. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193334. *sp = (png_byte)((v >> 8) & 0xff);
  193335. *(sp + 1) = (png_byte)(v & 0xff);
  193336. sp += 2;
  193337. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193338. *sp = (png_byte)((v >> 8) & 0xff);
  193339. *(sp + 1) = (png_byte)(v & 0xff);
  193340. sp += 2;
  193341. }
  193342. }
  193343. break;
  193344. }
  193345. case PNG_COLOR_TYPE_RGB_ALPHA:
  193346. {
  193347. if (row_info->bit_depth == 8)
  193348. {
  193349. sp = row;
  193350. for (i = 0; i < row_width; i++)
  193351. {
  193352. *sp = gamma_table[*sp];
  193353. sp++;
  193354. *sp = gamma_table[*sp];
  193355. sp++;
  193356. *sp = gamma_table[*sp];
  193357. sp++;
  193358. sp++;
  193359. }
  193360. }
  193361. else /* if (row_info->bit_depth == 16) */
  193362. {
  193363. sp = row;
  193364. for (i = 0; i < row_width; i++)
  193365. {
  193366. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193367. *sp = (png_byte)((v >> 8) & 0xff);
  193368. *(sp + 1) = (png_byte)(v & 0xff);
  193369. sp += 2;
  193370. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193371. *sp = (png_byte)((v >> 8) & 0xff);
  193372. *(sp + 1) = (png_byte)(v & 0xff);
  193373. sp += 2;
  193374. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193375. *sp = (png_byte)((v >> 8) & 0xff);
  193376. *(sp + 1) = (png_byte)(v & 0xff);
  193377. sp += 4;
  193378. }
  193379. }
  193380. break;
  193381. }
  193382. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193383. {
  193384. if (row_info->bit_depth == 8)
  193385. {
  193386. sp = row;
  193387. for (i = 0; i < row_width; i++)
  193388. {
  193389. *sp = gamma_table[*sp];
  193390. sp += 2;
  193391. }
  193392. }
  193393. else /* if (row_info->bit_depth == 16) */
  193394. {
  193395. sp = row;
  193396. for (i = 0; i < row_width; i++)
  193397. {
  193398. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193399. *sp = (png_byte)((v >> 8) & 0xff);
  193400. *(sp + 1) = (png_byte)(v & 0xff);
  193401. sp += 4;
  193402. }
  193403. }
  193404. break;
  193405. }
  193406. case PNG_COLOR_TYPE_GRAY:
  193407. {
  193408. if (row_info->bit_depth == 2)
  193409. {
  193410. sp = row;
  193411. for (i = 0; i < row_width; i += 4)
  193412. {
  193413. int a = *sp & 0xc0;
  193414. int b = *sp & 0x30;
  193415. int c = *sp & 0x0c;
  193416. int d = *sp & 0x03;
  193417. *sp = (png_byte)(
  193418. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193419. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193420. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193421. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193422. sp++;
  193423. }
  193424. }
  193425. if (row_info->bit_depth == 4)
  193426. {
  193427. sp = row;
  193428. for (i = 0; i < row_width; i += 2)
  193429. {
  193430. int msb = *sp & 0xf0;
  193431. int lsb = *sp & 0x0f;
  193432. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193433. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193434. sp++;
  193435. }
  193436. }
  193437. else if (row_info->bit_depth == 8)
  193438. {
  193439. sp = row;
  193440. for (i = 0; i < row_width; i++)
  193441. {
  193442. *sp = gamma_table[*sp];
  193443. sp++;
  193444. }
  193445. }
  193446. else if (row_info->bit_depth == 16)
  193447. {
  193448. sp = row;
  193449. for (i = 0; i < row_width; i++)
  193450. {
  193451. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193452. *sp = (png_byte)((v >> 8) & 0xff);
  193453. *(sp + 1) = (png_byte)(v & 0xff);
  193454. sp += 2;
  193455. }
  193456. }
  193457. break;
  193458. }
  193459. }
  193460. }
  193461. }
  193462. #endif
  193463. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193464. /* Expands a palette row to an RGB or RGBA row depending
  193465. * upon whether you supply trans and num_trans.
  193466. */
  193467. void /* PRIVATE */
  193468. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193469. png_colorp palette, png_bytep trans, int num_trans)
  193470. {
  193471. int shift, value;
  193472. png_bytep sp, dp;
  193473. png_uint_32 i;
  193474. png_uint_32 row_width=row_info->width;
  193475. png_debug(1, "in png_do_expand_palette\n");
  193476. if (
  193477. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193478. row != NULL && row_info != NULL &&
  193479. #endif
  193480. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193481. {
  193482. if (row_info->bit_depth < 8)
  193483. {
  193484. switch (row_info->bit_depth)
  193485. {
  193486. case 1:
  193487. {
  193488. sp = row + (png_size_t)((row_width - 1) >> 3);
  193489. dp = row + (png_size_t)row_width - 1;
  193490. shift = 7 - (int)((row_width + 7) & 0x07);
  193491. for (i = 0; i < row_width; i++)
  193492. {
  193493. if ((*sp >> shift) & 0x01)
  193494. *dp = 1;
  193495. else
  193496. *dp = 0;
  193497. if (shift == 7)
  193498. {
  193499. shift = 0;
  193500. sp--;
  193501. }
  193502. else
  193503. shift++;
  193504. dp--;
  193505. }
  193506. break;
  193507. }
  193508. case 2:
  193509. {
  193510. sp = row + (png_size_t)((row_width - 1) >> 2);
  193511. dp = row + (png_size_t)row_width - 1;
  193512. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193513. for (i = 0; i < row_width; i++)
  193514. {
  193515. value = (*sp >> shift) & 0x03;
  193516. *dp = (png_byte)value;
  193517. if (shift == 6)
  193518. {
  193519. shift = 0;
  193520. sp--;
  193521. }
  193522. else
  193523. shift += 2;
  193524. dp--;
  193525. }
  193526. break;
  193527. }
  193528. case 4:
  193529. {
  193530. sp = row + (png_size_t)((row_width - 1) >> 1);
  193531. dp = row + (png_size_t)row_width - 1;
  193532. shift = (int)((row_width & 0x01) << 2);
  193533. for (i = 0; i < row_width; i++)
  193534. {
  193535. value = (*sp >> shift) & 0x0f;
  193536. *dp = (png_byte)value;
  193537. if (shift == 4)
  193538. {
  193539. shift = 0;
  193540. sp--;
  193541. }
  193542. else
  193543. shift += 4;
  193544. dp--;
  193545. }
  193546. break;
  193547. }
  193548. }
  193549. row_info->bit_depth = 8;
  193550. row_info->pixel_depth = 8;
  193551. row_info->rowbytes = row_width;
  193552. }
  193553. switch (row_info->bit_depth)
  193554. {
  193555. case 8:
  193556. {
  193557. if (trans != NULL)
  193558. {
  193559. sp = row + (png_size_t)row_width - 1;
  193560. dp = row + (png_size_t)(row_width << 2) - 1;
  193561. for (i = 0; i < row_width; i++)
  193562. {
  193563. if ((int)(*sp) >= num_trans)
  193564. *dp-- = 0xff;
  193565. else
  193566. *dp-- = trans[*sp];
  193567. *dp-- = palette[*sp].blue;
  193568. *dp-- = palette[*sp].green;
  193569. *dp-- = palette[*sp].red;
  193570. sp--;
  193571. }
  193572. row_info->bit_depth = 8;
  193573. row_info->pixel_depth = 32;
  193574. row_info->rowbytes = row_width * 4;
  193575. row_info->color_type = 6;
  193576. row_info->channels = 4;
  193577. }
  193578. else
  193579. {
  193580. sp = row + (png_size_t)row_width - 1;
  193581. dp = row + (png_size_t)(row_width * 3) - 1;
  193582. for (i = 0; i < row_width; i++)
  193583. {
  193584. *dp-- = palette[*sp].blue;
  193585. *dp-- = palette[*sp].green;
  193586. *dp-- = palette[*sp].red;
  193587. sp--;
  193588. }
  193589. row_info->bit_depth = 8;
  193590. row_info->pixel_depth = 24;
  193591. row_info->rowbytes = row_width * 3;
  193592. row_info->color_type = 2;
  193593. row_info->channels = 3;
  193594. }
  193595. break;
  193596. }
  193597. }
  193598. }
  193599. }
  193600. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193601. * expanded transparency value is supplied, an alpha channel is built.
  193602. */
  193603. void /* PRIVATE */
  193604. png_do_expand(png_row_infop row_info, png_bytep row,
  193605. png_color_16p trans_value)
  193606. {
  193607. int shift, value;
  193608. png_bytep sp, dp;
  193609. png_uint_32 i;
  193610. png_uint_32 row_width=row_info->width;
  193611. png_debug(1, "in png_do_expand\n");
  193612. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193613. if (row != NULL && row_info != NULL)
  193614. #endif
  193615. {
  193616. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193617. {
  193618. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193619. if (row_info->bit_depth < 8)
  193620. {
  193621. switch (row_info->bit_depth)
  193622. {
  193623. case 1:
  193624. {
  193625. gray = (png_uint_16)((gray&0x01)*0xff);
  193626. sp = row + (png_size_t)((row_width - 1) >> 3);
  193627. dp = row + (png_size_t)row_width - 1;
  193628. shift = 7 - (int)((row_width + 7) & 0x07);
  193629. for (i = 0; i < row_width; i++)
  193630. {
  193631. if ((*sp >> shift) & 0x01)
  193632. *dp = 0xff;
  193633. else
  193634. *dp = 0;
  193635. if (shift == 7)
  193636. {
  193637. shift = 0;
  193638. sp--;
  193639. }
  193640. else
  193641. shift++;
  193642. dp--;
  193643. }
  193644. break;
  193645. }
  193646. case 2:
  193647. {
  193648. gray = (png_uint_16)((gray&0x03)*0x55);
  193649. sp = row + (png_size_t)((row_width - 1) >> 2);
  193650. dp = row + (png_size_t)row_width - 1;
  193651. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193652. for (i = 0; i < row_width; i++)
  193653. {
  193654. value = (*sp >> shift) & 0x03;
  193655. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193656. (value << 6));
  193657. if (shift == 6)
  193658. {
  193659. shift = 0;
  193660. sp--;
  193661. }
  193662. else
  193663. shift += 2;
  193664. dp--;
  193665. }
  193666. break;
  193667. }
  193668. case 4:
  193669. {
  193670. gray = (png_uint_16)((gray&0x0f)*0x11);
  193671. sp = row + (png_size_t)((row_width - 1) >> 1);
  193672. dp = row + (png_size_t)row_width - 1;
  193673. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193674. for (i = 0; i < row_width; i++)
  193675. {
  193676. value = (*sp >> shift) & 0x0f;
  193677. *dp = (png_byte)(value | (value << 4));
  193678. if (shift == 4)
  193679. {
  193680. shift = 0;
  193681. sp--;
  193682. }
  193683. else
  193684. shift = 4;
  193685. dp--;
  193686. }
  193687. break;
  193688. }
  193689. }
  193690. row_info->bit_depth = 8;
  193691. row_info->pixel_depth = 8;
  193692. row_info->rowbytes = row_width;
  193693. }
  193694. if (trans_value != NULL)
  193695. {
  193696. if (row_info->bit_depth == 8)
  193697. {
  193698. gray = gray & 0xff;
  193699. sp = row + (png_size_t)row_width - 1;
  193700. dp = row + (png_size_t)(row_width << 1) - 1;
  193701. for (i = 0; i < row_width; i++)
  193702. {
  193703. if (*sp == gray)
  193704. *dp-- = 0;
  193705. else
  193706. *dp-- = 0xff;
  193707. *dp-- = *sp--;
  193708. }
  193709. }
  193710. else if (row_info->bit_depth == 16)
  193711. {
  193712. png_byte gray_high = (gray >> 8) & 0xff;
  193713. png_byte gray_low = gray & 0xff;
  193714. sp = row + row_info->rowbytes - 1;
  193715. dp = row + (row_info->rowbytes << 1) - 1;
  193716. for (i = 0; i < row_width; i++)
  193717. {
  193718. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193719. {
  193720. *dp-- = 0;
  193721. *dp-- = 0;
  193722. }
  193723. else
  193724. {
  193725. *dp-- = 0xff;
  193726. *dp-- = 0xff;
  193727. }
  193728. *dp-- = *sp--;
  193729. *dp-- = *sp--;
  193730. }
  193731. }
  193732. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193733. row_info->channels = 2;
  193734. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193735. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193736. row_width);
  193737. }
  193738. }
  193739. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193740. {
  193741. if (row_info->bit_depth == 8)
  193742. {
  193743. png_byte red = trans_value->red & 0xff;
  193744. png_byte green = trans_value->green & 0xff;
  193745. png_byte blue = trans_value->blue & 0xff;
  193746. sp = row + (png_size_t)row_info->rowbytes - 1;
  193747. dp = row + (png_size_t)(row_width << 2) - 1;
  193748. for (i = 0; i < row_width; i++)
  193749. {
  193750. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193751. *dp-- = 0;
  193752. else
  193753. *dp-- = 0xff;
  193754. *dp-- = *sp--;
  193755. *dp-- = *sp--;
  193756. *dp-- = *sp--;
  193757. }
  193758. }
  193759. else if (row_info->bit_depth == 16)
  193760. {
  193761. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193762. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193763. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193764. png_byte red_low = trans_value->red & 0xff;
  193765. png_byte green_low = trans_value->green & 0xff;
  193766. png_byte blue_low = trans_value->blue & 0xff;
  193767. sp = row + row_info->rowbytes - 1;
  193768. dp = row + (png_size_t)(row_width << 3) - 1;
  193769. for (i = 0; i < row_width; i++)
  193770. {
  193771. if (*(sp - 5) == red_high &&
  193772. *(sp - 4) == red_low &&
  193773. *(sp - 3) == green_high &&
  193774. *(sp - 2) == green_low &&
  193775. *(sp - 1) == blue_high &&
  193776. *(sp ) == blue_low)
  193777. {
  193778. *dp-- = 0;
  193779. *dp-- = 0;
  193780. }
  193781. else
  193782. {
  193783. *dp-- = 0xff;
  193784. *dp-- = 0xff;
  193785. }
  193786. *dp-- = *sp--;
  193787. *dp-- = *sp--;
  193788. *dp-- = *sp--;
  193789. *dp-- = *sp--;
  193790. *dp-- = *sp--;
  193791. *dp-- = *sp--;
  193792. }
  193793. }
  193794. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193795. row_info->channels = 4;
  193796. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193797. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193798. }
  193799. }
  193800. }
  193801. #endif
  193802. #if defined(PNG_READ_DITHER_SUPPORTED)
  193803. void /* PRIVATE */
  193804. png_do_dither(png_row_infop row_info, png_bytep row,
  193805. png_bytep palette_lookup, png_bytep dither_lookup)
  193806. {
  193807. png_bytep sp, dp;
  193808. png_uint_32 i;
  193809. png_uint_32 row_width=row_info->width;
  193810. png_debug(1, "in png_do_dither\n");
  193811. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193812. if (row != NULL && row_info != NULL)
  193813. #endif
  193814. {
  193815. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193816. palette_lookup && row_info->bit_depth == 8)
  193817. {
  193818. int r, g, b, p;
  193819. sp = row;
  193820. dp = row;
  193821. for (i = 0; i < row_width; i++)
  193822. {
  193823. r = *sp++;
  193824. g = *sp++;
  193825. b = *sp++;
  193826. /* this looks real messy, but the compiler will reduce
  193827. it down to a reasonable formula. For example, with
  193828. 5 bits per color, we get:
  193829. p = (((r >> 3) & 0x1f) << 10) |
  193830. (((g >> 3) & 0x1f) << 5) |
  193831. ((b >> 3) & 0x1f);
  193832. */
  193833. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193834. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193835. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193836. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193837. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193838. (PNG_DITHER_BLUE_BITS)) |
  193839. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193840. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193841. *dp++ = palette_lookup[p];
  193842. }
  193843. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193844. row_info->channels = 1;
  193845. row_info->pixel_depth = row_info->bit_depth;
  193846. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193847. }
  193848. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193849. palette_lookup != NULL && row_info->bit_depth == 8)
  193850. {
  193851. int r, g, b, p;
  193852. sp = row;
  193853. dp = row;
  193854. for (i = 0; i < row_width; i++)
  193855. {
  193856. r = *sp++;
  193857. g = *sp++;
  193858. b = *sp++;
  193859. sp++;
  193860. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193861. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193862. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193863. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193864. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193865. (PNG_DITHER_BLUE_BITS)) |
  193866. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193867. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193868. *dp++ = palette_lookup[p];
  193869. }
  193870. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193871. row_info->channels = 1;
  193872. row_info->pixel_depth = row_info->bit_depth;
  193873. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193874. }
  193875. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193876. dither_lookup && row_info->bit_depth == 8)
  193877. {
  193878. sp = row;
  193879. for (i = 0; i < row_width; i++, sp++)
  193880. {
  193881. *sp = dither_lookup[*sp];
  193882. }
  193883. }
  193884. }
  193885. }
  193886. #endif
  193887. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193888. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193889. static PNG_CONST int png_gamma_shift[] =
  193890. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193891. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193892. * tables, we don't make a full table if we are reducing to 8-bit in
  193893. * the future. Note also how the gamma_16 tables are segmented so that
  193894. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193895. */
  193896. void /* PRIVATE */
  193897. png_build_gamma_table(png_structp png_ptr)
  193898. {
  193899. png_debug(1, "in png_build_gamma_table\n");
  193900. if (png_ptr->bit_depth <= 8)
  193901. {
  193902. int i;
  193903. double g;
  193904. if (png_ptr->screen_gamma > .000001)
  193905. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193906. else
  193907. g = 1.0;
  193908. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193909. (png_uint_32)256);
  193910. for (i = 0; i < 256; i++)
  193911. {
  193912. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193913. g) * 255.0 + .5);
  193914. }
  193915. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193916. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193917. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193918. {
  193919. g = 1.0 / (png_ptr->gamma);
  193920. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193921. (png_uint_32)256);
  193922. for (i = 0; i < 256; i++)
  193923. {
  193924. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193925. g) * 255.0 + .5);
  193926. }
  193927. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193928. (png_uint_32)256);
  193929. if(png_ptr->screen_gamma > 0.000001)
  193930. g = 1.0 / png_ptr->screen_gamma;
  193931. else
  193932. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193933. for (i = 0; i < 256; i++)
  193934. {
  193935. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193936. g) * 255.0 + .5);
  193937. }
  193938. }
  193939. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193940. }
  193941. else
  193942. {
  193943. double g;
  193944. int i, j, shift, num;
  193945. int sig_bit;
  193946. png_uint_32 ig;
  193947. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193948. {
  193949. sig_bit = (int)png_ptr->sig_bit.red;
  193950. if ((int)png_ptr->sig_bit.green > sig_bit)
  193951. sig_bit = png_ptr->sig_bit.green;
  193952. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193953. sig_bit = png_ptr->sig_bit.blue;
  193954. }
  193955. else
  193956. {
  193957. sig_bit = (int)png_ptr->sig_bit.gray;
  193958. }
  193959. if (sig_bit > 0)
  193960. shift = 16 - sig_bit;
  193961. else
  193962. shift = 0;
  193963. if (png_ptr->transformations & PNG_16_TO_8)
  193964. {
  193965. if (shift < (16 - PNG_MAX_GAMMA_8))
  193966. shift = (16 - PNG_MAX_GAMMA_8);
  193967. }
  193968. if (shift > 8)
  193969. shift = 8;
  193970. if (shift < 0)
  193971. shift = 0;
  193972. png_ptr->gamma_shift = (png_byte)shift;
  193973. num = (1 << (8 - shift));
  193974. if (png_ptr->screen_gamma > .000001)
  193975. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193976. else
  193977. g = 1.0;
  193978. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193979. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193980. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193981. {
  193982. double fin, fout;
  193983. png_uint_32 last, max;
  193984. for (i = 0; i < num; i++)
  193985. {
  193986. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193987. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193988. }
  193989. g = 1.0 / g;
  193990. last = 0;
  193991. for (i = 0; i < 256; i++)
  193992. {
  193993. fout = ((double)i + 0.5) / 256.0;
  193994. fin = pow(fout, g);
  193995. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193996. while (last <= max)
  193997. {
  193998. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193999. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194000. (png_uint_16)i | ((png_uint_16)i << 8));
  194001. last++;
  194002. }
  194003. }
  194004. while (last < ((png_uint_32)num << 8))
  194005. {
  194006. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194007. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194008. last++;
  194009. }
  194010. }
  194011. else
  194012. {
  194013. for (i = 0; i < num; i++)
  194014. {
  194015. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194016. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194017. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194018. for (j = 0; j < 256; j++)
  194019. {
  194020. png_ptr->gamma_16_table[i][j] =
  194021. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194022. 65535.0, g) * 65535.0 + .5);
  194023. }
  194024. }
  194025. }
  194026. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194027. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194028. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194029. {
  194030. g = 1.0 / (png_ptr->gamma);
  194031. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194032. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194033. for (i = 0; i < num; i++)
  194034. {
  194035. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194036. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194037. ig = (((png_uint_32)i *
  194038. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194039. for (j = 0; j < 256; j++)
  194040. {
  194041. png_ptr->gamma_16_to_1[i][j] =
  194042. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194043. 65535.0, g) * 65535.0 + .5);
  194044. }
  194045. }
  194046. if(png_ptr->screen_gamma > 0.000001)
  194047. g = 1.0 / png_ptr->screen_gamma;
  194048. else
  194049. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194050. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194051. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194052. for (i = 0; i < num; i++)
  194053. {
  194054. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194055. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194056. ig = (((png_uint_32)i *
  194057. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194058. for (j = 0; j < 256; j++)
  194059. {
  194060. png_ptr->gamma_16_from_1[i][j] =
  194061. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194062. 65535.0, g) * 65535.0 + .5);
  194063. }
  194064. }
  194065. }
  194066. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194067. }
  194068. }
  194069. #endif
  194070. /* To do: install integer version of png_build_gamma_table here */
  194071. #endif
  194072. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194073. /* undoes intrapixel differencing */
  194074. void /* PRIVATE */
  194075. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194076. {
  194077. png_debug(1, "in png_do_read_intrapixel\n");
  194078. if (
  194079. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194080. row != NULL && row_info != NULL &&
  194081. #endif
  194082. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194083. {
  194084. int bytes_per_pixel;
  194085. png_uint_32 row_width = row_info->width;
  194086. if (row_info->bit_depth == 8)
  194087. {
  194088. png_bytep rp;
  194089. png_uint_32 i;
  194090. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194091. bytes_per_pixel = 3;
  194092. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194093. bytes_per_pixel = 4;
  194094. else
  194095. return;
  194096. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194097. {
  194098. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194099. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194100. }
  194101. }
  194102. else if (row_info->bit_depth == 16)
  194103. {
  194104. png_bytep rp;
  194105. png_uint_32 i;
  194106. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194107. bytes_per_pixel = 6;
  194108. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194109. bytes_per_pixel = 8;
  194110. else
  194111. return;
  194112. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194113. {
  194114. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194115. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194116. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194117. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194118. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194119. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194120. *(rp+1) = (png_byte)(red & 0xff);
  194121. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194122. *(rp+5) = (png_byte)(blue & 0xff);
  194123. }
  194124. }
  194125. }
  194126. }
  194127. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194128. #endif /* PNG_READ_SUPPORTED */
  194129. /*** End of inlined file: pngrtran.c ***/
  194130. /*** Start of inlined file: pngrutil.c ***/
  194131. /* pngrutil.c - utilities to read a PNG file
  194132. *
  194133. * Last changed in libpng 1.2.21 [October 4, 2007]
  194134. * For conditions of distribution and use, see copyright notice in png.h
  194135. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194136. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194137. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194138. *
  194139. * This file contains routines that are only called from within
  194140. * libpng itself during the course of reading an image.
  194141. */
  194142. #define PNG_INTERNAL
  194143. #if defined(PNG_READ_SUPPORTED)
  194144. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194145. # define WIN32_WCE_OLD
  194146. #endif
  194147. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194148. # if defined(WIN32_WCE_OLD)
  194149. /* strtod() function is not supported on WindowsCE */
  194150. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194151. {
  194152. double result = 0;
  194153. int len;
  194154. wchar_t *str, *end;
  194155. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194156. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194157. if ( NULL != str )
  194158. {
  194159. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194160. result = wcstod(str, &end);
  194161. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194162. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194163. png_free(png_ptr, str);
  194164. }
  194165. return result;
  194166. }
  194167. # else
  194168. # define png_strtod(p,a,b) strtod(a,b)
  194169. # endif
  194170. #endif
  194171. png_uint_32 PNGAPI
  194172. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194173. {
  194174. png_uint_32 i = png_get_uint_32(buf);
  194175. if (i > PNG_UINT_31_MAX)
  194176. png_error(png_ptr, "PNG unsigned integer out of range.");
  194177. return (i);
  194178. }
  194179. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194180. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194181. png_uint_32 PNGAPI
  194182. png_get_uint_32(png_bytep buf)
  194183. {
  194184. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194185. ((png_uint_32)(*(buf + 1)) << 16) +
  194186. ((png_uint_32)(*(buf + 2)) << 8) +
  194187. (png_uint_32)(*(buf + 3));
  194188. return (i);
  194189. }
  194190. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194191. * data is stored in the PNG file in two's complement format, and it is
  194192. * assumed that the machine format for signed integers is the same. */
  194193. png_int_32 PNGAPI
  194194. png_get_int_32(png_bytep buf)
  194195. {
  194196. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194197. ((png_int_32)(*(buf + 1)) << 16) +
  194198. ((png_int_32)(*(buf + 2)) << 8) +
  194199. (png_int_32)(*(buf + 3));
  194200. return (i);
  194201. }
  194202. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194203. png_uint_16 PNGAPI
  194204. png_get_uint_16(png_bytep buf)
  194205. {
  194206. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194207. (png_uint_16)(*(buf + 1)));
  194208. return (i);
  194209. }
  194210. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194211. /* Read data, and (optionally) run it through the CRC. */
  194212. void /* PRIVATE */
  194213. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194214. {
  194215. if(png_ptr == NULL) return;
  194216. png_read_data(png_ptr, buf, length);
  194217. png_calculate_crc(png_ptr, buf, length);
  194218. }
  194219. /* Optionally skip data and then check the CRC. Depending on whether we
  194220. are reading a ancillary or critical chunk, and how the program has set
  194221. things up, we may calculate the CRC on the data and print a message.
  194222. Returns '1' if there was a CRC error, '0' otherwise. */
  194223. int /* PRIVATE */
  194224. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194225. {
  194226. png_size_t i;
  194227. png_size_t istop = png_ptr->zbuf_size;
  194228. for (i = (png_size_t)skip; i > istop; i -= istop)
  194229. {
  194230. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194231. }
  194232. if (i)
  194233. {
  194234. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194235. }
  194236. if (png_crc_error(png_ptr))
  194237. {
  194238. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194239. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194240. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194241. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194242. {
  194243. png_chunk_warning(png_ptr, "CRC error");
  194244. }
  194245. else
  194246. {
  194247. png_chunk_error(png_ptr, "CRC error");
  194248. }
  194249. return (1);
  194250. }
  194251. return (0);
  194252. }
  194253. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194254. the data it has read thus far. */
  194255. int /* PRIVATE */
  194256. png_crc_error(png_structp png_ptr)
  194257. {
  194258. png_byte crc_bytes[4];
  194259. png_uint_32 crc;
  194260. int need_crc = 1;
  194261. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194262. {
  194263. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194264. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194265. need_crc = 0;
  194266. }
  194267. else /* critical */
  194268. {
  194269. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194270. need_crc = 0;
  194271. }
  194272. png_read_data(png_ptr, crc_bytes, 4);
  194273. if (need_crc)
  194274. {
  194275. crc = png_get_uint_32(crc_bytes);
  194276. return ((int)(crc != png_ptr->crc));
  194277. }
  194278. else
  194279. return (0);
  194280. }
  194281. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194282. defined(PNG_READ_iCCP_SUPPORTED)
  194283. /*
  194284. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194285. * points at an allocated area holding the contents of a chunk with a
  194286. * trailing compressed part. What we get back is an allocated area
  194287. * holding the original prefix part and an uncompressed version of the
  194288. * trailing part (the malloc area passed in is freed).
  194289. */
  194290. png_charp /* PRIVATE */
  194291. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194292. png_charp chunkdata, png_size_t chunklength,
  194293. png_size_t prefix_size, png_size_t *newlength)
  194294. {
  194295. static PNG_CONST char msg[] = "Error decoding compressed text";
  194296. png_charp text;
  194297. png_size_t text_size;
  194298. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194299. {
  194300. int ret = Z_OK;
  194301. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194302. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194303. png_ptr->zstream.next_out = png_ptr->zbuf;
  194304. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194305. text_size = 0;
  194306. text = NULL;
  194307. while (png_ptr->zstream.avail_in)
  194308. {
  194309. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194310. if (ret != Z_OK && ret != Z_STREAM_END)
  194311. {
  194312. if (png_ptr->zstream.msg != NULL)
  194313. png_warning(png_ptr, png_ptr->zstream.msg);
  194314. else
  194315. png_warning(png_ptr, msg);
  194316. inflateReset(&png_ptr->zstream);
  194317. png_ptr->zstream.avail_in = 0;
  194318. if (text == NULL)
  194319. {
  194320. text_size = prefix_size + png_sizeof(msg) + 1;
  194321. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194322. if (text == NULL)
  194323. {
  194324. png_free(png_ptr,chunkdata);
  194325. png_error(png_ptr,"Not enough memory to decompress chunk");
  194326. }
  194327. png_memcpy(text, chunkdata, prefix_size);
  194328. }
  194329. text[text_size - 1] = 0x00;
  194330. /* Copy what we can of the error message into the text chunk */
  194331. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194332. text_size = png_sizeof(msg) > text_size ? text_size :
  194333. png_sizeof(msg);
  194334. png_memcpy(text + prefix_size, msg, text_size + 1);
  194335. break;
  194336. }
  194337. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194338. {
  194339. if (text == NULL)
  194340. {
  194341. text_size = prefix_size +
  194342. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194343. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194344. if (text == NULL)
  194345. {
  194346. png_free(png_ptr,chunkdata);
  194347. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194348. }
  194349. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194350. text_size - prefix_size);
  194351. png_memcpy(text, chunkdata, prefix_size);
  194352. *(text + text_size) = 0x00;
  194353. }
  194354. else
  194355. {
  194356. png_charp tmp;
  194357. tmp = text;
  194358. text = (png_charp)png_malloc_warn(png_ptr,
  194359. (png_uint_32)(text_size +
  194360. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194361. if (text == NULL)
  194362. {
  194363. png_free(png_ptr, tmp);
  194364. png_free(png_ptr, chunkdata);
  194365. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194366. }
  194367. png_memcpy(text, tmp, text_size);
  194368. png_free(png_ptr, tmp);
  194369. png_memcpy(text + text_size, png_ptr->zbuf,
  194370. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194371. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194372. *(text + text_size) = 0x00;
  194373. }
  194374. if (ret == Z_STREAM_END)
  194375. break;
  194376. else
  194377. {
  194378. png_ptr->zstream.next_out = png_ptr->zbuf;
  194379. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194380. }
  194381. }
  194382. }
  194383. if (ret != Z_STREAM_END)
  194384. {
  194385. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194386. char umsg[52];
  194387. if (ret == Z_BUF_ERROR)
  194388. png_snprintf(umsg, 52,
  194389. "Buffer error in compressed datastream in %s chunk",
  194390. png_ptr->chunk_name);
  194391. else if (ret == Z_DATA_ERROR)
  194392. png_snprintf(umsg, 52,
  194393. "Data error in compressed datastream in %s chunk",
  194394. png_ptr->chunk_name);
  194395. else
  194396. png_snprintf(umsg, 52,
  194397. "Incomplete compressed datastream in %s chunk",
  194398. png_ptr->chunk_name);
  194399. png_warning(png_ptr, umsg);
  194400. #else
  194401. png_warning(png_ptr,
  194402. "Incomplete compressed datastream in chunk other than IDAT");
  194403. #endif
  194404. text_size=prefix_size;
  194405. if (text == NULL)
  194406. {
  194407. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194408. if (text == NULL)
  194409. {
  194410. png_free(png_ptr, chunkdata);
  194411. png_error(png_ptr,"Not enough memory for text.");
  194412. }
  194413. png_memcpy(text, chunkdata, prefix_size);
  194414. }
  194415. *(text + text_size) = 0x00;
  194416. }
  194417. inflateReset(&png_ptr->zstream);
  194418. png_ptr->zstream.avail_in = 0;
  194419. png_free(png_ptr, chunkdata);
  194420. chunkdata = text;
  194421. *newlength=text_size;
  194422. }
  194423. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194424. {
  194425. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194426. char umsg[50];
  194427. png_snprintf(umsg, 50,
  194428. "Unknown zTXt compression type %d", comp_type);
  194429. png_warning(png_ptr, umsg);
  194430. #else
  194431. png_warning(png_ptr, "Unknown zTXt compression type");
  194432. #endif
  194433. *(chunkdata + prefix_size) = 0x00;
  194434. *newlength=prefix_size;
  194435. }
  194436. return chunkdata;
  194437. }
  194438. #endif
  194439. /* read and check the IDHR chunk */
  194440. void /* PRIVATE */
  194441. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194442. {
  194443. png_byte buf[13];
  194444. png_uint_32 width, height;
  194445. int bit_depth, color_type, compression_type, filter_type;
  194446. int interlace_type;
  194447. png_debug(1, "in png_handle_IHDR\n");
  194448. if (png_ptr->mode & PNG_HAVE_IHDR)
  194449. png_error(png_ptr, "Out of place IHDR");
  194450. /* check the length */
  194451. if (length != 13)
  194452. png_error(png_ptr, "Invalid IHDR chunk");
  194453. png_ptr->mode |= PNG_HAVE_IHDR;
  194454. png_crc_read(png_ptr, buf, 13);
  194455. png_crc_finish(png_ptr, 0);
  194456. width = png_get_uint_31(png_ptr, buf);
  194457. height = png_get_uint_31(png_ptr, buf + 4);
  194458. bit_depth = buf[8];
  194459. color_type = buf[9];
  194460. compression_type = buf[10];
  194461. filter_type = buf[11];
  194462. interlace_type = buf[12];
  194463. /* set internal variables */
  194464. png_ptr->width = width;
  194465. png_ptr->height = height;
  194466. png_ptr->bit_depth = (png_byte)bit_depth;
  194467. png_ptr->interlaced = (png_byte)interlace_type;
  194468. png_ptr->color_type = (png_byte)color_type;
  194469. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194470. png_ptr->filter_type = (png_byte)filter_type;
  194471. #endif
  194472. png_ptr->compression_type = (png_byte)compression_type;
  194473. /* find number of channels */
  194474. switch (png_ptr->color_type)
  194475. {
  194476. case PNG_COLOR_TYPE_GRAY:
  194477. case PNG_COLOR_TYPE_PALETTE:
  194478. png_ptr->channels = 1;
  194479. break;
  194480. case PNG_COLOR_TYPE_RGB:
  194481. png_ptr->channels = 3;
  194482. break;
  194483. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194484. png_ptr->channels = 2;
  194485. break;
  194486. case PNG_COLOR_TYPE_RGB_ALPHA:
  194487. png_ptr->channels = 4;
  194488. break;
  194489. }
  194490. /* set up other useful info */
  194491. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194492. png_ptr->channels);
  194493. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194494. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194495. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194496. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194497. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194498. color_type, interlace_type, compression_type, filter_type);
  194499. }
  194500. /* read and check the palette */
  194501. void /* PRIVATE */
  194502. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194503. {
  194504. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194505. int num, i;
  194506. #ifndef PNG_NO_POINTER_INDEXING
  194507. png_colorp pal_ptr;
  194508. #endif
  194509. png_debug(1, "in png_handle_PLTE\n");
  194510. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194511. png_error(png_ptr, "Missing IHDR before PLTE");
  194512. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194513. {
  194514. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194515. png_crc_finish(png_ptr, length);
  194516. return;
  194517. }
  194518. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194519. png_error(png_ptr, "Duplicate PLTE chunk");
  194520. png_ptr->mode |= PNG_HAVE_PLTE;
  194521. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194522. {
  194523. png_warning(png_ptr,
  194524. "Ignoring PLTE chunk in grayscale PNG");
  194525. png_crc_finish(png_ptr, length);
  194526. return;
  194527. }
  194528. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194529. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194530. {
  194531. png_crc_finish(png_ptr, length);
  194532. return;
  194533. }
  194534. #endif
  194535. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194536. {
  194537. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194538. {
  194539. png_warning(png_ptr, "Invalid palette chunk");
  194540. png_crc_finish(png_ptr, length);
  194541. return;
  194542. }
  194543. else
  194544. {
  194545. png_error(png_ptr, "Invalid palette chunk");
  194546. }
  194547. }
  194548. num = (int)length / 3;
  194549. #ifndef PNG_NO_POINTER_INDEXING
  194550. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194551. {
  194552. png_byte buf[3];
  194553. png_crc_read(png_ptr, buf, 3);
  194554. pal_ptr->red = buf[0];
  194555. pal_ptr->green = buf[1];
  194556. pal_ptr->blue = buf[2];
  194557. }
  194558. #else
  194559. for (i = 0; i < num; i++)
  194560. {
  194561. png_byte buf[3];
  194562. png_crc_read(png_ptr, buf, 3);
  194563. /* don't depend upon png_color being any order */
  194564. palette[i].red = buf[0];
  194565. palette[i].green = buf[1];
  194566. palette[i].blue = buf[2];
  194567. }
  194568. #endif
  194569. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194570. whatever the normal CRC configuration tells us. However, if we
  194571. have an RGB image, the PLTE can be considered ancillary, so
  194572. we will act as though it is. */
  194573. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194574. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194575. #endif
  194576. {
  194577. png_crc_finish(png_ptr, 0);
  194578. }
  194579. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194580. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194581. {
  194582. /* If we don't want to use the data from an ancillary chunk,
  194583. we have two options: an error abort, or a warning and we
  194584. ignore the data in this chunk (which should be OK, since
  194585. it's considered ancillary for a RGB or RGBA image). */
  194586. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194587. {
  194588. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194589. {
  194590. png_chunk_error(png_ptr, "CRC error");
  194591. }
  194592. else
  194593. {
  194594. png_chunk_warning(png_ptr, "CRC error");
  194595. return;
  194596. }
  194597. }
  194598. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194599. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194600. {
  194601. png_chunk_warning(png_ptr, "CRC error");
  194602. }
  194603. }
  194604. #endif
  194605. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194606. #if defined(PNG_READ_tRNS_SUPPORTED)
  194607. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194608. {
  194609. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194610. {
  194611. if (png_ptr->num_trans > (png_uint_16)num)
  194612. {
  194613. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194614. png_ptr->num_trans = (png_uint_16)num;
  194615. }
  194616. if (info_ptr->num_trans > (png_uint_16)num)
  194617. {
  194618. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194619. info_ptr->num_trans = (png_uint_16)num;
  194620. }
  194621. }
  194622. }
  194623. #endif
  194624. }
  194625. void /* PRIVATE */
  194626. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194627. {
  194628. png_debug(1, "in png_handle_IEND\n");
  194629. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194630. {
  194631. png_error(png_ptr, "No image in file");
  194632. }
  194633. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194634. if (length != 0)
  194635. {
  194636. png_warning(png_ptr, "Incorrect IEND chunk length");
  194637. }
  194638. png_crc_finish(png_ptr, length);
  194639. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194640. }
  194641. #if defined(PNG_READ_gAMA_SUPPORTED)
  194642. void /* PRIVATE */
  194643. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194644. {
  194645. png_fixed_point igamma;
  194646. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194647. float file_gamma;
  194648. #endif
  194649. png_byte buf[4];
  194650. png_debug(1, "in png_handle_gAMA\n");
  194651. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194652. png_error(png_ptr, "Missing IHDR before gAMA");
  194653. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194654. {
  194655. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194656. png_crc_finish(png_ptr, length);
  194657. return;
  194658. }
  194659. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194660. /* Should be an error, but we can cope with it */
  194661. png_warning(png_ptr, "Out of place gAMA chunk");
  194662. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194663. #if defined(PNG_READ_sRGB_SUPPORTED)
  194664. && !(info_ptr->valid & PNG_INFO_sRGB)
  194665. #endif
  194666. )
  194667. {
  194668. png_warning(png_ptr, "Duplicate gAMA chunk");
  194669. png_crc_finish(png_ptr, length);
  194670. return;
  194671. }
  194672. if (length != 4)
  194673. {
  194674. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194675. png_crc_finish(png_ptr, length);
  194676. return;
  194677. }
  194678. png_crc_read(png_ptr, buf, 4);
  194679. if (png_crc_finish(png_ptr, 0))
  194680. return;
  194681. igamma = (png_fixed_point)png_get_uint_32(buf);
  194682. /* check for zero gamma */
  194683. if (igamma == 0)
  194684. {
  194685. png_warning(png_ptr,
  194686. "Ignoring gAMA chunk with gamma=0");
  194687. return;
  194688. }
  194689. #if defined(PNG_READ_sRGB_SUPPORTED)
  194690. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194691. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194692. {
  194693. png_warning(png_ptr,
  194694. "Ignoring incorrect gAMA value when sRGB is also present");
  194695. #ifndef PNG_NO_CONSOLE_IO
  194696. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194697. #endif
  194698. return;
  194699. }
  194700. #endif /* PNG_READ_sRGB_SUPPORTED */
  194701. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194702. file_gamma = (float)igamma / (float)100000.0;
  194703. # ifdef PNG_READ_GAMMA_SUPPORTED
  194704. png_ptr->gamma = file_gamma;
  194705. # endif
  194706. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194707. #endif
  194708. #ifdef PNG_FIXED_POINT_SUPPORTED
  194709. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194710. #endif
  194711. }
  194712. #endif
  194713. #if defined(PNG_READ_sBIT_SUPPORTED)
  194714. void /* PRIVATE */
  194715. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194716. {
  194717. png_size_t truelen;
  194718. png_byte buf[4];
  194719. png_debug(1, "in png_handle_sBIT\n");
  194720. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194721. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194722. png_error(png_ptr, "Missing IHDR before sBIT");
  194723. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194724. {
  194725. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194726. png_crc_finish(png_ptr, length);
  194727. return;
  194728. }
  194729. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194730. {
  194731. /* Should be an error, but we can cope with it */
  194732. png_warning(png_ptr, "Out of place sBIT chunk");
  194733. }
  194734. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194735. {
  194736. png_warning(png_ptr, "Duplicate sBIT chunk");
  194737. png_crc_finish(png_ptr, length);
  194738. return;
  194739. }
  194740. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194741. truelen = 3;
  194742. else
  194743. truelen = (png_size_t)png_ptr->channels;
  194744. if (length != truelen || length > 4)
  194745. {
  194746. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194747. png_crc_finish(png_ptr, length);
  194748. return;
  194749. }
  194750. png_crc_read(png_ptr, buf, truelen);
  194751. if (png_crc_finish(png_ptr, 0))
  194752. return;
  194753. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194754. {
  194755. png_ptr->sig_bit.red = buf[0];
  194756. png_ptr->sig_bit.green = buf[1];
  194757. png_ptr->sig_bit.blue = buf[2];
  194758. png_ptr->sig_bit.alpha = buf[3];
  194759. }
  194760. else
  194761. {
  194762. png_ptr->sig_bit.gray = buf[0];
  194763. png_ptr->sig_bit.red = buf[0];
  194764. png_ptr->sig_bit.green = buf[0];
  194765. png_ptr->sig_bit.blue = buf[0];
  194766. png_ptr->sig_bit.alpha = buf[1];
  194767. }
  194768. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194769. }
  194770. #endif
  194771. #if defined(PNG_READ_cHRM_SUPPORTED)
  194772. void /* PRIVATE */
  194773. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194774. {
  194775. png_byte buf[4];
  194776. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194777. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194778. #endif
  194779. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194780. int_y_green, int_x_blue, int_y_blue;
  194781. png_uint_32 uint_x, uint_y;
  194782. png_debug(1, "in png_handle_cHRM\n");
  194783. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194784. png_error(png_ptr, "Missing IHDR before cHRM");
  194785. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194786. {
  194787. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194788. png_crc_finish(png_ptr, length);
  194789. return;
  194790. }
  194791. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194792. /* Should be an error, but we can cope with it */
  194793. png_warning(png_ptr, "Missing PLTE before cHRM");
  194794. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194795. #if defined(PNG_READ_sRGB_SUPPORTED)
  194796. && !(info_ptr->valid & PNG_INFO_sRGB)
  194797. #endif
  194798. )
  194799. {
  194800. png_warning(png_ptr, "Duplicate cHRM chunk");
  194801. png_crc_finish(png_ptr, length);
  194802. return;
  194803. }
  194804. if (length != 32)
  194805. {
  194806. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194807. png_crc_finish(png_ptr, length);
  194808. return;
  194809. }
  194810. png_crc_read(png_ptr, buf, 4);
  194811. uint_x = png_get_uint_32(buf);
  194812. png_crc_read(png_ptr, buf, 4);
  194813. uint_y = png_get_uint_32(buf);
  194814. if (uint_x > 80000L || uint_y > 80000L ||
  194815. uint_x + uint_y > 100000L)
  194816. {
  194817. png_warning(png_ptr, "Invalid cHRM white point");
  194818. png_crc_finish(png_ptr, 24);
  194819. return;
  194820. }
  194821. int_x_white = (png_fixed_point)uint_x;
  194822. int_y_white = (png_fixed_point)uint_y;
  194823. png_crc_read(png_ptr, buf, 4);
  194824. uint_x = png_get_uint_32(buf);
  194825. png_crc_read(png_ptr, buf, 4);
  194826. uint_y = png_get_uint_32(buf);
  194827. if (uint_x + uint_y > 100000L)
  194828. {
  194829. png_warning(png_ptr, "Invalid cHRM red point");
  194830. png_crc_finish(png_ptr, 16);
  194831. return;
  194832. }
  194833. int_x_red = (png_fixed_point)uint_x;
  194834. int_y_red = (png_fixed_point)uint_y;
  194835. png_crc_read(png_ptr, buf, 4);
  194836. uint_x = png_get_uint_32(buf);
  194837. png_crc_read(png_ptr, buf, 4);
  194838. uint_y = png_get_uint_32(buf);
  194839. if (uint_x + uint_y > 100000L)
  194840. {
  194841. png_warning(png_ptr, "Invalid cHRM green point");
  194842. png_crc_finish(png_ptr, 8);
  194843. return;
  194844. }
  194845. int_x_green = (png_fixed_point)uint_x;
  194846. int_y_green = (png_fixed_point)uint_y;
  194847. png_crc_read(png_ptr, buf, 4);
  194848. uint_x = png_get_uint_32(buf);
  194849. png_crc_read(png_ptr, buf, 4);
  194850. uint_y = png_get_uint_32(buf);
  194851. if (uint_x + uint_y > 100000L)
  194852. {
  194853. png_warning(png_ptr, "Invalid cHRM blue point");
  194854. png_crc_finish(png_ptr, 0);
  194855. return;
  194856. }
  194857. int_x_blue = (png_fixed_point)uint_x;
  194858. int_y_blue = (png_fixed_point)uint_y;
  194859. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194860. white_x = (float)int_x_white / (float)100000.0;
  194861. white_y = (float)int_y_white / (float)100000.0;
  194862. red_x = (float)int_x_red / (float)100000.0;
  194863. red_y = (float)int_y_red / (float)100000.0;
  194864. green_x = (float)int_x_green / (float)100000.0;
  194865. green_y = (float)int_y_green / (float)100000.0;
  194866. blue_x = (float)int_x_blue / (float)100000.0;
  194867. blue_y = (float)int_y_blue / (float)100000.0;
  194868. #endif
  194869. #if defined(PNG_READ_sRGB_SUPPORTED)
  194870. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194871. {
  194872. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194873. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194874. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194875. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194876. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194877. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194878. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194879. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194880. {
  194881. png_warning(png_ptr,
  194882. "Ignoring incorrect cHRM value when sRGB is also present");
  194883. #ifndef PNG_NO_CONSOLE_IO
  194884. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194885. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194886. white_x, white_y, red_x, red_y);
  194887. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194888. green_x, green_y, blue_x, blue_y);
  194889. #else
  194890. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194891. int_x_white, int_y_white, int_x_red, int_y_red);
  194892. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194893. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194894. #endif
  194895. #endif /* PNG_NO_CONSOLE_IO */
  194896. }
  194897. png_crc_finish(png_ptr, 0);
  194898. return;
  194899. }
  194900. #endif /* PNG_READ_sRGB_SUPPORTED */
  194901. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194902. png_set_cHRM(png_ptr, info_ptr,
  194903. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194904. #endif
  194905. #ifdef PNG_FIXED_POINT_SUPPORTED
  194906. png_set_cHRM_fixed(png_ptr, info_ptr,
  194907. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194908. int_y_green, int_x_blue, int_y_blue);
  194909. #endif
  194910. if (png_crc_finish(png_ptr, 0))
  194911. return;
  194912. }
  194913. #endif
  194914. #if defined(PNG_READ_sRGB_SUPPORTED)
  194915. void /* PRIVATE */
  194916. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194917. {
  194918. int intent;
  194919. png_byte buf[1];
  194920. png_debug(1, "in png_handle_sRGB\n");
  194921. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194922. png_error(png_ptr, "Missing IHDR before sRGB");
  194923. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194924. {
  194925. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194926. png_crc_finish(png_ptr, length);
  194927. return;
  194928. }
  194929. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194930. /* Should be an error, but we can cope with it */
  194931. png_warning(png_ptr, "Out of place sRGB chunk");
  194932. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194933. {
  194934. png_warning(png_ptr, "Duplicate sRGB chunk");
  194935. png_crc_finish(png_ptr, length);
  194936. return;
  194937. }
  194938. if (length != 1)
  194939. {
  194940. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194941. png_crc_finish(png_ptr, length);
  194942. return;
  194943. }
  194944. png_crc_read(png_ptr, buf, 1);
  194945. if (png_crc_finish(png_ptr, 0))
  194946. return;
  194947. intent = buf[0];
  194948. /* check for bad intent */
  194949. if (intent >= PNG_sRGB_INTENT_LAST)
  194950. {
  194951. png_warning(png_ptr, "Unknown sRGB intent");
  194952. return;
  194953. }
  194954. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194955. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194956. {
  194957. png_fixed_point igamma;
  194958. #ifdef PNG_FIXED_POINT_SUPPORTED
  194959. igamma=info_ptr->int_gamma;
  194960. #else
  194961. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194962. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194963. # endif
  194964. #endif
  194965. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194966. {
  194967. png_warning(png_ptr,
  194968. "Ignoring incorrect gAMA value when sRGB is also present");
  194969. #ifndef PNG_NO_CONSOLE_IO
  194970. # ifdef PNG_FIXED_POINT_SUPPORTED
  194971. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194972. # else
  194973. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194974. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194975. # endif
  194976. # endif
  194977. #endif
  194978. }
  194979. }
  194980. #endif /* PNG_READ_gAMA_SUPPORTED */
  194981. #ifdef PNG_READ_cHRM_SUPPORTED
  194982. #ifdef PNG_FIXED_POINT_SUPPORTED
  194983. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194984. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194985. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194986. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194987. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194988. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194989. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194990. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194991. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194992. {
  194993. png_warning(png_ptr,
  194994. "Ignoring incorrect cHRM value when sRGB is also present");
  194995. }
  194996. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194997. #endif /* PNG_READ_cHRM_SUPPORTED */
  194998. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194999. }
  195000. #endif /* PNG_READ_sRGB_SUPPORTED */
  195001. #if defined(PNG_READ_iCCP_SUPPORTED)
  195002. void /* PRIVATE */
  195003. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195004. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195005. {
  195006. png_charp chunkdata;
  195007. png_byte compression_type;
  195008. png_bytep pC;
  195009. png_charp profile;
  195010. png_uint_32 skip = 0;
  195011. png_uint_32 profile_size, profile_length;
  195012. png_size_t slength, prefix_length, data_length;
  195013. png_debug(1, "in png_handle_iCCP\n");
  195014. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195015. png_error(png_ptr, "Missing IHDR before iCCP");
  195016. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195017. {
  195018. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195019. png_crc_finish(png_ptr, length);
  195020. return;
  195021. }
  195022. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195023. /* Should be an error, but we can cope with it */
  195024. png_warning(png_ptr, "Out of place iCCP chunk");
  195025. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195026. {
  195027. png_warning(png_ptr, "Duplicate iCCP chunk");
  195028. png_crc_finish(png_ptr, length);
  195029. return;
  195030. }
  195031. #ifdef PNG_MAX_MALLOC_64K
  195032. if (length > (png_uint_32)65535L)
  195033. {
  195034. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195035. skip = length - (png_uint_32)65535L;
  195036. length = (png_uint_32)65535L;
  195037. }
  195038. #endif
  195039. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195040. slength = (png_size_t)length;
  195041. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195042. if (png_crc_finish(png_ptr, skip))
  195043. {
  195044. png_free(png_ptr, chunkdata);
  195045. return;
  195046. }
  195047. chunkdata[slength] = 0x00;
  195048. for (profile = chunkdata; *profile; profile++)
  195049. /* empty loop to find end of name */ ;
  195050. ++profile;
  195051. /* there should be at least one zero (the compression type byte)
  195052. following the separator, and we should be on it */
  195053. if ( profile >= chunkdata + slength - 1)
  195054. {
  195055. png_free(png_ptr, chunkdata);
  195056. png_warning(png_ptr, "Malformed iCCP chunk");
  195057. return;
  195058. }
  195059. /* compression_type should always be zero */
  195060. compression_type = *profile++;
  195061. if (compression_type)
  195062. {
  195063. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195064. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195065. wrote nonzero) */
  195066. }
  195067. prefix_length = profile - chunkdata;
  195068. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195069. slength, prefix_length, &data_length);
  195070. profile_length = data_length - prefix_length;
  195071. if ( prefix_length > data_length || profile_length < 4)
  195072. {
  195073. png_free(png_ptr, chunkdata);
  195074. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195075. return;
  195076. }
  195077. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195078. pC = (png_bytep)(chunkdata+prefix_length);
  195079. profile_size = ((*(pC ))<<24) |
  195080. ((*(pC+1))<<16) |
  195081. ((*(pC+2))<< 8) |
  195082. ((*(pC+3)) );
  195083. if(profile_size < profile_length)
  195084. profile_length = profile_size;
  195085. if(profile_size > profile_length)
  195086. {
  195087. png_free(png_ptr, chunkdata);
  195088. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195089. return;
  195090. }
  195091. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195092. chunkdata + prefix_length, profile_length);
  195093. png_free(png_ptr, chunkdata);
  195094. }
  195095. #endif /* PNG_READ_iCCP_SUPPORTED */
  195096. #if defined(PNG_READ_sPLT_SUPPORTED)
  195097. void /* PRIVATE */
  195098. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195099. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195100. {
  195101. png_bytep chunkdata;
  195102. png_bytep entry_start;
  195103. png_sPLT_t new_palette;
  195104. #ifdef PNG_NO_POINTER_INDEXING
  195105. png_sPLT_entryp pp;
  195106. #endif
  195107. int data_length, entry_size, i;
  195108. png_uint_32 skip = 0;
  195109. png_size_t slength;
  195110. png_debug(1, "in png_handle_sPLT\n");
  195111. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195112. png_error(png_ptr, "Missing IHDR before sPLT");
  195113. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195114. {
  195115. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195116. png_crc_finish(png_ptr, length);
  195117. return;
  195118. }
  195119. #ifdef PNG_MAX_MALLOC_64K
  195120. if (length > (png_uint_32)65535L)
  195121. {
  195122. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195123. skip = length - (png_uint_32)65535L;
  195124. length = (png_uint_32)65535L;
  195125. }
  195126. #endif
  195127. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195128. slength = (png_size_t)length;
  195129. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195130. if (png_crc_finish(png_ptr, skip))
  195131. {
  195132. png_free(png_ptr, chunkdata);
  195133. return;
  195134. }
  195135. chunkdata[slength] = 0x00;
  195136. for (entry_start = chunkdata; *entry_start; entry_start++)
  195137. /* empty loop to find end of name */ ;
  195138. ++entry_start;
  195139. /* a sample depth should follow the separator, and we should be on it */
  195140. if (entry_start > chunkdata + slength - 2)
  195141. {
  195142. png_free(png_ptr, chunkdata);
  195143. png_warning(png_ptr, "malformed sPLT chunk");
  195144. return;
  195145. }
  195146. new_palette.depth = *entry_start++;
  195147. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195148. data_length = (slength - (entry_start - chunkdata));
  195149. /* integrity-check the data length */
  195150. if (data_length % entry_size)
  195151. {
  195152. png_free(png_ptr, chunkdata);
  195153. png_warning(png_ptr, "sPLT chunk has bad length");
  195154. return;
  195155. }
  195156. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195157. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195158. png_sizeof(png_sPLT_entry)))
  195159. {
  195160. png_warning(png_ptr, "sPLT chunk too long");
  195161. return;
  195162. }
  195163. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195164. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195165. if (new_palette.entries == NULL)
  195166. {
  195167. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195168. return;
  195169. }
  195170. #ifndef PNG_NO_POINTER_INDEXING
  195171. for (i = 0; i < new_palette.nentries; i++)
  195172. {
  195173. png_sPLT_entryp pp = new_palette.entries + i;
  195174. if (new_palette.depth == 8)
  195175. {
  195176. pp->red = *entry_start++;
  195177. pp->green = *entry_start++;
  195178. pp->blue = *entry_start++;
  195179. pp->alpha = *entry_start++;
  195180. }
  195181. else
  195182. {
  195183. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195184. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195185. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195186. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195187. }
  195188. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195189. }
  195190. #else
  195191. pp = new_palette.entries;
  195192. for (i = 0; i < new_palette.nentries; i++)
  195193. {
  195194. if (new_palette.depth == 8)
  195195. {
  195196. pp[i].red = *entry_start++;
  195197. pp[i].green = *entry_start++;
  195198. pp[i].blue = *entry_start++;
  195199. pp[i].alpha = *entry_start++;
  195200. }
  195201. else
  195202. {
  195203. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195204. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195205. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195206. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195207. }
  195208. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195209. }
  195210. #endif
  195211. /* discard all chunk data except the name and stash that */
  195212. new_palette.name = (png_charp)chunkdata;
  195213. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195214. png_free(png_ptr, chunkdata);
  195215. png_free(png_ptr, new_palette.entries);
  195216. }
  195217. #endif /* PNG_READ_sPLT_SUPPORTED */
  195218. #if defined(PNG_READ_tRNS_SUPPORTED)
  195219. void /* PRIVATE */
  195220. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195221. {
  195222. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195223. int bit_mask;
  195224. png_debug(1, "in png_handle_tRNS\n");
  195225. /* For non-indexed color, mask off any bits in the tRNS value that
  195226. * exceed the bit depth. Some creators were writing extra bits there.
  195227. * This is not needed for indexed color. */
  195228. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195229. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195230. png_error(png_ptr, "Missing IHDR before tRNS");
  195231. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195232. {
  195233. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195234. png_crc_finish(png_ptr, length);
  195235. return;
  195236. }
  195237. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195238. {
  195239. png_warning(png_ptr, "Duplicate tRNS chunk");
  195240. png_crc_finish(png_ptr, length);
  195241. return;
  195242. }
  195243. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195244. {
  195245. png_byte buf[2];
  195246. if (length != 2)
  195247. {
  195248. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195249. png_crc_finish(png_ptr, length);
  195250. return;
  195251. }
  195252. png_crc_read(png_ptr, buf, 2);
  195253. png_ptr->num_trans = 1;
  195254. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195255. }
  195256. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195257. {
  195258. png_byte buf[6];
  195259. if (length != 6)
  195260. {
  195261. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195262. png_crc_finish(png_ptr, length);
  195263. return;
  195264. }
  195265. png_crc_read(png_ptr, buf, (png_size_t)length);
  195266. png_ptr->num_trans = 1;
  195267. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195268. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195269. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195270. }
  195271. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195272. {
  195273. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195274. {
  195275. /* Should be an error, but we can cope with it. */
  195276. png_warning(png_ptr, "Missing PLTE before tRNS");
  195277. }
  195278. if (length > (png_uint_32)png_ptr->num_palette ||
  195279. length > PNG_MAX_PALETTE_LENGTH)
  195280. {
  195281. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195282. png_crc_finish(png_ptr, length);
  195283. return;
  195284. }
  195285. if (length == 0)
  195286. {
  195287. png_warning(png_ptr, "Zero length tRNS chunk");
  195288. png_crc_finish(png_ptr, length);
  195289. return;
  195290. }
  195291. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195292. png_ptr->num_trans = (png_uint_16)length;
  195293. }
  195294. else
  195295. {
  195296. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195297. png_crc_finish(png_ptr, length);
  195298. return;
  195299. }
  195300. if (png_crc_finish(png_ptr, 0))
  195301. {
  195302. png_ptr->num_trans = 0;
  195303. return;
  195304. }
  195305. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195306. &(png_ptr->trans_values));
  195307. }
  195308. #endif
  195309. #if defined(PNG_READ_bKGD_SUPPORTED)
  195310. void /* PRIVATE */
  195311. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195312. {
  195313. png_size_t truelen;
  195314. png_byte buf[6];
  195315. png_debug(1, "in png_handle_bKGD\n");
  195316. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195317. png_error(png_ptr, "Missing IHDR before bKGD");
  195318. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195319. {
  195320. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195321. png_crc_finish(png_ptr, length);
  195322. return;
  195323. }
  195324. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195325. !(png_ptr->mode & PNG_HAVE_PLTE))
  195326. {
  195327. png_warning(png_ptr, "Missing PLTE before bKGD");
  195328. png_crc_finish(png_ptr, length);
  195329. return;
  195330. }
  195331. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195332. {
  195333. png_warning(png_ptr, "Duplicate bKGD chunk");
  195334. png_crc_finish(png_ptr, length);
  195335. return;
  195336. }
  195337. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195338. truelen = 1;
  195339. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195340. truelen = 6;
  195341. else
  195342. truelen = 2;
  195343. if (length != truelen)
  195344. {
  195345. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195346. png_crc_finish(png_ptr, length);
  195347. return;
  195348. }
  195349. png_crc_read(png_ptr, buf, truelen);
  195350. if (png_crc_finish(png_ptr, 0))
  195351. return;
  195352. /* We convert the index value into RGB components so that we can allow
  195353. * arbitrary RGB values for background when we have transparency, and
  195354. * so it is easy to determine the RGB values of the background color
  195355. * from the info_ptr struct. */
  195356. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195357. {
  195358. png_ptr->background.index = buf[0];
  195359. if(info_ptr->num_palette)
  195360. {
  195361. if(buf[0] > info_ptr->num_palette)
  195362. {
  195363. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195364. return;
  195365. }
  195366. png_ptr->background.red =
  195367. (png_uint_16)png_ptr->palette[buf[0]].red;
  195368. png_ptr->background.green =
  195369. (png_uint_16)png_ptr->palette[buf[0]].green;
  195370. png_ptr->background.blue =
  195371. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195372. }
  195373. }
  195374. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195375. {
  195376. png_ptr->background.red =
  195377. png_ptr->background.green =
  195378. png_ptr->background.blue =
  195379. png_ptr->background.gray = png_get_uint_16(buf);
  195380. }
  195381. else
  195382. {
  195383. png_ptr->background.red = png_get_uint_16(buf);
  195384. png_ptr->background.green = png_get_uint_16(buf + 2);
  195385. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195386. }
  195387. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195388. }
  195389. #endif
  195390. #if defined(PNG_READ_hIST_SUPPORTED)
  195391. void /* PRIVATE */
  195392. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195393. {
  195394. unsigned int num, i;
  195395. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195396. png_debug(1, "in png_handle_hIST\n");
  195397. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195398. png_error(png_ptr, "Missing IHDR before hIST");
  195399. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195400. {
  195401. png_warning(png_ptr, "Invalid hIST after IDAT");
  195402. png_crc_finish(png_ptr, length);
  195403. return;
  195404. }
  195405. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195406. {
  195407. png_warning(png_ptr, "Missing PLTE before hIST");
  195408. png_crc_finish(png_ptr, length);
  195409. return;
  195410. }
  195411. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195412. {
  195413. png_warning(png_ptr, "Duplicate hIST chunk");
  195414. png_crc_finish(png_ptr, length);
  195415. return;
  195416. }
  195417. num = length / 2 ;
  195418. if (num != (unsigned int) png_ptr->num_palette || num >
  195419. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195420. {
  195421. png_warning(png_ptr, "Incorrect hIST chunk length");
  195422. png_crc_finish(png_ptr, length);
  195423. return;
  195424. }
  195425. for (i = 0; i < num; i++)
  195426. {
  195427. png_byte buf[2];
  195428. png_crc_read(png_ptr, buf, 2);
  195429. readbuf[i] = png_get_uint_16(buf);
  195430. }
  195431. if (png_crc_finish(png_ptr, 0))
  195432. return;
  195433. png_set_hIST(png_ptr, info_ptr, readbuf);
  195434. }
  195435. #endif
  195436. #if defined(PNG_READ_pHYs_SUPPORTED)
  195437. void /* PRIVATE */
  195438. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195439. {
  195440. png_byte buf[9];
  195441. png_uint_32 res_x, res_y;
  195442. int unit_type;
  195443. png_debug(1, "in png_handle_pHYs\n");
  195444. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195445. png_error(png_ptr, "Missing IHDR before pHYs");
  195446. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195447. {
  195448. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195449. png_crc_finish(png_ptr, length);
  195450. return;
  195451. }
  195452. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195453. {
  195454. png_warning(png_ptr, "Duplicate pHYs chunk");
  195455. png_crc_finish(png_ptr, length);
  195456. return;
  195457. }
  195458. if (length != 9)
  195459. {
  195460. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195461. png_crc_finish(png_ptr, length);
  195462. return;
  195463. }
  195464. png_crc_read(png_ptr, buf, 9);
  195465. if (png_crc_finish(png_ptr, 0))
  195466. return;
  195467. res_x = png_get_uint_32(buf);
  195468. res_y = png_get_uint_32(buf + 4);
  195469. unit_type = buf[8];
  195470. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195471. }
  195472. #endif
  195473. #if defined(PNG_READ_oFFs_SUPPORTED)
  195474. void /* PRIVATE */
  195475. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195476. {
  195477. png_byte buf[9];
  195478. png_int_32 offset_x, offset_y;
  195479. int unit_type;
  195480. png_debug(1, "in png_handle_oFFs\n");
  195481. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195482. png_error(png_ptr, "Missing IHDR before oFFs");
  195483. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195484. {
  195485. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195486. png_crc_finish(png_ptr, length);
  195487. return;
  195488. }
  195489. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195490. {
  195491. png_warning(png_ptr, "Duplicate oFFs chunk");
  195492. png_crc_finish(png_ptr, length);
  195493. return;
  195494. }
  195495. if (length != 9)
  195496. {
  195497. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195498. png_crc_finish(png_ptr, length);
  195499. return;
  195500. }
  195501. png_crc_read(png_ptr, buf, 9);
  195502. if (png_crc_finish(png_ptr, 0))
  195503. return;
  195504. offset_x = png_get_int_32(buf);
  195505. offset_y = png_get_int_32(buf + 4);
  195506. unit_type = buf[8];
  195507. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195508. }
  195509. #endif
  195510. #if defined(PNG_READ_pCAL_SUPPORTED)
  195511. /* read the pCAL chunk (described in the PNG Extensions document) */
  195512. void /* PRIVATE */
  195513. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195514. {
  195515. png_charp purpose;
  195516. png_int_32 X0, X1;
  195517. png_byte type, nparams;
  195518. png_charp buf, units, endptr;
  195519. png_charpp params;
  195520. png_size_t slength;
  195521. int i;
  195522. png_debug(1, "in png_handle_pCAL\n");
  195523. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195524. png_error(png_ptr, "Missing IHDR before pCAL");
  195525. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195526. {
  195527. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195528. png_crc_finish(png_ptr, length);
  195529. return;
  195530. }
  195531. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195532. {
  195533. png_warning(png_ptr, "Duplicate pCAL chunk");
  195534. png_crc_finish(png_ptr, length);
  195535. return;
  195536. }
  195537. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195538. length + 1);
  195539. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195540. if (purpose == NULL)
  195541. {
  195542. png_warning(png_ptr, "No memory for pCAL purpose.");
  195543. return;
  195544. }
  195545. slength = (png_size_t)length;
  195546. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195547. if (png_crc_finish(png_ptr, 0))
  195548. {
  195549. png_free(png_ptr, purpose);
  195550. return;
  195551. }
  195552. purpose[slength] = 0x00; /* null terminate the last string */
  195553. png_debug(3, "Finding end of pCAL purpose string\n");
  195554. for (buf = purpose; *buf; buf++)
  195555. /* empty loop */ ;
  195556. endptr = purpose + slength;
  195557. /* We need to have at least 12 bytes after the purpose string
  195558. in order to get the parameter information. */
  195559. if (endptr <= buf + 12)
  195560. {
  195561. png_warning(png_ptr, "Invalid pCAL data");
  195562. png_free(png_ptr, purpose);
  195563. return;
  195564. }
  195565. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195566. X0 = png_get_int_32((png_bytep)buf+1);
  195567. X1 = png_get_int_32((png_bytep)buf+5);
  195568. type = buf[9];
  195569. nparams = buf[10];
  195570. units = buf + 11;
  195571. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195572. /* Check that we have the right number of parameters for known
  195573. equation types. */
  195574. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195575. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195576. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195577. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195578. {
  195579. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195580. png_free(png_ptr, purpose);
  195581. return;
  195582. }
  195583. else if (type >= PNG_EQUATION_LAST)
  195584. {
  195585. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195586. }
  195587. for (buf = units; *buf; buf++)
  195588. /* Empty loop to move past the units string. */ ;
  195589. png_debug(3, "Allocating pCAL parameters array\n");
  195590. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195591. *png_sizeof(png_charp))) ;
  195592. if (params == NULL)
  195593. {
  195594. png_free(png_ptr, purpose);
  195595. png_warning(png_ptr, "No memory for pCAL params.");
  195596. return;
  195597. }
  195598. /* Get pointers to the start of each parameter string. */
  195599. for (i = 0; i < (int)nparams; i++)
  195600. {
  195601. buf++; /* Skip the null string terminator from previous parameter. */
  195602. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195603. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195604. /* Empty loop to move past each parameter string */ ;
  195605. /* Make sure we haven't run out of data yet */
  195606. if (buf > endptr)
  195607. {
  195608. png_warning(png_ptr, "Invalid pCAL data");
  195609. png_free(png_ptr, purpose);
  195610. png_free(png_ptr, params);
  195611. return;
  195612. }
  195613. }
  195614. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195615. units, params);
  195616. png_free(png_ptr, purpose);
  195617. png_free(png_ptr, params);
  195618. }
  195619. #endif
  195620. #if defined(PNG_READ_sCAL_SUPPORTED)
  195621. /* read the sCAL chunk */
  195622. void /* PRIVATE */
  195623. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195624. {
  195625. png_charp buffer, ep;
  195626. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195627. double width, height;
  195628. png_charp vp;
  195629. #else
  195630. #ifdef PNG_FIXED_POINT_SUPPORTED
  195631. png_charp swidth, sheight;
  195632. #endif
  195633. #endif
  195634. png_size_t slength;
  195635. png_debug(1, "in png_handle_sCAL\n");
  195636. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195637. png_error(png_ptr, "Missing IHDR before sCAL");
  195638. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195639. {
  195640. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195641. png_crc_finish(png_ptr, length);
  195642. return;
  195643. }
  195644. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195645. {
  195646. png_warning(png_ptr, "Duplicate sCAL chunk");
  195647. png_crc_finish(png_ptr, length);
  195648. return;
  195649. }
  195650. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195651. length + 1);
  195652. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195653. if (buffer == NULL)
  195654. {
  195655. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195656. return;
  195657. }
  195658. slength = (png_size_t)length;
  195659. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195660. if (png_crc_finish(png_ptr, 0))
  195661. {
  195662. png_free(png_ptr, buffer);
  195663. return;
  195664. }
  195665. buffer[slength] = 0x00; /* null terminate the last string */
  195666. ep = buffer + 1; /* skip unit byte */
  195667. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195668. width = png_strtod(png_ptr, ep, &vp);
  195669. if (*vp)
  195670. {
  195671. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195672. return;
  195673. }
  195674. #else
  195675. #ifdef PNG_FIXED_POINT_SUPPORTED
  195676. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195677. if (swidth == NULL)
  195678. {
  195679. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195680. return;
  195681. }
  195682. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195683. #endif
  195684. #endif
  195685. for (ep = buffer; *ep; ep++)
  195686. /* empty loop */ ;
  195687. ep++;
  195688. if (buffer + slength < ep)
  195689. {
  195690. png_warning(png_ptr, "Truncated sCAL chunk");
  195691. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195692. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195693. png_free(png_ptr, swidth);
  195694. #endif
  195695. png_free(png_ptr, buffer);
  195696. return;
  195697. }
  195698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195699. height = png_strtod(png_ptr, ep, &vp);
  195700. if (*vp)
  195701. {
  195702. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195703. return;
  195704. }
  195705. #else
  195706. #ifdef PNG_FIXED_POINT_SUPPORTED
  195707. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195708. if (swidth == NULL)
  195709. {
  195710. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195711. return;
  195712. }
  195713. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195714. #endif
  195715. #endif
  195716. if (buffer + slength < ep
  195717. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195718. || width <= 0. || height <= 0.
  195719. #endif
  195720. )
  195721. {
  195722. png_warning(png_ptr, "Invalid sCAL data");
  195723. png_free(png_ptr, buffer);
  195724. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195725. png_free(png_ptr, swidth);
  195726. png_free(png_ptr, sheight);
  195727. #endif
  195728. return;
  195729. }
  195730. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195731. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195732. #else
  195733. #ifdef PNG_FIXED_POINT_SUPPORTED
  195734. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195735. #endif
  195736. #endif
  195737. png_free(png_ptr, buffer);
  195738. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195739. png_free(png_ptr, swidth);
  195740. png_free(png_ptr, sheight);
  195741. #endif
  195742. }
  195743. #endif
  195744. #if defined(PNG_READ_tIME_SUPPORTED)
  195745. void /* PRIVATE */
  195746. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195747. {
  195748. png_byte buf[7];
  195749. png_time mod_time;
  195750. png_debug(1, "in png_handle_tIME\n");
  195751. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195752. png_error(png_ptr, "Out of place tIME chunk");
  195753. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195754. {
  195755. png_warning(png_ptr, "Duplicate tIME chunk");
  195756. png_crc_finish(png_ptr, length);
  195757. return;
  195758. }
  195759. if (png_ptr->mode & PNG_HAVE_IDAT)
  195760. png_ptr->mode |= PNG_AFTER_IDAT;
  195761. if (length != 7)
  195762. {
  195763. png_warning(png_ptr, "Incorrect tIME chunk length");
  195764. png_crc_finish(png_ptr, length);
  195765. return;
  195766. }
  195767. png_crc_read(png_ptr, buf, 7);
  195768. if (png_crc_finish(png_ptr, 0))
  195769. return;
  195770. mod_time.second = buf[6];
  195771. mod_time.minute = buf[5];
  195772. mod_time.hour = buf[4];
  195773. mod_time.day = buf[3];
  195774. mod_time.month = buf[2];
  195775. mod_time.year = png_get_uint_16(buf);
  195776. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195777. }
  195778. #endif
  195779. #if defined(PNG_READ_tEXt_SUPPORTED)
  195780. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195781. void /* PRIVATE */
  195782. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195783. {
  195784. png_textp text_ptr;
  195785. png_charp key;
  195786. png_charp text;
  195787. png_uint_32 skip = 0;
  195788. png_size_t slength;
  195789. int ret;
  195790. png_debug(1, "in png_handle_tEXt\n");
  195791. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195792. png_error(png_ptr, "Missing IHDR before tEXt");
  195793. if (png_ptr->mode & PNG_HAVE_IDAT)
  195794. png_ptr->mode |= PNG_AFTER_IDAT;
  195795. #ifdef PNG_MAX_MALLOC_64K
  195796. if (length > (png_uint_32)65535L)
  195797. {
  195798. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195799. skip = length - (png_uint_32)65535L;
  195800. length = (png_uint_32)65535L;
  195801. }
  195802. #endif
  195803. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195804. if (key == NULL)
  195805. {
  195806. png_warning(png_ptr, "No memory to process text chunk.");
  195807. return;
  195808. }
  195809. slength = (png_size_t)length;
  195810. png_crc_read(png_ptr, (png_bytep)key, slength);
  195811. if (png_crc_finish(png_ptr, skip))
  195812. {
  195813. png_free(png_ptr, key);
  195814. return;
  195815. }
  195816. key[slength] = 0x00;
  195817. for (text = key; *text; text++)
  195818. /* empty loop to find end of key */ ;
  195819. if (text != key + slength)
  195820. text++;
  195821. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195822. (png_uint_32)png_sizeof(png_text));
  195823. if (text_ptr == NULL)
  195824. {
  195825. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195826. png_free(png_ptr, key);
  195827. return;
  195828. }
  195829. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195830. text_ptr->key = key;
  195831. #ifdef PNG_iTXt_SUPPORTED
  195832. text_ptr->lang = NULL;
  195833. text_ptr->lang_key = NULL;
  195834. text_ptr->itxt_length = 0;
  195835. #endif
  195836. text_ptr->text = text;
  195837. text_ptr->text_length = png_strlen(text);
  195838. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195839. png_free(png_ptr, key);
  195840. png_free(png_ptr, text_ptr);
  195841. if (ret)
  195842. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195843. }
  195844. #endif
  195845. #if defined(PNG_READ_zTXt_SUPPORTED)
  195846. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195847. void /* PRIVATE */
  195848. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195849. {
  195850. png_textp text_ptr;
  195851. png_charp chunkdata;
  195852. png_charp text;
  195853. int comp_type;
  195854. int ret;
  195855. png_size_t slength, prefix_len, data_len;
  195856. png_debug(1, "in png_handle_zTXt\n");
  195857. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195858. png_error(png_ptr, "Missing IHDR before zTXt");
  195859. if (png_ptr->mode & PNG_HAVE_IDAT)
  195860. png_ptr->mode |= PNG_AFTER_IDAT;
  195861. #ifdef PNG_MAX_MALLOC_64K
  195862. /* We will no doubt have problems with chunks even half this size, but
  195863. there is no hard and fast rule to tell us where to stop. */
  195864. if (length > (png_uint_32)65535L)
  195865. {
  195866. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195867. png_crc_finish(png_ptr, length);
  195868. return;
  195869. }
  195870. #endif
  195871. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195872. if (chunkdata == NULL)
  195873. {
  195874. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195875. return;
  195876. }
  195877. slength = (png_size_t)length;
  195878. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195879. if (png_crc_finish(png_ptr, 0))
  195880. {
  195881. png_free(png_ptr, chunkdata);
  195882. return;
  195883. }
  195884. chunkdata[slength] = 0x00;
  195885. for (text = chunkdata; *text; text++)
  195886. /* empty loop */ ;
  195887. /* zTXt must have some text after the chunkdataword */
  195888. if (text >= chunkdata + slength - 2)
  195889. {
  195890. png_warning(png_ptr, "Truncated zTXt chunk");
  195891. png_free(png_ptr, chunkdata);
  195892. return;
  195893. }
  195894. else
  195895. {
  195896. comp_type = *(++text);
  195897. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195898. {
  195899. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195900. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195901. }
  195902. text++; /* skip the compression_method byte */
  195903. }
  195904. prefix_len = text - chunkdata;
  195905. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195906. (png_size_t)length, prefix_len, &data_len);
  195907. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195908. (png_uint_32)png_sizeof(png_text));
  195909. if (text_ptr == NULL)
  195910. {
  195911. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195912. png_free(png_ptr, chunkdata);
  195913. return;
  195914. }
  195915. text_ptr->compression = comp_type;
  195916. text_ptr->key = chunkdata;
  195917. #ifdef PNG_iTXt_SUPPORTED
  195918. text_ptr->lang = NULL;
  195919. text_ptr->lang_key = NULL;
  195920. text_ptr->itxt_length = 0;
  195921. #endif
  195922. text_ptr->text = chunkdata + prefix_len;
  195923. text_ptr->text_length = data_len;
  195924. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195925. png_free(png_ptr, text_ptr);
  195926. png_free(png_ptr, chunkdata);
  195927. if (ret)
  195928. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195929. }
  195930. #endif
  195931. #if defined(PNG_READ_iTXt_SUPPORTED)
  195932. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195933. void /* PRIVATE */
  195934. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195935. {
  195936. png_textp text_ptr;
  195937. png_charp chunkdata;
  195938. png_charp key, lang, text, lang_key;
  195939. int comp_flag;
  195940. int comp_type = 0;
  195941. int ret;
  195942. png_size_t slength, prefix_len, data_len;
  195943. png_debug(1, "in png_handle_iTXt\n");
  195944. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195945. png_error(png_ptr, "Missing IHDR before iTXt");
  195946. if (png_ptr->mode & PNG_HAVE_IDAT)
  195947. png_ptr->mode |= PNG_AFTER_IDAT;
  195948. #ifdef PNG_MAX_MALLOC_64K
  195949. /* We will no doubt have problems with chunks even half this size, but
  195950. there is no hard and fast rule to tell us where to stop. */
  195951. if (length > (png_uint_32)65535L)
  195952. {
  195953. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195954. png_crc_finish(png_ptr, length);
  195955. return;
  195956. }
  195957. #endif
  195958. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195959. if (chunkdata == NULL)
  195960. {
  195961. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195962. return;
  195963. }
  195964. slength = (png_size_t)length;
  195965. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195966. if (png_crc_finish(png_ptr, 0))
  195967. {
  195968. png_free(png_ptr, chunkdata);
  195969. return;
  195970. }
  195971. chunkdata[slength] = 0x00;
  195972. for (lang = chunkdata; *lang; lang++)
  195973. /* empty loop */ ;
  195974. lang++; /* skip NUL separator */
  195975. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195976. translated keyword (possibly empty), and possibly some text after the
  195977. keyword */
  195978. if (lang >= chunkdata + slength - 3)
  195979. {
  195980. png_warning(png_ptr, "Truncated iTXt chunk");
  195981. png_free(png_ptr, chunkdata);
  195982. return;
  195983. }
  195984. else
  195985. {
  195986. comp_flag = *lang++;
  195987. comp_type = *lang++;
  195988. }
  195989. for (lang_key = lang; *lang_key; lang_key++)
  195990. /* empty loop */ ;
  195991. lang_key++; /* skip NUL separator */
  195992. if (lang_key >= chunkdata + slength)
  195993. {
  195994. png_warning(png_ptr, "Truncated iTXt chunk");
  195995. png_free(png_ptr, chunkdata);
  195996. return;
  195997. }
  195998. for (text = lang_key; *text; text++)
  195999. /* empty loop */ ;
  196000. text++; /* skip NUL separator */
  196001. if (text >= chunkdata + slength)
  196002. {
  196003. png_warning(png_ptr, "Malformed iTXt chunk");
  196004. png_free(png_ptr, chunkdata);
  196005. return;
  196006. }
  196007. prefix_len = text - chunkdata;
  196008. key=chunkdata;
  196009. if (comp_flag)
  196010. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196011. (size_t)length, prefix_len, &data_len);
  196012. else
  196013. data_len=png_strlen(chunkdata + prefix_len);
  196014. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196015. (png_uint_32)png_sizeof(png_text));
  196016. if (text_ptr == NULL)
  196017. {
  196018. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196019. png_free(png_ptr, chunkdata);
  196020. return;
  196021. }
  196022. text_ptr->compression = (int)comp_flag + 1;
  196023. text_ptr->lang_key = chunkdata+(lang_key-key);
  196024. text_ptr->lang = chunkdata+(lang-key);
  196025. text_ptr->itxt_length = data_len;
  196026. text_ptr->text_length = 0;
  196027. text_ptr->key = chunkdata;
  196028. text_ptr->text = chunkdata + prefix_len;
  196029. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196030. png_free(png_ptr, text_ptr);
  196031. png_free(png_ptr, chunkdata);
  196032. if (ret)
  196033. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196034. }
  196035. #endif
  196036. /* This function is called when we haven't found a handler for a
  196037. chunk. If there isn't a problem with the chunk itself (ie bad
  196038. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196039. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196040. case it will be saved away to be written out later. */
  196041. void /* PRIVATE */
  196042. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196043. {
  196044. png_uint_32 skip = 0;
  196045. png_debug(1, "in png_handle_unknown\n");
  196046. if (png_ptr->mode & PNG_HAVE_IDAT)
  196047. {
  196048. #ifdef PNG_USE_LOCAL_ARRAYS
  196049. PNG_CONST PNG_IDAT;
  196050. #endif
  196051. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196052. png_ptr->mode |= PNG_AFTER_IDAT;
  196053. }
  196054. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196055. if (!(png_ptr->chunk_name[0] & 0x20))
  196056. {
  196057. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196058. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196059. PNG_HANDLE_CHUNK_ALWAYS
  196060. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196061. && png_ptr->read_user_chunk_fn == NULL
  196062. #endif
  196063. )
  196064. #endif
  196065. png_chunk_error(png_ptr, "unknown critical chunk");
  196066. }
  196067. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196068. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196069. (png_ptr->read_user_chunk_fn != NULL))
  196070. {
  196071. #ifdef PNG_MAX_MALLOC_64K
  196072. if (length > (png_uint_32)65535L)
  196073. {
  196074. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196075. skip = length - (png_uint_32)65535L;
  196076. length = (png_uint_32)65535L;
  196077. }
  196078. #endif
  196079. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196080. (png_charp)png_ptr->chunk_name, 5);
  196081. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196082. png_ptr->unknown_chunk.size = (png_size_t)length;
  196083. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196084. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196085. if(png_ptr->read_user_chunk_fn != NULL)
  196086. {
  196087. /* callback to user unknown chunk handler */
  196088. int ret;
  196089. ret = (*(png_ptr->read_user_chunk_fn))
  196090. (png_ptr, &png_ptr->unknown_chunk);
  196091. if (ret < 0)
  196092. png_chunk_error(png_ptr, "error in user chunk");
  196093. if (ret == 0)
  196094. {
  196095. if (!(png_ptr->chunk_name[0] & 0x20))
  196096. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196097. PNG_HANDLE_CHUNK_ALWAYS)
  196098. png_chunk_error(png_ptr, "unknown critical chunk");
  196099. png_set_unknown_chunks(png_ptr, info_ptr,
  196100. &png_ptr->unknown_chunk, 1);
  196101. }
  196102. }
  196103. #else
  196104. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196105. #endif
  196106. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196107. png_ptr->unknown_chunk.data = NULL;
  196108. }
  196109. else
  196110. #endif
  196111. skip = length;
  196112. png_crc_finish(png_ptr, skip);
  196113. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196114. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196115. #endif
  196116. }
  196117. /* This function is called to verify that a chunk name is valid.
  196118. This function can't have the "critical chunk check" incorporated
  196119. into it, since in the future we will need to be able to call user
  196120. functions to handle unknown critical chunks after we check that
  196121. the chunk name itself is valid. */
  196122. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196123. void /* PRIVATE */
  196124. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196125. {
  196126. png_debug(1, "in png_check_chunk_name\n");
  196127. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196128. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196129. {
  196130. png_chunk_error(png_ptr, "invalid chunk type");
  196131. }
  196132. }
  196133. /* Combines the row recently read in with the existing pixels in the
  196134. row. This routine takes care of alpha and transparency if requested.
  196135. This routine also handles the two methods of progressive display
  196136. of interlaced images, depending on the mask value.
  196137. The mask value describes which pixels are to be combined with
  196138. the row. The pattern always repeats every 8 pixels, so just 8
  196139. bits are needed. A one indicates the pixel is to be combined,
  196140. a zero indicates the pixel is to be skipped. This is in addition
  196141. to any alpha or transparency value associated with the pixel. If
  196142. you want all pixels to be combined, pass 0xff (255) in mask. */
  196143. void /* PRIVATE */
  196144. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196145. {
  196146. png_debug(1,"in png_combine_row\n");
  196147. if (mask == 0xff)
  196148. {
  196149. png_memcpy(row, png_ptr->row_buf + 1,
  196150. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196151. }
  196152. else
  196153. {
  196154. switch (png_ptr->row_info.pixel_depth)
  196155. {
  196156. case 1:
  196157. {
  196158. png_bytep sp = png_ptr->row_buf + 1;
  196159. png_bytep dp = row;
  196160. int s_inc, s_start, s_end;
  196161. int m = 0x80;
  196162. int shift;
  196163. png_uint_32 i;
  196164. png_uint_32 row_width = png_ptr->width;
  196165. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196166. if (png_ptr->transformations & PNG_PACKSWAP)
  196167. {
  196168. s_start = 0;
  196169. s_end = 7;
  196170. s_inc = 1;
  196171. }
  196172. else
  196173. #endif
  196174. {
  196175. s_start = 7;
  196176. s_end = 0;
  196177. s_inc = -1;
  196178. }
  196179. shift = s_start;
  196180. for (i = 0; i < row_width; i++)
  196181. {
  196182. if (m & mask)
  196183. {
  196184. int value;
  196185. value = (*sp >> shift) & 0x01;
  196186. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196187. *dp |= (png_byte)(value << shift);
  196188. }
  196189. if (shift == s_end)
  196190. {
  196191. shift = s_start;
  196192. sp++;
  196193. dp++;
  196194. }
  196195. else
  196196. shift += s_inc;
  196197. if (m == 1)
  196198. m = 0x80;
  196199. else
  196200. m >>= 1;
  196201. }
  196202. break;
  196203. }
  196204. case 2:
  196205. {
  196206. png_bytep sp = png_ptr->row_buf + 1;
  196207. png_bytep dp = row;
  196208. int s_start, s_end, s_inc;
  196209. int m = 0x80;
  196210. int shift;
  196211. png_uint_32 i;
  196212. png_uint_32 row_width = png_ptr->width;
  196213. int value;
  196214. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196215. if (png_ptr->transformations & PNG_PACKSWAP)
  196216. {
  196217. s_start = 0;
  196218. s_end = 6;
  196219. s_inc = 2;
  196220. }
  196221. else
  196222. #endif
  196223. {
  196224. s_start = 6;
  196225. s_end = 0;
  196226. s_inc = -2;
  196227. }
  196228. shift = s_start;
  196229. for (i = 0; i < row_width; i++)
  196230. {
  196231. if (m & mask)
  196232. {
  196233. value = (*sp >> shift) & 0x03;
  196234. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196235. *dp |= (png_byte)(value << shift);
  196236. }
  196237. if (shift == s_end)
  196238. {
  196239. shift = s_start;
  196240. sp++;
  196241. dp++;
  196242. }
  196243. else
  196244. shift += s_inc;
  196245. if (m == 1)
  196246. m = 0x80;
  196247. else
  196248. m >>= 1;
  196249. }
  196250. break;
  196251. }
  196252. case 4:
  196253. {
  196254. png_bytep sp = png_ptr->row_buf + 1;
  196255. png_bytep dp = row;
  196256. int s_start, s_end, s_inc;
  196257. int m = 0x80;
  196258. int shift;
  196259. png_uint_32 i;
  196260. png_uint_32 row_width = png_ptr->width;
  196261. int value;
  196262. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196263. if (png_ptr->transformations & PNG_PACKSWAP)
  196264. {
  196265. s_start = 0;
  196266. s_end = 4;
  196267. s_inc = 4;
  196268. }
  196269. else
  196270. #endif
  196271. {
  196272. s_start = 4;
  196273. s_end = 0;
  196274. s_inc = -4;
  196275. }
  196276. shift = s_start;
  196277. for (i = 0; i < row_width; i++)
  196278. {
  196279. if (m & mask)
  196280. {
  196281. value = (*sp >> shift) & 0xf;
  196282. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196283. *dp |= (png_byte)(value << shift);
  196284. }
  196285. if (shift == s_end)
  196286. {
  196287. shift = s_start;
  196288. sp++;
  196289. dp++;
  196290. }
  196291. else
  196292. shift += s_inc;
  196293. if (m == 1)
  196294. m = 0x80;
  196295. else
  196296. m >>= 1;
  196297. }
  196298. break;
  196299. }
  196300. default:
  196301. {
  196302. png_bytep sp = png_ptr->row_buf + 1;
  196303. png_bytep dp = row;
  196304. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196305. png_uint_32 i;
  196306. png_uint_32 row_width = png_ptr->width;
  196307. png_byte m = 0x80;
  196308. for (i = 0; i < row_width; i++)
  196309. {
  196310. if (m & mask)
  196311. {
  196312. png_memcpy(dp, sp, pixel_bytes);
  196313. }
  196314. sp += pixel_bytes;
  196315. dp += pixel_bytes;
  196316. if (m == 1)
  196317. m = 0x80;
  196318. else
  196319. m >>= 1;
  196320. }
  196321. break;
  196322. }
  196323. }
  196324. }
  196325. }
  196326. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196327. /* OLD pre-1.0.9 interface:
  196328. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196329. png_uint_32 transformations)
  196330. */
  196331. void /* PRIVATE */
  196332. png_do_read_interlace(png_structp png_ptr)
  196333. {
  196334. png_row_infop row_info = &(png_ptr->row_info);
  196335. png_bytep row = png_ptr->row_buf + 1;
  196336. int pass = png_ptr->pass;
  196337. png_uint_32 transformations = png_ptr->transformations;
  196338. #ifdef PNG_USE_LOCAL_ARRAYS
  196339. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196340. /* offset to next interlace block */
  196341. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196342. #endif
  196343. png_debug(1,"in png_do_read_interlace\n");
  196344. if (row != NULL && row_info != NULL)
  196345. {
  196346. png_uint_32 final_width;
  196347. final_width = row_info->width * png_pass_inc[pass];
  196348. switch (row_info->pixel_depth)
  196349. {
  196350. case 1:
  196351. {
  196352. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196353. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196354. int sshift, dshift;
  196355. int s_start, s_end, s_inc;
  196356. int jstop = png_pass_inc[pass];
  196357. png_byte v;
  196358. png_uint_32 i;
  196359. int j;
  196360. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196361. if (transformations & PNG_PACKSWAP)
  196362. {
  196363. sshift = (int)((row_info->width + 7) & 0x07);
  196364. dshift = (int)((final_width + 7) & 0x07);
  196365. s_start = 7;
  196366. s_end = 0;
  196367. s_inc = -1;
  196368. }
  196369. else
  196370. #endif
  196371. {
  196372. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196373. dshift = 7 - (int)((final_width + 7) & 0x07);
  196374. s_start = 0;
  196375. s_end = 7;
  196376. s_inc = 1;
  196377. }
  196378. for (i = 0; i < row_info->width; i++)
  196379. {
  196380. v = (png_byte)((*sp >> sshift) & 0x01);
  196381. for (j = 0; j < jstop; j++)
  196382. {
  196383. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196384. *dp |= (png_byte)(v << dshift);
  196385. if (dshift == s_end)
  196386. {
  196387. dshift = s_start;
  196388. dp--;
  196389. }
  196390. else
  196391. dshift += s_inc;
  196392. }
  196393. if (sshift == s_end)
  196394. {
  196395. sshift = s_start;
  196396. sp--;
  196397. }
  196398. else
  196399. sshift += s_inc;
  196400. }
  196401. break;
  196402. }
  196403. case 2:
  196404. {
  196405. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196406. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196407. int sshift, dshift;
  196408. int s_start, s_end, s_inc;
  196409. int jstop = png_pass_inc[pass];
  196410. png_uint_32 i;
  196411. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196412. if (transformations & PNG_PACKSWAP)
  196413. {
  196414. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196415. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196416. s_start = 6;
  196417. s_end = 0;
  196418. s_inc = -2;
  196419. }
  196420. else
  196421. #endif
  196422. {
  196423. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196424. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196425. s_start = 0;
  196426. s_end = 6;
  196427. s_inc = 2;
  196428. }
  196429. for (i = 0; i < row_info->width; i++)
  196430. {
  196431. png_byte v;
  196432. int j;
  196433. v = (png_byte)((*sp >> sshift) & 0x03);
  196434. for (j = 0; j < jstop; j++)
  196435. {
  196436. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196437. *dp |= (png_byte)(v << dshift);
  196438. if (dshift == s_end)
  196439. {
  196440. dshift = s_start;
  196441. dp--;
  196442. }
  196443. else
  196444. dshift += s_inc;
  196445. }
  196446. if (sshift == s_end)
  196447. {
  196448. sshift = s_start;
  196449. sp--;
  196450. }
  196451. else
  196452. sshift += s_inc;
  196453. }
  196454. break;
  196455. }
  196456. case 4:
  196457. {
  196458. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196459. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196460. int sshift, dshift;
  196461. int s_start, s_end, s_inc;
  196462. png_uint_32 i;
  196463. int jstop = png_pass_inc[pass];
  196464. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196465. if (transformations & PNG_PACKSWAP)
  196466. {
  196467. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196468. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196469. s_start = 4;
  196470. s_end = 0;
  196471. s_inc = -4;
  196472. }
  196473. else
  196474. #endif
  196475. {
  196476. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196477. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196478. s_start = 0;
  196479. s_end = 4;
  196480. s_inc = 4;
  196481. }
  196482. for (i = 0; i < row_info->width; i++)
  196483. {
  196484. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196485. int j;
  196486. for (j = 0; j < jstop; j++)
  196487. {
  196488. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196489. *dp |= (png_byte)(v << dshift);
  196490. if (dshift == s_end)
  196491. {
  196492. dshift = s_start;
  196493. dp--;
  196494. }
  196495. else
  196496. dshift += s_inc;
  196497. }
  196498. if (sshift == s_end)
  196499. {
  196500. sshift = s_start;
  196501. sp--;
  196502. }
  196503. else
  196504. sshift += s_inc;
  196505. }
  196506. break;
  196507. }
  196508. default:
  196509. {
  196510. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196511. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196512. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196513. int jstop = png_pass_inc[pass];
  196514. png_uint_32 i;
  196515. for (i = 0; i < row_info->width; i++)
  196516. {
  196517. png_byte v[8];
  196518. int j;
  196519. png_memcpy(v, sp, pixel_bytes);
  196520. for (j = 0; j < jstop; j++)
  196521. {
  196522. png_memcpy(dp, v, pixel_bytes);
  196523. dp -= pixel_bytes;
  196524. }
  196525. sp -= pixel_bytes;
  196526. }
  196527. break;
  196528. }
  196529. }
  196530. row_info->width = final_width;
  196531. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196532. }
  196533. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196534. transformations = transformations; /* silence compiler warning */
  196535. #endif
  196536. }
  196537. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196538. void /* PRIVATE */
  196539. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196540. png_bytep prev_row, int filter)
  196541. {
  196542. png_debug(1, "in png_read_filter_row\n");
  196543. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196544. switch (filter)
  196545. {
  196546. case PNG_FILTER_VALUE_NONE:
  196547. break;
  196548. case PNG_FILTER_VALUE_SUB:
  196549. {
  196550. png_uint_32 i;
  196551. png_uint_32 istop = row_info->rowbytes;
  196552. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196553. png_bytep rp = row + bpp;
  196554. png_bytep lp = row;
  196555. for (i = bpp; i < istop; i++)
  196556. {
  196557. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196558. rp++;
  196559. }
  196560. break;
  196561. }
  196562. case PNG_FILTER_VALUE_UP:
  196563. {
  196564. png_uint_32 i;
  196565. png_uint_32 istop = row_info->rowbytes;
  196566. png_bytep rp = row;
  196567. png_bytep pp = prev_row;
  196568. for (i = 0; i < istop; i++)
  196569. {
  196570. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196571. rp++;
  196572. }
  196573. break;
  196574. }
  196575. case PNG_FILTER_VALUE_AVG:
  196576. {
  196577. png_uint_32 i;
  196578. png_bytep rp = row;
  196579. png_bytep pp = prev_row;
  196580. png_bytep lp = row;
  196581. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196582. png_uint_32 istop = row_info->rowbytes - bpp;
  196583. for (i = 0; i < bpp; i++)
  196584. {
  196585. *rp = (png_byte)(((int)(*rp) +
  196586. ((int)(*pp++) / 2 )) & 0xff);
  196587. rp++;
  196588. }
  196589. for (i = 0; i < istop; i++)
  196590. {
  196591. *rp = (png_byte)(((int)(*rp) +
  196592. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196593. rp++;
  196594. }
  196595. break;
  196596. }
  196597. case PNG_FILTER_VALUE_PAETH:
  196598. {
  196599. png_uint_32 i;
  196600. png_bytep rp = row;
  196601. png_bytep pp = prev_row;
  196602. png_bytep lp = row;
  196603. png_bytep cp = prev_row;
  196604. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196605. png_uint_32 istop=row_info->rowbytes - bpp;
  196606. for (i = 0; i < bpp; i++)
  196607. {
  196608. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196609. rp++;
  196610. }
  196611. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196612. {
  196613. int a, b, c, pa, pb, pc, p;
  196614. a = *lp++;
  196615. b = *pp++;
  196616. c = *cp++;
  196617. p = b - c;
  196618. pc = a - c;
  196619. #ifdef PNG_USE_ABS
  196620. pa = abs(p);
  196621. pb = abs(pc);
  196622. pc = abs(p + pc);
  196623. #else
  196624. pa = p < 0 ? -p : p;
  196625. pb = pc < 0 ? -pc : pc;
  196626. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196627. #endif
  196628. /*
  196629. if (pa <= pb && pa <= pc)
  196630. p = a;
  196631. else if (pb <= pc)
  196632. p = b;
  196633. else
  196634. p = c;
  196635. */
  196636. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196637. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196638. rp++;
  196639. }
  196640. break;
  196641. }
  196642. default:
  196643. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196644. *row=0;
  196645. break;
  196646. }
  196647. }
  196648. void /* PRIVATE */
  196649. png_read_finish_row(png_structp png_ptr)
  196650. {
  196651. #ifdef PNG_USE_LOCAL_ARRAYS
  196652. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196653. /* start of interlace block */
  196654. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196655. /* offset to next interlace block */
  196656. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196657. /* start of interlace block in the y direction */
  196658. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196659. /* offset to next interlace block in the y direction */
  196660. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196661. #endif
  196662. png_debug(1, "in png_read_finish_row\n");
  196663. png_ptr->row_number++;
  196664. if (png_ptr->row_number < png_ptr->num_rows)
  196665. return;
  196666. if (png_ptr->interlaced)
  196667. {
  196668. png_ptr->row_number = 0;
  196669. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196670. png_ptr->rowbytes + 1);
  196671. do
  196672. {
  196673. png_ptr->pass++;
  196674. if (png_ptr->pass >= 7)
  196675. break;
  196676. png_ptr->iwidth = (png_ptr->width +
  196677. png_pass_inc[png_ptr->pass] - 1 -
  196678. png_pass_start[png_ptr->pass]) /
  196679. png_pass_inc[png_ptr->pass];
  196680. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196681. png_ptr->iwidth) + 1;
  196682. if (!(png_ptr->transformations & PNG_INTERLACE))
  196683. {
  196684. png_ptr->num_rows = (png_ptr->height +
  196685. png_pass_yinc[png_ptr->pass] - 1 -
  196686. png_pass_ystart[png_ptr->pass]) /
  196687. png_pass_yinc[png_ptr->pass];
  196688. if (!(png_ptr->num_rows))
  196689. continue;
  196690. }
  196691. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196692. break;
  196693. } while (png_ptr->iwidth == 0);
  196694. if (png_ptr->pass < 7)
  196695. return;
  196696. }
  196697. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196698. {
  196699. #ifdef PNG_USE_LOCAL_ARRAYS
  196700. PNG_CONST PNG_IDAT;
  196701. #endif
  196702. char extra;
  196703. int ret;
  196704. png_ptr->zstream.next_out = (Bytef *)&extra;
  196705. png_ptr->zstream.avail_out = (uInt)1;
  196706. for(;;)
  196707. {
  196708. if (!(png_ptr->zstream.avail_in))
  196709. {
  196710. while (!png_ptr->idat_size)
  196711. {
  196712. png_byte chunk_length[4];
  196713. png_crc_finish(png_ptr, 0);
  196714. png_read_data(png_ptr, chunk_length, 4);
  196715. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196716. png_reset_crc(png_ptr);
  196717. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196718. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196719. png_error(png_ptr, "Not enough image data");
  196720. }
  196721. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196722. png_ptr->zstream.next_in = png_ptr->zbuf;
  196723. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196724. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196725. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196726. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196727. }
  196728. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196729. if (ret == Z_STREAM_END)
  196730. {
  196731. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196732. png_ptr->idat_size)
  196733. png_warning(png_ptr, "Extra compressed data");
  196734. png_ptr->mode |= PNG_AFTER_IDAT;
  196735. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196736. break;
  196737. }
  196738. if (ret != Z_OK)
  196739. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196740. "Decompression Error");
  196741. if (!(png_ptr->zstream.avail_out))
  196742. {
  196743. png_warning(png_ptr, "Extra compressed data.");
  196744. png_ptr->mode |= PNG_AFTER_IDAT;
  196745. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196746. break;
  196747. }
  196748. }
  196749. png_ptr->zstream.avail_out = 0;
  196750. }
  196751. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196752. png_warning(png_ptr, "Extra compression data");
  196753. inflateReset(&png_ptr->zstream);
  196754. png_ptr->mode |= PNG_AFTER_IDAT;
  196755. }
  196756. void /* PRIVATE */
  196757. png_read_start_row(png_structp png_ptr)
  196758. {
  196759. #ifdef PNG_USE_LOCAL_ARRAYS
  196760. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196761. /* start of interlace block */
  196762. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196763. /* offset to next interlace block */
  196764. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196765. /* start of interlace block in the y direction */
  196766. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196767. /* offset to next interlace block in the y direction */
  196768. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196769. #endif
  196770. int max_pixel_depth;
  196771. png_uint_32 row_bytes;
  196772. png_debug(1, "in png_read_start_row\n");
  196773. png_ptr->zstream.avail_in = 0;
  196774. png_init_read_transformations(png_ptr);
  196775. if (png_ptr->interlaced)
  196776. {
  196777. if (!(png_ptr->transformations & PNG_INTERLACE))
  196778. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196779. png_pass_ystart[0]) / png_pass_yinc[0];
  196780. else
  196781. png_ptr->num_rows = png_ptr->height;
  196782. png_ptr->iwidth = (png_ptr->width +
  196783. png_pass_inc[png_ptr->pass] - 1 -
  196784. png_pass_start[png_ptr->pass]) /
  196785. png_pass_inc[png_ptr->pass];
  196786. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196787. png_ptr->irowbytes = (png_size_t)row_bytes;
  196788. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196789. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196790. }
  196791. else
  196792. {
  196793. png_ptr->num_rows = png_ptr->height;
  196794. png_ptr->iwidth = png_ptr->width;
  196795. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196796. }
  196797. max_pixel_depth = png_ptr->pixel_depth;
  196798. #if defined(PNG_READ_PACK_SUPPORTED)
  196799. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196800. max_pixel_depth = 8;
  196801. #endif
  196802. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196803. if (png_ptr->transformations & PNG_EXPAND)
  196804. {
  196805. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196806. {
  196807. if (png_ptr->num_trans)
  196808. max_pixel_depth = 32;
  196809. else
  196810. max_pixel_depth = 24;
  196811. }
  196812. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196813. {
  196814. if (max_pixel_depth < 8)
  196815. max_pixel_depth = 8;
  196816. if (png_ptr->num_trans)
  196817. max_pixel_depth *= 2;
  196818. }
  196819. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196820. {
  196821. if (png_ptr->num_trans)
  196822. {
  196823. max_pixel_depth *= 4;
  196824. max_pixel_depth /= 3;
  196825. }
  196826. }
  196827. }
  196828. #endif
  196829. #if defined(PNG_READ_FILLER_SUPPORTED)
  196830. if (png_ptr->transformations & (PNG_FILLER))
  196831. {
  196832. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196833. max_pixel_depth = 32;
  196834. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196835. {
  196836. if (max_pixel_depth <= 8)
  196837. max_pixel_depth = 16;
  196838. else
  196839. max_pixel_depth = 32;
  196840. }
  196841. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196842. {
  196843. if (max_pixel_depth <= 32)
  196844. max_pixel_depth = 32;
  196845. else
  196846. max_pixel_depth = 64;
  196847. }
  196848. }
  196849. #endif
  196850. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196851. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196852. {
  196853. if (
  196854. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196855. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196856. #endif
  196857. #if defined(PNG_READ_FILLER_SUPPORTED)
  196858. (png_ptr->transformations & (PNG_FILLER)) ||
  196859. #endif
  196860. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196861. {
  196862. if (max_pixel_depth <= 16)
  196863. max_pixel_depth = 32;
  196864. else
  196865. max_pixel_depth = 64;
  196866. }
  196867. else
  196868. {
  196869. if (max_pixel_depth <= 8)
  196870. {
  196871. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196872. max_pixel_depth = 32;
  196873. else
  196874. max_pixel_depth = 24;
  196875. }
  196876. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196877. max_pixel_depth = 64;
  196878. else
  196879. max_pixel_depth = 48;
  196880. }
  196881. }
  196882. #endif
  196883. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196884. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196885. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196886. {
  196887. int user_pixel_depth=png_ptr->user_transform_depth*
  196888. png_ptr->user_transform_channels;
  196889. if(user_pixel_depth > max_pixel_depth)
  196890. max_pixel_depth=user_pixel_depth;
  196891. }
  196892. #endif
  196893. /* align the width on the next larger 8 pixels. Mainly used
  196894. for interlacing */
  196895. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196896. /* calculate the maximum bytes needed, adding a byte and a pixel
  196897. for safety's sake */
  196898. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196899. 1 + ((max_pixel_depth + 7) >> 3);
  196900. #ifdef PNG_MAX_MALLOC_64K
  196901. if (row_bytes > (png_uint_32)65536L)
  196902. png_error(png_ptr, "This image requires a row greater than 64KB");
  196903. #endif
  196904. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196905. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196906. #ifdef PNG_MAX_MALLOC_64K
  196907. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196908. png_error(png_ptr, "This image requires a row greater than 64KB");
  196909. #endif
  196910. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196911. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196912. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196913. png_ptr->rowbytes + 1));
  196914. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196915. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196916. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196917. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196918. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196919. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196920. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196921. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196922. }
  196923. #endif /* PNG_READ_SUPPORTED */
  196924. /*** End of inlined file: pngrutil.c ***/
  196925. /*** Start of inlined file: pngset.c ***/
  196926. /* pngset.c - storage of image information into info struct
  196927. *
  196928. * Last changed in libpng 1.2.21 [October 4, 2007]
  196929. * For conditions of distribution and use, see copyright notice in png.h
  196930. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196931. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196932. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196933. *
  196934. * The functions here are used during reads to store data from the file
  196935. * into the info struct, and during writes to store application data
  196936. * into the info struct for writing into the file. This abstracts the
  196937. * info struct and allows us to change the structure in the future.
  196938. */
  196939. #define PNG_INTERNAL
  196940. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196941. #if defined(PNG_bKGD_SUPPORTED)
  196942. void PNGAPI
  196943. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196944. {
  196945. png_debug1(1, "in %s storage function\n", "bKGD");
  196946. if (png_ptr == NULL || info_ptr == NULL)
  196947. return;
  196948. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196949. info_ptr->valid |= PNG_INFO_bKGD;
  196950. }
  196951. #endif
  196952. #if defined(PNG_cHRM_SUPPORTED)
  196953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196954. void PNGAPI
  196955. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196956. double white_x, double white_y, double red_x, double red_y,
  196957. double green_x, double green_y, double blue_x, double blue_y)
  196958. {
  196959. png_debug1(1, "in %s storage function\n", "cHRM");
  196960. if (png_ptr == NULL || info_ptr == NULL)
  196961. return;
  196962. if (white_x < 0.0 || white_y < 0.0 ||
  196963. red_x < 0.0 || red_y < 0.0 ||
  196964. green_x < 0.0 || green_y < 0.0 ||
  196965. blue_x < 0.0 || blue_y < 0.0)
  196966. {
  196967. png_warning(png_ptr,
  196968. "Ignoring attempt to set negative chromaticity value");
  196969. return;
  196970. }
  196971. if (white_x > 21474.83 || white_y > 21474.83 ||
  196972. red_x > 21474.83 || red_y > 21474.83 ||
  196973. green_x > 21474.83 || green_y > 21474.83 ||
  196974. blue_x > 21474.83 || blue_y > 21474.83)
  196975. {
  196976. png_warning(png_ptr,
  196977. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196978. return;
  196979. }
  196980. info_ptr->x_white = (float)white_x;
  196981. info_ptr->y_white = (float)white_y;
  196982. info_ptr->x_red = (float)red_x;
  196983. info_ptr->y_red = (float)red_y;
  196984. info_ptr->x_green = (float)green_x;
  196985. info_ptr->y_green = (float)green_y;
  196986. info_ptr->x_blue = (float)blue_x;
  196987. info_ptr->y_blue = (float)blue_y;
  196988. #ifdef PNG_FIXED_POINT_SUPPORTED
  196989. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196990. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196991. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196992. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196993. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196994. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196995. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196996. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196997. #endif
  196998. info_ptr->valid |= PNG_INFO_cHRM;
  196999. }
  197000. #endif
  197001. #ifdef PNG_FIXED_POINT_SUPPORTED
  197002. void PNGAPI
  197003. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197004. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197005. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197006. png_fixed_point blue_x, png_fixed_point blue_y)
  197007. {
  197008. png_debug1(1, "in %s storage function\n", "cHRM");
  197009. if (png_ptr == NULL || info_ptr == NULL)
  197010. return;
  197011. if (white_x < 0 || white_y < 0 ||
  197012. red_x < 0 || red_y < 0 ||
  197013. green_x < 0 || green_y < 0 ||
  197014. blue_x < 0 || blue_y < 0)
  197015. {
  197016. png_warning(png_ptr,
  197017. "Ignoring attempt to set negative chromaticity value");
  197018. return;
  197019. }
  197020. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197021. if (white_x > (double) PNG_UINT_31_MAX ||
  197022. white_y > (double) PNG_UINT_31_MAX ||
  197023. red_x > (double) PNG_UINT_31_MAX ||
  197024. red_y > (double) PNG_UINT_31_MAX ||
  197025. green_x > (double) PNG_UINT_31_MAX ||
  197026. green_y > (double) PNG_UINT_31_MAX ||
  197027. blue_x > (double) PNG_UINT_31_MAX ||
  197028. blue_y > (double) PNG_UINT_31_MAX)
  197029. #else
  197030. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197031. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197032. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197033. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197034. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197035. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197036. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197037. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197038. #endif
  197039. {
  197040. png_warning(png_ptr,
  197041. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197042. return;
  197043. }
  197044. info_ptr->int_x_white = white_x;
  197045. info_ptr->int_y_white = white_y;
  197046. info_ptr->int_x_red = red_x;
  197047. info_ptr->int_y_red = red_y;
  197048. info_ptr->int_x_green = green_x;
  197049. info_ptr->int_y_green = green_y;
  197050. info_ptr->int_x_blue = blue_x;
  197051. info_ptr->int_y_blue = blue_y;
  197052. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197053. info_ptr->x_white = (float)(white_x/100000.);
  197054. info_ptr->y_white = (float)(white_y/100000.);
  197055. info_ptr->x_red = (float)( red_x/100000.);
  197056. info_ptr->y_red = (float)( red_y/100000.);
  197057. info_ptr->x_green = (float)(green_x/100000.);
  197058. info_ptr->y_green = (float)(green_y/100000.);
  197059. info_ptr->x_blue = (float)( blue_x/100000.);
  197060. info_ptr->y_blue = (float)( blue_y/100000.);
  197061. #endif
  197062. info_ptr->valid |= PNG_INFO_cHRM;
  197063. }
  197064. #endif
  197065. #endif
  197066. #if defined(PNG_gAMA_SUPPORTED)
  197067. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197068. void PNGAPI
  197069. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197070. {
  197071. double gamma;
  197072. png_debug1(1, "in %s storage function\n", "gAMA");
  197073. if (png_ptr == NULL || info_ptr == NULL)
  197074. return;
  197075. /* Check for overflow */
  197076. if (file_gamma > 21474.83)
  197077. {
  197078. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197079. gamma=21474.83;
  197080. }
  197081. else
  197082. gamma=file_gamma;
  197083. info_ptr->gamma = (float)gamma;
  197084. #ifdef PNG_FIXED_POINT_SUPPORTED
  197085. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197086. #endif
  197087. info_ptr->valid |= PNG_INFO_gAMA;
  197088. if(gamma == 0.0)
  197089. png_warning(png_ptr, "Setting gamma=0");
  197090. }
  197091. #endif
  197092. void PNGAPI
  197093. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197094. int_gamma)
  197095. {
  197096. png_fixed_point gamma;
  197097. png_debug1(1, "in %s storage function\n", "gAMA");
  197098. if (png_ptr == NULL || info_ptr == NULL)
  197099. return;
  197100. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197101. {
  197102. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197103. gamma=PNG_UINT_31_MAX;
  197104. }
  197105. else
  197106. {
  197107. if (int_gamma < 0)
  197108. {
  197109. png_warning(png_ptr, "Setting negative gamma to zero");
  197110. gamma=0;
  197111. }
  197112. else
  197113. gamma=int_gamma;
  197114. }
  197115. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197116. info_ptr->gamma = (float)(gamma/100000.);
  197117. #endif
  197118. #ifdef PNG_FIXED_POINT_SUPPORTED
  197119. info_ptr->int_gamma = gamma;
  197120. #endif
  197121. info_ptr->valid |= PNG_INFO_gAMA;
  197122. if(gamma == 0)
  197123. png_warning(png_ptr, "Setting gamma=0");
  197124. }
  197125. #endif
  197126. #if defined(PNG_hIST_SUPPORTED)
  197127. void PNGAPI
  197128. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197129. {
  197130. int i;
  197131. png_debug1(1, "in %s storage function\n", "hIST");
  197132. if (png_ptr == NULL || info_ptr == NULL)
  197133. return;
  197134. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197135. > PNG_MAX_PALETTE_LENGTH)
  197136. {
  197137. png_warning(png_ptr,
  197138. "Invalid palette size, hIST allocation skipped.");
  197139. return;
  197140. }
  197141. #ifdef PNG_FREE_ME_SUPPORTED
  197142. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197143. #endif
  197144. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197145. 1.2.1 */
  197146. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197147. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197148. if (png_ptr->hist == NULL)
  197149. {
  197150. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197151. return;
  197152. }
  197153. for (i = 0; i < info_ptr->num_palette; i++)
  197154. png_ptr->hist[i] = hist[i];
  197155. info_ptr->hist = png_ptr->hist;
  197156. info_ptr->valid |= PNG_INFO_hIST;
  197157. #ifdef PNG_FREE_ME_SUPPORTED
  197158. info_ptr->free_me |= PNG_FREE_HIST;
  197159. #else
  197160. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197161. #endif
  197162. }
  197163. #endif
  197164. void PNGAPI
  197165. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197166. png_uint_32 width, png_uint_32 height, int bit_depth,
  197167. int color_type, int interlace_type, int compression_type,
  197168. int filter_type)
  197169. {
  197170. png_debug1(1, "in %s storage function\n", "IHDR");
  197171. if (png_ptr == NULL || info_ptr == NULL)
  197172. return;
  197173. /* check for width and height valid values */
  197174. if (width == 0 || height == 0)
  197175. png_error(png_ptr, "Image width or height is zero in IHDR");
  197176. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197177. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197178. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197179. #else
  197180. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197181. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197182. #endif
  197183. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197184. png_error(png_ptr, "Invalid image size in IHDR");
  197185. if ( width > (PNG_UINT_32_MAX
  197186. >> 3) /* 8-byte RGBA pixels */
  197187. - 64 /* bigrowbuf hack */
  197188. - 1 /* filter byte */
  197189. - 7*8 /* rounding of width to multiple of 8 pixels */
  197190. - 8) /* extra max_pixel_depth pad */
  197191. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197192. /* check other values */
  197193. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197194. bit_depth != 8 && bit_depth != 16)
  197195. png_error(png_ptr, "Invalid bit depth in IHDR");
  197196. if (color_type < 0 || color_type == 1 ||
  197197. color_type == 5 || color_type > 6)
  197198. png_error(png_ptr, "Invalid color type in IHDR");
  197199. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197200. ((color_type == PNG_COLOR_TYPE_RGB ||
  197201. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197202. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197203. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197204. if (interlace_type >= PNG_INTERLACE_LAST)
  197205. png_error(png_ptr, "Unknown interlace method in IHDR");
  197206. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197207. png_error(png_ptr, "Unknown compression method in IHDR");
  197208. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197209. /* Accept filter_method 64 (intrapixel differencing) only if
  197210. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197211. * 2. Libpng did not read a PNG signature (this filter_method is only
  197212. * used in PNG datastreams that are embedded in MNG datastreams) and
  197213. * 3. The application called png_permit_mng_features with a mask that
  197214. * included PNG_FLAG_MNG_FILTER_64 and
  197215. * 4. The filter_method is 64 and
  197216. * 5. The color_type is RGB or RGBA
  197217. */
  197218. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197219. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197220. if(filter_type != PNG_FILTER_TYPE_BASE)
  197221. {
  197222. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197223. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197224. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197225. (color_type == PNG_COLOR_TYPE_RGB ||
  197226. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197227. png_error(png_ptr, "Unknown filter method in IHDR");
  197228. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197229. png_warning(png_ptr, "Invalid filter method in IHDR");
  197230. }
  197231. #else
  197232. if(filter_type != PNG_FILTER_TYPE_BASE)
  197233. png_error(png_ptr, "Unknown filter method in IHDR");
  197234. #endif
  197235. info_ptr->width = width;
  197236. info_ptr->height = height;
  197237. info_ptr->bit_depth = (png_byte)bit_depth;
  197238. info_ptr->color_type =(png_byte) color_type;
  197239. info_ptr->compression_type = (png_byte)compression_type;
  197240. info_ptr->filter_type = (png_byte)filter_type;
  197241. info_ptr->interlace_type = (png_byte)interlace_type;
  197242. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197243. info_ptr->channels = 1;
  197244. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197245. info_ptr->channels = 3;
  197246. else
  197247. info_ptr->channels = 1;
  197248. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197249. info_ptr->channels++;
  197250. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197251. /* check for potential overflow */
  197252. if (width > (PNG_UINT_32_MAX
  197253. >> 3) /* 8-byte RGBA pixels */
  197254. - 64 /* bigrowbuf hack */
  197255. - 1 /* filter byte */
  197256. - 7*8 /* rounding of width to multiple of 8 pixels */
  197257. - 8) /* extra max_pixel_depth pad */
  197258. info_ptr->rowbytes = (png_size_t)0;
  197259. else
  197260. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197261. }
  197262. #if defined(PNG_oFFs_SUPPORTED)
  197263. void PNGAPI
  197264. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197265. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197266. {
  197267. png_debug1(1, "in %s storage function\n", "oFFs");
  197268. if (png_ptr == NULL || info_ptr == NULL)
  197269. return;
  197270. info_ptr->x_offset = offset_x;
  197271. info_ptr->y_offset = offset_y;
  197272. info_ptr->offset_unit_type = (png_byte)unit_type;
  197273. info_ptr->valid |= PNG_INFO_oFFs;
  197274. }
  197275. #endif
  197276. #if defined(PNG_pCAL_SUPPORTED)
  197277. void PNGAPI
  197278. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197279. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197280. png_charp units, png_charpp params)
  197281. {
  197282. png_uint_32 length;
  197283. int i;
  197284. png_debug1(1, "in %s storage function\n", "pCAL");
  197285. if (png_ptr == NULL || info_ptr == NULL)
  197286. return;
  197287. length = png_strlen(purpose) + 1;
  197288. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197289. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197290. if (info_ptr->pcal_purpose == NULL)
  197291. {
  197292. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197293. return;
  197294. }
  197295. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197296. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197297. info_ptr->pcal_X0 = X0;
  197298. info_ptr->pcal_X1 = X1;
  197299. info_ptr->pcal_type = (png_byte)type;
  197300. info_ptr->pcal_nparams = (png_byte)nparams;
  197301. length = png_strlen(units) + 1;
  197302. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197303. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197304. if (info_ptr->pcal_units == NULL)
  197305. {
  197306. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197307. return;
  197308. }
  197309. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197310. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197311. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197312. if (info_ptr->pcal_params == NULL)
  197313. {
  197314. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197315. return;
  197316. }
  197317. info_ptr->pcal_params[nparams] = NULL;
  197318. for (i = 0; i < nparams; i++)
  197319. {
  197320. length = png_strlen(params[i]) + 1;
  197321. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197322. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197323. if (info_ptr->pcal_params[i] == NULL)
  197324. {
  197325. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197326. return;
  197327. }
  197328. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197329. }
  197330. info_ptr->valid |= PNG_INFO_pCAL;
  197331. #ifdef PNG_FREE_ME_SUPPORTED
  197332. info_ptr->free_me |= PNG_FREE_PCAL;
  197333. #endif
  197334. }
  197335. #endif
  197336. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197337. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197338. void PNGAPI
  197339. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197340. int unit, double width, double height)
  197341. {
  197342. png_debug1(1, "in %s storage function\n", "sCAL");
  197343. if (png_ptr == NULL || info_ptr == NULL)
  197344. return;
  197345. info_ptr->scal_unit = (png_byte)unit;
  197346. info_ptr->scal_pixel_width = width;
  197347. info_ptr->scal_pixel_height = height;
  197348. info_ptr->valid |= PNG_INFO_sCAL;
  197349. }
  197350. #else
  197351. #ifdef PNG_FIXED_POINT_SUPPORTED
  197352. void PNGAPI
  197353. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197354. int unit, png_charp swidth, png_charp sheight)
  197355. {
  197356. png_uint_32 length;
  197357. png_debug1(1, "in %s storage function\n", "sCAL");
  197358. if (png_ptr == NULL || info_ptr == NULL)
  197359. return;
  197360. info_ptr->scal_unit = (png_byte)unit;
  197361. length = png_strlen(swidth) + 1;
  197362. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197363. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197364. if (info_ptr->scal_s_width == NULL)
  197365. {
  197366. png_warning(png_ptr,
  197367. "Memory allocation failed while processing sCAL.");
  197368. }
  197369. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197370. length = png_strlen(sheight) + 1;
  197371. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197372. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197373. if (info_ptr->scal_s_height == NULL)
  197374. {
  197375. png_free (png_ptr, info_ptr->scal_s_width);
  197376. png_warning(png_ptr,
  197377. "Memory allocation failed while processing sCAL.");
  197378. }
  197379. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197380. info_ptr->valid |= PNG_INFO_sCAL;
  197381. #ifdef PNG_FREE_ME_SUPPORTED
  197382. info_ptr->free_me |= PNG_FREE_SCAL;
  197383. #endif
  197384. }
  197385. #endif
  197386. #endif
  197387. #endif
  197388. #if defined(PNG_pHYs_SUPPORTED)
  197389. void PNGAPI
  197390. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197391. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197392. {
  197393. png_debug1(1, "in %s storage function\n", "pHYs");
  197394. if (png_ptr == NULL || info_ptr == NULL)
  197395. return;
  197396. info_ptr->x_pixels_per_unit = res_x;
  197397. info_ptr->y_pixels_per_unit = res_y;
  197398. info_ptr->phys_unit_type = (png_byte)unit_type;
  197399. info_ptr->valid |= PNG_INFO_pHYs;
  197400. }
  197401. #endif
  197402. void PNGAPI
  197403. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197404. png_colorp palette, int num_palette)
  197405. {
  197406. png_debug1(1, "in %s storage function\n", "PLTE");
  197407. if (png_ptr == NULL || info_ptr == NULL)
  197408. return;
  197409. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197410. {
  197411. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197412. png_error(png_ptr, "Invalid palette length");
  197413. else
  197414. {
  197415. png_warning(png_ptr, "Invalid palette length");
  197416. return;
  197417. }
  197418. }
  197419. /*
  197420. * It may not actually be necessary to set png_ptr->palette here;
  197421. * we do it for backward compatibility with the way the png_handle_tRNS
  197422. * function used to do the allocation.
  197423. */
  197424. #ifdef PNG_FREE_ME_SUPPORTED
  197425. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197426. #endif
  197427. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197428. of num_palette entries,
  197429. in case of an invalid PNG file that has too-large sample values. */
  197430. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197431. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197432. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197433. png_sizeof(png_color));
  197434. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197435. info_ptr->palette = png_ptr->palette;
  197436. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197437. #ifdef PNG_FREE_ME_SUPPORTED
  197438. info_ptr->free_me |= PNG_FREE_PLTE;
  197439. #else
  197440. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197441. #endif
  197442. info_ptr->valid |= PNG_INFO_PLTE;
  197443. }
  197444. #if defined(PNG_sBIT_SUPPORTED)
  197445. void PNGAPI
  197446. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197447. png_color_8p sig_bit)
  197448. {
  197449. png_debug1(1, "in %s storage function\n", "sBIT");
  197450. if (png_ptr == NULL || info_ptr == NULL)
  197451. return;
  197452. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197453. info_ptr->valid |= PNG_INFO_sBIT;
  197454. }
  197455. #endif
  197456. #if defined(PNG_sRGB_SUPPORTED)
  197457. void PNGAPI
  197458. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197459. {
  197460. png_debug1(1, "in %s storage function\n", "sRGB");
  197461. if (png_ptr == NULL || info_ptr == NULL)
  197462. return;
  197463. info_ptr->srgb_intent = (png_byte)intent;
  197464. info_ptr->valid |= PNG_INFO_sRGB;
  197465. }
  197466. void PNGAPI
  197467. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197468. int intent)
  197469. {
  197470. #if defined(PNG_gAMA_SUPPORTED)
  197471. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197472. float file_gamma;
  197473. #endif
  197474. #ifdef PNG_FIXED_POINT_SUPPORTED
  197475. png_fixed_point int_file_gamma;
  197476. #endif
  197477. #endif
  197478. #if defined(PNG_cHRM_SUPPORTED)
  197479. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197480. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197481. #endif
  197482. #ifdef PNG_FIXED_POINT_SUPPORTED
  197483. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197484. int_green_y, int_blue_x, int_blue_y;
  197485. #endif
  197486. #endif
  197487. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197488. if (png_ptr == NULL || info_ptr == NULL)
  197489. return;
  197490. png_set_sRGB(png_ptr, info_ptr, intent);
  197491. #if defined(PNG_gAMA_SUPPORTED)
  197492. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197493. file_gamma = (float).45455;
  197494. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197495. #endif
  197496. #ifdef PNG_FIXED_POINT_SUPPORTED
  197497. int_file_gamma = 45455L;
  197498. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197499. #endif
  197500. #endif
  197501. #if defined(PNG_cHRM_SUPPORTED)
  197502. #ifdef PNG_FIXED_POINT_SUPPORTED
  197503. int_white_x = 31270L;
  197504. int_white_y = 32900L;
  197505. int_red_x = 64000L;
  197506. int_red_y = 33000L;
  197507. int_green_x = 30000L;
  197508. int_green_y = 60000L;
  197509. int_blue_x = 15000L;
  197510. int_blue_y = 6000L;
  197511. png_set_cHRM_fixed(png_ptr, info_ptr,
  197512. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197513. int_blue_x, int_blue_y);
  197514. #endif
  197515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197516. white_x = (float).3127;
  197517. white_y = (float).3290;
  197518. red_x = (float).64;
  197519. red_y = (float).33;
  197520. green_x = (float).30;
  197521. green_y = (float).60;
  197522. blue_x = (float).15;
  197523. blue_y = (float).06;
  197524. png_set_cHRM(png_ptr, info_ptr,
  197525. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197526. #endif
  197527. #endif
  197528. }
  197529. #endif
  197530. #if defined(PNG_iCCP_SUPPORTED)
  197531. void PNGAPI
  197532. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197533. png_charp name, int compression_type,
  197534. png_charp profile, png_uint_32 proflen)
  197535. {
  197536. png_charp new_iccp_name;
  197537. png_charp new_iccp_profile;
  197538. png_debug1(1, "in %s storage function\n", "iCCP");
  197539. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197540. return;
  197541. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197542. if (new_iccp_name == NULL)
  197543. {
  197544. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197545. return;
  197546. }
  197547. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197548. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197549. if (new_iccp_profile == NULL)
  197550. {
  197551. png_free (png_ptr, new_iccp_name);
  197552. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197553. return;
  197554. }
  197555. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197556. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197557. info_ptr->iccp_proflen = proflen;
  197558. info_ptr->iccp_name = new_iccp_name;
  197559. info_ptr->iccp_profile = new_iccp_profile;
  197560. /* Compression is always zero but is here so the API and info structure
  197561. * does not have to change if we introduce multiple compression types */
  197562. info_ptr->iccp_compression = (png_byte)compression_type;
  197563. #ifdef PNG_FREE_ME_SUPPORTED
  197564. info_ptr->free_me |= PNG_FREE_ICCP;
  197565. #endif
  197566. info_ptr->valid |= PNG_INFO_iCCP;
  197567. }
  197568. #endif
  197569. #if defined(PNG_TEXT_SUPPORTED)
  197570. void PNGAPI
  197571. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197572. int num_text)
  197573. {
  197574. int ret;
  197575. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197576. if (ret)
  197577. png_error(png_ptr, "Insufficient memory to store text");
  197578. }
  197579. int /* PRIVATE */
  197580. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197581. int num_text)
  197582. {
  197583. int i;
  197584. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197585. "text" : (png_const_charp)png_ptr->chunk_name));
  197586. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197587. return(0);
  197588. /* Make sure we have enough space in the "text" array in info_struct
  197589. * to hold all of the incoming text_ptr objects.
  197590. */
  197591. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197592. {
  197593. if (info_ptr->text != NULL)
  197594. {
  197595. png_textp old_text;
  197596. int old_max;
  197597. old_max = info_ptr->max_text;
  197598. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197599. old_text = info_ptr->text;
  197600. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197601. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197602. if (info_ptr->text == NULL)
  197603. {
  197604. png_free(png_ptr, old_text);
  197605. return(1);
  197606. }
  197607. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197608. png_sizeof(png_text)));
  197609. png_free(png_ptr, old_text);
  197610. }
  197611. else
  197612. {
  197613. info_ptr->max_text = num_text + 8;
  197614. info_ptr->num_text = 0;
  197615. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197616. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197617. if (info_ptr->text == NULL)
  197618. return(1);
  197619. #ifdef PNG_FREE_ME_SUPPORTED
  197620. info_ptr->free_me |= PNG_FREE_TEXT;
  197621. #endif
  197622. }
  197623. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197624. info_ptr->max_text);
  197625. }
  197626. for (i = 0; i < num_text; i++)
  197627. {
  197628. png_size_t text_length,key_len;
  197629. png_size_t lang_len,lang_key_len;
  197630. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197631. if (text_ptr[i].key == NULL)
  197632. continue;
  197633. key_len = png_strlen(text_ptr[i].key);
  197634. if(text_ptr[i].compression <= 0)
  197635. {
  197636. lang_len = 0;
  197637. lang_key_len = 0;
  197638. }
  197639. else
  197640. #ifdef PNG_iTXt_SUPPORTED
  197641. {
  197642. /* set iTXt data */
  197643. if (text_ptr[i].lang != NULL)
  197644. lang_len = png_strlen(text_ptr[i].lang);
  197645. else
  197646. lang_len = 0;
  197647. if (text_ptr[i].lang_key != NULL)
  197648. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197649. else
  197650. lang_key_len = 0;
  197651. }
  197652. #else
  197653. {
  197654. png_warning(png_ptr, "iTXt chunk not supported.");
  197655. continue;
  197656. }
  197657. #endif
  197658. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197659. {
  197660. text_length = 0;
  197661. #ifdef PNG_iTXt_SUPPORTED
  197662. if(text_ptr[i].compression > 0)
  197663. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197664. else
  197665. #endif
  197666. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197667. }
  197668. else
  197669. {
  197670. text_length = png_strlen(text_ptr[i].text);
  197671. textp->compression = text_ptr[i].compression;
  197672. }
  197673. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197674. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197675. if (textp->key == NULL)
  197676. return(1);
  197677. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197678. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197679. (int)textp->key);
  197680. png_memcpy(textp->key, text_ptr[i].key,
  197681. (png_size_t)(key_len));
  197682. *(textp->key+key_len) = '\0';
  197683. #ifdef PNG_iTXt_SUPPORTED
  197684. if (text_ptr[i].compression > 0)
  197685. {
  197686. textp->lang=textp->key + key_len + 1;
  197687. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197688. *(textp->lang+lang_len) = '\0';
  197689. textp->lang_key=textp->lang + lang_len + 1;
  197690. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197691. *(textp->lang_key+lang_key_len) = '\0';
  197692. textp->text=textp->lang_key + lang_key_len + 1;
  197693. }
  197694. else
  197695. #endif
  197696. {
  197697. #ifdef PNG_iTXt_SUPPORTED
  197698. textp->lang=NULL;
  197699. textp->lang_key=NULL;
  197700. #endif
  197701. textp->text=textp->key + key_len + 1;
  197702. }
  197703. if(text_length)
  197704. png_memcpy(textp->text, text_ptr[i].text,
  197705. (png_size_t)(text_length));
  197706. *(textp->text+text_length) = '\0';
  197707. #ifdef PNG_iTXt_SUPPORTED
  197708. if(textp->compression > 0)
  197709. {
  197710. textp->text_length = 0;
  197711. textp->itxt_length = text_length;
  197712. }
  197713. else
  197714. #endif
  197715. {
  197716. textp->text_length = text_length;
  197717. #ifdef PNG_iTXt_SUPPORTED
  197718. textp->itxt_length = 0;
  197719. #endif
  197720. }
  197721. info_ptr->num_text++;
  197722. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197723. }
  197724. return(0);
  197725. }
  197726. #endif
  197727. #if defined(PNG_tIME_SUPPORTED)
  197728. void PNGAPI
  197729. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197730. {
  197731. png_debug1(1, "in %s storage function\n", "tIME");
  197732. if (png_ptr == NULL || info_ptr == NULL ||
  197733. (png_ptr->mode & PNG_WROTE_tIME))
  197734. return;
  197735. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197736. info_ptr->valid |= PNG_INFO_tIME;
  197737. }
  197738. #endif
  197739. #if defined(PNG_tRNS_SUPPORTED)
  197740. void PNGAPI
  197741. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197742. png_bytep trans, int num_trans, png_color_16p trans_values)
  197743. {
  197744. png_debug1(1, "in %s storage function\n", "tRNS");
  197745. if (png_ptr == NULL || info_ptr == NULL)
  197746. return;
  197747. if (trans != NULL)
  197748. {
  197749. /*
  197750. * It may not actually be necessary to set png_ptr->trans here;
  197751. * we do it for backward compatibility with the way the png_handle_tRNS
  197752. * function used to do the allocation.
  197753. */
  197754. #ifdef PNG_FREE_ME_SUPPORTED
  197755. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197756. #endif
  197757. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197758. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197759. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197760. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197761. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197762. #ifdef PNG_FREE_ME_SUPPORTED
  197763. info_ptr->free_me |= PNG_FREE_TRNS;
  197764. #else
  197765. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197766. #endif
  197767. }
  197768. if (trans_values != NULL)
  197769. {
  197770. png_memcpy(&(info_ptr->trans_values), trans_values,
  197771. png_sizeof(png_color_16));
  197772. if (num_trans == 0)
  197773. num_trans = 1;
  197774. }
  197775. info_ptr->num_trans = (png_uint_16)num_trans;
  197776. info_ptr->valid |= PNG_INFO_tRNS;
  197777. }
  197778. #endif
  197779. #if defined(PNG_sPLT_SUPPORTED)
  197780. void PNGAPI
  197781. png_set_sPLT(png_structp png_ptr,
  197782. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197783. {
  197784. png_sPLT_tp np;
  197785. int i;
  197786. if (png_ptr == NULL || info_ptr == NULL)
  197787. return;
  197788. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197789. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197790. if (np == NULL)
  197791. {
  197792. png_warning(png_ptr, "No memory for sPLT palettes.");
  197793. return;
  197794. }
  197795. png_memcpy(np, info_ptr->splt_palettes,
  197796. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197797. png_free(png_ptr, info_ptr->splt_palettes);
  197798. info_ptr->splt_palettes=NULL;
  197799. for (i = 0; i < nentries; i++)
  197800. {
  197801. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197802. png_sPLT_tp from = entries + i;
  197803. to->name = (png_charp)png_malloc_warn(png_ptr,
  197804. png_strlen(from->name) + 1);
  197805. if (to->name == NULL)
  197806. {
  197807. png_warning(png_ptr,
  197808. "Out of memory while processing sPLT chunk");
  197809. }
  197810. /* TODO: use png_malloc_warn */
  197811. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197812. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197813. from->nentries * png_sizeof(png_sPLT_entry));
  197814. /* TODO: use png_malloc_warn */
  197815. png_memcpy(to->entries, from->entries,
  197816. from->nentries * png_sizeof(png_sPLT_entry));
  197817. if (to->entries == NULL)
  197818. {
  197819. png_warning(png_ptr,
  197820. "Out of memory while processing sPLT chunk");
  197821. png_free(png_ptr,to->name);
  197822. to->name = NULL;
  197823. }
  197824. to->nentries = from->nentries;
  197825. to->depth = from->depth;
  197826. }
  197827. info_ptr->splt_palettes = np;
  197828. info_ptr->splt_palettes_num += nentries;
  197829. info_ptr->valid |= PNG_INFO_sPLT;
  197830. #ifdef PNG_FREE_ME_SUPPORTED
  197831. info_ptr->free_me |= PNG_FREE_SPLT;
  197832. #endif
  197833. }
  197834. #endif /* PNG_sPLT_SUPPORTED */
  197835. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197836. void PNGAPI
  197837. png_set_unknown_chunks(png_structp png_ptr,
  197838. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197839. {
  197840. png_unknown_chunkp np;
  197841. int i;
  197842. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197843. return;
  197844. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197845. (info_ptr->unknown_chunks_num + num_unknowns) *
  197846. png_sizeof(png_unknown_chunk));
  197847. if (np == NULL)
  197848. {
  197849. png_warning(png_ptr,
  197850. "Out of memory while processing unknown chunk.");
  197851. return;
  197852. }
  197853. png_memcpy(np, info_ptr->unknown_chunks,
  197854. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197855. png_free(png_ptr, info_ptr->unknown_chunks);
  197856. info_ptr->unknown_chunks=NULL;
  197857. for (i = 0; i < num_unknowns; i++)
  197858. {
  197859. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197860. png_unknown_chunkp from = unknowns + i;
  197861. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197862. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197863. if (to->data == NULL)
  197864. {
  197865. png_warning(png_ptr,
  197866. "Out of memory while processing unknown chunk.");
  197867. }
  197868. else
  197869. {
  197870. png_memcpy(to->data, from->data, from->size);
  197871. to->size = from->size;
  197872. /* note our location in the read or write sequence */
  197873. to->location = (png_byte)(png_ptr->mode & 0xff);
  197874. }
  197875. }
  197876. info_ptr->unknown_chunks = np;
  197877. info_ptr->unknown_chunks_num += num_unknowns;
  197878. #ifdef PNG_FREE_ME_SUPPORTED
  197879. info_ptr->free_me |= PNG_FREE_UNKN;
  197880. #endif
  197881. }
  197882. void PNGAPI
  197883. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197884. int chunk, int location)
  197885. {
  197886. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197887. (int)info_ptr->unknown_chunks_num)
  197888. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197889. }
  197890. #endif
  197891. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197892. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197893. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197894. void PNGAPI
  197895. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197896. {
  197897. /* This function is deprecated in favor of png_permit_mng_features()
  197898. and will be removed from libpng-1.3.0 */
  197899. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197900. if (png_ptr == NULL)
  197901. return;
  197902. png_ptr->mng_features_permitted = (png_byte)
  197903. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197904. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197905. }
  197906. #endif
  197907. #endif
  197908. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197909. png_uint_32 PNGAPI
  197910. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197911. {
  197912. png_debug(1, "in png_permit_mng_features\n");
  197913. if (png_ptr == NULL)
  197914. return (png_uint_32)0;
  197915. png_ptr->mng_features_permitted =
  197916. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197917. return (png_uint_32)png_ptr->mng_features_permitted;
  197918. }
  197919. #endif
  197920. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197921. void PNGAPI
  197922. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197923. chunk_list, int num_chunks)
  197924. {
  197925. png_bytep new_list, p;
  197926. int i, old_num_chunks;
  197927. if (png_ptr == NULL)
  197928. return;
  197929. if (num_chunks == 0)
  197930. {
  197931. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197932. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197933. else
  197934. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197935. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197936. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197937. else
  197938. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197939. return;
  197940. }
  197941. if (chunk_list == NULL)
  197942. return;
  197943. old_num_chunks=png_ptr->num_chunk_list;
  197944. new_list=(png_bytep)png_malloc(png_ptr,
  197945. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197946. if(png_ptr->chunk_list != NULL)
  197947. {
  197948. png_memcpy(new_list, png_ptr->chunk_list,
  197949. (png_size_t)(5*old_num_chunks));
  197950. png_free(png_ptr, png_ptr->chunk_list);
  197951. png_ptr->chunk_list=NULL;
  197952. }
  197953. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197954. (png_size_t)(5*num_chunks));
  197955. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197956. *p=(png_byte)keep;
  197957. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197958. png_ptr->chunk_list=new_list;
  197959. #ifdef PNG_FREE_ME_SUPPORTED
  197960. png_ptr->free_me |= PNG_FREE_LIST;
  197961. #endif
  197962. }
  197963. #endif
  197964. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197965. void PNGAPI
  197966. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197967. png_user_chunk_ptr read_user_chunk_fn)
  197968. {
  197969. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197970. if (png_ptr == NULL)
  197971. return;
  197972. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197973. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197974. }
  197975. #endif
  197976. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197977. void PNGAPI
  197978. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197979. {
  197980. png_debug1(1, "in %s storage function\n", "rows");
  197981. if (png_ptr == NULL || info_ptr == NULL)
  197982. return;
  197983. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197984. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197985. info_ptr->row_pointers = row_pointers;
  197986. if(row_pointers)
  197987. info_ptr->valid |= PNG_INFO_IDAT;
  197988. }
  197989. #endif
  197990. #ifdef PNG_WRITE_SUPPORTED
  197991. void PNGAPI
  197992. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197993. {
  197994. if (png_ptr == NULL)
  197995. return;
  197996. if(png_ptr->zbuf)
  197997. png_free(png_ptr, png_ptr->zbuf);
  197998. png_ptr->zbuf_size = (png_size_t)size;
  197999. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198000. png_ptr->zstream.next_out = png_ptr->zbuf;
  198001. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198002. }
  198003. #endif
  198004. void PNGAPI
  198005. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198006. {
  198007. if (png_ptr && info_ptr)
  198008. info_ptr->valid &= ~(mask);
  198009. }
  198010. #ifndef PNG_1_0_X
  198011. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198012. /* function was added to libpng 1.2.0 and should always exist by default */
  198013. void PNGAPI
  198014. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198015. {
  198016. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198017. if (png_ptr != NULL)
  198018. png_ptr->asm_flags = 0;
  198019. }
  198020. /* this function was added to libpng 1.2.0 */
  198021. void PNGAPI
  198022. png_set_mmx_thresholds (png_structp png_ptr,
  198023. png_byte,
  198024. png_uint_32)
  198025. {
  198026. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198027. if (png_ptr == NULL)
  198028. return;
  198029. }
  198030. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198031. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198032. /* this function was added to libpng 1.2.6 */
  198033. void PNGAPI
  198034. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198035. png_uint_32 user_height_max)
  198036. {
  198037. /* Images with dimensions larger than these limits will be
  198038. * rejected by png_set_IHDR(). To accept any PNG datastream
  198039. * regardless of dimensions, set both limits to 0x7ffffffL.
  198040. */
  198041. if(png_ptr == NULL) return;
  198042. png_ptr->user_width_max = user_width_max;
  198043. png_ptr->user_height_max = user_height_max;
  198044. }
  198045. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198046. #endif /* ?PNG_1_0_X */
  198047. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198048. /*** End of inlined file: pngset.c ***/
  198049. /*** Start of inlined file: pngtrans.c ***/
  198050. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198051. *
  198052. * Last changed in libpng 1.2.17 May 15, 2007
  198053. * For conditions of distribution and use, see copyright notice in png.h
  198054. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198055. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198056. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198057. */
  198058. #define PNG_INTERNAL
  198059. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198060. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198061. /* turn on BGR-to-RGB mapping */
  198062. void PNGAPI
  198063. png_set_bgr(png_structp png_ptr)
  198064. {
  198065. png_debug(1, "in png_set_bgr\n");
  198066. if(png_ptr == NULL) return;
  198067. png_ptr->transformations |= PNG_BGR;
  198068. }
  198069. #endif
  198070. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198071. /* turn on 16 bit byte swapping */
  198072. void PNGAPI
  198073. png_set_swap(png_structp png_ptr)
  198074. {
  198075. png_debug(1, "in png_set_swap\n");
  198076. if(png_ptr == NULL) return;
  198077. if (png_ptr->bit_depth == 16)
  198078. png_ptr->transformations |= PNG_SWAP_BYTES;
  198079. }
  198080. #endif
  198081. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198082. /* turn on pixel packing */
  198083. void PNGAPI
  198084. png_set_packing(png_structp png_ptr)
  198085. {
  198086. png_debug(1, "in png_set_packing\n");
  198087. if(png_ptr == NULL) return;
  198088. if (png_ptr->bit_depth < 8)
  198089. {
  198090. png_ptr->transformations |= PNG_PACK;
  198091. png_ptr->usr_bit_depth = 8;
  198092. }
  198093. }
  198094. #endif
  198095. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198096. /* turn on packed pixel swapping */
  198097. void PNGAPI
  198098. png_set_packswap(png_structp png_ptr)
  198099. {
  198100. png_debug(1, "in png_set_packswap\n");
  198101. if(png_ptr == NULL) return;
  198102. if (png_ptr->bit_depth < 8)
  198103. png_ptr->transformations |= PNG_PACKSWAP;
  198104. }
  198105. #endif
  198106. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198107. void PNGAPI
  198108. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198109. {
  198110. png_debug(1, "in png_set_shift\n");
  198111. if(png_ptr == NULL) return;
  198112. png_ptr->transformations |= PNG_SHIFT;
  198113. png_ptr->shift = *true_bits;
  198114. }
  198115. #endif
  198116. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198117. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198118. int PNGAPI
  198119. png_set_interlace_handling(png_structp png_ptr)
  198120. {
  198121. png_debug(1, "in png_set_interlace handling\n");
  198122. if (png_ptr && png_ptr->interlaced)
  198123. {
  198124. png_ptr->transformations |= PNG_INTERLACE;
  198125. return (7);
  198126. }
  198127. return (1);
  198128. }
  198129. #endif
  198130. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198131. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198132. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198133. * for 48-bit input data, as well as to avoid problems with some compilers
  198134. * that don't like bytes as parameters.
  198135. */
  198136. void PNGAPI
  198137. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198138. {
  198139. png_debug(1, "in png_set_filler\n");
  198140. if(png_ptr == NULL) return;
  198141. png_ptr->transformations |= PNG_FILLER;
  198142. png_ptr->filler = (png_byte)filler;
  198143. if (filler_loc == PNG_FILLER_AFTER)
  198144. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198145. else
  198146. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198147. /* This should probably go in the "do_read_filler" routine.
  198148. * I attempted to do that in libpng-1.0.1a but that caused problems
  198149. * so I restored it in libpng-1.0.2a
  198150. */
  198151. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198152. {
  198153. png_ptr->usr_channels = 4;
  198154. }
  198155. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198156. * a less-than-8-bit grayscale to GA? */
  198157. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198158. {
  198159. png_ptr->usr_channels = 2;
  198160. }
  198161. }
  198162. #if !defined(PNG_1_0_X)
  198163. /* Added to libpng-1.2.7 */
  198164. void PNGAPI
  198165. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198166. {
  198167. png_debug(1, "in png_set_add_alpha\n");
  198168. if(png_ptr == NULL) return;
  198169. png_set_filler(png_ptr, filler, filler_loc);
  198170. png_ptr->transformations |= PNG_ADD_ALPHA;
  198171. }
  198172. #endif
  198173. #endif
  198174. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198175. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198176. void PNGAPI
  198177. png_set_swap_alpha(png_structp png_ptr)
  198178. {
  198179. png_debug(1, "in png_set_swap_alpha\n");
  198180. if(png_ptr == NULL) return;
  198181. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198182. }
  198183. #endif
  198184. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198185. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198186. void PNGAPI
  198187. png_set_invert_alpha(png_structp png_ptr)
  198188. {
  198189. png_debug(1, "in png_set_invert_alpha\n");
  198190. if(png_ptr == NULL) return;
  198191. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198192. }
  198193. #endif
  198194. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198195. void PNGAPI
  198196. png_set_invert_mono(png_structp png_ptr)
  198197. {
  198198. png_debug(1, "in png_set_invert_mono\n");
  198199. if(png_ptr == NULL) return;
  198200. png_ptr->transformations |= PNG_INVERT_MONO;
  198201. }
  198202. /* invert monochrome grayscale data */
  198203. void /* PRIVATE */
  198204. png_do_invert(png_row_infop row_info, png_bytep row)
  198205. {
  198206. png_debug(1, "in png_do_invert\n");
  198207. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198208. * if (row_info->bit_depth == 1 &&
  198209. */
  198210. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198211. if (row == NULL || row_info == NULL)
  198212. return;
  198213. #endif
  198214. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198215. {
  198216. png_bytep rp = row;
  198217. png_uint_32 i;
  198218. png_uint_32 istop = row_info->rowbytes;
  198219. for (i = 0; i < istop; i++)
  198220. {
  198221. *rp = (png_byte)(~(*rp));
  198222. rp++;
  198223. }
  198224. }
  198225. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198226. row_info->bit_depth == 8)
  198227. {
  198228. png_bytep rp = row;
  198229. png_uint_32 i;
  198230. png_uint_32 istop = row_info->rowbytes;
  198231. for (i = 0; i < istop; i+=2)
  198232. {
  198233. *rp = (png_byte)(~(*rp));
  198234. rp+=2;
  198235. }
  198236. }
  198237. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198238. row_info->bit_depth == 16)
  198239. {
  198240. png_bytep rp = row;
  198241. png_uint_32 i;
  198242. png_uint_32 istop = row_info->rowbytes;
  198243. for (i = 0; i < istop; i+=4)
  198244. {
  198245. *rp = (png_byte)(~(*rp));
  198246. *(rp+1) = (png_byte)(~(*(rp+1)));
  198247. rp+=4;
  198248. }
  198249. }
  198250. }
  198251. #endif
  198252. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198253. /* swaps byte order on 16 bit depth images */
  198254. void /* PRIVATE */
  198255. png_do_swap(png_row_infop row_info, png_bytep row)
  198256. {
  198257. png_debug(1, "in png_do_swap\n");
  198258. if (
  198259. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198260. row != NULL && row_info != NULL &&
  198261. #endif
  198262. row_info->bit_depth == 16)
  198263. {
  198264. png_bytep rp = row;
  198265. png_uint_32 i;
  198266. png_uint_32 istop= row_info->width * row_info->channels;
  198267. for (i = 0; i < istop; i++, rp += 2)
  198268. {
  198269. png_byte t = *rp;
  198270. *rp = *(rp + 1);
  198271. *(rp + 1) = t;
  198272. }
  198273. }
  198274. }
  198275. #endif
  198276. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198277. static PNG_CONST png_byte onebppswaptable[256] = {
  198278. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198279. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198280. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198281. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198282. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198283. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198284. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198285. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198286. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198287. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198288. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198289. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198290. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198291. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198292. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198293. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198294. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198295. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198296. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198297. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198298. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198299. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198300. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198301. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198302. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198303. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198304. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198305. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198306. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198307. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198308. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198309. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198310. };
  198311. static PNG_CONST png_byte twobppswaptable[256] = {
  198312. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198313. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198314. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198315. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198316. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198317. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198318. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198319. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198320. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198321. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198322. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198323. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198324. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198325. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198326. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198327. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198328. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198329. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198330. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198331. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198332. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198333. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198334. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198335. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198336. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198337. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198338. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198339. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198340. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198341. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198342. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198343. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198344. };
  198345. static PNG_CONST png_byte fourbppswaptable[256] = {
  198346. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198347. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198348. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198349. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198350. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198351. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198352. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198353. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198354. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198355. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198356. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198357. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198358. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198359. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198360. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198361. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198362. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198363. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198364. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198365. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198366. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198367. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198368. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198369. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198370. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198371. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198372. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198373. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198374. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198375. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198376. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198377. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198378. };
  198379. /* swaps pixel packing order within bytes */
  198380. void /* PRIVATE */
  198381. png_do_packswap(png_row_infop row_info, png_bytep row)
  198382. {
  198383. png_debug(1, "in png_do_packswap\n");
  198384. if (
  198385. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198386. row != NULL && row_info != NULL &&
  198387. #endif
  198388. row_info->bit_depth < 8)
  198389. {
  198390. png_bytep rp, end, table;
  198391. end = row + row_info->rowbytes;
  198392. if (row_info->bit_depth == 1)
  198393. table = (png_bytep)onebppswaptable;
  198394. else if (row_info->bit_depth == 2)
  198395. table = (png_bytep)twobppswaptable;
  198396. else if (row_info->bit_depth == 4)
  198397. table = (png_bytep)fourbppswaptable;
  198398. else
  198399. return;
  198400. for (rp = row; rp < end; rp++)
  198401. *rp = table[*rp];
  198402. }
  198403. }
  198404. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198405. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198406. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198407. /* remove filler or alpha byte(s) */
  198408. void /* PRIVATE */
  198409. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198410. {
  198411. png_debug(1, "in png_do_strip_filler\n");
  198412. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198413. if (row != NULL && row_info != NULL)
  198414. #endif
  198415. {
  198416. png_bytep sp=row;
  198417. png_bytep dp=row;
  198418. png_uint_32 row_width=row_info->width;
  198419. png_uint_32 i;
  198420. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198421. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198422. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198423. row_info->channels == 4)
  198424. {
  198425. if (row_info->bit_depth == 8)
  198426. {
  198427. /* This converts from RGBX or RGBA to RGB */
  198428. if (flags & PNG_FLAG_FILLER_AFTER)
  198429. {
  198430. dp+=3; sp+=4;
  198431. for (i = 1; i < row_width; i++)
  198432. {
  198433. *dp++ = *sp++;
  198434. *dp++ = *sp++;
  198435. *dp++ = *sp++;
  198436. sp++;
  198437. }
  198438. }
  198439. /* This converts from XRGB or ARGB to RGB */
  198440. else
  198441. {
  198442. for (i = 0; i < row_width; i++)
  198443. {
  198444. sp++;
  198445. *dp++ = *sp++;
  198446. *dp++ = *sp++;
  198447. *dp++ = *sp++;
  198448. }
  198449. }
  198450. row_info->pixel_depth = 24;
  198451. row_info->rowbytes = row_width * 3;
  198452. }
  198453. else /* if (row_info->bit_depth == 16) */
  198454. {
  198455. if (flags & PNG_FLAG_FILLER_AFTER)
  198456. {
  198457. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198458. sp += 8; dp += 6;
  198459. for (i = 1; i < row_width; i++)
  198460. {
  198461. /* This could be (although png_memcpy is probably slower):
  198462. png_memcpy(dp, sp, 6);
  198463. sp += 8;
  198464. dp += 6;
  198465. */
  198466. *dp++ = *sp++;
  198467. *dp++ = *sp++;
  198468. *dp++ = *sp++;
  198469. *dp++ = *sp++;
  198470. *dp++ = *sp++;
  198471. *dp++ = *sp++;
  198472. sp += 2;
  198473. }
  198474. }
  198475. else
  198476. {
  198477. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198478. for (i = 0; i < row_width; i++)
  198479. {
  198480. /* This could be (although png_memcpy is probably slower):
  198481. png_memcpy(dp, sp, 6);
  198482. sp += 8;
  198483. dp += 6;
  198484. */
  198485. sp+=2;
  198486. *dp++ = *sp++;
  198487. *dp++ = *sp++;
  198488. *dp++ = *sp++;
  198489. *dp++ = *sp++;
  198490. *dp++ = *sp++;
  198491. *dp++ = *sp++;
  198492. }
  198493. }
  198494. row_info->pixel_depth = 48;
  198495. row_info->rowbytes = row_width * 6;
  198496. }
  198497. row_info->channels = 3;
  198498. }
  198499. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198500. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198501. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198502. row_info->channels == 2)
  198503. {
  198504. if (row_info->bit_depth == 8)
  198505. {
  198506. /* This converts from GX or GA to G */
  198507. if (flags & PNG_FLAG_FILLER_AFTER)
  198508. {
  198509. for (i = 0; i < row_width; i++)
  198510. {
  198511. *dp++ = *sp++;
  198512. sp++;
  198513. }
  198514. }
  198515. /* This converts from XG or AG to G */
  198516. else
  198517. {
  198518. for (i = 0; i < row_width; i++)
  198519. {
  198520. sp++;
  198521. *dp++ = *sp++;
  198522. }
  198523. }
  198524. row_info->pixel_depth = 8;
  198525. row_info->rowbytes = row_width;
  198526. }
  198527. else /* if (row_info->bit_depth == 16) */
  198528. {
  198529. if (flags & PNG_FLAG_FILLER_AFTER)
  198530. {
  198531. /* This converts from GGXX or GGAA to GG */
  198532. sp += 4; dp += 2;
  198533. for (i = 1; i < row_width; i++)
  198534. {
  198535. *dp++ = *sp++;
  198536. *dp++ = *sp++;
  198537. sp += 2;
  198538. }
  198539. }
  198540. else
  198541. {
  198542. /* This converts from XXGG or AAGG to GG */
  198543. for (i = 0; i < row_width; i++)
  198544. {
  198545. sp += 2;
  198546. *dp++ = *sp++;
  198547. *dp++ = *sp++;
  198548. }
  198549. }
  198550. row_info->pixel_depth = 16;
  198551. row_info->rowbytes = row_width * 2;
  198552. }
  198553. row_info->channels = 1;
  198554. }
  198555. if (flags & PNG_FLAG_STRIP_ALPHA)
  198556. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198557. }
  198558. }
  198559. #endif
  198560. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198561. /* swaps red and blue bytes within a pixel */
  198562. void /* PRIVATE */
  198563. png_do_bgr(png_row_infop row_info, png_bytep row)
  198564. {
  198565. png_debug(1, "in png_do_bgr\n");
  198566. if (
  198567. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198568. row != NULL && row_info != NULL &&
  198569. #endif
  198570. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198571. {
  198572. png_uint_32 row_width = row_info->width;
  198573. if (row_info->bit_depth == 8)
  198574. {
  198575. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198576. {
  198577. png_bytep rp;
  198578. png_uint_32 i;
  198579. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198580. {
  198581. png_byte save = *rp;
  198582. *rp = *(rp + 2);
  198583. *(rp + 2) = save;
  198584. }
  198585. }
  198586. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198587. {
  198588. png_bytep rp;
  198589. png_uint_32 i;
  198590. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198591. {
  198592. png_byte save = *rp;
  198593. *rp = *(rp + 2);
  198594. *(rp + 2) = save;
  198595. }
  198596. }
  198597. }
  198598. else if (row_info->bit_depth == 16)
  198599. {
  198600. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198601. {
  198602. png_bytep rp;
  198603. png_uint_32 i;
  198604. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198605. {
  198606. png_byte save = *rp;
  198607. *rp = *(rp + 4);
  198608. *(rp + 4) = save;
  198609. save = *(rp + 1);
  198610. *(rp + 1) = *(rp + 5);
  198611. *(rp + 5) = save;
  198612. }
  198613. }
  198614. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198615. {
  198616. png_bytep rp;
  198617. png_uint_32 i;
  198618. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198619. {
  198620. png_byte save = *rp;
  198621. *rp = *(rp + 4);
  198622. *(rp + 4) = save;
  198623. save = *(rp + 1);
  198624. *(rp + 1) = *(rp + 5);
  198625. *(rp + 5) = save;
  198626. }
  198627. }
  198628. }
  198629. }
  198630. }
  198631. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198632. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198633. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198634. defined(PNG_LEGACY_SUPPORTED)
  198635. void PNGAPI
  198636. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198637. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198638. {
  198639. png_debug(1, "in png_set_user_transform_info\n");
  198640. if(png_ptr == NULL) return;
  198641. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198642. png_ptr->user_transform_ptr = user_transform_ptr;
  198643. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198644. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198645. #else
  198646. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198647. png_warning(png_ptr,
  198648. "This version of libpng does not support user transform info");
  198649. #endif
  198650. }
  198651. #endif
  198652. /* This function returns a pointer to the user_transform_ptr associated with
  198653. * the user transform functions. The application should free any memory
  198654. * associated with this pointer before png_write_destroy and png_read_destroy
  198655. * are called.
  198656. */
  198657. png_voidp PNGAPI
  198658. png_get_user_transform_ptr(png_structp png_ptr)
  198659. {
  198660. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198661. if (png_ptr == NULL) return (NULL);
  198662. return ((png_voidp)png_ptr->user_transform_ptr);
  198663. #else
  198664. return (NULL);
  198665. #endif
  198666. }
  198667. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198668. /*** End of inlined file: pngtrans.c ***/
  198669. /*** Start of inlined file: pngwio.c ***/
  198670. /* pngwio.c - functions for data output
  198671. *
  198672. * Last changed in libpng 1.2.13 November 13, 2006
  198673. * For conditions of distribution and use, see copyright notice in png.h
  198674. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198675. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198676. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198677. *
  198678. * This file provides a location for all output. Users who need
  198679. * special handling are expected to write functions that have the same
  198680. * arguments as these and perform similar functions, but that possibly
  198681. * use different output methods. Note that you shouldn't change these
  198682. * functions, but rather write replacement functions and then change
  198683. * them at run time with png_set_write_fn(...).
  198684. */
  198685. #define PNG_INTERNAL
  198686. #ifdef PNG_WRITE_SUPPORTED
  198687. /* Write the data to whatever output you are using. The default routine
  198688. writes to a file pointer. Note that this routine sometimes gets called
  198689. with very small lengths, so you should implement some kind of simple
  198690. buffering if you are using unbuffered writes. This should never be asked
  198691. to write more than 64K on a 16 bit machine. */
  198692. void /* PRIVATE */
  198693. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198694. {
  198695. if (png_ptr->write_data_fn != NULL )
  198696. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198697. else
  198698. png_error(png_ptr, "Call to NULL write function");
  198699. }
  198700. #if !defined(PNG_NO_STDIO)
  198701. /* This is the function that does the actual writing of data. If you are
  198702. not writing to a standard C stream, you should create a replacement
  198703. write_data function and use it at run time with png_set_write_fn(), rather
  198704. than changing the library. */
  198705. #ifndef USE_FAR_KEYWORD
  198706. void PNGAPI
  198707. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198708. {
  198709. png_uint_32 check;
  198710. if(png_ptr == NULL) return;
  198711. #if defined(_WIN32_WCE)
  198712. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198713. check = 0;
  198714. #else
  198715. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198716. #endif
  198717. if (check != length)
  198718. png_error(png_ptr, "Write Error");
  198719. }
  198720. #else
  198721. /* this is the model-independent version. Since the standard I/O library
  198722. can't handle far buffers in the medium and small models, we have to copy
  198723. the data.
  198724. */
  198725. #define NEAR_BUF_SIZE 1024
  198726. #define MIN(a,b) (a <= b ? a : b)
  198727. void PNGAPI
  198728. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198729. {
  198730. png_uint_32 check;
  198731. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198732. png_FILE_p io_ptr;
  198733. if(png_ptr == NULL) return;
  198734. /* Check if data really is near. If so, use usual code. */
  198735. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198736. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198737. if ((png_bytep)near_data == data)
  198738. {
  198739. #if defined(_WIN32_WCE)
  198740. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198741. check = 0;
  198742. #else
  198743. check = fwrite(near_data, 1, length, io_ptr);
  198744. #endif
  198745. }
  198746. else
  198747. {
  198748. png_byte buf[NEAR_BUF_SIZE];
  198749. png_size_t written, remaining, err;
  198750. check = 0;
  198751. remaining = length;
  198752. do
  198753. {
  198754. written = MIN(NEAR_BUF_SIZE, remaining);
  198755. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198756. #if defined(_WIN32_WCE)
  198757. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198758. err = 0;
  198759. #else
  198760. err = fwrite(buf, 1, written, io_ptr);
  198761. #endif
  198762. if (err != written)
  198763. break;
  198764. else
  198765. check += err;
  198766. data += written;
  198767. remaining -= written;
  198768. }
  198769. while (remaining != 0);
  198770. }
  198771. if (check != length)
  198772. png_error(png_ptr, "Write Error");
  198773. }
  198774. #endif
  198775. #endif
  198776. /* This function is called to output any data pending writing (normally
  198777. to disk). After png_flush is called, there should be no data pending
  198778. writing in any buffers. */
  198779. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198780. void /* PRIVATE */
  198781. png_flush(png_structp png_ptr)
  198782. {
  198783. if (png_ptr->output_flush_fn != NULL)
  198784. (*(png_ptr->output_flush_fn))(png_ptr);
  198785. }
  198786. #if !defined(PNG_NO_STDIO)
  198787. void PNGAPI
  198788. png_default_flush(png_structp png_ptr)
  198789. {
  198790. #if !defined(_WIN32_WCE)
  198791. png_FILE_p io_ptr;
  198792. #endif
  198793. if(png_ptr == NULL) return;
  198794. #if !defined(_WIN32_WCE)
  198795. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198796. if (io_ptr != NULL)
  198797. fflush(io_ptr);
  198798. #endif
  198799. }
  198800. #endif
  198801. #endif
  198802. /* This function allows the application to supply new output functions for
  198803. libpng if standard C streams aren't being used.
  198804. This function takes as its arguments:
  198805. png_ptr - pointer to a png output data structure
  198806. io_ptr - pointer to user supplied structure containing info about
  198807. the output functions. May be NULL.
  198808. write_data_fn - pointer to a new output function that takes as its
  198809. arguments a pointer to a png_struct, a pointer to
  198810. data to be written, and a 32-bit unsigned int that is
  198811. the number of bytes to be written. The new write
  198812. function should call png_error(png_ptr, "Error msg")
  198813. to exit and output any fatal error messages.
  198814. flush_data_fn - pointer to a new flush function that takes as its
  198815. arguments a pointer to a png_struct. After a call to
  198816. the flush function, there should be no data in any buffers
  198817. or pending transmission. If the output method doesn't do
  198818. any buffering of ouput, a function prototype must still be
  198819. supplied although it doesn't have to do anything. If
  198820. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198821. time, output_flush_fn will be ignored, although it must be
  198822. supplied for compatibility. */
  198823. void PNGAPI
  198824. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198825. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198826. {
  198827. if(png_ptr == NULL) return;
  198828. png_ptr->io_ptr = io_ptr;
  198829. #if !defined(PNG_NO_STDIO)
  198830. if (write_data_fn != NULL)
  198831. png_ptr->write_data_fn = write_data_fn;
  198832. else
  198833. png_ptr->write_data_fn = png_default_write_data;
  198834. #else
  198835. png_ptr->write_data_fn = write_data_fn;
  198836. #endif
  198837. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198838. #if !defined(PNG_NO_STDIO)
  198839. if (output_flush_fn != NULL)
  198840. png_ptr->output_flush_fn = output_flush_fn;
  198841. else
  198842. png_ptr->output_flush_fn = png_default_flush;
  198843. #else
  198844. png_ptr->output_flush_fn = output_flush_fn;
  198845. #endif
  198846. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198847. /* It is an error to read while writing a png file */
  198848. if (png_ptr->read_data_fn != NULL)
  198849. {
  198850. png_ptr->read_data_fn = NULL;
  198851. png_warning(png_ptr,
  198852. "Attempted to set both read_data_fn and write_data_fn in");
  198853. png_warning(png_ptr,
  198854. "the same structure. Resetting read_data_fn to NULL.");
  198855. }
  198856. }
  198857. #if defined(USE_FAR_KEYWORD)
  198858. #if defined(_MSC_VER)
  198859. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198860. {
  198861. void *near_ptr;
  198862. void FAR *far_ptr;
  198863. FP_OFF(near_ptr) = FP_OFF(ptr);
  198864. far_ptr = (void FAR *)near_ptr;
  198865. if(check != 0)
  198866. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198867. png_error(png_ptr,"segment lost in conversion");
  198868. return(near_ptr);
  198869. }
  198870. # else
  198871. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198872. {
  198873. void *near_ptr;
  198874. void FAR *far_ptr;
  198875. near_ptr = (void FAR *)ptr;
  198876. far_ptr = (void FAR *)near_ptr;
  198877. if(check != 0)
  198878. if(far_ptr != ptr)
  198879. png_error(png_ptr,"segment lost in conversion");
  198880. return(near_ptr);
  198881. }
  198882. # endif
  198883. # endif
  198884. #endif /* PNG_WRITE_SUPPORTED */
  198885. /*** End of inlined file: pngwio.c ***/
  198886. /*** Start of inlined file: pngwrite.c ***/
  198887. /* pngwrite.c - general routines to write a PNG file
  198888. *
  198889. * Last changed in libpng 1.2.15 January 5, 2007
  198890. * For conditions of distribution and use, see copyright notice in png.h
  198891. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198892. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198893. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198894. */
  198895. /* get internal access to png.h */
  198896. #define PNG_INTERNAL
  198897. #ifdef PNG_WRITE_SUPPORTED
  198898. /* Writes all the PNG information. This is the suggested way to use the
  198899. * library. If you have a new chunk to add, make a function to write it,
  198900. * and put it in the correct location here. If you want the chunk written
  198901. * after the image data, put it in png_write_end(). I strongly encourage
  198902. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198903. * the chunk, as that will keep the code from breaking if you want to just
  198904. * write a plain PNG file. If you have long comments, I suggest writing
  198905. * them in png_write_end(), and compressing them.
  198906. */
  198907. void PNGAPI
  198908. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198909. {
  198910. png_debug(1, "in png_write_info_before_PLTE\n");
  198911. if (png_ptr == NULL || info_ptr == NULL)
  198912. return;
  198913. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198914. {
  198915. png_write_sig(png_ptr); /* write PNG signature */
  198916. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198917. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198918. {
  198919. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198920. png_ptr->mng_features_permitted=0;
  198921. }
  198922. #endif
  198923. /* write IHDR information. */
  198924. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198925. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198926. info_ptr->filter_type,
  198927. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198928. info_ptr->interlace_type);
  198929. #else
  198930. 0);
  198931. #endif
  198932. /* the rest of these check to see if the valid field has the appropriate
  198933. flag set, and if it does, writes the chunk. */
  198934. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198935. if (info_ptr->valid & PNG_INFO_gAMA)
  198936. {
  198937. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198938. png_write_gAMA(png_ptr, info_ptr->gamma);
  198939. #else
  198940. #ifdef PNG_FIXED_POINT_SUPPORTED
  198941. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198942. # endif
  198943. #endif
  198944. }
  198945. #endif
  198946. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198947. if (info_ptr->valid & PNG_INFO_sRGB)
  198948. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198949. #endif
  198950. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198951. if (info_ptr->valid & PNG_INFO_iCCP)
  198952. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198953. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198954. #endif
  198955. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198956. if (info_ptr->valid & PNG_INFO_sBIT)
  198957. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198958. #endif
  198959. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198960. if (info_ptr->valid & PNG_INFO_cHRM)
  198961. {
  198962. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198963. png_write_cHRM(png_ptr,
  198964. info_ptr->x_white, info_ptr->y_white,
  198965. info_ptr->x_red, info_ptr->y_red,
  198966. info_ptr->x_green, info_ptr->y_green,
  198967. info_ptr->x_blue, info_ptr->y_blue);
  198968. #else
  198969. # ifdef PNG_FIXED_POINT_SUPPORTED
  198970. png_write_cHRM_fixed(png_ptr,
  198971. info_ptr->int_x_white, info_ptr->int_y_white,
  198972. info_ptr->int_x_red, info_ptr->int_y_red,
  198973. info_ptr->int_x_green, info_ptr->int_y_green,
  198974. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198975. # endif
  198976. #endif
  198977. }
  198978. #endif
  198979. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198980. if (info_ptr->unknown_chunks_num)
  198981. {
  198982. png_unknown_chunk *up;
  198983. png_debug(5, "writing extra chunks\n");
  198984. for (up = info_ptr->unknown_chunks;
  198985. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198986. up++)
  198987. {
  198988. int keep=png_handle_as_unknown(png_ptr, up->name);
  198989. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198990. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198991. !(up->location & PNG_HAVE_IDAT) &&
  198992. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198993. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198994. {
  198995. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198996. }
  198997. }
  198998. }
  198999. #endif
  199000. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199001. }
  199002. }
  199003. void PNGAPI
  199004. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199005. {
  199006. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199007. int i;
  199008. #endif
  199009. png_debug(1, "in png_write_info\n");
  199010. if (png_ptr == NULL || info_ptr == NULL)
  199011. return;
  199012. png_write_info_before_PLTE(png_ptr, info_ptr);
  199013. if (info_ptr->valid & PNG_INFO_PLTE)
  199014. png_write_PLTE(png_ptr, info_ptr->palette,
  199015. (png_uint_32)info_ptr->num_palette);
  199016. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199017. png_error(png_ptr, "Valid palette required for paletted images");
  199018. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199019. if (info_ptr->valid & PNG_INFO_tRNS)
  199020. {
  199021. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199022. /* invert the alpha channel (in tRNS) */
  199023. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199024. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199025. {
  199026. int j;
  199027. for (j=0; j<(int)info_ptr->num_trans; j++)
  199028. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199029. }
  199030. #endif
  199031. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199032. info_ptr->num_trans, info_ptr->color_type);
  199033. }
  199034. #endif
  199035. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199036. if (info_ptr->valid & PNG_INFO_bKGD)
  199037. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199038. #endif
  199039. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199040. if (info_ptr->valid & PNG_INFO_hIST)
  199041. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199042. #endif
  199043. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199044. if (info_ptr->valid & PNG_INFO_oFFs)
  199045. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199046. info_ptr->offset_unit_type);
  199047. #endif
  199048. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199049. if (info_ptr->valid & PNG_INFO_pCAL)
  199050. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199051. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199052. info_ptr->pcal_units, info_ptr->pcal_params);
  199053. #endif
  199054. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199055. if (info_ptr->valid & PNG_INFO_sCAL)
  199056. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199057. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199058. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199059. #else
  199060. #ifdef PNG_FIXED_POINT_SUPPORTED
  199061. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199062. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199063. #else
  199064. png_warning(png_ptr,
  199065. "png_write_sCAL not supported; sCAL chunk not written.");
  199066. #endif
  199067. #endif
  199068. #endif
  199069. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199070. if (info_ptr->valid & PNG_INFO_pHYs)
  199071. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199072. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199073. #endif
  199074. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199075. if (info_ptr->valid & PNG_INFO_tIME)
  199076. {
  199077. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199078. png_ptr->mode |= PNG_WROTE_tIME;
  199079. }
  199080. #endif
  199081. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199082. if (info_ptr->valid & PNG_INFO_sPLT)
  199083. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199084. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199085. #endif
  199086. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199087. /* Check to see if we need to write text chunks */
  199088. for (i = 0; i < info_ptr->num_text; i++)
  199089. {
  199090. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199091. info_ptr->text[i].compression);
  199092. /* an internationalized chunk? */
  199093. if (info_ptr->text[i].compression > 0)
  199094. {
  199095. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199096. /* write international chunk */
  199097. png_write_iTXt(png_ptr,
  199098. info_ptr->text[i].compression,
  199099. info_ptr->text[i].key,
  199100. info_ptr->text[i].lang,
  199101. info_ptr->text[i].lang_key,
  199102. info_ptr->text[i].text);
  199103. #else
  199104. png_warning(png_ptr, "Unable to write international text");
  199105. #endif
  199106. /* Mark this chunk as written */
  199107. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199108. }
  199109. /* If we want a compressed text chunk */
  199110. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199111. {
  199112. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199113. /* write compressed chunk */
  199114. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199115. info_ptr->text[i].text, 0,
  199116. info_ptr->text[i].compression);
  199117. #else
  199118. png_warning(png_ptr, "Unable to write compressed text");
  199119. #endif
  199120. /* Mark this chunk as written */
  199121. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199122. }
  199123. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199124. {
  199125. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199126. /* write uncompressed chunk */
  199127. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199128. info_ptr->text[i].text,
  199129. 0);
  199130. #else
  199131. png_warning(png_ptr, "Unable to write uncompressed text");
  199132. #endif
  199133. /* Mark this chunk as written */
  199134. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199135. }
  199136. }
  199137. #endif
  199138. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199139. if (info_ptr->unknown_chunks_num)
  199140. {
  199141. png_unknown_chunk *up;
  199142. png_debug(5, "writing extra chunks\n");
  199143. for (up = info_ptr->unknown_chunks;
  199144. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199145. up++)
  199146. {
  199147. int keep=png_handle_as_unknown(png_ptr, up->name);
  199148. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199149. up->location && (up->location & PNG_HAVE_PLTE) &&
  199150. !(up->location & PNG_HAVE_IDAT) &&
  199151. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199152. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199153. {
  199154. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199155. }
  199156. }
  199157. }
  199158. #endif
  199159. }
  199160. /* Writes the end of the PNG file. If you don't want to write comments or
  199161. * time information, you can pass NULL for info. If you already wrote these
  199162. * in png_write_info(), do not write them again here. If you have long
  199163. * comments, I suggest writing them here, and compressing them.
  199164. */
  199165. void PNGAPI
  199166. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199167. {
  199168. png_debug(1, "in png_write_end\n");
  199169. if (png_ptr == NULL)
  199170. return;
  199171. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199172. png_error(png_ptr, "No IDATs written into file");
  199173. /* see if user wants us to write information chunks */
  199174. if (info_ptr != NULL)
  199175. {
  199176. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199177. int i; /* local index variable */
  199178. #endif
  199179. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199180. /* check to see if user has supplied a time chunk */
  199181. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199182. !(png_ptr->mode & PNG_WROTE_tIME))
  199183. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199184. #endif
  199185. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199186. /* loop through comment chunks */
  199187. for (i = 0; i < info_ptr->num_text; i++)
  199188. {
  199189. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199190. info_ptr->text[i].compression);
  199191. /* an internationalized chunk? */
  199192. if (info_ptr->text[i].compression > 0)
  199193. {
  199194. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199195. /* write international chunk */
  199196. png_write_iTXt(png_ptr,
  199197. info_ptr->text[i].compression,
  199198. info_ptr->text[i].key,
  199199. info_ptr->text[i].lang,
  199200. info_ptr->text[i].lang_key,
  199201. info_ptr->text[i].text);
  199202. #else
  199203. png_warning(png_ptr, "Unable to write international text");
  199204. #endif
  199205. /* Mark this chunk as written */
  199206. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199207. }
  199208. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199209. {
  199210. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199211. /* write compressed chunk */
  199212. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199213. info_ptr->text[i].text, 0,
  199214. info_ptr->text[i].compression);
  199215. #else
  199216. png_warning(png_ptr, "Unable to write compressed text");
  199217. #endif
  199218. /* Mark this chunk as written */
  199219. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199220. }
  199221. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199222. {
  199223. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199224. /* write uncompressed chunk */
  199225. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199226. info_ptr->text[i].text, 0);
  199227. #else
  199228. png_warning(png_ptr, "Unable to write uncompressed text");
  199229. #endif
  199230. /* Mark this chunk as written */
  199231. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199232. }
  199233. }
  199234. #endif
  199235. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199236. if (info_ptr->unknown_chunks_num)
  199237. {
  199238. png_unknown_chunk *up;
  199239. png_debug(5, "writing extra chunks\n");
  199240. for (up = info_ptr->unknown_chunks;
  199241. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199242. up++)
  199243. {
  199244. int keep=png_handle_as_unknown(png_ptr, up->name);
  199245. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199246. up->location && (up->location & PNG_AFTER_IDAT) &&
  199247. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199248. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199249. {
  199250. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199251. }
  199252. }
  199253. }
  199254. #endif
  199255. }
  199256. png_ptr->mode |= PNG_AFTER_IDAT;
  199257. /* write end of PNG file */
  199258. png_write_IEND(png_ptr);
  199259. }
  199260. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199261. #if !defined(_WIN32_WCE)
  199262. /* "time.h" functions are not supported on WindowsCE */
  199263. void PNGAPI
  199264. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199265. {
  199266. png_debug(1, "in png_convert_from_struct_tm\n");
  199267. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199268. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199269. ptime->day = (png_byte)ttime->tm_mday;
  199270. ptime->hour = (png_byte)ttime->tm_hour;
  199271. ptime->minute = (png_byte)ttime->tm_min;
  199272. ptime->second = (png_byte)ttime->tm_sec;
  199273. }
  199274. void PNGAPI
  199275. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199276. {
  199277. struct tm *tbuf;
  199278. png_debug(1, "in png_convert_from_time_t\n");
  199279. tbuf = gmtime(&ttime);
  199280. png_convert_from_struct_tm(ptime, tbuf);
  199281. }
  199282. #endif
  199283. #endif
  199284. /* Initialize png_ptr structure, and allocate any memory needed */
  199285. png_structp PNGAPI
  199286. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199287. png_error_ptr error_fn, png_error_ptr warn_fn)
  199288. {
  199289. #ifdef PNG_USER_MEM_SUPPORTED
  199290. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199291. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199292. }
  199293. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199294. png_structp PNGAPI
  199295. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199296. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199297. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199298. {
  199299. #endif /* PNG_USER_MEM_SUPPORTED */
  199300. png_structp png_ptr;
  199301. #ifdef PNG_SETJMP_SUPPORTED
  199302. #ifdef USE_FAR_KEYWORD
  199303. jmp_buf jmpbuf;
  199304. #endif
  199305. #endif
  199306. int i;
  199307. png_debug(1, "in png_create_write_struct\n");
  199308. #ifdef PNG_USER_MEM_SUPPORTED
  199309. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199310. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199311. #else
  199312. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199313. #endif /* PNG_USER_MEM_SUPPORTED */
  199314. if (png_ptr == NULL)
  199315. return (NULL);
  199316. /* added at libpng-1.2.6 */
  199317. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199318. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199319. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199320. #endif
  199321. #ifdef PNG_SETJMP_SUPPORTED
  199322. #ifdef USE_FAR_KEYWORD
  199323. if (setjmp(jmpbuf))
  199324. #else
  199325. if (setjmp(png_ptr->jmpbuf))
  199326. #endif
  199327. {
  199328. png_free(png_ptr, png_ptr->zbuf);
  199329. png_ptr->zbuf=NULL;
  199330. png_destroy_struct(png_ptr);
  199331. return (NULL);
  199332. }
  199333. #ifdef USE_FAR_KEYWORD
  199334. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199335. #endif
  199336. #endif
  199337. #ifdef PNG_USER_MEM_SUPPORTED
  199338. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199339. #endif /* PNG_USER_MEM_SUPPORTED */
  199340. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199341. i=0;
  199342. do
  199343. {
  199344. if(user_png_ver[i] != png_libpng_ver[i])
  199345. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199346. } while (png_libpng_ver[i++]);
  199347. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199348. {
  199349. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199350. * we must recompile any applications that use any older library version.
  199351. * For versions after libpng 1.0, we will be compatible, so we need
  199352. * only check the first digit.
  199353. */
  199354. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199355. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199356. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199357. {
  199358. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199359. char msg[80];
  199360. if (user_png_ver)
  199361. {
  199362. png_snprintf(msg, 80,
  199363. "Application was compiled with png.h from libpng-%.20s",
  199364. user_png_ver);
  199365. png_warning(png_ptr, msg);
  199366. }
  199367. png_snprintf(msg, 80,
  199368. "Application is running with png.c from libpng-%.20s",
  199369. png_libpng_ver);
  199370. png_warning(png_ptr, msg);
  199371. #endif
  199372. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199373. png_ptr->flags=0;
  199374. #endif
  199375. png_error(png_ptr,
  199376. "Incompatible libpng version in application and library");
  199377. }
  199378. }
  199379. /* initialize zbuf - compression buffer */
  199380. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199381. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199382. (png_uint_32)png_ptr->zbuf_size);
  199383. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199384. png_flush_ptr_NULL);
  199385. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199386. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199387. 1, png_doublep_NULL, png_doublep_NULL);
  199388. #endif
  199389. #ifdef PNG_SETJMP_SUPPORTED
  199390. /* Applications that neglect to set up their own setjmp() and then encounter
  199391. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199392. abort instead of returning. */
  199393. #ifdef USE_FAR_KEYWORD
  199394. if (setjmp(jmpbuf))
  199395. PNG_ABORT();
  199396. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199397. #else
  199398. if (setjmp(png_ptr->jmpbuf))
  199399. PNG_ABORT();
  199400. #endif
  199401. #endif
  199402. return (png_ptr);
  199403. }
  199404. /* Initialize png_ptr structure, and allocate any memory needed */
  199405. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199406. /* Deprecated. */
  199407. #undef png_write_init
  199408. void PNGAPI
  199409. png_write_init(png_structp png_ptr)
  199410. {
  199411. /* We only come here via pre-1.0.7-compiled applications */
  199412. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199413. }
  199414. void PNGAPI
  199415. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199416. png_size_t png_struct_size, png_size_t png_info_size)
  199417. {
  199418. /* We only come here via pre-1.0.12-compiled applications */
  199419. if(png_ptr == NULL) return;
  199420. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199421. if(png_sizeof(png_struct) > png_struct_size ||
  199422. png_sizeof(png_info) > png_info_size)
  199423. {
  199424. char msg[80];
  199425. png_ptr->warning_fn=NULL;
  199426. if (user_png_ver)
  199427. {
  199428. png_snprintf(msg, 80,
  199429. "Application was compiled with png.h from libpng-%.20s",
  199430. user_png_ver);
  199431. png_warning(png_ptr, msg);
  199432. }
  199433. png_snprintf(msg, 80,
  199434. "Application is running with png.c from libpng-%.20s",
  199435. png_libpng_ver);
  199436. png_warning(png_ptr, msg);
  199437. }
  199438. #endif
  199439. if(png_sizeof(png_struct) > png_struct_size)
  199440. {
  199441. png_ptr->error_fn=NULL;
  199442. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199443. png_ptr->flags=0;
  199444. #endif
  199445. png_error(png_ptr,
  199446. "The png struct allocated by the application for writing is too small.");
  199447. }
  199448. if(png_sizeof(png_info) > png_info_size)
  199449. {
  199450. png_ptr->error_fn=NULL;
  199451. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199452. png_ptr->flags=0;
  199453. #endif
  199454. png_error(png_ptr,
  199455. "The info struct allocated by the application for writing is too small.");
  199456. }
  199457. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199458. }
  199459. #endif /* PNG_1_0_X || PNG_1_2_X */
  199460. void PNGAPI
  199461. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199462. png_size_t png_struct_size)
  199463. {
  199464. png_structp png_ptr=*ptr_ptr;
  199465. #ifdef PNG_SETJMP_SUPPORTED
  199466. jmp_buf tmp_jmp; /* to save current jump buffer */
  199467. #endif
  199468. int i = 0;
  199469. if (png_ptr == NULL)
  199470. return;
  199471. do
  199472. {
  199473. if (user_png_ver[i] != png_libpng_ver[i])
  199474. {
  199475. #ifdef PNG_LEGACY_SUPPORTED
  199476. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199477. #else
  199478. png_ptr->warning_fn=NULL;
  199479. png_warning(png_ptr,
  199480. "Application uses deprecated png_write_init() and should be recompiled.");
  199481. break;
  199482. #endif
  199483. }
  199484. } while (png_libpng_ver[i++]);
  199485. png_debug(1, "in png_write_init_3\n");
  199486. #ifdef PNG_SETJMP_SUPPORTED
  199487. /* save jump buffer and error functions */
  199488. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199489. #endif
  199490. if (png_sizeof(png_struct) > png_struct_size)
  199491. {
  199492. png_destroy_struct(png_ptr);
  199493. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199494. *ptr_ptr = png_ptr;
  199495. }
  199496. /* reset all variables to 0 */
  199497. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199498. /* added at libpng-1.2.6 */
  199499. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199500. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199501. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199502. #endif
  199503. #ifdef PNG_SETJMP_SUPPORTED
  199504. /* restore jump buffer */
  199505. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199506. #endif
  199507. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199508. png_flush_ptr_NULL);
  199509. /* initialize zbuf - compression buffer */
  199510. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199511. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199512. (png_uint_32)png_ptr->zbuf_size);
  199513. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199514. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199515. 1, png_doublep_NULL, png_doublep_NULL);
  199516. #endif
  199517. }
  199518. /* Write a few rows of image data. If the image is interlaced,
  199519. * either you will have to write the 7 sub images, or, if you
  199520. * have called png_set_interlace_handling(), you will have to
  199521. * "write" the image seven times.
  199522. */
  199523. void PNGAPI
  199524. png_write_rows(png_structp png_ptr, png_bytepp row,
  199525. png_uint_32 num_rows)
  199526. {
  199527. png_uint_32 i; /* row counter */
  199528. png_bytepp rp; /* row pointer */
  199529. png_debug(1, "in png_write_rows\n");
  199530. if (png_ptr == NULL)
  199531. return;
  199532. /* loop through the rows */
  199533. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199534. {
  199535. png_write_row(png_ptr, *rp);
  199536. }
  199537. }
  199538. /* Write the image. You only need to call this function once, even
  199539. * if you are writing an interlaced image.
  199540. */
  199541. void PNGAPI
  199542. png_write_image(png_structp png_ptr, png_bytepp image)
  199543. {
  199544. png_uint_32 i; /* row index */
  199545. int pass, num_pass; /* pass variables */
  199546. png_bytepp rp; /* points to current row */
  199547. if (png_ptr == NULL)
  199548. return;
  199549. png_debug(1, "in png_write_image\n");
  199550. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199551. /* intialize interlace handling. If image is not interlaced,
  199552. this will set pass to 1 */
  199553. num_pass = png_set_interlace_handling(png_ptr);
  199554. #else
  199555. num_pass = 1;
  199556. #endif
  199557. /* loop through passes */
  199558. for (pass = 0; pass < num_pass; pass++)
  199559. {
  199560. /* loop through image */
  199561. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199562. {
  199563. png_write_row(png_ptr, *rp);
  199564. }
  199565. }
  199566. }
  199567. /* called by user to write a row of image data */
  199568. void PNGAPI
  199569. png_write_row(png_structp png_ptr, png_bytep row)
  199570. {
  199571. if (png_ptr == NULL)
  199572. return;
  199573. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199574. png_ptr->row_number, png_ptr->pass);
  199575. /* initialize transformations and other stuff if first time */
  199576. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199577. {
  199578. /* make sure we wrote the header info */
  199579. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199580. png_error(png_ptr,
  199581. "png_write_info was never called before png_write_row.");
  199582. /* check for transforms that have been set but were defined out */
  199583. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199584. if (png_ptr->transformations & PNG_INVERT_MONO)
  199585. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199586. #endif
  199587. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199588. if (png_ptr->transformations & PNG_FILLER)
  199589. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199590. #endif
  199591. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199592. if (png_ptr->transformations & PNG_PACKSWAP)
  199593. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199594. #endif
  199595. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199596. if (png_ptr->transformations & PNG_PACK)
  199597. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199598. #endif
  199599. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199600. if (png_ptr->transformations & PNG_SHIFT)
  199601. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199602. #endif
  199603. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199604. if (png_ptr->transformations & PNG_BGR)
  199605. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199606. #endif
  199607. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199608. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199609. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199610. #endif
  199611. png_write_start_row(png_ptr);
  199612. }
  199613. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199614. /* if interlaced and not interested in row, return */
  199615. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199616. {
  199617. switch (png_ptr->pass)
  199618. {
  199619. case 0:
  199620. if (png_ptr->row_number & 0x07)
  199621. {
  199622. png_write_finish_row(png_ptr);
  199623. return;
  199624. }
  199625. break;
  199626. case 1:
  199627. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199628. {
  199629. png_write_finish_row(png_ptr);
  199630. return;
  199631. }
  199632. break;
  199633. case 2:
  199634. if ((png_ptr->row_number & 0x07) != 4)
  199635. {
  199636. png_write_finish_row(png_ptr);
  199637. return;
  199638. }
  199639. break;
  199640. case 3:
  199641. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199642. {
  199643. png_write_finish_row(png_ptr);
  199644. return;
  199645. }
  199646. break;
  199647. case 4:
  199648. if ((png_ptr->row_number & 0x03) != 2)
  199649. {
  199650. png_write_finish_row(png_ptr);
  199651. return;
  199652. }
  199653. break;
  199654. case 5:
  199655. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199656. {
  199657. png_write_finish_row(png_ptr);
  199658. return;
  199659. }
  199660. break;
  199661. case 6:
  199662. if (!(png_ptr->row_number & 0x01))
  199663. {
  199664. png_write_finish_row(png_ptr);
  199665. return;
  199666. }
  199667. break;
  199668. }
  199669. }
  199670. #endif
  199671. /* set up row info for transformations */
  199672. png_ptr->row_info.color_type = png_ptr->color_type;
  199673. png_ptr->row_info.width = png_ptr->usr_width;
  199674. png_ptr->row_info.channels = png_ptr->usr_channels;
  199675. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199676. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199677. png_ptr->row_info.channels);
  199678. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199679. png_ptr->row_info.width);
  199680. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199681. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199682. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199683. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199684. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199685. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199686. /* Copy user's row into buffer, leaving room for filter byte. */
  199687. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199688. png_ptr->row_info.rowbytes);
  199689. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199690. /* handle interlacing */
  199691. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199692. (png_ptr->transformations & PNG_INTERLACE))
  199693. {
  199694. png_do_write_interlace(&(png_ptr->row_info),
  199695. png_ptr->row_buf + 1, png_ptr->pass);
  199696. /* this should always get caught above, but still ... */
  199697. if (!(png_ptr->row_info.width))
  199698. {
  199699. png_write_finish_row(png_ptr);
  199700. return;
  199701. }
  199702. }
  199703. #endif
  199704. /* handle other transformations */
  199705. if (png_ptr->transformations)
  199706. png_do_write_transformations(png_ptr);
  199707. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199708. /* Write filter_method 64 (intrapixel differencing) only if
  199709. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199710. * 2. Libpng did not write a PNG signature (this filter_method is only
  199711. * used in PNG datastreams that are embedded in MNG datastreams) and
  199712. * 3. The application called png_permit_mng_features with a mask that
  199713. * included PNG_FLAG_MNG_FILTER_64 and
  199714. * 4. The filter_method is 64 and
  199715. * 5. The color_type is RGB or RGBA
  199716. */
  199717. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199718. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199719. {
  199720. /* Intrapixel differencing */
  199721. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199722. }
  199723. #endif
  199724. /* Find a filter if necessary, filter the row and write it out. */
  199725. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199726. if (png_ptr->write_row_fn != NULL)
  199727. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199728. }
  199729. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199730. /* Set the automatic flush interval or 0 to turn flushing off */
  199731. void PNGAPI
  199732. png_set_flush(png_structp png_ptr, int nrows)
  199733. {
  199734. png_debug(1, "in png_set_flush\n");
  199735. if (png_ptr == NULL)
  199736. return;
  199737. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199738. }
  199739. /* flush the current output buffers now */
  199740. void PNGAPI
  199741. png_write_flush(png_structp png_ptr)
  199742. {
  199743. int wrote_IDAT;
  199744. png_debug(1, "in png_write_flush\n");
  199745. if (png_ptr == NULL)
  199746. return;
  199747. /* We have already written out all of the data */
  199748. if (png_ptr->row_number >= png_ptr->num_rows)
  199749. return;
  199750. do
  199751. {
  199752. int ret;
  199753. /* compress the data */
  199754. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199755. wrote_IDAT = 0;
  199756. /* check for compression errors */
  199757. if (ret != Z_OK)
  199758. {
  199759. if (png_ptr->zstream.msg != NULL)
  199760. png_error(png_ptr, png_ptr->zstream.msg);
  199761. else
  199762. png_error(png_ptr, "zlib error");
  199763. }
  199764. if (!(png_ptr->zstream.avail_out))
  199765. {
  199766. /* write the IDAT and reset the zlib output buffer */
  199767. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199768. png_ptr->zbuf_size);
  199769. png_ptr->zstream.next_out = png_ptr->zbuf;
  199770. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199771. wrote_IDAT = 1;
  199772. }
  199773. } while(wrote_IDAT == 1);
  199774. /* If there is any data left to be output, write it into a new IDAT */
  199775. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199776. {
  199777. /* write the IDAT and reset the zlib output buffer */
  199778. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199779. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199780. png_ptr->zstream.next_out = png_ptr->zbuf;
  199781. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199782. }
  199783. png_ptr->flush_rows = 0;
  199784. png_flush(png_ptr);
  199785. }
  199786. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199787. /* free all memory used by the write */
  199788. void PNGAPI
  199789. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199790. {
  199791. png_structp png_ptr = NULL;
  199792. png_infop info_ptr = NULL;
  199793. #ifdef PNG_USER_MEM_SUPPORTED
  199794. png_free_ptr free_fn = NULL;
  199795. png_voidp mem_ptr = NULL;
  199796. #endif
  199797. png_debug(1, "in png_destroy_write_struct\n");
  199798. if (png_ptr_ptr != NULL)
  199799. {
  199800. png_ptr = *png_ptr_ptr;
  199801. #ifdef PNG_USER_MEM_SUPPORTED
  199802. free_fn = png_ptr->free_fn;
  199803. mem_ptr = png_ptr->mem_ptr;
  199804. #endif
  199805. }
  199806. if (info_ptr_ptr != NULL)
  199807. info_ptr = *info_ptr_ptr;
  199808. if (info_ptr != NULL)
  199809. {
  199810. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199811. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199812. if (png_ptr->num_chunk_list)
  199813. {
  199814. png_free(png_ptr, png_ptr->chunk_list);
  199815. png_ptr->chunk_list=NULL;
  199816. png_ptr->num_chunk_list=0;
  199817. }
  199818. #endif
  199819. #ifdef PNG_USER_MEM_SUPPORTED
  199820. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199821. (png_voidp)mem_ptr);
  199822. #else
  199823. png_destroy_struct((png_voidp)info_ptr);
  199824. #endif
  199825. *info_ptr_ptr = NULL;
  199826. }
  199827. if (png_ptr != NULL)
  199828. {
  199829. png_write_destroy(png_ptr);
  199830. #ifdef PNG_USER_MEM_SUPPORTED
  199831. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199832. (png_voidp)mem_ptr);
  199833. #else
  199834. png_destroy_struct((png_voidp)png_ptr);
  199835. #endif
  199836. *png_ptr_ptr = NULL;
  199837. }
  199838. }
  199839. /* Free any memory used in png_ptr struct (old method) */
  199840. void /* PRIVATE */
  199841. png_write_destroy(png_structp png_ptr)
  199842. {
  199843. #ifdef PNG_SETJMP_SUPPORTED
  199844. jmp_buf tmp_jmp; /* save jump buffer */
  199845. #endif
  199846. png_error_ptr error_fn;
  199847. png_error_ptr warning_fn;
  199848. png_voidp error_ptr;
  199849. #ifdef PNG_USER_MEM_SUPPORTED
  199850. png_free_ptr free_fn;
  199851. #endif
  199852. png_debug(1, "in png_write_destroy\n");
  199853. /* free any memory zlib uses */
  199854. deflateEnd(&png_ptr->zstream);
  199855. /* free our memory. png_free checks NULL for us. */
  199856. png_free(png_ptr, png_ptr->zbuf);
  199857. png_free(png_ptr, png_ptr->row_buf);
  199858. png_free(png_ptr, png_ptr->prev_row);
  199859. png_free(png_ptr, png_ptr->sub_row);
  199860. png_free(png_ptr, png_ptr->up_row);
  199861. png_free(png_ptr, png_ptr->avg_row);
  199862. png_free(png_ptr, png_ptr->paeth_row);
  199863. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199864. png_free(png_ptr, png_ptr->time_buffer);
  199865. #endif
  199866. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199867. png_free(png_ptr, png_ptr->prev_filters);
  199868. png_free(png_ptr, png_ptr->filter_weights);
  199869. png_free(png_ptr, png_ptr->inv_filter_weights);
  199870. png_free(png_ptr, png_ptr->filter_costs);
  199871. png_free(png_ptr, png_ptr->inv_filter_costs);
  199872. #endif
  199873. #ifdef PNG_SETJMP_SUPPORTED
  199874. /* reset structure */
  199875. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199876. #endif
  199877. error_fn = png_ptr->error_fn;
  199878. warning_fn = png_ptr->warning_fn;
  199879. error_ptr = png_ptr->error_ptr;
  199880. #ifdef PNG_USER_MEM_SUPPORTED
  199881. free_fn = png_ptr->free_fn;
  199882. #endif
  199883. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199884. png_ptr->error_fn = error_fn;
  199885. png_ptr->warning_fn = warning_fn;
  199886. png_ptr->error_ptr = error_ptr;
  199887. #ifdef PNG_USER_MEM_SUPPORTED
  199888. png_ptr->free_fn = free_fn;
  199889. #endif
  199890. #ifdef PNG_SETJMP_SUPPORTED
  199891. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199892. #endif
  199893. }
  199894. /* Allow the application to select one or more row filters to use. */
  199895. void PNGAPI
  199896. png_set_filter(png_structp png_ptr, int method, int filters)
  199897. {
  199898. png_debug(1, "in png_set_filter\n");
  199899. if (png_ptr == NULL)
  199900. return;
  199901. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199902. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199903. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199904. method = PNG_FILTER_TYPE_BASE;
  199905. #endif
  199906. if (method == PNG_FILTER_TYPE_BASE)
  199907. {
  199908. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199909. {
  199910. #ifndef PNG_NO_WRITE_FILTER
  199911. case 5:
  199912. case 6:
  199913. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199914. #endif /* PNG_NO_WRITE_FILTER */
  199915. case PNG_FILTER_VALUE_NONE:
  199916. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199917. #ifndef PNG_NO_WRITE_FILTER
  199918. case PNG_FILTER_VALUE_SUB:
  199919. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199920. case PNG_FILTER_VALUE_UP:
  199921. png_ptr->do_filter=PNG_FILTER_UP; break;
  199922. case PNG_FILTER_VALUE_AVG:
  199923. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199924. case PNG_FILTER_VALUE_PAETH:
  199925. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199926. default: png_ptr->do_filter = (png_byte)filters; break;
  199927. #else
  199928. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199929. #endif /* PNG_NO_WRITE_FILTER */
  199930. }
  199931. /* If we have allocated the row_buf, this means we have already started
  199932. * with the image and we should have allocated all of the filter buffers
  199933. * that have been selected. If prev_row isn't already allocated, then
  199934. * it is too late to start using the filters that need it, since we
  199935. * will be missing the data in the previous row. If an application
  199936. * wants to start and stop using particular filters during compression,
  199937. * it should start out with all of the filters, and then add and
  199938. * remove them after the start of compression.
  199939. */
  199940. if (png_ptr->row_buf != NULL)
  199941. {
  199942. #ifndef PNG_NO_WRITE_FILTER
  199943. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199944. {
  199945. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199946. (png_ptr->rowbytes + 1));
  199947. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199948. }
  199949. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199950. {
  199951. if (png_ptr->prev_row == NULL)
  199952. {
  199953. png_warning(png_ptr, "Can't add Up filter after starting");
  199954. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199955. }
  199956. else
  199957. {
  199958. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199959. (png_ptr->rowbytes + 1));
  199960. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199961. }
  199962. }
  199963. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199964. {
  199965. if (png_ptr->prev_row == NULL)
  199966. {
  199967. png_warning(png_ptr, "Can't add Average filter after starting");
  199968. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199969. }
  199970. else
  199971. {
  199972. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199973. (png_ptr->rowbytes + 1));
  199974. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199975. }
  199976. }
  199977. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199978. png_ptr->paeth_row == NULL)
  199979. {
  199980. if (png_ptr->prev_row == NULL)
  199981. {
  199982. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199983. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199984. }
  199985. else
  199986. {
  199987. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199988. (png_ptr->rowbytes + 1));
  199989. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199990. }
  199991. }
  199992. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199993. #endif /* PNG_NO_WRITE_FILTER */
  199994. png_ptr->do_filter = PNG_FILTER_NONE;
  199995. }
  199996. }
  199997. else
  199998. png_error(png_ptr, "Unknown custom filter method");
  199999. }
  200000. /* This allows us to influence the way in which libpng chooses the "best"
  200001. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200002. * differences metric is relatively fast and effective, there is some
  200003. * question as to whether it can be improved upon by trying to keep the
  200004. * filtered data going to zlib more consistent, hopefully resulting in
  200005. * better compression.
  200006. */
  200007. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200008. void PNGAPI
  200009. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200010. int num_weights, png_doublep filter_weights,
  200011. png_doublep filter_costs)
  200012. {
  200013. int i;
  200014. png_debug(1, "in png_set_filter_heuristics\n");
  200015. if (png_ptr == NULL)
  200016. return;
  200017. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200018. {
  200019. png_warning(png_ptr, "Unknown filter heuristic method");
  200020. return;
  200021. }
  200022. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200023. {
  200024. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200025. }
  200026. if (num_weights < 0 || filter_weights == NULL ||
  200027. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200028. {
  200029. num_weights = 0;
  200030. }
  200031. png_ptr->num_prev_filters = (png_byte)num_weights;
  200032. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200033. if (num_weights > 0)
  200034. {
  200035. if (png_ptr->prev_filters == NULL)
  200036. {
  200037. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200038. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200039. /* To make sure that the weighting starts out fairly */
  200040. for (i = 0; i < num_weights; i++)
  200041. {
  200042. png_ptr->prev_filters[i] = 255;
  200043. }
  200044. }
  200045. if (png_ptr->filter_weights == NULL)
  200046. {
  200047. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200048. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200049. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200050. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200051. for (i = 0; i < num_weights; i++)
  200052. {
  200053. png_ptr->inv_filter_weights[i] =
  200054. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200055. }
  200056. }
  200057. for (i = 0; i < num_weights; i++)
  200058. {
  200059. if (filter_weights[i] < 0.0)
  200060. {
  200061. png_ptr->inv_filter_weights[i] =
  200062. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200063. }
  200064. else
  200065. {
  200066. png_ptr->inv_filter_weights[i] =
  200067. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200068. png_ptr->filter_weights[i] =
  200069. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200070. }
  200071. }
  200072. }
  200073. /* If, in the future, there are other filter methods, this would
  200074. * need to be based on png_ptr->filter.
  200075. */
  200076. if (png_ptr->filter_costs == NULL)
  200077. {
  200078. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200079. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200080. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200081. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200082. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200083. {
  200084. png_ptr->inv_filter_costs[i] =
  200085. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200086. }
  200087. }
  200088. /* Here is where we set the relative costs of the different filters. We
  200089. * should take the desired compression level into account when setting
  200090. * the costs, so that Paeth, for instance, has a high relative cost at low
  200091. * compression levels, while it has a lower relative cost at higher
  200092. * compression settings. The filter types are in order of increasing
  200093. * relative cost, so it would be possible to do this with an algorithm.
  200094. */
  200095. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200096. {
  200097. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200098. {
  200099. png_ptr->inv_filter_costs[i] =
  200100. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200101. }
  200102. else if (filter_costs[i] >= 1.0)
  200103. {
  200104. png_ptr->inv_filter_costs[i] =
  200105. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200106. png_ptr->filter_costs[i] =
  200107. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200108. }
  200109. }
  200110. }
  200111. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200112. void PNGAPI
  200113. png_set_compression_level(png_structp png_ptr, int level)
  200114. {
  200115. png_debug(1, "in png_set_compression_level\n");
  200116. if (png_ptr == NULL)
  200117. return;
  200118. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200119. png_ptr->zlib_level = level;
  200120. }
  200121. void PNGAPI
  200122. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200123. {
  200124. png_debug(1, "in png_set_compression_mem_level\n");
  200125. if (png_ptr == NULL)
  200126. return;
  200127. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200128. png_ptr->zlib_mem_level = mem_level;
  200129. }
  200130. void PNGAPI
  200131. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200132. {
  200133. png_debug(1, "in png_set_compression_strategy\n");
  200134. if (png_ptr == NULL)
  200135. return;
  200136. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200137. png_ptr->zlib_strategy = strategy;
  200138. }
  200139. void PNGAPI
  200140. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200141. {
  200142. if (png_ptr == NULL)
  200143. return;
  200144. if (window_bits > 15)
  200145. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200146. else if (window_bits < 8)
  200147. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200148. #ifndef WBITS_8_OK
  200149. /* avoid libpng bug with 256-byte windows */
  200150. if (window_bits == 8)
  200151. {
  200152. png_warning(png_ptr, "Compression window is being reset to 512");
  200153. window_bits=9;
  200154. }
  200155. #endif
  200156. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200157. png_ptr->zlib_window_bits = window_bits;
  200158. }
  200159. void PNGAPI
  200160. png_set_compression_method(png_structp png_ptr, int method)
  200161. {
  200162. png_debug(1, "in png_set_compression_method\n");
  200163. if (png_ptr == NULL)
  200164. return;
  200165. if (method != 8)
  200166. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200167. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200168. png_ptr->zlib_method = method;
  200169. }
  200170. void PNGAPI
  200171. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200172. {
  200173. if (png_ptr == NULL)
  200174. return;
  200175. png_ptr->write_row_fn = write_row_fn;
  200176. }
  200177. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200178. void PNGAPI
  200179. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200180. write_user_transform_fn)
  200181. {
  200182. png_debug(1, "in png_set_write_user_transform_fn\n");
  200183. if (png_ptr == NULL)
  200184. return;
  200185. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200186. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200187. }
  200188. #endif
  200189. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200190. void PNGAPI
  200191. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200192. int transforms, voidp params)
  200193. {
  200194. if (png_ptr == NULL || info_ptr == NULL)
  200195. return;
  200196. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200197. /* invert the alpha channel from opacity to transparency */
  200198. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200199. png_set_invert_alpha(png_ptr);
  200200. #endif
  200201. /* Write the file header information. */
  200202. png_write_info(png_ptr, info_ptr);
  200203. /* ------ these transformations don't touch the info structure ------- */
  200204. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200205. /* invert monochrome pixels */
  200206. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200207. png_set_invert_mono(png_ptr);
  200208. #endif
  200209. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200210. /* Shift the pixels up to a legal bit depth and fill in
  200211. * as appropriate to correctly scale the image.
  200212. */
  200213. if ((transforms & PNG_TRANSFORM_SHIFT)
  200214. && (info_ptr->valid & PNG_INFO_sBIT))
  200215. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200216. #endif
  200217. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200218. /* pack pixels into bytes */
  200219. if (transforms & PNG_TRANSFORM_PACKING)
  200220. png_set_packing(png_ptr);
  200221. #endif
  200222. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200223. /* swap location of alpha bytes from ARGB to RGBA */
  200224. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200225. png_set_swap_alpha(png_ptr);
  200226. #endif
  200227. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200228. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200229. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200230. */
  200231. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200232. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200233. #endif
  200234. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200235. /* flip BGR pixels to RGB */
  200236. if (transforms & PNG_TRANSFORM_BGR)
  200237. png_set_bgr(png_ptr);
  200238. #endif
  200239. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200240. /* swap bytes of 16-bit files to most significant byte first */
  200241. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200242. png_set_swap(png_ptr);
  200243. #endif
  200244. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200245. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200246. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200247. png_set_packswap(png_ptr);
  200248. #endif
  200249. /* ----------------------- end of transformations ------------------- */
  200250. /* write the bits */
  200251. if (info_ptr->valid & PNG_INFO_IDAT)
  200252. png_write_image(png_ptr, info_ptr->row_pointers);
  200253. /* It is REQUIRED to call this to finish writing the rest of the file */
  200254. png_write_end(png_ptr, info_ptr);
  200255. transforms = transforms; /* quiet compiler warnings */
  200256. params = params;
  200257. }
  200258. #endif
  200259. #endif /* PNG_WRITE_SUPPORTED */
  200260. /*** End of inlined file: pngwrite.c ***/
  200261. /*** Start of inlined file: pngwtran.c ***/
  200262. /* pngwtran.c - transforms the data in a row for PNG writers
  200263. *
  200264. * Last changed in libpng 1.2.9 April 14, 2006
  200265. * For conditions of distribution and use, see copyright notice in png.h
  200266. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200267. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200268. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200269. */
  200270. #define PNG_INTERNAL
  200271. #ifdef PNG_WRITE_SUPPORTED
  200272. /* Transform the data according to the user's wishes. The order of
  200273. * transformations is significant.
  200274. */
  200275. void /* PRIVATE */
  200276. png_do_write_transformations(png_structp png_ptr)
  200277. {
  200278. png_debug(1, "in png_do_write_transformations\n");
  200279. if (png_ptr == NULL)
  200280. return;
  200281. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200282. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200283. if(png_ptr->write_user_transform_fn != NULL)
  200284. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200285. (png_ptr, /* png_ptr */
  200286. &(png_ptr->row_info), /* row_info: */
  200287. /* png_uint_32 width; width of row */
  200288. /* png_uint_32 rowbytes; number of bytes in row */
  200289. /* png_byte color_type; color type of pixels */
  200290. /* png_byte bit_depth; bit depth of samples */
  200291. /* png_byte channels; number of channels (1-4) */
  200292. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200293. png_ptr->row_buf + 1); /* start of pixel data for row */
  200294. #endif
  200295. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200296. if (png_ptr->transformations & PNG_FILLER)
  200297. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200298. png_ptr->flags);
  200299. #endif
  200300. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200301. if (png_ptr->transformations & PNG_PACKSWAP)
  200302. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200303. #endif
  200304. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200305. if (png_ptr->transformations & PNG_PACK)
  200306. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200307. (png_uint_32)png_ptr->bit_depth);
  200308. #endif
  200309. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200310. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200311. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200312. #endif
  200313. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200314. if (png_ptr->transformations & PNG_SHIFT)
  200315. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200316. &(png_ptr->shift));
  200317. #endif
  200318. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200319. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200320. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200321. #endif
  200322. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200323. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200324. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200325. #endif
  200326. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200327. if (png_ptr->transformations & PNG_BGR)
  200328. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200329. #endif
  200330. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200331. if (png_ptr->transformations & PNG_INVERT_MONO)
  200332. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200333. #endif
  200334. }
  200335. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200336. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200337. * row_info bit depth should be 8 (one pixel per byte). The channels
  200338. * should be 1 (this only happens on grayscale and paletted images).
  200339. */
  200340. void /* PRIVATE */
  200341. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200342. {
  200343. png_debug(1, "in png_do_pack\n");
  200344. if (row_info->bit_depth == 8 &&
  200345. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200346. row != NULL && row_info != NULL &&
  200347. #endif
  200348. row_info->channels == 1)
  200349. {
  200350. switch ((int)bit_depth)
  200351. {
  200352. case 1:
  200353. {
  200354. png_bytep sp, dp;
  200355. int mask, v;
  200356. png_uint_32 i;
  200357. png_uint_32 row_width = row_info->width;
  200358. sp = row;
  200359. dp = row;
  200360. mask = 0x80;
  200361. v = 0;
  200362. for (i = 0; i < row_width; i++)
  200363. {
  200364. if (*sp != 0)
  200365. v |= mask;
  200366. sp++;
  200367. if (mask > 1)
  200368. mask >>= 1;
  200369. else
  200370. {
  200371. mask = 0x80;
  200372. *dp = (png_byte)v;
  200373. dp++;
  200374. v = 0;
  200375. }
  200376. }
  200377. if (mask != 0x80)
  200378. *dp = (png_byte)v;
  200379. break;
  200380. }
  200381. case 2:
  200382. {
  200383. png_bytep sp, dp;
  200384. int shift, v;
  200385. png_uint_32 i;
  200386. png_uint_32 row_width = row_info->width;
  200387. sp = row;
  200388. dp = row;
  200389. shift = 6;
  200390. v = 0;
  200391. for (i = 0; i < row_width; i++)
  200392. {
  200393. png_byte value;
  200394. value = (png_byte)(*sp & 0x03);
  200395. v |= (value << shift);
  200396. if (shift == 0)
  200397. {
  200398. shift = 6;
  200399. *dp = (png_byte)v;
  200400. dp++;
  200401. v = 0;
  200402. }
  200403. else
  200404. shift -= 2;
  200405. sp++;
  200406. }
  200407. if (shift != 6)
  200408. *dp = (png_byte)v;
  200409. break;
  200410. }
  200411. case 4:
  200412. {
  200413. png_bytep sp, dp;
  200414. int shift, v;
  200415. png_uint_32 i;
  200416. png_uint_32 row_width = row_info->width;
  200417. sp = row;
  200418. dp = row;
  200419. shift = 4;
  200420. v = 0;
  200421. for (i = 0; i < row_width; i++)
  200422. {
  200423. png_byte value;
  200424. value = (png_byte)(*sp & 0x0f);
  200425. v |= (value << shift);
  200426. if (shift == 0)
  200427. {
  200428. shift = 4;
  200429. *dp = (png_byte)v;
  200430. dp++;
  200431. v = 0;
  200432. }
  200433. else
  200434. shift -= 4;
  200435. sp++;
  200436. }
  200437. if (shift != 4)
  200438. *dp = (png_byte)v;
  200439. break;
  200440. }
  200441. }
  200442. row_info->bit_depth = (png_byte)bit_depth;
  200443. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200444. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200445. row_info->width);
  200446. }
  200447. }
  200448. #endif
  200449. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200450. /* Shift pixel values to take advantage of whole range. Pass the
  200451. * true number of bits in bit_depth. The row should be packed
  200452. * according to row_info->bit_depth. Thus, if you had a row of
  200453. * bit depth 4, but the pixels only had values from 0 to 7, you
  200454. * would pass 3 as bit_depth, and this routine would translate the
  200455. * data to 0 to 15.
  200456. */
  200457. void /* PRIVATE */
  200458. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200459. {
  200460. png_debug(1, "in png_do_shift\n");
  200461. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200462. if (row != NULL && row_info != NULL &&
  200463. #else
  200464. if (
  200465. #endif
  200466. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200467. {
  200468. int shift_start[4], shift_dec[4];
  200469. int channels = 0;
  200470. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200471. {
  200472. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200473. shift_dec[channels] = bit_depth->red;
  200474. channels++;
  200475. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200476. shift_dec[channels] = bit_depth->green;
  200477. channels++;
  200478. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200479. shift_dec[channels] = bit_depth->blue;
  200480. channels++;
  200481. }
  200482. else
  200483. {
  200484. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200485. shift_dec[channels] = bit_depth->gray;
  200486. channels++;
  200487. }
  200488. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200489. {
  200490. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200491. shift_dec[channels] = bit_depth->alpha;
  200492. channels++;
  200493. }
  200494. /* with low row depths, could only be grayscale, so one channel */
  200495. if (row_info->bit_depth < 8)
  200496. {
  200497. png_bytep bp = row;
  200498. png_uint_32 i;
  200499. png_byte mask;
  200500. png_uint_32 row_bytes = row_info->rowbytes;
  200501. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200502. mask = 0x55;
  200503. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200504. mask = 0x11;
  200505. else
  200506. mask = 0xff;
  200507. for (i = 0; i < row_bytes; i++, bp++)
  200508. {
  200509. png_uint_16 v;
  200510. int j;
  200511. v = *bp;
  200512. *bp = 0;
  200513. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200514. {
  200515. if (j > 0)
  200516. *bp |= (png_byte)((v << j) & 0xff);
  200517. else
  200518. *bp |= (png_byte)((v >> (-j)) & mask);
  200519. }
  200520. }
  200521. }
  200522. else if (row_info->bit_depth == 8)
  200523. {
  200524. png_bytep bp = row;
  200525. png_uint_32 i;
  200526. png_uint_32 istop = channels * row_info->width;
  200527. for (i = 0; i < istop; i++, bp++)
  200528. {
  200529. png_uint_16 v;
  200530. int j;
  200531. int c = (int)(i%channels);
  200532. v = *bp;
  200533. *bp = 0;
  200534. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200535. {
  200536. if (j > 0)
  200537. *bp |= (png_byte)((v << j) & 0xff);
  200538. else
  200539. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200540. }
  200541. }
  200542. }
  200543. else
  200544. {
  200545. png_bytep bp;
  200546. png_uint_32 i;
  200547. png_uint_32 istop = channels * row_info->width;
  200548. for (bp = row, i = 0; i < istop; i++)
  200549. {
  200550. int c = (int)(i%channels);
  200551. png_uint_16 value, v;
  200552. int j;
  200553. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200554. value = 0;
  200555. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200556. {
  200557. if (j > 0)
  200558. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200559. else
  200560. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200561. }
  200562. *bp++ = (png_byte)(value >> 8);
  200563. *bp++ = (png_byte)(value & 0xff);
  200564. }
  200565. }
  200566. }
  200567. }
  200568. #endif
  200569. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200570. void /* PRIVATE */
  200571. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200572. {
  200573. png_debug(1, "in png_do_write_swap_alpha\n");
  200574. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200575. if (row != NULL && row_info != NULL)
  200576. #endif
  200577. {
  200578. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200579. {
  200580. /* This converts from ARGB to RGBA */
  200581. if (row_info->bit_depth == 8)
  200582. {
  200583. png_bytep sp, dp;
  200584. png_uint_32 i;
  200585. png_uint_32 row_width = row_info->width;
  200586. for (i = 0, sp = dp = row; i < row_width; i++)
  200587. {
  200588. png_byte save = *(sp++);
  200589. *(dp++) = *(sp++);
  200590. *(dp++) = *(sp++);
  200591. *(dp++) = *(sp++);
  200592. *(dp++) = save;
  200593. }
  200594. }
  200595. /* This converts from AARRGGBB to RRGGBBAA */
  200596. else
  200597. {
  200598. png_bytep sp, dp;
  200599. png_uint_32 i;
  200600. png_uint_32 row_width = row_info->width;
  200601. for (i = 0, sp = dp = row; i < row_width; i++)
  200602. {
  200603. png_byte save[2];
  200604. save[0] = *(sp++);
  200605. save[1] = *(sp++);
  200606. *(dp++) = *(sp++);
  200607. *(dp++) = *(sp++);
  200608. *(dp++) = *(sp++);
  200609. *(dp++) = *(sp++);
  200610. *(dp++) = *(sp++);
  200611. *(dp++) = *(sp++);
  200612. *(dp++) = save[0];
  200613. *(dp++) = save[1];
  200614. }
  200615. }
  200616. }
  200617. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200618. {
  200619. /* This converts from AG to GA */
  200620. if (row_info->bit_depth == 8)
  200621. {
  200622. png_bytep sp, dp;
  200623. png_uint_32 i;
  200624. png_uint_32 row_width = row_info->width;
  200625. for (i = 0, sp = dp = row; i < row_width; i++)
  200626. {
  200627. png_byte save = *(sp++);
  200628. *(dp++) = *(sp++);
  200629. *(dp++) = save;
  200630. }
  200631. }
  200632. /* This converts from AAGG to GGAA */
  200633. else
  200634. {
  200635. png_bytep sp, dp;
  200636. png_uint_32 i;
  200637. png_uint_32 row_width = row_info->width;
  200638. for (i = 0, sp = dp = row; i < row_width; i++)
  200639. {
  200640. png_byte save[2];
  200641. save[0] = *(sp++);
  200642. save[1] = *(sp++);
  200643. *(dp++) = *(sp++);
  200644. *(dp++) = *(sp++);
  200645. *(dp++) = save[0];
  200646. *(dp++) = save[1];
  200647. }
  200648. }
  200649. }
  200650. }
  200651. }
  200652. #endif
  200653. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200654. void /* PRIVATE */
  200655. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200656. {
  200657. png_debug(1, "in png_do_write_invert_alpha\n");
  200658. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200659. if (row != NULL && row_info != NULL)
  200660. #endif
  200661. {
  200662. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200663. {
  200664. /* This inverts the alpha channel in RGBA */
  200665. if (row_info->bit_depth == 8)
  200666. {
  200667. png_bytep sp, dp;
  200668. png_uint_32 i;
  200669. png_uint_32 row_width = row_info->width;
  200670. for (i = 0, sp = dp = row; i < row_width; i++)
  200671. {
  200672. /* does nothing
  200673. *(dp++) = *(sp++);
  200674. *(dp++) = *(sp++);
  200675. *(dp++) = *(sp++);
  200676. */
  200677. sp+=3; dp = sp;
  200678. *(dp++) = (png_byte)(255 - *(sp++));
  200679. }
  200680. }
  200681. /* This inverts the alpha channel in RRGGBBAA */
  200682. else
  200683. {
  200684. png_bytep sp, dp;
  200685. png_uint_32 i;
  200686. png_uint_32 row_width = row_info->width;
  200687. for (i = 0, sp = dp = row; i < row_width; i++)
  200688. {
  200689. /* does nothing
  200690. *(dp++) = *(sp++);
  200691. *(dp++) = *(sp++);
  200692. *(dp++) = *(sp++);
  200693. *(dp++) = *(sp++);
  200694. *(dp++) = *(sp++);
  200695. *(dp++) = *(sp++);
  200696. */
  200697. sp+=6; dp = sp;
  200698. *(dp++) = (png_byte)(255 - *(sp++));
  200699. *(dp++) = (png_byte)(255 - *(sp++));
  200700. }
  200701. }
  200702. }
  200703. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200704. {
  200705. /* This inverts the alpha channel in GA */
  200706. if (row_info->bit_depth == 8)
  200707. {
  200708. png_bytep sp, dp;
  200709. png_uint_32 i;
  200710. png_uint_32 row_width = row_info->width;
  200711. for (i = 0, sp = dp = row; i < row_width; i++)
  200712. {
  200713. *(dp++) = *(sp++);
  200714. *(dp++) = (png_byte)(255 - *(sp++));
  200715. }
  200716. }
  200717. /* This inverts the alpha channel in GGAA */
  200718. else
  200719. {
  200720. png_bytep sp, dp;
  200721. png_uint_32 i;
  200722. png_uint_32 row_width = row_info->width;
  200723. for (i = 0, sp = dp = row; i < row_width; i++)
  200724. {
  200725. /* does nothing
  200726. *(dp++) = *(sp++);
  200727. *(dp++) = *(sp++);
  200728. */
  200729. sp+=2; dp = sp;
  200730. *(dp++) = (png_byte)(255 - *(sp++));
  200731. *(dp++) = (png_byte)(255 - *(sp++));
  200732. }
  200733. }
  200734. }
  200735. }
  200736. }
  200737. #endif
  200738. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200739. /* undoes intrapixel differencing */
  200740. void /* PRIVATE */
  200741. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200742. {
  200743. png_debug(1, "in png_do_write_intrapixel\n");
  200744. if (
  200745. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200746. row != NULL && row_info != NULL &&
  200747. #endif
  200748. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200749. {
  200750. int bytes_per_pixel;
  200751. png_uint_32 row_width = row_info->width;
  200752. if (row_info->bit_depth == 8)
  200753. {
  200754. png_bytep rp;
  200755. png_uint_32 i;
  200756. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200757. bytes_per_pixel = 3;
  200758. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200759. bytes_per_pixel = 4;
  200760. else
  200761. return;
  200762. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200763. {
  200764. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200765. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200766. }
  200767. }
  200768. else if (row_info->bit_depth == 16)
  200769. {
  200770. png_bytep rp;
  200771. png_uint_32 i;
  200772. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200773. bytes_per_pixel = 6;
  200774. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200775. bytes_per_pixel = 8;
  200776. else
  200777. return;
  200778. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200779. {
  200780. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200781. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200782. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200783. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200784. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200785. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200786. *(rp+1) = (png_byte)(red & 0xff);
  200787. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200788. *(rp+5) = (png_byte)(blue & 0xff);
  200789. }
  200790. }
  200791. }
  200792. }
  200793. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200794. #endif /* PNG_WRITE_SUPPORTED */
  200795. /*** End of inlined file: pngwtran.c ***/
  200796. /*** Start of inlined file: pngwutil.c ***/
  200797. /* pngwutil.c - utilities to write a PNG file
  200798. *
  200799. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200800. * For conditions of distribution and use, see copyright notice in png.h
  200801. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200802. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200803. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200804. */
  200805. #define PNG_INTERNAL
  200806. #ifdef PNG_WRITE_SUPPORTED
  200807. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200808. * with unsigned numbers for convenience, although one supported
  200809. * ancillary chunk uses signed (two's complement) numbers.
  200810. */
  200811. void PNGAPI
  200812. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200813. {
  200814. buf[0] = (png_byte)((i >> 24) & 0xff);
  200815. buf[1] = (png_byte)((i >> 16) & 0xff);
  200816. buf[2] = (png_byte)((i >> 8) & 0xff);
  200817. buf[3] = (png_byte)(i & 0xff);
  200818. }
  200819. /* The png_save_int_32 function assumes integers are stored in two's
  200820. * complement format. If this isn't the case, then this routine needs to
  200821. * be modified to write data in two's complement format.
  200822. */
  200823. void PNGAPI
  200824. png_save_int_32(png_bytep buf, png_int_32 i)
  200825. {
  200826. buf[0] = (png_byte)((i >> 24) & 0xff);
  200827. buf[1] = (png_byte)((i >> 16) & 0xff);
  200828. buf[2] = (png_byte)((i >> 8) & 0xff);
  200829. buf[3] = (png_byte)(i & 0xff);
  200830. }
  200831. /* Place a 16-bit number into a buffer in PNG byte order.
  200832. * The parameter is declared unsigned int, not png_uint_16,
  200833. * just to avoid potential problems on pre-ANSI C compilers.
  200834. */
  200835. void PNGAPI
  200836. png_save_uint_16(png_bytep buf, unsigned int i)
  200837. {
  200838. buf[0] = (png_byte)((i >> 8) & 0xff);
  200839. buf[1] = (png_byte)(i & 0xff);
  200840. }
  200841. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200842. * representing the chunk name. The array must be at least 4 bytes in
  200843. * length, and does not need to be null terminated. To be safe, pass the
  200844. * pre-defined chunk names here, and if you need a new one, define it
  200845. * where the others are defined. The length is the length of the data.
  200846. * All the data must be present. If that is not possible, use the
  200847. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200848. * functions instead.
  200849. */
  200850. void PNGAPI
  200851. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200852. png_bytep data, png_size_t length)
  200853. {
  200854. if(png_ptr == NULL) return;
  200855. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200856. png_write_chunk_data(png_ptr, data, length);
  200857. png_write_chunk_end(png_ptr);
  200858. }
  200859. /* Write the start of a PNG chunk. The type is the chunk type.
  200860. * The total_length is the sum of the lengths of all the data you will be
  200861. * passing in png_write_chunk_data().
  200862. */
  200863. void PNGAPI
  200864. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200865. png_uint_32 length)
  200866. {
  200867. png_byte buf[4];
  200868. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200869. if(png_ptr == NULL) return;
  200870. /* write the length */
  200871. png_save_uint_32(buf, length);
  200872. png_write_data(png_ptr, buf, (png_size_t)4);
  200873. /* write the chunk name */
  200874. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200875. /* reset the crc and run it over the chunk name */
  200876. png_reset_crc(png_ptr);
  200877. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200878. }
  200879. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200880. * Note that multiple calls to this function are allowed, and that the
  200881. * sum of the lengths from these calls *must* add up to the total_length
  200882. * given to png_write_chunk_start().
  200883. */
  200884. void PNGAPI
  200885. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200886. {
  200887. /* write the data, and run the CRC over it */
  200888. if(png_ptr == NULL) return;
  200889. if (data != NULL && length > 0)
  200890. {
  200891. png_calculate_crc(png_ptr, data, length);
  200892. png_write_data(png_ptr, data, length);
  200893. }
  200894. }
  200895. /* Finish a chunk started with png_write_chunk_start(). */
  200896. void PNGAPI
  200897. png_write_chunk_end(png_structp png_ptr)
  200898. {
  200899. png_byte buf[4];
  200900. if(png_ptr == NULL) return;
  200901. /* write the crc */
  200902. png_save_uint_32(buf, png_ptr->crc);
  200903. png_write_data(png_ptr, buf, (png_size_t)4);
  200904. }
  200905. /* Simple function to write the signature. If we have already written
  200906. * the magic bytes of the signature, or more likely, the PNG stream is
  200907. * being embedded into another stream and doesn't need its own signature,
  200908. * we should call png_set_sig_bytes() to tell libpng how many of the
  200909. * bytes have already been written.
  200910. */
  200911. void /* PRIVATE */
  200912. png_write_sig(png_structp png_ptr)
  200913. {
  200914. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200915. /* write the rest of the 8 byte signature */
  200916. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200917. (png_size_t)8 - png_ptr->sig_bytes);
  200918. if(png_ptr->sig_bytes < 3)
  200919. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200920. }
  200921. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200922. /*
  200923. * This pair of functions encapsulates the operation of (a) compressing a
  200924. * text string, and (b) issuing it later as a series of chunk data writes.
  200925. * The compression_state structure is shared context for these functions
  200926. * set up by the caller in order to make the whole mess thread-safe.
  200927. */
  200928. typedef struct
  200929. {
  200930. char *input; /* the uncompressed input data */
  200931. int input_len; /* its length */
  200932. int num_output_ptr; /* number of output pointers used */
  200933. int max_output_ptr; /* size of output_ptr */
  200934. png_charpp output_ptr; /* array of pointers to output */
  200935. } compression_state;
  200936. /* compress given text into storage in the png_ptr structure */
  200937. static int /* PRIVATE */
  200938. png_text_compress(png_structp png_ptr,
  200939. png_charp text, png_size_t text_len, int compression,
  200940. compression_state *comp)
  200941. {
  200942. int ret;
  200943. comp->num_output_ptr = 0;
  200944. comp->max_output_ptr = 0;
  200945. comp->output_ptr = NULL;
  200946. comp->input = NULL;
  200947. comp->input_len = 0;
  200948. /* we may just want to pass the text right through */
  200949. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200950. {
  200951. comp->input = text;
  200952. comp->input_len = text_len;
  200953. return((int)text_len);
  200954. }
  200955. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200956. {
  200957. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200958. char msg[50];
  200959. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200960. png_warning(png_ptr, msg);
  200961. #else
  200962. png_warning(png_ptr, "Unknown compression type");
  200963. #endif
  200964. }
  200965. /* We can't write the chunk until we find out how much data we have,
  200966. * which means we need to run the compressor first and save the
  200967. * output. This shouldn't be a problem, as the vast majority of
  200968. * comments should be reasonable, but we will set up an array of
  200969. * malloc'd pointers to be sure.
  200970. *
  200971. * If we knew the application was well behaved, we could simplify this
  200972. * greatly by assuming we can always malloc an output buffer large
  200973. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200974. * and malloc this directly. The only time this would be a bad idea is
  200975. * if we can't malloc more than 64K and we have 64K of random input
  200976. * data, or if the input string is incredibly large (although this
  200977. * wouldn't cause a failure, just a slowdown due to swapping).
  200978. */
  200979. /* set up the compression buffers */
  200980. png_ptr->zstream.avail_in = (uInt)text_len;
  200981. png_ptr->zstream.next_in = (Bytef *)text;
  200982. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200983. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200984. /* this is the same compression loop as in png_write_row() */
  200985. do
  200986. {
  200987. /* compress the data */
  200988. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200989. if (ret != Z_OK)
  200990. {
  200991. /* error */
  200992. if (png_ptr->zstream.msg != NULL)
  200993. png_error(png_ptr, png_ptr->zstream.msg);
  200994. else
  200995. png_error(png_ptr, "zlib error");
  200996. }
  200997. /* check to see if we need more room */
  200998. if (!(png_ptr->zstream.avail_out))
  200999. {
  201000. /* make sure the output array has room */
  201001. if (comp->num_output_ptr >= comp->max_output_ptr)
  201002. {
  201003. int old_max;
  201004. old_max = comp->max_output_ptr;
  201005. comp->max_output_ptr = comp->num_output_ptr + 4;
  201006. if (comp->output_ptr != NULL)
  201007. {
  201008. png_charpp old_ptr;
  201009. old_ptr = comp->output_ptr;
  201010. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201011. (png_uint_32)(comp->max_output_ptr *
  201012. png_sizeof (png_charpp)));
  201013. png_memcpy(comp->output_ptr, old_ptr, old_max
  201014. * png_sizeof (png_charp));
  201015. png_free(png_ptr, old_ptr);
  201016. }
  201017. else
  201018. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201019. (png_uint_32)(comp->max_output_ptr *
  201020. png_sizeof (png_charp)));
  201021. }
  201022. /* save the data */
  201023. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201024. (png_uint_32)png_ptr->zbuf_size);
  201025. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201026. png_ptr->zbuf_size);
  201027. comp->num_output_ptr++;
  201028. /* and reset the buffer */
  201029. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201030. png_ptr->zstream.next_out = png_ptr->zbuf;
  201031. }
  201032. /* continue until we don't have any more to compress */
  201033. } while (png_ptr->zstream.avail_in);
  201034. /* finish the compression */
  201035. do
  201036. {
  201037. /* tell zlib we are finished */
  201038. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201039. if (ret == Z_OK)
  201040. {
  201041. /* check to see if we need more room */
  201042. if (!(png_ptr->zstream.avail_out))
  201043. {
  201044. /* check to make sure our output array has room */
  201045. if (comp->num_output_ptr >= comp->max_output_ptr)
  201046. {
  201047. int old_max;
  201048. old_max = comp->max_output_ptr;
  201049. comp->max_output_ptr = comp->num_output_ptr + 4;
  201050. if (comp->output_ptr != NULL)
  201051. {
  201052. png_charpp old_ptr;
  201053. old_ptr = comp->output_ptr;
  201054. /* This could be optimized to realloc() */
  201055. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201056. (png_uint_32)(comp->max_output_ptr *
  201057. png_sizeof (png_charpp)));
  201058. png_memcpy(comp->output_ptr, old_ptr,
  201059. old_max * png_sizeof (png_charp));
  201060. png_free(png_ptr, old_ptr);
  201061. }
  201062. else
  201063. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201064. (png_uint_32)(comp->max_output_ptr *
  201065. png_sizeof (png_charp)));
  201066. }
  201067. /* save off the data */
  201068. comp->output_ptr[comp->num_output_ptr] =
  201069. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201070. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201071. png_ptr->zbuf_size);
  201072. comp->num_output_ptr++;
  201073. /* and reset the buffer pointers */
  201074. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201075. png_ptr->zstream.next_out = png_ptr->zbuf;
  201076. }
  201077. }
  201078. else if (ret != Z_STREAM_END)
  201079. {
  201080. /* we got an error */
  201081. if (png_ptr->zstream.msg != NULL)
  201082. png_error(png_ptr, png_ptr->zstream.msg);
  201083. else
  201084. png_error(png_ptr, "zlib error");
  201085. }
  201086. } while (ret != Z_STREAM_END);
  201087. /* text length is number of buffers plus last buffer */
  201088. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201089. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201090. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201091. return((int)text_len);
  201092. }
  201093. /* ship the compressed text out via chunk writes */
  201094. static void /* PRIVATE */
  201095. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201096. {
  201097. int i;
  201098. /* handle the no-compression case */
  201099. if (comp->input)
  201100. {
  201101. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201102. (png_size_t)comp->input_len);
  201103. return;
  201104. }
  201105. /* write saved output buffers, if any */
  201106. for (i = 0; i < comp->num_output_ptr; i++)
  201107. {
  201108. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201109. png_ptr->zbuf_size);
  201110. png_free(png_ptr, comp->output_ptr[i]);
  201111. comp->output_ptr[i]=NULL;
  201112. }
  201113. if (comp->max_output_ptr != 0)
  201114. png_free(png_ptr, comp->output_ptr);
  201115. comp->output_ptr=NULL;
  201116. /* write anything left in zbuf */
  201117. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201118. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201119. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201120. /* reset zlib for another zTXt/iTXt or image data */
  201121. deflateReset(&png_ptr->zstream);
  201122. png_ptr->zstream.data_type = Z_BINARY;
  201123. }
  201124. #endif
  201125. /* Write the IHDR chunk, and update the png_struct with the necessary
  201126. * information. Note that the rest of this code depends upon this
  201127. * information being correct.
  201128. */
  201129. void /* PRIVATE */
  201130. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201131. int bit_depth, int color_type, int compression_type, int filter_type,
  201132. int interlace_type)
  201133. {
  201134. #ifdef PNG_USE_LOCAL_ARRAYS
  201135. PNG_IHDR;
  201136. #endif
  201137. png_byte buf[13]; /* buffer to store the IHDR info */
  201138. png_debug(1, "in png_write_IHDR\n");
  201139. /* Check that we have valid input data from the application info */
  201140. switch (color_type)
  201141. {
  201142. case PNG_COLOR_TYPE_GRAY:
  201143. switch (bit_depth)
  201144. {
  201145. case 1:
  201146. case 2:
  201147. case 4:
  201148. case 8:
  201149. case 16: png_ptr->channels = 1; break;
  201150. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201151. }
  201152. break;
  201153. case PNG_COLOR_TYPE_RGB:
  201154. if (bit_depth != 8 && bit_depth != 16)
  201155. png_error(png_ptr, "Invalid bit depth for RGB image");
  201156. png_ptr->channels = 3;
  201157. break;
  201158. case PNG_COLOR_TYPE_PALETTE:
  201159. switch (bit_depth)
  201160. {
  201161. case 1:
  201162. case 2:
  201163. case 4:
  201164. case 8: png_ptr->channels = 1; break;
  201165. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201166. }
  201167. break;
  201168. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201169. if (bit_depth != 8 && bit_depth != 16)
  201170. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201171. png_ptr->channels = 2;
  201172. break;
  201173. case PNG_COLOR_TYPE_RGB_ALPHA:
  201174. if (bit_depth != 8 && bit_depth != 16)
  201175. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201176. png_ptr->channels = 4;
  201177. break;
  201178. default:
  201179. png_error(png_ptr, "Invalid image color type specified");
  201180. }
  201181. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201182. {
  201183. png_warning(png_ptr, "Invalid compression type specified");
  201184. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201185. }
  201186. /* Write filter_method 64 (intrapixel differencing) only if
  201187. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201188. * 2. Libpng did not write a PNG signature (this filter_method is only
  201189. * used in PNG datastreams that are embedded in MNG datastreams) and
  201190. * 3. The application called png_permit_mng_features with a mask that
  201191. * included PNG_FLAG_MNG_FILTER_64 and
  201192. * 4. The filter_method is 64 and
  201193. * 5. The color_type is RGB or RGBA
  201194. */
  201195. if (
  201196. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201197. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201198. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201199. (color_type == PNG_COLOR_TYPE_RGB ||
  201200. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201201. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201202. #endif
  201203. filter_type != PNG_FILTER_TYPE_BASE)
  201204. {
  201205. png_warning(png_ptr, "Invalid filter type specified");
  201206. filter_type = PNG_FILTER_TYPE_BASE;
  201207. }
  201208. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201209. if (interlace_type != PNG_INTERLACE_NONE &&
  201210. interlace_type != PNG_INTERLACE_ADAM7)
  201211. {
  201212. png_warning(png_ptr, "Invalid interlace type specified");
  201213. interlace_type = PNG_INTERLACE_ADAM7;
  201214. }
  201215. #else
  201216. interlace_type=PNG_INTERLACE_NONE;
  201217. #endif
  201218. /* save off the relevent information */
  201219. png_ptr->bit_depth = (png_byte)bit_depth;
  201220. png_ptr->color_type = (png_byte)color_type;
  201221. png_ptr->interlaced = (png_byte)interlace_type;
  201222. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201223. png_ptr->filter_type = (png_byte)filter_type;
  201224. #endif
  201225. png_ptr->compression_type = (png_byte)compression_type;
  201226. png_ptr->width = width;
  201227. png_ptr->height = height;
  201228. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201229. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201230. /* set the usr info, so any transformations can modify it */
  201231. png_ptr->usr_width = png_ptr->width;
  201232. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201233. png_ptr->usr_channels = png_ptr->channels;
  201234. /* pack the header information into the buffer */
  201235. png_save_uint_32(buf, width);
  201236. png_save_uint_32(buf + 4, height);
  201237. buf[8] = (png_byte)bit_depth;
  201238. buf[9] = (png_byte)color_type;
  201239. buf[10] = (png_byte)compression_type;
  201240. buf[11] = (png_byte)filter_type;
  201241. buf[12] = (png_byte)interlace_type;
  201242. /* write the chunk */
  201243. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201244. /* initialize zlib with PNG info */
  201245. png_ptr->zstream.zalloc = png_zalloc;
  201246. png_ptr->zstream.zfree = png_zfree;
  201247. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201248. if (!(png_ptr->do_filter))
  201249. {
  201250. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201251. png_ptr->bit_depth < 8)
  201252. png_ptr->do_filter = PNG_FILTER_NONE;
  201253. else
  201254. png_ptr->do_filter = PNG_ALL_FILTERS;
  201255. }
  201256. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201257. {
  201258. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201259. png_ptr->zlib_strategy = Z_FILTERED;
  201260. else
  201261. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201262. }
  201263. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201264. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201265. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201266. png_ptr->zlib_mem_level = 8;
  201267. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201268. png_ptr->zlib_window_bits = 15;
  201269. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201270. png_ptr->zlib_method = 8;
  201271. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201272. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201273. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201274. png_error(png_ptr, "zlib failed to initialize compressor");
  201275. png_ptr->zstream.next_out = png_ptr->zbuf;
  201276. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201277. /* libpng is not interested in zstream.data_type */
  201278. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201279. png_ptr->zstream.data_type = Z_BINARY;
  201280. png_ptr->mode = PNG_HAVE_IHDR;
  201281. }
  201282. /* write the palette. We are careful not to trust png_color to be in the
  201283. * correct order for PNG, so people can redefine it to any convenient
  201284. * structure.
  201285. */
  201286. void /* PRIVATE */
  201287. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201288. {
  201289. #ifdef PNG_USE_LOCAL_ARRAYS
  201290. PNG_PLTE;
  201291. #endif
  201292. png_uint_32 i;
  201293. png_colorp pal_ptr;
  201294. png_byte buf[3];
  201295. png_debug(1, "in png_write_PLTE\n");
  201296. if ((
  201297. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201298. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201299. #endif
  201300. num_pal == 0) || num_pal > 256)
  201301. {
  201302. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201303. {
  201304. png_error(png_ptr, "Invalid number of colors in palette");
  201305. }
  201306. else
  201307. {
  201308. png_warning(png_ptr, "Invalid number of colors in palette");
  201309. return;
  201310. }
  201311. }
  201312. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201313. {
  201314. png_warning(png_ptr,
  201315. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201316. return;
  201317. }
  201318. png_ptr->num_palette = (png_uint_16)num_pal;
  201319. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201320. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201321. #ifndef PNG_NO_POINTER_INDEXING
  201322. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201323. {
  201324. buf[0] = pal_ptr->red;
  201325. buf[1] = pal_ptr->green;
  201326. buf[2] = pal_ptr->blue;
  201327. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201328. }
  201329. #else
  201330. /* This is a little slower but some buggy compilers need to do this instead */
  201331. pal_ptr=palette;
  201332. for (i = 0; i < num_pal; i++)
  201333. {
  201334. buf[0] = pal_ptr[i].red;
  201335. buf[1] = pal_ptr[i].green;
  201336. buf[2] = pal_ptr[i].blue;
  201337. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201338. }
  201339. #endif
  201340. png_write_chunk_end(png_ptr);
  201341. png_ptr->mode |= PNG_HAVE_PLTE;
  201342. }
  201343. /* write an IDAT chunk */
  201344. void /* PRIVATE */
  201345. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201346. {
  201347. #ifdef PNG_USE_LOCAL_ARRAYS
  201348. PNG_IDAT;
  201349. #endif
  201350. png_debug(1, "in png_write_IDAT\n");
  201351. /* Optimize the CMF field in the zlib stream. */
  201352. /* This hack of the zlib stream is compliant to the stream specification. */
  201353. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201354. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201355. {
  201356. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201357. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201358. {
  201359. /* Avoid memory underflows and multiplication overflows. */
  201360. /* The conditions below are practically always satisfied;
  201361. however, they still must be checked. */
  201362. if (length >= 2 &&
  201363. png_ptr->height < 16384 && png_ptr->width < 16384)
  201364. {
  201365. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201366. ((png_ptr->width *
  201367. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201368. unsigned int z_cinfo = z_cmf >> 4;
  201369. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201370. while (uncompressed_idat_size <= half_z_window_size &&
  201371. half_z_window_size >= 256)
  201372. {
  201373. z_cinfo--;
  201374. half_z_window_size >>= 1;
  201375. }
  201376. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201377. if (data[0] != (png_byte)z_cmf)
  201378. {
  201379. data[0] = (png_byte)z_cmf;
  201380. data[1] &= 0xe0;
  201381. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201382. }
  201383. }
  201384. }
  201385. else
  201386. png_error(png_ptr,
  201387. "Invalid zlib compression method or flags in IDAT");
  201388. }
  201389. png_write_chunk(png_ptr, png_IDAT, data, length);
  201390. png_ptr->mode |= PNG_HAVE_IDAT;
  201391. }
  201392. /* write an IEND chunk */
  201393. void /* PRIVATE */
  201394. png_write_IEND(png_structp png_ptr)
  201395. {
  201396. #ifdef PNG_USE_LOCAL_ARRAYS
  201397. PNG_IEND;
  201398. #endif
  201399. png_debug(1, "in png_write_IEND\n");
  201400. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201401. (png_size_t)0);
  201402. png_ptr->mode |= PNG_HAVE_IEND;
  201403. }
  201404. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201405. /* write a gAMA chunk */
  201406. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201407. void /* PRIVATE */
  201408. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201409. {
  201410. #ifdef PNG_USE_LOCAL_ARRAYS
  201411. PNG_gAMA;
  201412. #endif
  201413. png_uint_32 igamma;
  201414. png_byte buf[4];
  201415. png_debug(1, "in png_write_gAMA\n");
  201416. /* file_gamma is saved in 1/100,000ths */
  201417. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201418. png_save_uint_32(buf, igamma);
  201419. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201420. }
  201421. #endif
  201422. #ifdef PNG_FIXED_POINT_SUPPORTED
  201423. void /* PRIVATE */
  201424. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201425. {
  201426. #ifdef PNG_USE_LOCAL_ARRAYS
  201427. PNG_gAMA;
  201428. #endif
  201429. png_byte buf[4];
  201430. png_debug(1, "in png_write_gAMA\n");
  201431. /* file_gamma is saved in 1/100,000ths */
  201432. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201433. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201434. }
  201435. #endif
  201436. #endif
  201437. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201438. /* write a sRGB chunk */
  201439. void /* PRIVATE */
  201440. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201441. {
  201442. #ifdef PNG_USE_LOCAL_ARRAYS
  201443. PNG_sRGB;
  201444. #endif
  201445. png_byte buf[1];
  201446. png_debug(1, "in png_write_sRGB\n");
  201447. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201448. png_warning(png_ptr,
  201449. "Invalid sRGB rendering intent specified");
  201450. buf[0]=(png_byte)srgb_intent;
  201451. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201452. }
  201453. #endif
  201454. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201455. /* write an iCCP chunk */
  201456. void /* PRIVATE */
  201457. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201458. png_charp profile, int profile_len)
  201459. {
  201460. #ifdef PNG_USE_LOCAL_ARRAYS
  201461. PNG_iCCP;
  201462. #endif
  201463. png_size_t name_len;
  201464. png_charp new_name;
  201465. compression_state comp;
  201466. int embedded_profile_len = 0;
  201467. png_debug(1, "in png_write_iCCP\n");
  201468. comp.num_output_ptr = 0;
  201469. comp.max_output_ptr = 0;
  201470. comp.output_ptr = NULL;
  201471. comp.input = NULL;
  201472. comp.input_len = 0;
  201473. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201474. &new_name)) == 0)
  201475. {
  201476. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201477. return;
  201478. }
  201479. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201480. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201481. if (profile == NULL)
  201482. profile_len = 0;
  201483. if (profile_len > 3)
  201484. embedded_profile_len =
  201485. ((*( (png_bytep)profile ))<<24) |
  201486. ((*( (png_bytep)profile+1))<<16) |
  201487. ((*( (png_bytep)profile+2))<< 8) |
  201488. ((*( (png_bytep)profile+3)) );
  201489. if (profile_len < embedded_profile_len)
  201490. {
  201491. png_warning(png_ptr,
  201492. "Embedded profile length too large in iCCP chunk");
  201493. return;
  201494. }
  201495. if (profile_len > embedded_profile_len)
  201496. {
  201497. png_warning(png_ptr,
  201498. "Truncating profile to actual length in iCCP chunk");
  201499. profile_len = embedded_profile_len;
  201500. }
  201501. if (profile_len)
  201502. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201503. PNG_COMPRESSION_TYPE_BASE, &comp);
  201504. /* make sure we include the NULL after the name and the compression type */
  201505. png_write_chunk_start(png_ptr, png_iCCP,
  201506. (png_uint_32)name_len+profile_len+2);
  201507. new_name[name_len+1]=0x00;
  201508. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201509. if (profile_len)
  201510. png_write_compressed_data_out(png_ptr, &comp);
  201511. png_write_chunk_end(png_ptr);
  201512. png_free(png_ptr, new_name);
  201513. }
  201514. #endif
  201515. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201516. /* write a sPLT chunk */
  201517. void /* PRIVATE */
  201518. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201519. {
  201520. #ifdef PNG_USE_LOCAL_ARRAYS
  201521. PNG_sPLT;
  201522. #endif
  201523. png_size_t name_len;
  201524. png_charp new_name;
  201525. png_byte entrybuf[10];
  201526. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201527. int palette_size = entry_size * spalette->nentries;
  201528. png_sPLT_entryp ep;
  201529. #ifdef PNG_NO_POINTER_INDEXING
  201530. int i;
  201531. #endif
  201532. png_debug(1, "in png_write_sPLT\n");
  201533. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201534. spalette->name, &new_name))==0)
  201535. {
  201536. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201537. return;
  201538. }
  201539. /* make sure we include the NULL after the name */
  201540. png_write_chunk_start(png_ptr, png_sPLT,
  201541. (png_uint_32)(name_len + 2 + palette_size));
  201542. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201543. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201544. /* loop through each palette entry, writing appropriately */
  201545. #ifndef PNG_NO_POINTER_INDEXING
  201546. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201547. {
  201548. if (spalette->depth == 8)
  201549. {
  201550. entrybuf[0] = (png_byte)ep->red;
  201551. entrybuf[1] = (png_byte)ep->green;
  201552. entrybuf[2] = (png_byte)ep->blue;
  201553. entrybuf[3] = (png_byte)ep->alpha;
  201554. png_save_uint_16(entrybuf + 4, ep->frequency);
  201555. }
  201556. else
  201557. {
  201558. png_save_uint_16(entrybuf + 0, ep->red);
  201559. png_save_uint_16(entrybuf + 2, ep->green);
  201560. png_save_uint_16(entrybuf + 4, ep->blue);
  201561. png_save_uint_16(entrybuf + 6, ep->alpha);
  201562. png_save_uint_16(entrybuf + 8, ep->frequency);
  201563. }
  201564. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201565. }
  201566. #else
  201567. ep=spalette->entries;
  201568. for (i=0; i>spalette->nentries; i++)
  201569. {
  201570. if (spalette->depth == 8)
  201571. {
  201572. entrybuf[0] = (png_byte)ep[i].red;
  201573. entrybuf[1] = (png_byte)ep[i].green;
  201574. entrybuf[2] = (png_byte)ep[i].blue;
  201575. entrybuf[3] = (png_byte)ep[i].alpha;
  201576. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201577. }
  201578. else
  201579. {
  201580. png_save_uint_16(entrybuf + 0, ep[i].red);
  201581. png_save_uint_16(entrybuf + 2, ep[i].green);
  201582. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201583. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201584. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201585. }
  201586. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201587. }
  201588. #endif
  201589. png_write_chunk_end(png_ptr);
  201590. png_free(png_ptr, new_name);
  201591. }
  201592. #endif
  201593. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201594. /* write the sBIT chunk */
  201595. void /* PRIVATE */
  201596. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201597. {
  201598. #ifdef PNG_USE_LOCAL_ARRAYS
  201599. PNG_sBIT;
  201600. #endif
  201601. png_byte buf[4];
  201602. png_size_t size;
  201603. png_debug(1, "in png_write_sBIT\n");
  201604. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201605. if (color_type & PNG_COLOR_MASK_COLOR)
  201606. {
  201607. png_byte maxbits;
  201608. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201609. png_ptr->usr_bit_depth);
  201610. if (sbit->red == 0 || sbit->red > maxbits ||
  201611. sbit->green == 0 || sbit->green > maxbits ||
  201612. sbit->blue == 0 || sbit->blue > maxbits)
  201613. {
  201614. png_warning(png_ptr, "Invalid sBIT depth specified");
  201615. return;
  201616. }
  201617. buf[0] = sbit->red;
  201618. buf[1] = sbit->green;
  201619. buf[2] = sbit->blue;
  201620. size = 3;
  201621. }
  201622. else
  201623. {
  201624. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201625. {
  201626. png_warning(png_ptr, "Invalid sBIT depth specified");
  201627. return;
  201628. }
  201629. buf[0] = sbit->gray;
  201630. size = 1;
  201631. }
  201632. if (color_type & PNG_COLOR_MASK_ALPHA)
  201633. {
  201634. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201635. {
  201636. png_warning(png_ptr, "Invalid sBIT depth specified");
  201637. return;
  201638. }
  201639. buf[size++] = sbit->alpha;
  201640. }
  201641. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201642. }
  201643. #endif
  201644. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201645. /* write the cHRM chunk */
  201646. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201647. void /* PRIVATE */
  201648. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201649. double red_x, double red_y, double green_x, double green_y,
  201650. double blue_x, double blue_y)
  201651. {
  201652. #ifdef PNG_USE_LOCAL_ARRAYS
  201653. PNG_cHRM;
  201654. #endif
  201655. png_byte buf[32];
  201656. png_uint_32 itemp;
  201657. png_debug(1, "in png_write_cHRM\n");
  201658. /* each value is saved in 1/100,000ths */
  201659. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201660. white_x + white_y > 1.0)
  201661. {
  201662. png_warning(png_ptr, "Invalid cHRM white point specified");
  201663. #if !defined(PNG_NO_CONSOLE_IO)
  201664. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201665. #endif
  201666. return;
  201667. }
  201668. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201669. png_save_uint_32(buf, itemp);
  201670. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201671. png_save_uint_32(buf + 4, itemp);
  201672. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201673. {
  201674. png_warning(png_ptr, "Invalid cHRM red point specified");
  201675. return;
  201676. }
  201677. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201678. png_save_uint_32(buf + 8, itemp);
  201679. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201680. png_save_uint_32(buf + 12, itemp);
  201681. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201682. {
  201683. png_warning(png_ptr, "Invalid cHRM green point specified");
  201684. return;
  201685. }
  201686. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201687. png_save_uint_32(buf + 16, itemp);
  201688. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201689. png_save_uint_32(buf + 20, itemp);
  201690. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201691. {
  201692. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201693. return;
  201694. }
  201695. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201696. png_save_uint_32(buf + 24, itemp);
  201697. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201698. png_save_uint_32(buf + 28, itemp);
  201699. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201700. }
  201701. #endif
  201702. #ifdef PNG_FIXED_POINT_SUPPORTED
  201703. void /* PRIVATE */
  201704. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201705. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201706. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201707. png_fixed_point blue_y)
  201708. {
  201709. #ifdef PNG_USE_LOCAL_ARRAYS
  201710. PNG_cHRM;
  201711. #endif
  201712. png_byte buf[32];
  201713. png_debug(1, "in png_write_cHRM\n");
  201714. /* each value is saved in 1/100,000ths */
  201715. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201716. {
  201717. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201718. #if !defined(PNG_NO_CONSOLE_IO)
  201719. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201720. #endif
  201721. return;
  201722. }
  201723. png_save_uint_32(buf, (png_uint_32)white_x);
  201724. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201725. if (red_x + red_y > 100000L)
  201726. {
  201727. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201728. return;
  201729. }
  201730. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201731. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201732. if (green_x + green_y > 100000L)
  201733. {
  201734. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201735. return;
  201736. }
  201737. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201738. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201739. if (blue_x + blue_y > 100000L)
  201740. {
  201741. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201742. return;
  201743. }
  201744. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201745. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201746. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201747. }
  201748. #endif
  201749. #endif
  201750. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201751. /* write the tRNS chunk */
  201752. void /* PRIVATE */
  201753. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201754. int num_trans, int color_type)
  201755. {
  201756. #ifdef PNG_USE_LOCAL_ARRAYS
  201757. PNG_tRNS;
  201758. #endif
  201759. png_byte buf[6];
  201760. png_debug(1, "in png_write_tRNS\n");
  201761. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201762. {
  201763. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201764. {
  201765. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201766. return;
  201767. }
  201768. /* write the chunk out as it is */
  201769. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201770. }
  201771. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201772. {
  201773. /* one 16 bit value */
  201774. if(tran->gray >= (1 << png_ptr->bit_depth))
  201775. {
  201776. png_warning(png_ptr,
  201777. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201778. return;
  201779. }
  201780. png_save_uint_16(buf, tran->gray);
  201781. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201782. }
  201783. else if (color_type == PNG_COLOR_TYPE_RGB)
  201784. {
  201785. /* three 16 bit values */
  201786. png_save_uint_16(buf, tran->red);
  201787. png_save_uint_16(buf + 2, tran->green);
  201788. png_save_uint_16(buf + 4, tran->blue);
  201789. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201790. {
  201791. png_warning(png_ptr,
  201792. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201793. return;
  201794. }
  201795. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201796. }
  201797. else
  201798. {
  201799. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201800. }
  201801. }
  201802. #endif
  201803. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201804. /* write the background chunk */
  201805. void /* PRIVATE */
  201806. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201807. {
  201808. #ifdef PNG_USE_LOCAL_ARRAYS
  201809. PNG_bKGD;
  201810. #endif
  201811. png_byte buf[6];
  201812. png_debug(1, "in png_write_bKGD\n");
  201813. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201814. {
  201815. if (
  201816. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201817. (png_ptr->num_palette ||
  201818. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201819. #endif
  201820. back->index > png_ptr->num_palette)
  201821. {
  201822. png_warning(png_ptr, "Invalid background palette index");
  201823. return;
  201824. }
  201825. buf[0] = back->index;
  201826. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201827. }
  201828. else if (color_type & PNG_COLOR_MASK_COLOR)
  201829. {
  201830. png_save_uint_16(buf, back->red);
  201831. png_save_uint_16(buf + 2, back->green);
  201832. png_save_uint_16(buf + 4, back->blue);
  201833. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201834. {
  201835. png_warning(png_ptr,
  201836. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201837. return;
  201838. }
  201839. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201840. }
  201841. else
  201842. {
  201843. if(back->gray >= (1 << png_ptr->bit_depth))
  201844. {
  201845. png_warning(png_ptr,
  201846. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201847. return;
  201848. }
  201849. png_save_uint_16(buf, back->gray);
  201850. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201851. }
  201852. }
  201853. #endif
  201854. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201855. /* write the histogram */
  201856. void /* PRIVATE */
  201857. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201858. {
  201859. #ifdef PNG_USE_LOCAL_ARRAYS
  201860. PNG_hIST;
  201861. #endif
  201862. int i;
  201863. png_byte buf[3];
  201864. png_debug(1, "in png_write_hIST\n");
  201865. if (num_hist > (int)png_ptr->num_palette)
  201866. {
  201867. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201868. png_ptr->num_palette);
  201869. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201870. return;
  201871. }
  201872. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201873. for (i = 0; i < num_hist; i++)
  201874. {
  201875. png_save_uint_16(buf, hist[i]);
  201876. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201877. }
  201878. png_write_chunk_end(png_ptr);
  201879. }
  201880. #endif
  201881. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201882. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201883. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201884. * and if invalid, correct the keyword rather than discarding the entire
  201885. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201886. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201887. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201888. *
  201889. * The new_key is allocated to hold the corrected keyword and must be freed
  201890. * by the calling routine. This avoids problems with trying to write to
  201891. * static keywords without having to have duplicate copies of the strings.
  201892. */
  201893. png_size_t /* PRIVATE */
  201894. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201895. {
  201896. png_size_t key_len;
  201897. png_charp kp, dp;
  201898. int kflag;
  201899. int kwarn=0;
  201900. png_debug(1, "in png_check_keyword\n");
  201901. *new_key = NULL;
  201902. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201903. {
  201904. png_warning(png_ptr, "zero length keyword");
  201905. return ((png_size_t)0);
  201906. }
  201907. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201908. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201909. if (*new_key == NULL)
  201910. {
  201911. png_warning(png_ptr, "Out of memory while procesing keyword");
  201912. return ((png_size_t)0);
  201913. }
  201914. /* Replace non-printing characters with a blank and print a warning */
  201915. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201916. {
  201917. if ((png_byte)*kp < 0x20 ||
  201918. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201919. {
  201920. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201921. char msg[40];
  201922. png_snprintf(msg, 40,
  201923. "invalid keyword character 0x%02X", (png_byte)*kp);
  201924. png_warning(png_ptr, msg);
  201925. #else
  201926. png_warning(png_ptr, "invalid character in keyword");
  201927. #endif
  201928. *dp = ' ';
  201929. }
  201930. else
  201931. {
  201932. *dp = *kp;
  201933. }
  201934. }
  201935. *dp = '\0';
  201936. /* Remove any trailing white space. */
  201937. kp = *new_key + key_len - 1;
  201938. if (*kp == ' ')
  201939. {
  201940. png_warning(png_ptr, "trailing spaces removed from keyword");
  201941. while (*kp == ' ')
  201942. {
  201943. *(kp--) = '\0';
  201944. key_len--;
  201945. }
  201946. }
  201947. /* Remove any leading white space. */
  201948. kp = *new_key;
  201949. if (*kp == ' ')
  201950. {
  201951. png_warning(png_ptr, "leading spaces removed from keyword");
  201952. while (*kp == ' ')
  201953. {
  201954. kp++;
  201955. key_len--;
  201956. }
  201957. }
  201958. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201959. /* Remove multiple internal spaces. */
  201960. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201961. {
  201962. if (*kp == ' ' && kflag == 0)
  201963. {
  201964. *(dp++) = *kp;
  201965. kflag = 1;
  201966. }
  201967. else if (*kp == ' ')
  201968. {
  201969. key_len--;
  201970. kwarn=1;
  201971. }
  201972. else
  201973. {
  201974. *(dp++) = *kp;
  201975. kflag = 0;
  201976. }
  201977. }
  201978. *dp = '\0';
  201979. if(kwarn)
  201980. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201981. if (key_len == 0)
  201982. {
  201983. png_free(png_ptr, *new_key);
  201984. *new_key=NULL;
  201985. png_warning(png_ptr, "Zero length keyword");
  201986. }
  201987. if (key_len > 79)
  201988. {
  201989. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201990. new_key[79] = '\0';
  201991. key_len = 79;
  201992. }
  201993. return (key_len);
  201994. }
  201995. #endif
  201996. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201997. /* write a tEXt chunk */
  201998. void /* PRIVATE */
  201999. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202000. png_size_t text_len)
  202001. {
  202002. #ifdef PNG_USE_LOCAL_ARRAYS
  202003. PNG_tEXt;
  202004. #endif
  202005. png_size_t key_len;
  202006. png_charp new_key;
  202007. png_debug(1, "in png_write_tEXt\n");
  202008. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202009. {
  202010. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202011. return;
  202012. }
  202013. if (text == NULL || *text == '\0')
  202014. text_len = 0;
  202015. else
  202016. text_len = png_strlen(text);
  202017. /* make sure we include the 0 after the key */
  202018. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202019. /*
  202020. * We leave it to the application to meet PNG-1.0 requirements on the
  202021. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202022. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202023. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202024. */
  202025. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202026. if (text_len)
  202027. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202028. png_write_chunk_end(png_ptr);
  202029. png_free(png_ptr, new_key);
  202030. }
  202031. #endif
  202032. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202033. /* write a compressed text chunk */
  202034. void /* PRIVATE */
  202035. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202036. png_size_t text_len, int compression)
  202037. {
  202038. #ifdef PNG_USE_LOCAL_ARRAYS
  202039. PNG_zTXt;
  202040. #endif
  202041. png_size_t key_len;
  202042. char buf[1];
  202043. png_charp new_key;
  202044. compression_state comp;
  202045. png_debug(1, "in png_write_zTXt\n");
  202046. comp.num_output_ptr = 0;
  202047. comp.max_output_ptr = 0;
  202048. comp.output_ptr = NULL;
  202049. comp.input = NULL;
  202050. comp.input_len = 0;
  202051. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202052. {
  202053. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202054. return;
  202055. }
  202056. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202057. {
  202058. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202059. png_free(png_ptr, new_key);
  202060. return;
  202061. }
  202062. text_len = png_strlen(text);
  202063. /* compute the compressed data; do it now for the length */
  202064. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202065. &comp);
  202066. /* write start of chunk */
  202067. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202068. (key_len+text_len+2));
  202069. /* write key */
  202070. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202071. png_free(png_ptr, new_key);
  202072. buf[0] = (png_byte)compression;
  202073. /* write compression */
  202074. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202075. /* write the compressed data */
  202076. png_write_compressed_data_out(png_ptr, &comp);
  202077. /* close the chunk */
  202078. png_write_chunk_end(png_ptr);
  202079. }
  202080. #endif
  202081. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202082. /* write an iTXt chunk */
  202083. void /* PRIVATE */
  202084. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202085. png_charp lang, png_charp lang_key, png_charp text)
  202086. {
  202087. #ifdef PNG_USE_LOCAL_ARRAYS
  202088. PNG_iTXt;
  202089. #endif
  202090. png_size_t lang_len, key_len, lang_key_len, text_len;
  202091. png_charp new_lang, new_key;
  202092. png_byte cbuf[2];
  202093. compression_state comp;
  202094. png_debug(1, "in png_write_iTXt\n");
  202095. comp.num_output_ptr = 0;
  202096. comp.max_output_ptr = 0;
  202097. comp.output_ptr = NULL;
  202098. comp.input = NULL;
  202099. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202100. {
  202101. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202102. return;
  202103. }
  202104. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202105. {
  202106. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202107. new_lang = NULL;
  202108. lang_len = 0;
  202109. }
  202110. if (lang_key == NULL)
  202111. lang_key_len = 0;
  202112. else
  202113. lang_key_len = png_strlen(lang_key);
  202114. if (text == NULL)
  202115. text_len = 0;
  202116. else
  202117. text_len = png_strlen(text);
  202118. /* compute the compressed data; do it now for the length */
  202119. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202120. &comp);
  202121. /* make sure we include the compression flag, the compression byte,
  202122. * and the NULs after the key, lang, and lang_key parts */
  202123. png_write_chunk_start(png_ptr, png_iTXt,
  202124. (png_uint_32)(
  202125. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202126. + key_len
  202127. + lang_len
  202128. + lang_key_len
  202129. + text_len));
  202130. /*
  202131. * We leave it to the application to meet PNG-1.0 requirements on the
  202132. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202133. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202134. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202135. */
  202136. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202137. /* set the compression flag */
  202138. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202139. compression == PNG_TEXT_COMPRESSION_NONE)
  202140. cbuf[0] = 0;
  202141. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202142. cbuf[0] = 1;
  202143. /* set the compression method */
  202144. cbuf[1] = 0;
  202145. png_write_chunk_data(png_ptr, cbuf, 2);
  202146. cbuf[0] = 0;
  202147. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202148. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202149. png_write_compressed_data_out(png_ptr, &comp);
  202150. png_write_chunk_end(png_ptr);
  202151. png_free(png_ptr, new_key);
  202152. if (new_lang)
  202153. png_free(png_ptr, new_lang);
  202154. }
  202155. #endif
  202156. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202157. /* write the oFFs chunk */
  202158. void /* PRIVATE */
  202159. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202160. int unit_type)
  202161. {
  202162. #ifdef PNG_USE_LOCAL_ARRAYS
  202163. PNG_oFFs;
  202164. #endif
  202165. png_byte buf[9];
  202166. png_debug(1, "in png_write_oFFs\n");
  202167. if (unit_type >= PNG_OFFSET_LAST)
  202168. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202169. png_save_int_32(buf, x_offset);
  202170. png_save_int_32(buf + 4, y_offset);
  202171. buf[8] = (png_byte)unit_type;
  202172. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202173. }
  202174. #endif
  202175. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202176. /* write the pCAL chunk (described in the PNG extensions document) */
  202177. void /* PRIVATE */
  202178. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202179. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202180. {
  202181. #ifdef PNG_USE_LOCAL_ARRAYS
  202182. PNG_pCAL;
  202183. #endif
  202184. png_size_t purpose_len, units_len, total_len;
  202185. png_uint_32p params_len;
  202186. png_byte buf[10];
  202187. png_charp new_purpose;
  202188. int i;
  202189. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202190. if (type >= PNG_EQUATION_LAST)
  202191. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202192. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202193. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202194. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202195. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202196. total_len = purpose_len + units_len + 10;
  202197. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202198. *png_sizeof(png_uint_32)));
  202199. /* Find the length of each parameter, making sure we don't count the
  202200. null terminator for the last parameter. */
  202201. for (i = 0; i < nparams; i++)
  202202. {
  202203. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202204. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202205. total_len += (png_size_t)params_len[i];
  202206. }
  202207. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202208. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202209. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202210. png_save_int_32(buf, X0);
  202211. png_save_int_32(buf + 4, X1);
  202212. buf[8] = (png_byte)type;
  202213. buf[9] = (png_byte)nparams;
  202214. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202215. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202216. png_free(png_ptr, new_purpose);
  202217. for (i = 0; i < nparams; i++)
  202218. {
  202219. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202220. (png_size_t)params_len[i]);
  202221. }
  202222. png_free(png_ptr, params_len);
  202223. png_write_chunk_end(png_ptr);
  202224. }
  202225. #endif
  202226. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202227. /* write the sCAL chunk */
  202228. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202229. void /* PRIVATE */
  202230. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202231. {
  202232. #ifdef PNG_USE_LOCAL_ARRAYS
  202233. PNG_sCAL;
  202234. #endif
  202235. char buf[64];
  202236. png_size_t total_len;
  202237. png_debug(1, "in png_write_sCAL\n");
  202238. buf[0] = (char)unit;
  202239. #if defined(_WIN32_WCE)
  202240. /* sprintf() function is not supported on WindowsCE */
  202241. {
  202242. wchar_t wc_buf[32];
  202243. size_t wc_len;
  202244. swprintf(wc_buf, TEXT("%12.12e"), width);
  202245. wc_len = wcslen(wc_buf);
  202246. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202247. total_len = wc_len + 2;
  202248. swprintf(wc_buf, TEXT("%12.12e"), height);
  202249. wc_len = wcslen(wc_buf);
  202250. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202251. NULL, NULL);
  202252. total_len += wc_len;
  202253. }
  202254. #else
  202255. png_snprintf(buf + 1, 63, "%12.12e", width);
  202256. total_len = 1 + png_strlen(buf + 1) + 1;
  202257. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202258. total_len += png_strlen(buf + total_len);
  202259. #endif
  202260. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202261. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202262. }
  202263. #else
  202264. #ifdef PNG_FIXED_POINT_SUPPORTED
  202265. void /* PRIVATE */
  202266. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202267. png_charp height)
  202268. {
  202269. #ifdef PNG_USE_LOCAL_ARRAYS
  202270. PNG_sCAL;
  202271. #endif
  202272. png_byte buf[64];
  202273. png_size_t wlen, hlen, total_len;
  202274. png_debug(1, "in png_write_sCAL_s\n");
  202275. wlen = png_strlen(width);
  202276. hlen = png_strlen(height);
  202277. total_len = wlen + hlen + 2;
  202278. if (total_len > 64)
  202279. {
  202280. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202281. return;
  202282. }
  202283. buf[0] = (png_byte)unit;
  202284. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202285. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202286. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202287. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202288. }
  202289. #endif
  202290. #endif
  202291. #endif
  202292. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202293. /* write the pHYs chunk */
  202294. void /* PRIVATE */
  202295. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202296. png_uint_32 y_pixels_per_unit,
  202297. int unit_type)
  202298. {
  202299. #ifdef PNG_USE_LOCAL_ARRAYS
  202300. PNG_pHYs;
  202301. #endif
  202302. png_byte buf[9];
  202303. png_debug(1, "in png_write_pHYs\n");
  202304. if (unit_type >= PNG_RESOLUTION_LAST)
  202305. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202306. png_save_uint_32(buf, x_pixels_per_unit);
  202307. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202308. buf[8] = (png_byte)unit_type;
  202309. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202310. }
  202311. #endif
  202312. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202313. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202314. * or png_convert_from_time_t(), or fill in the structure yourself.
  202315. */
  202316. void /* PRIVATE */
  202317. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202318. {
  202319. #ifdef PNG_USE_LOCAL_ARRAYS
  202320. PNG_tIME;
  202321. #endif
  202322. png_byte buf[7];
  202323. png_debug(1, "in png_write_tIME\n");
  202324. if (mod_time->month > 12 || mod_time->month < 1 ||
  202325. mod_time->day > 31 || mod_time->day < 1 ||
  202326. mod_time->hour > 23 || mod_time->second > 60)
  202327. {
  202328. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202329. return;
  202330. }
  202331. png_save_uint_16(buf, mod_time->year);
  202332. buf[2] = mod_time->month;
  202333. buf[3] = mod_time->day;
  202334. buf[4] = mod_time->hour;
  202335. buf[5] = mod_time->minute;
  202336. buf[6] = mod_time->second;
  202337. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202338. }
  202339. #endif
  202340. /* initializes the row writing capability of libpng */
  202341. void /* PRIVATE */
  202342. png_write_start_row(png_structp png_ptr)
  202343. {
  202344. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202345. #ifdef PNG_USE_LOCAL_ARRAYS
  202346. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202347. /* start of interlace block */
  202348. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202349. /* offset to next interlace block */
  202350. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202351. /* start of interlace block in the y direction */
  202352. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202353. /* offset to next interlace block in the y direction */
  202354. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202355. #endif
  202356. #endif
  202357. png_size_t buf_size;
  202358. png_debug(1, "in png_write_start_row\n");
  202359. buf_size = (png_size_t)(PNG_ROWBYTES(
  202360. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202361. /* set up row buffer */
  202362. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202363. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202364. #ifndef PNG_NO_WRITE_FILTERING
  202365. /* set up filtering buffer, if using this filter */
  202366. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202367. {
  202368. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202369. (png_ptr->rowbytes + 1));
  202370. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202371. }
  202372. /* We only need to keep the previous row if we are using one of these. */
  202373. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202374. {
  202375. /* set up previous row buffer */
  202376. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202377. png_memset(png_ptr->prev_row, 0, buf_size);
  202378. if (png_ptr->do_filter & PNG_FILTER_UP)
  202379. {
  202380. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202381. (png_ptr->rowbytes + 1));
  202382. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202383. }
  202384. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202385. {
  202386. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202387. (png_ptr->rowbytes + 1));
  202388. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202389. }
  202390. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202391. {
  202392. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202393. (png_ptr->rowbytes + 1));
  202394. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202395. }
  202396. #endif /* PNG_NO_WRITE_FILTERING */
  202397. }
  202398. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202399. /* if interlaced, we need to set up width and height of pass */
  202400. if (png_ptr->interlaced)
  202401. {
  202402. if (!(png_ptr->transformations & PNG_INTERLACE))
  202403. {
  202404. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202405. png_pass_ystart[0]) / png_pass_yinc[0];
  202406. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202407. png_pass_start[0]) / png_pass_inc[0];
  202408. }
  202409. else
  202410. {
  202411. png_ptr->num_rows = png_ptr->height;
  202412. png_ptr->usr_width = png_ptr->width;
  202413. }
  202414. }
  202415. else
  202416. #endif
  202417. {
  202418. png_ptr->num_rows = png_ptr->height;
  202419. png_ptr->usr_width = png_ptr->width;
  202420. }
  202421. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202422. png_ptr->zstream.next_out = png_ptr->zbuf;
  202423. }
  202424. /* Internal use only. Called when finished processing a row of data. */
  202425. void /* PRIVATE */
  202426. png_write_finish_row(png_structp png_ptr)
  202427. {
  202428. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202429. #ifdef PNG_USE_LOCAL_ARRAYS
  202430. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202431. /* start of interlace block */
  202432. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202433. /* offset to next interlace block */
  202434. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202435. /* start of interlace block in the y direction */
  202436. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202437. /* offset to next interlace block in the y direction */
  202438. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202439. #endif
  202440. #endif
  202441. int ret;
  202442. png_debug(1, "in png_write_finish_row\n");
  202443. /* next row */
  202444. png_ptr->row_number++;
  202445. /* see if we are done */
  202446. if (png_ptr->row_number < png_ptr->num_rows)
  202447. return;
  202448. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202449. /* if interlaced, go to next pass */
  202450. if (png_ptr->interlaced)
  202451. {
  202452. png_ptr->row_number = 0;
  202453. if (png_ptr->transformations & PNG_INTERLACE)
  202454. {
  202455. png_ptr->pass++;
  202456. }
  202457. else
  202458. {
  202459. /* loop until we find a non-zero width or height pass */
  202460. do
  202461. {
  202462. png_ptr->pass++;
  202463. if (png_ptr->pass >= 7)
  202464. break;
  202465. png_ptr->usr_width = (png_ptr->width +
  202466. png_pass_inc[png_ptr->pass] - 1 -
  202467. png_pass_start[png_ptr->pass]) /
  202468. png_pass_inc[png_ptr->pass];
  202469. png_ptr->num_rows = (png_ptr->height +
  202470. png_pass_yinc[png_ptr->pass] - 1 -
  202471. png_pass_ystart[png_ptr->pass]) /
  202472. png_pass_yinc[png_ptr->pass];
  202473. if (png_ptr->transformations & PNG_INTERLACE)
  202474. break;
  202475. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202476. }
  202477. /* reset the row above the image for the next pass */
  202478. if (png_ptr->pass < 7)
  202479. {
  202480. if (png_ptr->prev_row != NULL)
  202481. png_memset(png_ptr->prev_row, 0,
  202482. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202483. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202484. return;
  202485. }
  202486. }
  202487. #endif
  202488. /* if we get here, we've just written the last row, so we need
  202489. to flush the compressor */
  202490. do
  202491. {
  202492. /* tell the compressor we are done */
  202493. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202494. /* check for an error */
  202495. if (ret == Z_OK)
  202496. {
  202497. /* check to see if we need more room */
  202498. if (!(png_ptr->zstream.avail_out))
  202499. {
  202500. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202501. png_ptr->zstream.next_out = png_ptr->zbuf;
  202502. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202503. }
  202504. }
  202505. else if (ret != Z_STREAM_END)
  202506. {
  202507. if (png_ptr->zstream.msg != NULL)
  202508. png_error(png_ptr, png_ptr->zstream.msg);
  202509. else
  202510. png_error(png_ptr, "zlib error");
  202511. }
  202512. } while (ret != Z_STREAM_END);
  202513. /* write any extra space */
  202514. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202515. {
  202516. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202517. png_ptr->zstream.avail_out);
  202518. }
  202519. deflateReset(&png_ptr->zstream);
  202520. png_ptr->zstream.data_type = Z_BINARY;
  202521. }
  202522. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202523. /* Pick out the correct pixels for the interlace pass.
  202524. * The basic idea here is to go through the row with a source
  202525. * pointer and a destination pointer (sp and dp), and copy the
  202526. * correct pixels for the pass. As the row gets compacted,
  202527. * sp will always be >= dp, so we should never overwrite anything.
  202528. * See the default: case for the easiest code to understand.
  202529. */
  202530. void /* PRIVATE */
  202531. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202532. {
  202533. #ifdef PNG_USE_LOCAL_ARRAYS
  202534. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202535. /* start of interlace block */
  202536. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202537. /* offset to next interlace block */
  202538. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202539. #endif
  202540. png_debug(1, "in png_do_write_interlace\n");
  202541. /* we don't have to do anything on the last pass (6) */
  202542. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202543. if (row != NULL && row_info != NULL && pass < 6)
  202544. #else
  202545. if (pass < 6)
  202546. #endif
  202547. {
  202548. /* each pixel depth is handled separately */
  202549. switch (row_info->pixel_depth)
  202550. {
  202551. case 1:
  202552. {
  202553. png_bytep sp;
  202554. png_bytep dp;
  202555. int shift;
  202556. int d;
  202557. int value;
  202558. png_uint_32 i;
  202559. png_uint_32 row_width = row_info->width;
  202560. dp = row;
  202561. d = 0;
  202562. shift = 7;
  202563. for (i = png_pass_start[pass]; i < row_width;
  202564. i += png_pass_inc[pass])
  202565. {
  202566. sp = row + (png_size_t)(i >> 3);
  202567. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202568. d |= (value << shift);
  202569. if (shift == 0)
  202570. {
  202571. shift = 7;
  202572. *dp++ = (png_byte)d;
  202573. d = 0;
  202574. }
  202575. else
  202576. shift--;
  202577. }
  202578. if (shift != 7)
  202579. *dp = (png_byte)d;
  202580. break;
  202581. }
  202582. case 2:
  202583. {
  202584. png_bytep sp;
  202585. png_bytep dp;
  202586. int shift;
  202587. int d;
  202588. int value;
  202589. png_uint_32 i;
  202590. png_uint_32 row_width = row_info->width;
  202591. dp = row;
  202592. shift = 6;
  202593. d = 0;
  202594. for (i = png_pass_start[pass]; i < row_width;
  202595. i += png_pass_inc[pass])
  202596. {
  202597. sp = row + (png_size_t)(i >> 2);
  202598. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202599. d |= (value << shift);
  202600. if (shift == 0)
  202601. {
  202602. shift = 6;
  202603. *dp++ = (png_byte)d;
  202604. d = 0;
  202605. }
  202606. else
  202607. shift -= 2;
  202608. }
  202609. if (shift != 6)
  202610. *dp = (png_byte)d;
  202611. break;
  202612. }
  202613. case 4:
  202614. {
  202615. png_bytep sp;
  202616. png_bytep dp;
  202617. int shift;
  202618. int d;
  202619. int value;
  202620. png_uint_32 i;
  202621. png_uint_32 row_width = row_info->width;
  202622. dp = row;
  202623. shift = 4;
  202624. d = 0;
  202625. for (i = png_pass_start[pass]; i < row_width;
  202626. i += png_pass_inc[pass])
  202627. {
  202628. sp = row + (png_size_t)(i >> 1);
  202629. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202630. d |= (value << shift);
  202631. if (shift == 0)
  202632. {
  202633. shift = 4;
  202634. *dp++ = (png_byte)d;
  202635. d = 0;
  202636. }
  202637. else
  202638. shift -= 4;
  202639. }
  202640. if (shift != 4)
  202641. *dp = (png_byte)d;
  202642. break;
  202643. }
  202644. default:
  202645. {
  202646. png_bytep sp;
  202647. png_bytep dp;
  202648. png_uint_32 i;
  202649. png_uint_32 row_width = row_info->width;
  202650. png_size_t pixel_bytes;
  202651. /* start at the beginning */
  202652. dp = row;
  202653. /* find out how many bytes each pixel takes up */
  202654. pixel_bytes = (row_info->pixel_depth >> 3);
  202655. /* loop through the row, only looking at the pixels that
  202656. matter */
  202657. for (i = png_pass_start[pass]; i < row_width;
  202658. i += png_pass_inc[pass])
  202659. {
  202660. /* find out where the original pixel is */
  202661. sp = row + (png_size_t)i * pixel_bytes;
  202662. /* move the pixel */
  202663. if (dp != sp)
  202664. png_memcpy(dp, sp, pixel_bytes);
  202665. /* next pixel */
  202666. dp += pixel_bytes;
  202667. }
  202668. break;
  202669. }
  202670. }
  202671. /* set new row width */
  202672. row_info->width = (row_info->width +
  202673. png_pass_inc[pass] - 1 -
  202674. png_pass_start[pass]) /
  202675. png_pass_inc[pass];
  202676. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202677. row_info->width);
  202678. }
  202679. }
  202680. #endif
  202681. /* This filters the row, chooses which filter to use, if it has not already
  202682. * been specified by the application, and then writes the row out with the
  202683. * chosen filter.
  202684. */
  202685. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202686. #define PNG_HISHIFT 10
  202687. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202688. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202689. void /* PRIVATE */
  202690. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202691. {
  202692. png_bytep best_row;
  202693. #ifndef PNG_NO_WRITE_FILTER
  202694. png_bytep prev_row, row_buf;
  202695. png_uint_32 mins, bpp;
  202696. png_byte filter_to_do = png_ptr->do_filter;
  202697. png_uint_32 row_bytes = row_info->rowbytes;
  202698. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202699. int num_p_filters = (int)png_ptr->num_prev_filters;
  202700. #endif
  202701. png_debug(1, "in png_write_find_filter\n");
  202702. /* find out how many bytes offset each pixel is */
  202703. bpp = (row_info->pixel_depth + 7) >> 3;
  202704. prev_row = png_ptr->prev_row;
  202705. #endif
  202706. best_row = png_ptr->row_buf;
  202707. #ifndef PNG_NO_WRITE_FILTER
  202708. row_buf = best_row;
  202709. mins = PNG_MAXSUM;
  202710. /* The prediction method we use is to find which method provides the
  202711. * smallest value when summing the absolute values of the distances
  202712. * from zero, using anything >= 128 as negative numbers. This is known
  202713. * as the "minimum sum of absolute differences" heuristic. Other
  202714. * heuristics are the "weighted minimum sum of absolute differences"
  202715. * (experimental and can in theory improve compression), and the "zlib
  202716. * predictive" method (not implemented yet), which does test compressions
  202717. * of lines using different filter methods, and then chooses the
  202718. * (series of) filter(s) that give minimum compressed data size (VERY
  202719. * computationally expensive).
  202720. *
  202721. * GRR 980525: consider also
  202722. * (1) minimum sum of absolute differences from running average (i.e.,
  202723. * keep running sum of non-absolute differences & count of bytes)
  202724. * [track dispersion, too? restart average if dispersion too large?]
  202725. * (1b) minimum sum of absolute differences from sliding average, probably
  202726. * with window size <= deflate window (usually 32K)
  202727. * (2) minimum sum of squared differences from zero or running average
  202728. * (i.e., ~ root-mean-square approach)
  202729. */
  202730. /* We don't need to test the 'no filter' case if this is the only filter
  202731. * that has been chosen, as it doesn't actually do anything to the data.
  202732. */
  202733. if ((filter_to_do & PNG_FILTER_NONE) &&
  202734. filter_to_do != PNG_FILTER_NONE)
  202735. {
  202736. png_bytep rp;
  202737. png_uint_32 sum = 0;
  202738. png_uint_32 i;
  202739. int v;
  202740. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202741. {
  202742. v = *rp;
  202743. sum += (v < 128) ? v : 256 - v;
  202744. }
  202745. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202746. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202747. {
  202748. png_uint_32 sumhi, sumlo;
  202749. int j;
  202750. sumlo = sum & PNG_LOMASK;
  202751. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202752. /* Reduce the sum if we match any of the previous rows */
  202753. for (j = 0; j < num_p_filters; j++)
  202754. {
  202755. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202756. {
  202757. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202758. PNG_WEIGHT_SHIFT;
  202759. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202760. PNG_WEIGHT_SHIFT;
  202761. }
  202762. }
  202763. /* Factor in the cost of this filter (this is here for completeness,
  202764. * but it makes no sense to have a "cost" for the NONE filter, as
  202765. * it has the minimum possible computational cost - none).
  202766. */
  202767. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202768. PNG_COST_SHIFT;
  202769. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202770. PNG_COST_SHIFT;
  202771. if (sumhi > PNG_HIMASK)
  202772. sum = PNG_MAXSUM;
  202773. else
  202774. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202775. }
  202776. #endif
  202777. mins = sum;
  202778. }
  202779. /* sub filter */
  202780. if (filter_to_do == PNG_FILTER_SUB)
  202781. /* it's the only filter so no testing is needed */
  202782. {
  202783. png_bytep rp, lp, dp;
  202784. png_uint_32 i;
  202785. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202786. i++, rp++, dp++)
  202787. {
  202788. *dp = *rp;
  202789. }
  202790. for (lp = row_buf + 1; i < row_bytes;
  202791. i++, rp++, lp++, dp++)
  202792. {
  202793. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202794. }
  202795. best_row = png_ptr->sub_row;
  202796. }
  202797. else if (filter_to_do & PNG_FILTER_SUB)
  202798. {
  202799. png_bytep rp, dp, lp;
  202800. png_uint_32 sum = 0, lmins = mins;
  202801. png_uint_32 i;
  202802. int v;
  202803. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202804. /* We temporarily increase the "minimum sum" by the factor we
  202805. * would reduce the sum of this filter, so that we can do the
  202806. * early exit comparison without scaling the sum each time.
  202807. */
  202808. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202809. {
  202810. int j;
  202811. png_uint_32 lmhi, lmlo;
  202812. lmlo = lmins & PNG_LOMASK;
  202813. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202814. for (j = 0; j < num_p_filters; j++)
  202815. {
  202816. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202817. {
  202818. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202819. PNG_WEIGHT_SHIFT;
  202820. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202821. PNG_WEIGHT_SHIFT;
  202822. }
  202823. }
  202824. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202825. PNG_COST_SHIFT;
  202826. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202827. PNG_COST_SHIFT;
  202828. if (lmhi > PNG_HIMASK)
  202829. lmins = PNG_MAXSUM;
  202830. else
  202831. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202832. }
  202833. #endif
  202834. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202835. i++, rp++, dp++)
  202836. {
  202837. v = *dp = *rp;
  202838. sum += (v < 128) ? v : 256 - v;
  202839. }
  202840. for (lp = row_buf + 1; i < row_bytes;
  202841. i++, rp++, lp++, dp++)
  202842. {
  202843. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202844. sum += (v < 128) ? v : 256 - v;
  202845. if (sum > lmins) /* We are already worse, don't continue. */
  202846. break;
  202847. }
  202848. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202849. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202850. {
  202851. int j;
  202852. png_uint_32 sumhi, sumlo;
  202853. sumlo = sum & PNG_LOMASK;
  202854. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202855. for (j = 0; j < num_p_filters; j++)
  202856. {
  202857. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202858. {
  202859. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202860. PNG_WEIGHT_SHIFT;
  202861. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202862. PNG_WEIGHT_SHIFT;
  202863. }
  202864. }
  202865. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202866. PNG_COST_SHIFT;
  202867. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202868. PNG_COST_SHIFT;
  202869. if (sumhi > PNG_HIMASK)
  202870. sum = PNG_MAXSUM;
  202871. else
  202872. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202873. }
  202874. #endif
  202875. if (sum < mins)
  202876. {
  202877. mins = sum;
  202878. best_row = png_ptr->sub_row;
  202879. }
  202880. }
  202881. /* up filter */
  202882. if (filter_to_do == PNG_FILTER_UP)
  202883. {
  202884. png_bytep rp, dp, pp;
  202885. png_uint_32 i;
  202886. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202887. pp = prev_row + 1; i < row_bytes;
  202888. i++, rp++, pp++, dp++)
  202889. {
  202890. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202891. }
  202892. best_row = png_ptr->up_row;
  202893. }
  202894. else if (filter_to_do & PNG_FILTER_UP)
  202895. {
  202896. png_bytep rp, dp, pp;
  202897. png_uint_32 sum = 0, lmins = mins;
  202898. png_uint_32 i;
  202899. int v;
  202900. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202901. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202902. {
  202903. int j;
  202904. png_uint_32 lmhi, lmlo;
  202905. lmlo = lmins & PNG_LOMASK;
  202906. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202907. for (j = 0; j < num_p_filters; j++)
  202908. {
  202909. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202910. {
  202911. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202912. PNG_WEIGHT_SHIFT;
  202913. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202914. PNG_WEIGHT_SHIFT;
  202915. }
  202916. }
  202917. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202918. PNG_COST_SHIFT;
  202919. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202920. PNG_COST_SHIFT;
  202921. if (lmhi > PNG_HIMASK)
  202922. lmins = PNG_MAXSUM;
  202923. else
  202924. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202925. }
  202926. #endif
  202927. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202928. pp = prev_row + 1; i < row_bytes; i++)
  202929. {
  202930. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202931. sum += (v < 128) ? v : 256 - v;
  202932. if (sum > lmins) /* We are already worse, don't continue. */
  202933. break;
  202934. }
  202935. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202936. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202937. {
  202938. int j;
  202939. png_uint_32 sumhi, sumlo;
  202940. sumlo = sum & PNG_LOMASK;
  202941. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202942. for (j = 0; j < num_p_filters; j++)
  202943. {
  202944. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202945. {
  202946. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202947. PNG_WEIGHT_SHIFT;
  202948. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202949. PNG_WEIGHT_SHIFT;
  202950. }
  202951. }
  202952. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202953. PNG_COST_SHIFT;
  202954. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202955. PNG_COST_SHIFT;
  202956. if (sumhi > PNG_HIMASK)
  202957. sum = PNG_MAXSUM;
  202958. else
  202959. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202960. }
  202961. #endif
  202962. if (sum < mins)
  202963. {
  202964. mins = sum;
  202965. best_row = png_ptr->up_row;
  202966. }
  202967. }
  202968. /* avg filter */
  202969. if (filter_to_do == PNG_FILTER_AVG)
  202970. {
  202971. png_bytep rp, dp, pp, lp;
  202972. png_uint_32 i;
  202973. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202974. pp = prev_row + 1; i < bpp; i++)
  202975. {
  202976. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202977. }
  202978. for (lp = row_buf + 1; i < row_bytes; i++)
  202979. {
  202980. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202981. & 0xff);
  202982. }
  202983. best_row = png_ptr->avg_row;
  202984. }
  202985. else if (filter_to_do & PNG_FILTER_AVG)
  202986. {
  202987. png_bytep rp, dp, pp, lp;
  202988. png_uint_32 sum = 0, lmins = mins;
  202989. png_uint_32 i;
  202990. int v;
  202991. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202992. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202993. {
  202994. int j;
  202995. png_uint_32 lmhi, lmlo;
  202996. lmlo = lmins & PNG_LOMASK;
  202997. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202998. for (j = 0; j < num_p_filters; j++)
  202999. {
  203000. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203001. {
  203002. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203003. PNG_WEIGHT_SHIFT;
  203004. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203005. PNG_WEIGHT_SHIFT;
  203006. }
  203007. }
  203008. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203009. PNG_COST_SHIFT;
  203010. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203011. PNG_COST_SHIFT;
  203012. if (lmhi > PNG_HIMASK)
  203013. lmins = PNG_MAXSUM;
  203014. else
  203015. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203016. }
  203017. #endif
  203018. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203019. pp = prev_row + 1; i < bpp; i++)
  203020. {
  203021. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203022. sum += (v < 128) ? v : 256 - v;
  203023. }
  203024. for (lp = row_buf + 1; i < row_bytes; i++)
  203025. {
  203026. v = *dp++ =
  203027. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203028. sum += (v < 128) ? v : 256 - v;
  203029. if (sum > lmins) /* We are already worse, don't continue. */
  203030. break;
  203031. }
  203032. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203033. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203034. {
  203035. int j;
  203036. png_uint_32 sumhi, sumlo;
  203037. sumlo = sum & PNG_LOMASK;
  203038. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203039. for (j = 0; j < num_p_filters; j++)
  203040. {
  203041. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203042. {
  203043. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203044. PNG_WEIGHT_SHIFT;
  203045. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203046. PNG_WEIGHT_SHIFT;
  203047. }
  203048. }
  203049. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203050. PNG_COST_SHIFT;
  203051. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203052. PNG_COST_SHIFT;
  203053. if (sumhi > PNG_HIMASK)
  203054. sum = PNG_MAXSUM;
  203055. else
  203056. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203057. }
  203058. #endif
  203059. if (sum < mins)
  203060. {
  203061. mins = sum;
  203062. best_row = png_ptr->avg_row;
  203063. }
  203064. }
  203065. /* Paeth filter */
  203066. if (filter_to_do == PNG_FILTER_PAETH)
  203067. {
  203068. png_bytep rp, dp, pp, cp, lp;
  203069. png_uint_32 i;
  203070. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203071. pp = prev_row + 1; i < bpp; i++)
  203072. {
  203073. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203074. }
  203075. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203076. {
  203077. int a, b, c, pa, pb, pc, p;
  203078. b = *pp++;
  203079. c = *cp++;
  203080. a = *lp++;
  203081. p = b - c;
  203082. pc = a - c;
  203083. #ifdef PNG_USE_ABS
  203084. pa = abs(p);
  203085. pb = abs(pc);
  203086. pc = abs(p + pc);
  203087. #else
  203088. pa = p < 0 ? -p : p;
  203089. pb = pc < 0 ? -pc : pc;
  203090. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203091. #endif
  203092. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203093. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203094. }
  203095. best_row = png_ptr->paeth_row;
  203096. }
  203097. else if (filter_to_do & PNG_FILTER_PAETH)
  203098. {
  203099. png_bytep rp, dp, pp, cp, lp;
  203100. png_uint_32 sum = 0, lmins = mins;
  203101. png_uint_32 i;
  203102. int v;
  203103. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203104. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203105. {
  203106. int j;
  203107. png_uint_32 lmhi, lmlo;
  203108. lmlo = lmins & PNG_LOMASK;
  203109. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203110. for (j = 0; j < num_p_filters; j++)
  203111. {
  203112. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203113. {
  203114. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203115. PNG_WEIGHT_SHIFT;
  203116. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203117. PNG_WEIGHT_SHIFT;
  203118. }
  203119. }
  203120. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203121. PNG_COST_SHIFT;
  203122. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203123. PNG_COST_SHIFT;
  203124. if (lmhi > PNG_HIMASK)
  203125. lmins = PNG_MAXSUM;
  203126. else
  203127. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203128. }
  203129. #endif
  203130. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203131. pp = prev_row + 1; i < bpp; i++)
  203132. {
  203133. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203134. sum += (v < 128) ? v : 256 - v;
  203135. }
  203136. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203137. {
  203138. int a, b, c, pa, pb, pc, p;
  203139. b = *pp++;
  203140. c = *cp++;
  203141. a = *lp++;
  203142. #ifndef PNG_SLOW_PAETH
  203143. p = b - c;
  203144. pc = a - c;
  203145. #ifdef PNG_USE_ABS
  203146. pa = abs(p);
  203147. pb = abs(pc);
  203148. pc = abs(p + pc);
  203149. #else
  203150. pa = p < 0 ? -p : p;
  203151. pb = pc < 0 ? -pc : pc;
  203152. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203153. #endif
  203154. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203155. #else /* PNG_SLOW_PAETH */
  203156. p = a + b - c;
  203157. pa = abs(p - a);
  203158. pb = abs(p - b);
  203159. pc = abs(p - c);
  203160. if (pa <= pb && pa <= pc)
  203161. p = a;
  203162. else if (pb <= pc)
  203163. p = b;
  203164. else
  203165. p = c;
  203166. #endif /* PNG_SLOW_PAETH */
  203167. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203168. sum += (v < 128) ? v : 256 - v;
  203169. if (sum > lmins) /* We are already worse, don't continue. */
  203170. break;
  203171. }
  203172. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203173. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203174. {
  203175. int j;
  203176. png_uint_32 sumhi, sumlo;
  203177. sumlo = sum & PNG_LOMASK;
  203178. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203179. for (j = 0; j < num_p_filters; j++)
  203180. {
  203181. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203182. {
  203183. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203184. PNG_WEIGHT_SHIFT;
  203185. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203186. PNG_WEIGHT_SHIFT;
  203187. }
  203188. }
  203189. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203190. PNG_COST_SHIFT;
  203191. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203192. PNG_COST_SHIFT;
  203193. if (sumhi > PNG_HIMASK)
  203194. sum = PNG_MAXSUM;
  203195. else
  203196. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203197. }
  203198. #endif
  203199. if (sum < mins)
  203200. {
  203201. best_row = png_ptr->paeth_row;
  203202. }
  203203. }
  203204. #endif /* PNG_NO_WRITE_FILTER */
  203205. /* Do the actual writing of the filtered row data from the chosen filter. */
  203206. png_write_filtered_row(png_ptr, best_row);
  203207. #ifndef PNG_NO_WRITE_FILTER
  203208. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203209. /* Save the type of filter we picked this time for future calculations */
  203210. if (png_ptr->num_prev_filters > 0)
  203211. {
  203212. int j;
  203213. for (j = 1; j < num_p_filters; j++)
  203214. {
  203215. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203216. }
  203217. png_ptr->prev_filters[j] = best_row[0];
  203218. }
  203219. #endif
  203220. #endif /* PNG_NO_WRITE_FILTER */
  203221. }
  203222. /* Do the actual writing of a previously filtered row. */
  203223. void /* PRIVATE */
  203224. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203225. {
  203226. png_debug(1, "in png_write_filtered_row\n");
  203227. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203228. /* set up the zlib input buffer */
  203229. png_ptr->zstream.next_in = filtered_row;
  203230. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203231. /* repeat until we have compressed all the data */
  203232. do
  203233. {
  203234. int ret; /* return of zlib */
  203235. /* compress the data */
  203236. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203237. /* check for compression errors */
  203238. if (ret != Z_OK)
  203239. {
  203240. if (png_ptr->zstream.msg != NULL)
  203241. png_error(png_ptr, png_ptr->zstream.msg);
  203242. else
  203243. png_error(png_ptr, "zlib error");
  203244. }
  203245. /* see if it is time to write another IDAT */
  203246. if (!(png_ptr->zstream.avail_out))
  203247. {
  203248. /* write the IDAT and reset the zlib output buffer */
  203249. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203250. png_ptr->zstream.next_out = png_ptr->zbuf;
  203251. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203252. }
  203253. /* repeat until all data has been compressed */
  203254. } while (png_ptr->zstream.avail_in);
  203255. /* swap the current and previous rows */
  203256. if (png_ptr->prev_row != NULL)
  203257. {
  203258. png_bytep tptr;
  203259. tptr = png_ptr->prev_row;
  203260. png_ptr->prev_row = png_ptr->row_buf;
  203261. png_ptr->row_buf = tptr;
  203262. }
  203263. /* finish row - updates counters and flushes zlib if last row */
  203264. png_write_finish_row(png_ptr);
  203265. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203266. png_ptr->flush_rows++;
  203267. if (png_ptr->flush_dist > 0 &&
  203268. png_ptr->flush_rows >= png_ptr->flush_dist)
  203269. {
  203270. png_write_flush(png_ptr);
  203271. }
  203272. #endif
  203273. }
  203274. #endif /* PNG_WRITE_SUPPORTED */
  203275. /*** End of inlined file: pngwutil.c ***/
  203276. #else
  203277. extern "C"
  203278. {
  203279. #include <png.h>
  203280. #include <pngconf.h>
  203281. }
  203282. #endif
  203283. }
  203284. #undef max
  203285. #undef min
  203286. #if JUCE_MSVC
  203287. #pragma warning (pop)
  203288. #endif
  203289. BEGIN_JUCE_NAMESPACE
  203290. using ::calloc;
  203291. using ::malloc;
  203292. using ::free;
  203293. namespace PNGHelpers
  203294. {
  203295. using namespace pnglibNamespace;
  203296. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203297. {
  203298. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203299. }
  203300. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203301. {
  203302. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203303. }
  203304. struct PNGErrorStruct {};
  203305. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203306. {
  203307. throw PNGErrorStruct();
  203308. }
  203309. }
  203310. PNGImageFormat::PNGImageFormat() {}
  203311. PNGImageFormat::~PNGImageFormat() {}
  203312. const String PNGImageFormat::getFormatName()
  203313. {
  203314. return "PNG";
  203315. }
  203316. bool PNGImageFormat::canUnderstand (InputStream& in)
  203317. {
  203318. const int bytesNeeded = 4;
  203319. char header [bytesNeeded];
  203320. return in.read (header, bytesNeeded) == bytesNeeded
  203321. && header[1] == 'P'
  203322. && header[2] == 'N'
  203323. && header[3] == 'G';
  203324. }
  203325. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203326. const Image juce_loadWithCoreImage (InputStream& input);
  203327. #endif
  203328. const Image PNGImageFormat::decodeImage (InputStream& in)
  203329. {
  203330. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203331. return juce_loadWithCoreImage (in);
  203332. #else
  203333. using namespace pnglibNamespace;
  203334. Image image;
  203335. png_structp pngReadStruct;
  203336. png_infop pngInfoStruct;
  203337. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203338. if (pngReadStruct != 0)
  203339. {
  203340. try
  203341. {
  203342. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203343. if (pngInfoStruct == 0)
  203344. {
  203345. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203346. return Image::null;
  203347. }
  203348. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203349. // read the header..
  203350. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203351. png_uint_32 width, height;
  203352. int bitDepth, colorType, interlaceType;
  203353. png_read_info (pngReadStruct, pngInfoStruct);
  203354. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203355. &width, &height,
  203356. &bitDepth, &colorType,
  203357. &interlaceType, 0, 0);
  203358. if (bitDepth == 16)
  203359. png_set_strip_16 (pngReadStruct);
  203360. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203361. png_set_expand (pngReadStruct);
  203362. if (bitDepth < 8)
  203363. png_set_expand (pngReadStruct);
  203364. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203365. png_set_expand (pngReadStruct);
  203366. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203367. png_set_gray_to_rgb (pngReadStruct);
  203368. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203369. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203370. || pngInfoStruct->num_trans > 0;
  203371. // Load the image into a temp buffer in the pnglib format..
  203372. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203373. {
  203374. HeapBlock <png_bytep> rows (height);
  203375. for (int y = (int) height; --y >= 0;)
  203376. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203377. try
  203378. {
  203379. png_read_image (pngReadStruct, rows);
  203380. png_read_end (pngReadStruct, pngInfoStruct);
  203381. }
  203382. catch (PNGHelpers::PNGErrorStruct&)
  203383. {}
  203384. }
  203385. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203386. // now convert the data to a juce image format..
  203387. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203388. (int) width, (int) height, hasAlphaChan);
  203389. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203390. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203391. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  203392. uint8* srcRow = tempBuffer;
  203393. uint8* destRow = destData.data;
  203394. for (int y = 0; y < (int) height; ++y)
  203395. {
  203396. const uint8* src = srcRow;
  203397. srcRow += (width << 2);
  203398. uint8* dest = destRow;
  203399. destRow += destData.lineStride;
  203400. if (hasAlphaChan)
  203401. {
  203402. for (int i = (int) width; --i >= 0;)
  203403. {
  203404. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203405. ((PixelARGB*) dest)->premultiply();
  203406. dest += destData.pixelStride;
  203407. src += 4;
  203408. }
  203409. }
  203410. else
  203411. {
  203412. for (int i = (int) width; --i >= 0;)
  203413. {
  203414. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203415. dest += destData.pixelStride;
  203416. src += 4;
  203417. }
  203418. }
  203419. }
  203420. }
  203421. catch (PNGHelpers::PNGErrorStruct&)
  203422. {}
  203423. }
  203424. return image;
  203425. #endif
  203426. }
  203427. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203428. {
  203429. using namespace pnglibNamespace;
  203430. const int width = image.getWidth();
  203431. const int height = image.getHeight();
  203432. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203433. if (pngWriteStruct == 0)
  203434. return false;
  203435. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203436. if (pngInfoStruct == 0)
  203437. {
  203438. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203439. return false;
  203440. }
  203441. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203442. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203443. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203444. : PNG_COLOR_TYPE_RGB,
  203445. PNG_INTERLACE_NONE,
  203446. PNG_COMPRESSION_TYPE_BASE,
  203447. PNG_FILTER_TYPE_BASE);
  203448. HeapBlock <uint8> rowData (width * 4);
  203449. png_color_8 sig_bit;
  203450. sig_bit.red = 8;
  203451. sig_bit.green = 8;
  203452. sig_bit.blue = 8;
  203453. sig_bit.alpha = 8;
  203454. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203455. png_write_info (pngWriteStruct, pngInfoStruct);
  203456. png_set_shift (pngWriteStruct, &sig_bit);
  203457. png_set_packing (pngWriteStruct);
  203458. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  203459. for (int y = 0; y < height; ++y)
  203460. {
  203461. uint8* dst = rowData;
  203462. const uint8* src = srcData.getLinePointer (y);
  203463. if (image.hasAlphaChannel())
  203464. {
  203465. for (int i = width; --i >= 0;)
  203466. {
  203467. PixelARGB p (*(const PixelARGB*) src);
  203468. p.unpremultiply();
  203469. *dst++ = p.getRed();
  203470. *dst++ = p.getGreen();
  203471. *dst++ = p.getBlue();
  203472. *dst++ = p.getAlpha();
  203473. src += srcData.pixelStride;
  203474. }
  203475. }
  203476. else
  203477. {
  203478. for (int i = width; --i >= 0;)
  203479. {
  203480. *dst++ = ((const PixelRGB*) src)->getRed();
  203481. *dst++ = ((const PixelRGB*) src)->getGreen();
  203482. *dst++ = ((const PixelRGB*) src)->getBlue();
  203483. src += srcData.pixelStride;
  203484. }
  203485. }
  203486. png_bytep rowPtr = rowData;
  203487. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203488. }
  203489. png_write_end (pngWriteStruct, pngInfoStruct);
  203490. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203491. out.flush();
  203492. return true;
  203493. }
  203494. END_JUCE_NAMESPACE
  203495. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203496. #endif
  203497. //==============================================================================
  203498. #if JUCE_BUILD_NATIVE
  203499. // Non-public headers that are needed by more than one platform must be included
  203500. // before the platform-specific sections..
  203501. BEGIN_JUCE_NAMESPACE
  203502. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203503. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203504. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203505. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203506. /**
  203507. Helper class that takes chunks of incoming midi bytes, packages them into
  203508. messages, and dispatches them to a midi callback.
  203509. */
  203510. class MidiDataConcatenator
  203511. {
  203512. public:
  203513. MidiDataConcatenator (const int initialBufferSize)
  203514. : pendingData (initialBufferSize),
  203515. pendingBytes (0), pendingDataTime (0)
  203516. {
  203517. }
  203518. void reset()
  203519. {
  203520. pendingBytes = 0;
  203521. pendingDataTime = 0;
  203522. }
  203523. void pushMidiData (const void* data, int numBytes, double time,
  203524. MidiInput* input, MidiInputCallback& callback)
  203525. {
  203526. const uint8* d = static_cast <const uint8*> (data);
  203527. while (numBytes > 0)
  203528. {
  203529. if (pendingBytes > 0 || d[0] == 0xf0)
  203530. {
  203531. processSysex (d, numBytes, time, input, callback);
  203532. }
  203533. else
  203534. {
  203535. int used = 0;
  203536. const MidiMessage m (d, numBytes, used, 0, time);
  203537. if (used <= 0)
  203538. break; // malformed message..
  203539. callback.handleIncomingMidiMessage (input, m);
  203540. numBytes -= used;
  203541. d += used;
  203542. }
  203543. }
  203544. }
  203545. private:
  203546. void processSysex (const uint8*& d, int& numBytes, double time,
  203547. MidiInput* input, MidiInputCallback& callback)
  203548. {
  203549. if (*d == 0xf0)
  203550. {
  203551. pendingBytes = 0;
  203552. pendingDataTime = time;
  203553. }
  203554. pendingData.ensureSize (pendingBytes + numBytes, false);
  203555. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203556. uint8* dest = totalMessage + pendingBytes;
  203557. do
  203558. {
  203559. if (pendingBytes > 0 && *d >= 0x80)
  203560. {
  203561. if (*d >= 0xfa || *d == 0xf8)
  203562. {
  203563. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203564. ++d;
  203565. --numBytes;
  203566. }
  203567. else
  203568. {
  203569. if (*d == 0xf7)
  203570. {
  203571. *dest++ = *d++;
  203572. pendingBytes++;
  203573. --numBytes;
  203574. }
  203575. break;
  203576. }
  203577. }
  203578. else
  203579. {
  203580. *dest++ = *d++;
  203581. pendingBytes++;
  203582. --numBytes;
  203583. }
  203584. }
  203585. while (numBytes > 0);
  203586. if (pendingBytes > 0)
  203587. {
  203588. if (totalMessage [pendingBytes - 1] == 0xf7)
  203589. {
  203590. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203591. pendingBytes = 0;
  203592. }
  203593. else
  203594. {
  203595. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203596. }
  203597. }
  203598. }
  203599. MemoryBlock pendingData;
  203600. int pendingBytes;
  203601. double pendingDataTime;
  203602. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203603. };
  203604. #endif
  203605. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203606. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203607. END_JUCE_NAMESPACE
  203608. #if JUCE_WINDOWS
  203609. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203610. /*
  203611. This file wraps together all the win32-specific code, so that
  203612. we can include all the native headers just once, and compile all our
  203613. platform-specific stuff in one big lump, keeping it out of the way of
  203614. the rest of the codebase.
  203615. */
  203616. #if JUCE_WINDOWS
  203617. #undef JUCE_BUILD_NATIVE
  203618. #define JUCE_BUILD_NATIVE 1
  203619. BEGIN_JUCE_NAMESPACE
  203620. #define JUCE_INCLUDED_FILE 1
  203621. // Now include the actual code files..
  203622. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203623. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203624. // compiled on its own).
  203625. #if JUCE_INCLUDED_FILE
  203626. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203627. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203628. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203629. #ifndef DOXYGEN
  203630. // use with DynamicLibraryLoader to simplify importing functions
  203631. //
  203632. // functionName: function to import
  203633. // localFunctionName: name you want to use to actually call it (must be different)
  203634. // returnType: the return type
  203635. // object: the DynamicLibraryLoader to use
  203636. // params: list of params (bracketed)
  203637. //
  203638. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203639. typedef returnType (WINAPI *type##localFunctionName) params; \
  203640. type##localFunctionName localFunctionName \
  203641. = (type##localFunctionName)object.findProcAddress (#functionName);
  203642. // loads and unloads a DLL automatically
  203643. class JUCE_API DynamicLibraryLoader
  203644. {
  203645. public:
  203646. DynamicLibraryLoader (const String& name = String::empty);
  203647. ~DynamicLibraryLoader();
  203648. bool load (const String& libraryName);
  203649. void* findProcAddress (const String& functionName);
  203650. private:
  203651. void* libHandle;
  203652. };
  203653. #endif
  203654. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203655. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203656. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203657. : libHandle (0)
  203658. {
  203659. load (name);
  203660. }
  203661. DynamicLibraryLoader::~DynamicLibraryLoader()
  203662. {
  203663. load (String::empty);
  203664. }
  203665. bool DynamicLibraryLoader::load (const String& name)
  203666. {
  203667. FreeLibrary ((HMODULE) libHandle);
  203668. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203669. return libHandle != 0;
  203670. }
  203671. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203672. {
  203673. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203674. }
  203675. #endif
  203676. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203677. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203678. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203679. // compiled on its own).
  203680. #if JUCE_INCLUDED_FILE
  203681. void Logger::outputDebugString (const String& text)
  203682. {
  203683. OutputDebugString ((text + "\n").toUTF16());
  203684. }
  203685. static int64 hiResTicksPerSecond;
  203686. static double hiResTicksScaleFactor;
  203687. #if JUCE_USE_INTRINSICS
  203688. // CPU info functions using intrinsics...
  203689. #pragma intrinsic (__cpuid)
  203690. #pragma intrinsic (__rdtsc)
  203691. const String SystemStats::getCpuVendor()
  203692. {
  203693. int info [4];
  203694. __cpuid (info, 0);
  203695. char v [12];
  203696. memcpy (v, info + 1, 4);
  203697. memcpy (v + 4, info + 3, 4);
  203698. memcpy (v + 8, info + 2, 4);
  203699. return String (v, 12);
  203700. }
  203701. #else
  203702. // CPU info functions using old fashioned inline asm...
  203703. static void juce_getCpuVendor (char* const v)
  203704. {
  203705. int vendor[4];
  203706. zeromem (vendor, 16);
  203707. #ifdef JUCE_64BIT
  203708. #else
  203709. #ifndef __MINGW32__
  203710. __try
  203711. #endif
  203712. {
  203713. #if JUCE_GCC
  203714. unsigned int dummy = 0;
  203715. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203716. #else
  203717. __asm
  203718. {
  203719. mov eax, 0
  203720. cpuid
  203721. mov [vendor], ebx
  203722. mov [vendor + 4], edx
  203723. mov [vendor + 8], ecx
  203724. }
  203725. #endif
  203726. }
  203727. #ifndef __MINGW32__
  203728. __except (EXCEPTION_EXECUTE_HANDLER)
  203729. {
  203730. *v = 0;
  203731. }
  203732. #endif
  203733. #endif
  203734. memcpy (v, vendor, 16);
  203735. }
  203736. const String SystemStats::getCpuVendor()
  203737. {
  203738. char v [16];
  203739. juce_getCpuVendor (v);
  203740. return String (v, 16);
  203741. }
  203742. #endif
  203743. void SystemStats::initialiseStats()
  203744. {
  203745. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203746. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203747. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203748. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203749. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203750. #else
  203751. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203752. #endif
  203753. {
  203754. SYSTEM_INFO systemInfo;
  203755. GetSystemInfo (&systemInfo);
  203756. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203757. }
  203758. LARGE_INTEGER f;
  203759. QueryPerformanceFrequency (&f);
  203760. hiResTicksPerSecond = f.QuadPart;
  203761. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203762. String s (SystemStats::getJUCEVersion());
  203763. const MMRESULT res = timeBeginPeriod (1);
  203764. (void) res;
  203765. jassert (res == TIMERR_NOERROR);
  203766. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203767. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203768. #endif
  203769. }
  203770. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203771. {
  203772. OSVERSIONINFO info;
  203773. info.dwOSVersionInfoSize = sizeof (info);
  203774. GetVersionEx (&info);
  203775. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203776. {
  203777. switch (info.dwMajorVersion)
  203778. {
  203779. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203780. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203781. default: jassertfalse; break; // !! not a supported OS!
  203782. }
  203783. }
  203784. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203785. {
  203786. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203787. return Win98;
  203788. }
  203789. return UnknownOS;
  203790. }
  203791. const String SystemStats::getOperatingSystemName()
  203792. {
  203793. const char* name = "Unknown OS";
  203794. switch (getOperatingSystemType())
  203795. {
  203796. case Windows7: name = "Windows 7"; break;
  203797. case WinVista: name = "Windows Vista"; break;
  203798. case WinXP: name = "Windows XP"; break;
  203799. case Win2000: name = "Windows 2000"; break;
  203800. case Win98: name = "Windows 98"; break;
  203801. default: jassertfalse; break; // !! new type of OS?
  203802. }
  203803. return name;
  203804. }
  203805. bool SystemStats::isOperatingSystem64Bit()
  203806. {
  203807. #ifdef _WIN64
  203808. return true;
  203809. #else
  203810. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203811. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203812. BOOL isWow64 = FALSE;
  203813. return (fnIsWow64Process != 0)
  203814. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203815. && (isWow64 != FALSE);
  203816. #endif
  203817. }
  203818. int SystemStats::getMemorySizeInMegabytes()
  203819. {
  203820. MEMORYSTATUSEX mem;
  203821. mem.dwLength = sizeof (mem);
  203822. GlobalMemoryStatusEx (&mem);
  203823. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203824. }
  203825. uint32 juce_millisecondsSinceStartup() throw()
  203826. {
  203827. return (uint32) timeGetTime();
  203828. }
  203829. int64 Time::getHighResolutionTicks() throw()
  203830. {
  203831. LARGE_INTEGER ticks;
  203832. QueryPerformanceCounter (&ticks);
  203833. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203834. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203835. // fix for a very obscure PCI hardware bug that can make the counter
  203836. // sometimes jump forwards by a few seconds..
  203837. static int64 hiResTicksOffset = 0;
  203838. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203839. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203840. hiResTicksOffset = newOffset;
  203841. return ticks.QuadPart + hiResTicksOffset;
  203842. }
  203843. double Time::getMillisecondCounterHiRes() throw()
  203844. {
  203845. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203846. }
  203847. int64 Time::getHighResolutionTicksPerSecond() throw()
  203848. {
  203849. return hiResTicksPerSecond;
  203850. }
  203851. static int64 juce_getClockCycleCounter() throw()
  203852. {
  203853. #if JUCE_USE_INTRINSICS
  203854. // MS intrinsics version...
  203855. return __rdtsc();
  203856. #elif JUCE_GCC
  203857. // GNU inline asm version...
  203858. unsigned int hi = 0, lo = 0;
  203859. __asm__ __volatile__ (
  203860. "xor %%eax, %%eax \n\
  203861. xor %%edx, %%edx \n\
  203862. rdtsc \n\
  203863. movl %%eax, %[lo] \n\
  203864. movl %%edx, %[hi]"
  203865. :
  203866. : [hi] "m" (hi),
  203867. [lo] "m" (lo)
  203868. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203869. return (int64) ((((uint64) hi) << 32) | lo);
  203870. #else
  203871. // MSVC inline asm version...
  203872. unsigned int hi = 0, lo = 0;
  203873. __asm
  203874. {
  203875. xor eax, eax
  203876. xor edx, edx
  203877. rdtsc
  203878. mov lo, eax
  203879. mov hi, edx
  203880. }
  203881. return (int64) ((((uint64) hi) << 32) | lo);
  203882. #endif
  203883. }
  203884. int SystemStats::getCpuSpeedInMegaherz()
  203885. {
  203886. const int64 cycles = juce_getClockCycleCounter();
  203887. const uint32 millis = Time::getMillisecondCounter();
  203888. int lastResult = 0;
  203889. for (;;)
  203890. {
  203891. int n = 1000000;
  203892. while (--n > 0) {}
  203893. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203894. const int64 cyclesNow = juce_getClockCycleCounter();
  203895. if (millisElapsed > 80)
  203896. {
  203897. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203898. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203899. return newResult;
  203900. lastResult = newResult;
  203901. }
  203902. }
  203903. }
  203904. bool Time::setSystemTimeToThisTime() const
  203905. {
  203906. SYSTEMTIME st;
  203907. st.wDayOfWeek = 0;
  203908. st.wYear = (WORD) getYear();
  203909. st.wMonth = (WORD) (getMonth() + 1);
  203910. st.wDay = (WORD) getDayOfMonth();
  203911. st.wHour = (WORD) getHours();
  203912. st.wMinute = (WORD) getMinutes();
  203913. st.wSecond = (WORD) getSeconds();
  203914. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203915. // do this twice because of daylight saving conversion problems - the
  203916. // first one sets it up, the second one kicks it in.
  203917. return SetLocalTime (&st) != 0
  203918. && SetLocalTime (&st) != 0;
  203919. }
  203920. int SystemStats::getPageSize()
  203921. {
  203922. SYSTEM_INFO systemInfo;
  203923. GetSystemInfo (&systemInfo);
  203924. return systemInfo.dwPageSize;
  203925. }
  203926. const String SystemStats::getLogonName()
  203927. {
  203928. TCHAR text [256];
  203929. DWORD len = numElementsInArray (text) - 2;
  203930. zerostruct (text);
  203931. GetUserName (text, &len);
  203932. return String (text, len);
  203933. }
  203934. const String SystemStats::getFullUserName()
  203935. {
  203936. return getLogonName();
  203937. }
  203938. #endif
  203939. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203940. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203941. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203942. // compiled on its own).
  203943. #if JUCE_INCLUDED_FILE
  203944. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203945. extern HWND juce_messageWindowHandle;
  203946. #endif
  203947. #if ! JUCE_USE_INTRINSICS
  203948. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203949. // older ones we have to actually call the ops as win32 functions..
  203950. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203951. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203952. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203953. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203954. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203955. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203956. {
  203957. jassertfalse; // This operation isn't available in old MS compiler versions!
  203958. __int64 oldValue = *value;
  203959. if (oldValue == valueToCompare)
  203960. *value = newValue;
  203961. return oldValue;
  203962. }
  203963. #endif
  203964. CriticalSection::CriticalSection() throw()
  203965. {
  203966. // (just to check the MS haven't changed this structure and broken things...)
  203967. #if JUCE_VC7_OR_EARLIER
  203968. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203969. #else
  203970. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203971. #endif
  203972. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203973. }
  203974. CriticalSection::~CriticalSection() throw()
  203975. {
  203976. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203977. }
  203978. void CriticalSection::enter() const throw()
  203979. {
  203980. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203981. }
  203982. bool CriticalSection::tryEnter() const throw()
  203983. {
  203984. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203985. }
  203986. void CriticalSection::exit() const throw()
  203987. {
  203988. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203989. }
  203990. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203991. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203992. {
  203993. }
  203994. WaitableEvent::~WaitableEvent() throw()
  203995. {
  203996. CloseHandle (internal);
  203997. }
  203998. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203999. {
  204000. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204001. }
  204002. void WaitableEvent::signal() const throw()
  204003. {
  204004. SetEvent (internal);
  204005. }
  204006. void WaitableEvent::reset() const throw()
  204007. {
  204008. ResetEvent (internal);
  204009. }
  204010. void JUCE_API juce_threadEntryPoint (void*);
  204011. static unsigned int __stdcall threadEntryProc (void* userData)
  204012. {
  204013. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204014. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204015. GetCurrentThreadId(), TRUE);
  204016. #endif
  204017. juce_threadEntryPoint (userData);
  204018. _endthreadex (0);
  204019. return 0;
  204020. }
  204021. void Thread::launchThread()
  204022. {
  204023. unsigned int newThreadId;
  204024. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  204025. threadId_ = (ThreadID) newThreadId;
  204026. }
  204027. void Thread::closeThreadHandle()
  204028. {
  204029. CloseHandle ((HANDLE) threadHandle_);
  204030. threadId_ = 0;
  204031. threadHandle_ = 0;
  204032. }
  204033. void Thread::killThread()
  204034. {
  204035. if (threadHandle_ != 0)
  204036. {
  204037. #if JUCE_DEBUG
  204038. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204039. #endif
  204040. TerminateThread (threadHandle_, 0);
  204041. }
  204042. }
  204043. void Thread::setCurrentThreadName (const String& name)
  204044. {
  204045. #if JUCE_DEBUG && JUCE_MSVC
  204046. struct
  204047. {
  204048. DWORD dwType;
  204049. LPCSTR szName;
  204050. DWORD dwThreadID;
  204051. DWORD dwFlags;
  204052. } info;
  204053. info.dwType = 0x1000;
  204054. info.szName = name.toCString();
  204055. info.dwThreadID = GetCurrentThreadId();
  204056. info.dwFlags = 0;
  204057. __try
  204058. {
  204059. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204060. }
  204061. __except (EXCEPTION_CONTINUE_EXECUTION)
  204062. {}
  204063. #else
  204064. (void) name;
  204065. #endif
  204066. }
  204067. Thread::ThreadID Thread::getCurrentThreadId()
  204068. {
  204069. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204070. }
  204071. bool Thread::setThreadPriority (void* handle, int priority)
  204072. {
  204073. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204074. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204075. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204076. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204077. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204078. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204079. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204080. if (handle == 0)
  204081. handle = GetCurrentThread();
  204082. return SetThreadPriority (handle, pri) != FALSE;
  204083. }
  204084. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204085. {
  204086. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204087. }
  204088. struct SleepEvent
  204089. {
  204090. SleepEvent()
  204091. : handle (CreateEvent (0, 0, 0,
  204092. #if JUCE_DEBUG
  204093. _T("Juce Sleep Event")))
  204094. #else
  204095. 0))
  204096. #endif
  204097. {
  204098. }
  204099. HANDLE handle;
  204100. };
  204101. static SleepEvent sleepEvent;
  204102. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204103. {
  204104. if (millisecs >= 10)
  204105. {
  204106. Sleep (millisecs);
  204107. }
  204108. else
  204109. {
  204110. // unlike Sleep() this is guaranteed to return to the current thread after
  204111. // the time expires, so we'll use this for short waits, which are more likely
  204112. // to need to be accurate
  204113. WaitForSingleObject (sleepEvent.handle, millisecs);
  204114. }
  204115. }
  204116. void Thread::yield()
  204117. {
  204118. Sleep (0);
  204119. }
  204120. static int lastProcessPriority = -1;
  204121. // called by WindowDriver because Windows does wierd things to process priority
  204122. // when you swap apps, and this forces an update when the app is brought to the front.
  204123. void juce_repeatLastProcessPriority()
  204124. {
  204125. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204126. {
  204127. DWORD p;
  204128. switch (lastProcessPriority)
  204129. {
  204130. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204131. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204132. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204133. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204134. default: jassertfalse; return; // bad priority value
  204135. }
  204136. SetPriorityClass (GetCurrentProcess(), p);
  204137. }
  204138. }
  204139. void Process::setPriority (ProcessPriority prior)
  204140. {
  204141. if (lastProcessPriority != (int) prior)
  204142. {
  204143. lastProcessPriority = (int) prior;
  204144. juce_repeatLastProcessPriority();
  204145. }
  204146. }
  204147. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204148. {
  204149. return IsDebuggerPresent() != FALSE;
  204150. }
  204151. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204152. {
  204153. return juce_isRunningUnderDebugger();
  204154. }
  204155. void Process::raisePrivilege()
  204156. {
  204157. jassertfalse; // xxx not implemented
  204158. }
  204159. void Process::lowerPrivilege()
  204160. {
  204161. jassertfalse; // xxx not implemented
  204162. }
  204163. void Process::terminate()
  204164. {
  204165. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204166. _CrtDumpMemoryLeaks();
  204167. #endif
  204168. // bullet in the head in case there's a problem shutting down..
  204169. ExitProcess (0);
  204170. }
  204171. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204172. {
  204173. void* result = 0;
  204174. JUCE_TRY
  204175. {
  204176. result = LoadLibrary (name.toUTF16());
  204177. }
  204178. JUCE_CATCH_ALL
  204179. return result;
  204180. }
  204181. void PlatformUtilities::freeDynamicLibrary (void* h)
  204182. {
  204183. JUCE_TRY
  204184. {
  204185. if (h != 0)
  204186. FreeLibrary ((HMODULE) h);
  204187. }
  204188. JUCE_CATCH_ALL
  204189. }
  204190. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204191. {
  204192. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204193. }
  204194. class InterProcessLock::Pimpl
  204195. {
  204196. public:
  204197. Pimpl (const String& name, const int timeOutMillisecs)
  204198. : handle (0), refCount (1)
  204199. {
  204200. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  204201. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204202. {
  204203. if (timeOutMillisecs == 0)
  204204. {
  204205. close();
  204206. return;
  204207. }
  204208. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204209. {
  204210. case WAIT_OBJECT_0:
  204211. case WAIT_ABANDONED:
  204212. break;
  204213. case WAIT_TIMEOUT:
  204214. default:
  204215. close();
  204216. break;
  204217. }
  204218. }
  204219. }
  204220. ~Pimpl()
  204221. {
  204222. close();
  204223. }
  204224. void close()
  204225. {
  204226. if (handle != 0)
  204227. {
  204228. ReleaseMutex (handle);
  204229. CloseHandle (handle);
  204230. handle = 0;
  204231. }
  204232. }
  204233. HANDLE handle;
  204234. int refCount;
  204235. };
  204236. InterProcessLock::InterProcessLock (const String& name_)
  204237. : name (name_)
  204238. {
  204239. }
  204240. InterProcessLock::~InterProcessLock()
  204241. {
  204242. }
  204243. bool InterProcessLock::enter (const int timeOutMillisecs)
  204244. {
  204245. const ScopedLock sl (lock);
  204246. if (pimpl == 0)
  204247. {
  204248. pimpl = new Pimpl (name, timeOutMillisecs);
  204249. if (pimpl->handle == 0)
  204250. pimpl = 0;
  204251. }
  204252. else
  204253. {
  204254. pimpl->refCount++;
  204255. }
  204256. return pimpl != 0;
  204257. }
  204258. void InterProcessLock::exit()
  204259. {
  204260. const ScopedLock sl (lock);
  204261. // Trying to release the lock too many times!
  204262. jassert (pimpl != 0);
  204263. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204264. pimpl = 0;
  204265. }
  204266. #endif
  204267. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204268. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204269. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204270. // compiled on its own).
  204271. #if JUCE_INCLUDED_FILE
  204272. #ifndef CSIDL_MYMUSIC
  204273. #define CSIDL_MYMUSIC 0x000d
  204274. #endif
  204275. #ifndef CSIDL_MYVIDEO
  204276. #define CSIDL_MYVIDEO 0x000e
  204277. #endif
  204278. #ifndef INVALID_FILE_ATTRIBUTES
  204279. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204280. #endif
  204281. namespace WindowsFileHelpers
  204282. {
  204283. int64 fileTimeToTime (const FILETIME* const ft)
  204284. {
  204285. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204286. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204287. }
  204288. void timeToFileTime (const int64 time, FILETIME* const ft)
  204289. {
  204290. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204291. }
  204292. const String getDriveFromPath (String path)
  204293. {
  204294. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  204295. if (PathStripToRoot (p))
  204296. return String ((const WCHAR*) p);
  204297. return path;
  204298. }
  204299. int64 getDiskSpaceInfo (const String& path, const bool total)
  204300. {
  204301. ULARGE_INTEGER spc, tot, totFree;
  204302. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  204303. return total ? (int64) tot.QuadPart
  204304. : (int64) spc.QuadPart;
  204305. return 0;
  204306. }
  204307. unsigned int getWindowsDriveType (const String& path)
  204308. {
  204309. return GetDriveType (getDriveFromPath (path).toUTF16());
  204310. }
  204311. const File getSpecialFolderPath (int type)
  204312. {
  204313. WCHAR path [MAX_PATH + 256];
  204314. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204315. return File (String (path));
  204316. return File::nonexistent;
  204317. }
  204318. }
  204319. const juce_wchar File::separator = '\\';
  204320. const String File::separatorString ("\\");
  204321. bool File::exists() const
  204322. {
  204323. return fullPath.isNotEmpty()
  204324. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  204325. }
  204326. bool File::existsAsFile() const
  204327. {
  204328. return fullPath.isNotEmpty()
  204329. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204330. }
  204331. bool File::isDirectory() const
  204332. {
  204333. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  204334. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204335. }
  204336. bool File::hasWriteAccess() const
  204337. {
  204338. if (exists())
  204339. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  204340. // on windows, it seems that even read-only directories can still be written into,
  204341. // so checking the parent directory's permissions would return the wrong result..
  204342. return true;
  204343. }
  204344. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204345. {
  204346. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  204347. if (attr == INVALID_FILE_ATTRIBUTES)
  204348. return false;
  204349. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204350. return true;
  204351. if (shouldBeReadOnly)
  204352. attr |= FILE_ATTRIBUTE_READONLY;
  204353. else
  204354. attr &= ~FILE_ATTRIBUTE_READONLY;
  204355. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  204356. }
  204357. bool File::isHidden() const
  204358. {
  204359. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204360. }
  204361. bool File::deleteFile() const
  204362. {
  204363. if (! exists())
  204364. return true;
  204365. else if (isDirectory())
  204366. return RemoveDirectory (fullPath.toUTF16()) != 0;
  204367. else
  204368. return DeleteFile (fullPath.toUTF16()) != 0;
  204369. }
  204370. bool File::moveToTrash() const
  204371. {
  204372. if (! exists())
  204373. return true;
  204374. SHFILEOPSTRUCT fos;
  204375. zerostruct (fos);
  204376. // The string we pass in must be double null terminated..
  204377. String doubleNullTermPath (getFullPathName() + " ");
  204378. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  204379. p [getFullPathName().length()] = 0;
  204380. fos.wFunc = FO_DELETE;
  204381. fos.pFrom = p;
  204382. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204383. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204384. return SHFileOperation (&fos) == 0;
  204385. }
  204386. bool File::copyInternal (const File& dest) const
  204387. {
  204388. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  204389. }
  204390. bool File::moveInternal (const File& dest) const
  204391. {
  204392. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  204393. }
  204394. void File::createDirectoryInternal (const String& fileName) const
  204395. {
  204396. CreateDirectory (fileName.toUTF16(), 0);
  204397. }
  204398. int64 juce_fileSetPosition (void* handle, int64 pos)
  204399. {
  204400. LARGE_INTEGER li;
  204401. li.QuadPart = pos;
  204402. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204403. return li.QuadPart;
  204404. }
  204405. void FileInputStream::openHandle()
  204406. {
  204407. totalSize = file.getSize();
  204408. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204409. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204410. if (h != INVALID_HANDLE_VALUE)
  204411. fileHandle = (void*) h;
  204412. }
  204413. void FileInputStream::closeHandle()
  204414. {
  204415. CloseHandle ((HANDLE) fileHandle);
  204416. }
  204417. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204418. {
  204419. if (fileHandle != 0)
  204420. {
  204421. DWORD actualNum = 0;
  204422. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204423. return (size_t) actualNum;
  204424. }
  204425. return 0;
  204426. }
  204427. void FileOutputStream::openHandle()
  204428. {
  204429. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204430. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204431. if (h != INVALID_HANDLE_VALUE)
  204432. {
  204433. LARGE_INTEGER li;
  204434. li.QuadPart = 0;
  204435. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204436. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204437. {
  204438. fileHandle = (void*) h;
  204439. currentPosition = li.QuadPart;
  204440. }
  204441. }
  204442. }
  204443. void FileOutputStream::closeHandle()
  204444. {
  204445. CloseHandle ((HANDLE) fileHandle);
  204446. }
  204447. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204448. {
  204449. if (fileHandle != 0)
  204450. {
  204451. DWORD actualNum = 0;
  204452. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204453. return (int) actualNum;
  204454. }
  204455. return 0;
  204456. }
  204457. void FileOutputStream::flushInternal()
  204458. {
  204459. if (fileHandle != 0)
  204460. FlushFileBuffers ((HANDLE) fileHandle);
  204461. }
  204462. int64 File::getSize() const
  204463. {
  204464. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204465. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  204466. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204467. return 0;
  204468. }
  204469. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204470. {
  204471. using namespace WindowsFileHelpers;
  204472. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204473. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  204474. {
  204475. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204476. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204477. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204478. }
  204479. else
  204480. {
  204481. creationTime = accessTime = modificationTime = 0;
  204482. }
  204483. }
  204484. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204485. {
  204486. using namespace WindowsFileHelpers;
  204487. bool ok = false;
  204488. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204489. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204490. if (h != INVALID_HANDLE_VALUE)
  204491. {
  204492. FILETIME m, a, c;
  204493. timeToFileTime (modificationTime, &m);
  204494. timeToFileTime (accessTime, &a);
  204495. timeToFileTime (creationTime, &c);
  204496. ok = SetFileTime (h,
  204497. creationTime > 0 ? &c : 0,
  204498. accessTime > 0 ? &a : 0,
  204499. modificationTime > 0 ? &m : 0) != 0;
  204500. CloseHandle (h);
  204501. }
  204502. return ok;
  204503. }
  204504. void File::findFileSystemRoots (Array<File>& destArray)
  204505. {
  204506. TCHAR buffer [2048];
  204507. buffer[0] = 0;
  204508. buffer[1] = 0;
  204509. GetLogicalDriveStrings (2048, buffer);
  204510. const TCHAR* n = buffer;
  204511. StringArray roots;
  204512. while (*n != 0)
  204513. {
  204514. roots.add (String (n));
  204515. while (*n++ != 0)
  204516. {}
  204517. }
  204518. roots.sort (true);
  204519. for (int i = 0; i < roots.size(); ++i)
  204520. destArray.add (roots [i]);
  204521. }
  204522. const String File::getVolumeLabel() const
  204523. {
  204524. TCHAR dest[64];
  204525. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204526. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204527. dest[0] = 0;
  204528. return dest;
  204529. }
  204530. int File::getVolumeSerialNumber() const
  204531. {
  204532. TCHAR dest[64];
  204533. DWORD serialNum;
  204534. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204535. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204536. return 0;
  204537. return (int) serialNum;
  204538. }
  204539. int64 File::getBytesFreeOnVolume() const
  204540. {
  204541. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204542. }
  204543. int64 File::getVolumeTotalSize() const
  204544. {
  204545. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204546. }
  204547. bool File::isOnCDRomDrive() const
  204548. {
  204549. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204550. }
  204551. bool File::isOnHardDisk() const
  204552. {
  204553. if (fullPath.isEmpty())
  204554. return false;
  204555. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204556. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204557. return n != DRIVE_REMOVABLE;
  204558. else
  204559. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204560. }
  204561. bool File::isOnRemovableDrive() const
  204562. {
  204563. if (fullPath.isEmpty())
  204564. return false;
  204565. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204566. return n == DRIVE_CDROM
  204567. || n == DRIVE_REMOTE
  204568. || n == DRIVE_REMOVABLE
  204569. || n == DRIVE_RAMDISK;
  204570. }
  204571. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204572. {
  204573. int csidlType = 0;
  204574. switch (type)
  204575. {
  204576. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204577. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204578. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204579. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204580. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204581. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204582. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204583. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204584. case tempDirectory:
  204585. {
  204586. WCHAR dest [2048];
  204587. dest[0] = 0;
  204588. GetTempPath (numElementsInArray (dest), dest);
  204589. return File (String (dest));
  204590. }
  204591. case invokedExecutableFile:
  204592. case currentExecutableFile:
  204593. case currentApplicationFile:
  204594. {
  204595. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204596. WCHAR dest [MAX_PATH + 256];
  204597. dest[0] = 0;
  204598. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204599. return File (String (dest));
  204600. }
  204601. case hostApplicationPath:
  204602. {
  204603. WCHAR dest [MAX_PATH + 256];
  204604. dest[0] = 0;
  204605. GetModuleFileName (0, dest, numElementsInArray (dest));
  204606. return File (String (dest));
  204607. }
  204608. default:
  204609. jassertfalse; // unknown type?
  204610. return File::nonexistent;
  204611. }
  204612. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204613. }
  204614. const File File::getCurrentWorkingDirectory()
  204615. {
  204616. WCHAR dest [MAX_PATH + 256];
  204617. dest[0] = 0;
  204618. GetCurrentDirectory (numElementsInArray (dest), dest);
  204619. return File (String (dest));
  204620. }
  204621. bool File::setAsCurrentWorkingDirectory() const
  204622. {
  204623. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204624. }
  204625. const String File::getVersion() const
  204626. {
  204627. String result;
  204628. DWORD handle = 0;
  204629. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204630. HeapBlock<char> buffer;
  204631. buffer.calloc (bufferSize);
  204632. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204633. {
  204634. VS_FIXEDFILEINFO* vffi;
  204635. UINT len = 0;
  204636. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204637. {
  204638. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204639. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204640. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204641. << (int) LOWORD (vffi->dwFileVersionLS);
  204642. }
  204643. }
  204644. return result;
  204645. }
  204646. const File File::getLinkedTarget() const
  204647. {
  204648. File result (*this);
  204649. String p (getFullPathName());
  204650. if (! exists())
  204651. p += ".lnk";
  204652. else if (getFileExtension() != ".lnk")
  204653. return result;
  204654. ComSmartPtr <IShellLink> shellLink;
  204655. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204656. {
  204657. ComSmartPtr <IPersistFile> persistFile;
  204658. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204659. {
  204660. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204661. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204662. {
  204663. WIN32_FIND_DATA winFindData;
  204664. WCHAR resolvedPath [MAX_PATH];
  204665. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204666. result = File (resolvedPath);
  204667. }
  204668. }
  204669. }
  204670. return result;
  204671. }
  204672. class DirectoryIterator::NativeIterator::Pimpl
  204673. {
  204674. public:
  204675. Pimpl (const File& directory, const String& wildCard)
  204676. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204677. handle (INVALID_HANDLE_VALUE)
  204678. {
  204679. }
  204680. ~Pimpl()
  204681. {
  204682. if (handle != INVALID_HANDLE_VALUE)
  204683. FindClose (handle);
  204684. }
  204685. bool next (String& filenameFound,
  204686. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204687. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204688. {
  204689. using namespace WindowsFileHelpers;
  204690. WIN32_FIND_DATA findData;
  204691. if (handle == INVALID_HANDLE_VALUE)
  204692. {
  204693. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204694. if (handle == INVALID_HANDLE_VALUE)
  204695. return false;
  204696. }
  204697. else
  204698. {
  204699. if (FindNextFile (handle, &findData) == 0)
  204700. return false;
  204701. }
  204702. filenameFound = findData.cFileName;
  204703. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204704. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204705. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204706. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204707. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204708. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204709. return true;
  204710. }
  204711. private:
  204712. const String directoryWithWildCard;
  204713. HANDLE handle;
  204714. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204715. };
  204716. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204717. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204718. {
  204719. }
  204720. DirectoryIterator::NativeIterator::~NativeIterator()
  204721. {
  204722. }
  204723. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204724. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204725. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204726. {
  204727. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204728. }
  204729. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204730. {
  204731. HINSTANCE hInstance = 0;
  204732. JUCE_TRY
  204733. {
  204734. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204735. }
  204736. JUCE_CATCH_ALL
  204737. return hInstance > (HINSTANCE) 32;
  204738. }
  204739. void File::revealToUser() const
  204740. {
  204741. if (isDirectory())
  204742. startAsProcess();
  204743. else if (getParentDirectory().exists())
  204744. getParentDirectory().startAsProcess();
  204745. }
  204746. class NamedPipeInternal
  204747. {
  204748. public:
  204749. NamedPipeInternal (const String& file, const bool isPipe_)
  204750. : pipeH (0),
  204751. cancelEvent (0),
  204752. connected (false),
  204753. isPipe (isPipe_)
  204754. {
  204755. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204756. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204757. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204758. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204759. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204760. }
  204761. ~NamedPipeInternal()
  204762. {
  204763. disconnectPipe();
  204764. if (pipeH != 0)
  204765. CloseHandle (pipeH);
  204766. CloseHandle (cancelEvent);
  204767. }
  204768. bool connect (const int timeOutMs)
  204769. {
  204770. if (! isPipe)
  204771. return true;
  204772. if (! connected)
  204773. {
  204774. OVERLAPPED over;
  204775. zerostruct (over);
  204776. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204777. if (ConnectNamedPipe (pipeH, &over))
  204778. {
  204779. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204780. }
  204781. else
  204782. {
  204783. const int err = GetLastError();
  204784. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204785. {
  204786. HANDLE handles[] = { over.hEvent, cancelEvent };
  204787. if (WaitForMultipleObjects (2, handles, FALSE,
  204788. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204789. connected = true;
  204790. }
  204791. else if (err == ERROR_PIPE_CONNECTED)
  204792. {
  204793. connected = true;
  204794. }
  204795. }
  204796. CloseHandle (over.hEvent);
  204797. }
  204798. return connected;
  204799. }
  204800. void disconnectPipe()
  204801. {
  204802. if (connected)
  204803. {
  204804. DisconnectNamedPipe (pipeH);
  204805. connected = false;
  204806. }
  204807. }
  204808. HANDLE pipeH;
  204809. HANDLE cancelEvent;
  204810. bool connected, isPipe;
  204811. };
  204812. void NamedPipe::close()
  204813. {
  204814. cancelPendingReads();
  204815. const ScopedLock sl (lock);
  204816. delete static_cast<NamedPipeInternal*> (internal);
  204817. internal = 0;
  204818. }
  204819. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204820. {
  204821. close();
  204822. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204823. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204824. {
  204825. internal = intern.release();
  204826. return true;
  204827. }
  204828. return false;
  204829. }
  204830. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204831. {
  204832. const ScopedLock sl (lock);
  204833. int bytesRead = -1;
  204834. bool waitAgain = true;
  204835. while (waitAgain && internal != 0)
  204836. {
  204837. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204838. waitAgain = false;
  204839. if (! intern->connect (timeOutMilliseconds))
  204840. break;
  204841. if (maxBytesToRead <= 0)
  204842. return 0;
  204843. OVERLAPPED over;
  204844. zerostruct (over);
  204845. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204846. unsigned long numRead;
  204847. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204848. {
  204849. bytesRead = (int) numRead;
  204850. }
  204851. else if (GetLastError() == ERROR_IO_PENDING)
  204852. {
  204853. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204854. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204855. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204856. : INFINITE);
  204857. if (waitResult != WAIT_OBJECT_0)
  204858. {
  204859. // if the operation timed out, let's cancel it...
  204860. CancelIo (intern->pipeH);
  204861. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204862. }
  204863. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204864. {
  204865. bytesRead = (int) numRead;
  204866. }
  204867. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204868. {
  204869. intern->disconnectPipe();
  204870. waitAgain = true;
  204871. }
  204872. }
  204873. else
  204874. {
  204875. waitAgain = internal != 0;
  204876. Sleep (5);
  204877. }
  204878. CloseHandle (over.hEvent);
  204879. }
  204880. return bytesRead;
  204881. }
  204882. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204883. {
  204884. int bytesWritten = -1;
  204885. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204886. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204887. {
  204888. if (numBytesToWrite <= 0)
  204889. return 0;
  204890. OVERLAPPED over;
  204891. zerostruct (over);
  204892. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204893. unsigned long numWritten;
  204894. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204895. {
  204896. bytesWritten = (int) numWritten;
  204897. }
  204898. else if (GetLastError() == ERROR_IO_PENDING)
  204899. {
  204900. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204901. DWORD waitResult;
  204902. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204903. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204904. : INFINITE);
  204905. if (waitResult != WAIT_OBJECT_0)
  204906. {
  204907. CancelIo (intern->pipeH);
  204908. WaitForSingleObject (over.hEvent, INFINITE);
  204909. }
  204910. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204911. {
  204912. bytesWritten = (int) numWritten;
  204913. }
  204914. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204915. {
  204916. intern->disconnectPipe();
  204917. }
  204918. }
  204919. CloseHandle (over.hEvent);
  204920. }
  204921. return bytesWritten;
  204922. }
  204923. void NamedPipe::cancelPendingReads()
  204924. {
  204925. if (internal != 0)
  204926. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204927. }
  204928. #endif
  204929. /*** End of inlined file: juce_win32_Files.cpp ***/
  204930. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204931. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204932. // compiled on its own).
  204933. #if JUCE_INCLUDED_FILE
  204934. #ifndef INTERNET_FLAG_NEED_FILE
  204935. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204936. #endif
  204937. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204938. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204939. #endif
  204940. #ifndef WORKAROUND_TIMEOUT_BUG
  204941. //#define WORKAROUND_TIMEOUT_BUG 1
  204942. #endif
  204943. #if WORKAROUND_TIMEOUT_BUG
  204944. // Required because of a Microsoft bug in setting a timeout
  204945. class InternetConnectThread : public Thread
  204946. {
  204947. public:
  204948. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204949. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204950. {
  204951. startThread();
  204952. }
  204953. ~InternetConnectThread()
  204954. {
  204955. stopThread (60000);
  204956. }
  204957. void run()
  204958. {
  204959. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204960. uc.nPort, _T(""), _T(""),
  204961. isFtp ? INTERNET_SERVICE_FTP
  204962. : INTERNET_SERVICE_HTTP,
  204963. 0, 0);
  204964. notify();
  204965. }
  204966. private:
  204967. URL_COMPONENTS& uc;
  204968. HINTERNET sessionHandle;
  204969. HINTERNET& connection;
  204970. const bool isFtp;
  204971. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204972. };
  204973. #endif
  204974. class WebInputStream : public InputStream
  204975. {
  204976. public:
  204977. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204978. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204979. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204980. : connection (0), request (0),
  204981. address (address_), headers (headers_), postData (postData_), position (0),
  204982. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204983. {
  204984. createConnection (progressCallback, progressCallbackContext);
  204985. if (responseHeaders != 0 && ! isError())
  204986. {
  204987. DWORD bufferSizeBytes = 4096;
  204988. for (;;)
  204989. {
  204990. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204991. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204992. {
  204993. StringArray headersArray;
  204994. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204995. for (int i = 0; i < headersArray.size(); ++i)
  204996. {
  204997. const String& header = headersArray[i];
  204998. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204999. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205000. const String previousValue ((*responseHeaders) [key]);
  205001. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205002. }
  205003. break;
  205004. }
  205005. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205006. break;
  205007. }
  205008. }
  205009. }
  205010. ~WebInputStream()
  205011. {
  205012. close();
  205013. }
  205014. bool isError() const { return request == 0; }
  205015. bool isExhausted() { return finished; }
  205016. int64 getPosition() { return position; }
  205017. int64 getTotalLength()
  205018. {
  205019. if (! isError())
  205020. {
  205021. DWORD index = 0, result = 0, size = sizeof (result);
  205022. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205023. return (int64) result;
  205024. }
  205025. return -1;
  205026. }
  205027. int read (void* buffer, int bytesToRead)
  205028. {
  205029. DWORD bytesRead = 0;
  205030. if (! (finished || isError()))
  205031. {
  205032. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  205033. position += bytesRead;
  205034. if (bytesRead == 0)
  205035. finished = true;
  205036. }
  205037. return (int) bytesRead;
  205038. }
  205039. bool setPosition (int64 wantedPos)
  205040. {
  205041. if (isError())
  205042. return false;
  205043. if (wantedPos != position)
  205044. {
  205045. finished = false;
  205046. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  205047. if (position == wantedPos)
  205048. return true;
  205049. if (wantedPos < position)
  205050. {
  205051. close();
  205052. position = 0;
  205053. createConnection (0, 0);
  205054. }
  205055. skipNextBytes (wantedPos - position);
  205056. }
  205057. return true;
  205058. }
  205059. private:
  205060. HINTERNET connection, request;
  205061. String address, headers;
  205062. MemoryBlock postData;
  205063. int64 position;
  205064. bool finished;
  205065. const bool isPost;
  205066. int timeOutMs;
  205067. void close()
  205068. {
  205069. if (request != 0)
  205070. {
  205071. InternetCloseHandle (request);
  205072. request = 0;
  205073. }
  205074. if (connection != 0)
  205075. {
  205076. InternetCloseHandle (connection);
  205077. connection = 0;
  205078. }
  205079. }
  205080. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  205081. void* progressCallbackContext)
  205082. {
  205083. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  205084. close();
  205085. if (sessionHandle != 0)
  205086. {
  205087. // break up the url..
  205088. TCHAR file[1024], server[1024];
  205089. URL_COMPONENTS uc;
  205090. zerostruct (uc);
  205091. uc.dwStructSize = sizeof (uc);
  205092. uc.dwUrlPathLength = sizeof (file);
  205093. uc.dwHostNameLength = sizeof (server);
  205094. uc.lpszUrlPath = file;
  205095. uc.lpszHostName = server;
  205096. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  205097. {
  205098. int disable = 1;
  205099. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205100. if (timeOutMs == 0)
  205101. timeOutMs = 30000;
  205102. else if (timeOutMs < 0)
  205103. timeOutMs = -1;
  205104. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205105. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  205106. #if WORKAROUND_TIMEOUT_BUG
  205107. connection = 0;
  205108. {
  205109. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  205110. connectThread.wait (timeOutMs);
  205111. if (connection == 0)
  205112. {
  205113. InternetCloseHandle (sessionHandle);
  205114. sessionHandle = 0;
  205115. }
  205116. }
  205117. #else
  205118. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  205119. _T(""), _T(""),
  205120. isFtp ? INTERNET_SERVICE_FTP
  205121. : INTERNET_SERVICE_HTTP,
  205122. 0, 0);
  205123. #endif
  205124. if (connection != 0)
  205125. {
  205126. if (isFtp)
  205127. {
  205128. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  205129. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  205130. }
  205131. else
  205132. {
  205133. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205134. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205135. if (address.startsWithIgnoreCase ("https:"))
  205136. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205137. // IE7 seems to automatically work out when it's https)
  205138. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  205139. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  205140. if (request != 0)
  205141. {
  205142. INTERNET_BUFFERS buffers;
  205143. zerostruct (buffers);
  205144. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205145. buffers.lpcszHeader = headers.toUTF16();
  205146. buffers.dwHeadersLength = headers.length();
  205147. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205148. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205149. {
  205150. int bytesSent = 0;
  205151. for (;;)
  205152. {
  205153. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205154. DWORD bytesDone = 0;
  205155. if (bytesToDo > 0
  205156. && ! InternetWriteFile (request,
  205157. static_cast <const char*> (postData.getData()) + bytesSent,
  205158. bytesToDo, &bytesDone))
  205159. {
  205160. break;
  205161. }
  205162. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205163. {
  205164. if (HttpEndRequest (request, 0, 0, 0))
  205165. return;
  205166. break;
  205167. }
  205168. bytesSent += bytesDone;
  205169. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  205170. break;
  205171. }
  205172. }
  205173. }
  205174. close();
  205175. }
  205176. }
  205177. }
  205178. }
  205179. }
  205180. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  205181. };
  205182. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  205183. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205184. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  205185. {
  205186. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  205187. progressCallback, progressCallbackContext,
  205188. headers, timeOutMs, responseHeaders));
  205189. return wi->isError() ? 0 : wi.release();
  205190. }
  205191. namespace MACAddressHelpers
  205192. {
  205193. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205194. {
  205195. DynamicLibraryLoader dll ("iphlpapi.dll");
  205196. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205197. if (getAdaptersInfo != 0)
  205198. {
  205199. ULONG len = sizeof (IP_ADAPTER_INFO);
  205200. MemoryBlock mb;
  205201. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205202. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205203. {
  205204. mb.setSize (len);
  205205. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205206. }
  205207. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205208. {
  205209. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205210. {
  205211. if (adapter->AddressLength >= 6)
  205212. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205213. }
  205214. }
  205215. }
  205216. }
  205217. void getViaNetBios (Array<MACAddress>& result)
  205218. {
  205219. DynamicLibraryLoader dll ("netapi32.dll");
  205220. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205221. if (NetbiosCall != 0)
  205222. {
  205223. NCB ncb;
  205224. zerostruct (ncb);
  205225. struct ASTAT
  205226. {
  205227. ADAPTER_STATUS adapt;
  205228. NAME_BUFFER NameBuff [30];
  205229. };
  205230. ASTAT astat;
  205231. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205232. LANA_ENUM enums;
  205233. zerostruct (enums);
  205234. ncb.ncb_command = NCBENUM;
  205235. ncb.ncb_buffer = (unsigned char*) &enums;
  205236. ncb.ncb_length = sizeof (LANA_ENUM);
  205237. NetbiosCall (&ncb);
  205238. for (int i = 0; i < enums.length; ++i)
  205239. {
  205240. zerostruct (ncb);
  205241. ncb.ncb_command = NCBRESET;
  205242. ncb.ncb_lana_num = enums.lana[i];
  205243. if (NetbiosCall (&ncb) == 0)
  205244. {
  205245. zerostruct (ncb);
  205246. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205247. ncb.ncb_command = NCBASTAT;
  205248. ncb.ncb_lana_num = enums.lana[i];
  205249. ncb.ncb_buffer = (unsigned char*) &astat;
  205250. ncb.ncb_length = sizeof (ASTAT);
  205251. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205252. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205253. }
  205254. }
  205255. }
  205256. }
  205257. }
  205258. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205259. {
  205260. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205261. MACAddressHelpers::getViaNetBios (result);
  205262. }
  205263. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205264. const String& emailSubject,
  205265. const String& bodyText,
  205266. const StringArray& filesToAttach)
  205267. {
  205268. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205269. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205270. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205271. bool ok = false;
  205272. if (mapiSendMail != 0)
  205273. {
  205274. MapiMessage message;
  205275. zerostruct (message);
  205276. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205277. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205278. MapiRecipDesc recip;
  205279. zerostruct (recip);
  205280. recip.ulRecipClass = MAPI_TO;
  205281. String targetEmailAddress_ (targetEmailAddress);
  205282. if (targetEmailAddress_.isEmpty())
  205283. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205284. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205285. message.nRecipCount = 1;
  205286. message.lpRecips = &recip;
  205287. HeapBlock <MapiFileDesc> files;
  205288. files.calloc (filesToAttach.size());
  205289. message.nFileCount = filesToAttach.size();
  205290. message.lpFiles = files;
  205291. for (int i = 0; i < filesToAttach.size(); ++i)
  205292. {
  205293. files[i].nPosition = (ULONG) -1;
  205294. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205295. }
  205296. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205297. }
  205298. FreeLibrary (h);
  205299. return ok;
  205300. }
  205301. #endif
  205302. /*** End of inlined file: juce_win32_Network.cpp ***/
  205303. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205304. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205305. // compiled on its own).
  205306. #if JUCE_INCLUDED_FILE
  205307. namespace
  205308. {
  205309. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205310. {
  205311. HKEY rootKey = 0;
  205312. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205313. rootKey = HKEY_CURRENT_USER;
  205314. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205315. rootKey = HKEY_LOCAL_MACHINE;
  205316. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205317. rootKey = HKEY_CLASSES_ROOT;
  205318. if (rootKey != 0)
  205319. {
  205320. name = name.substring (name.indexOfChar ('\\') + 1);
  205321. const int lastSlash = name.lastIndexOfChar ('\\');
  205322. valueName = name.substring (lastSlash + 1);
  205323. name = name.substring (0, lastSlash);
  205324. HKEY key;
  205325. DWORD result;
  205326. if (createForWriting)
  205327. {
  205328. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  205329. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205330. return key;
  205331. }
  205332. else
  205333. {
  205334. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205335. return key;
  205336. }
  205337. }
  205338. return 0;
  205339. }
  205340. }
  205341. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205342. const String& defaultValue)
  205343. {
  205344. String valueName, result (defaultValue);
  205345. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205346. if (k != 0)
  205347. {
  205348. WCHAR buffer [2048];
  205349. unsigned long bufferSize = sizeof (buffer);
  205350. DWORD type = REG_SZ;
  205351. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205352. {
  205353. if (type == REG_SZ)
  205354. result = buffer;
  205355. else if (type == REG_DWORD)
  205356. result = String ((int) *(DWORD*) buffer);
  205357. }
  205358. RegCloseKey (k);
  205359. }
  205360. return result;
  205361. }
  205362. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205363. const String& value)
  205364. {
  205365. String valueName;
  205366. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205367. if (k != 0)
  205368. {
  205369. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  205370. (const BYTE*) value.toUTF16().getAddress(),
  205371. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  205372. RegCloseKey (k);
  205373. }
  205374. }
  205375. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205376. {
  205377. bool exists = false;
  205378. String valueName;
  205379. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205380. if (k != 0)
  205381. {
  205382. unsigned char buffer [2048];
  205383. unsigned long bufferSize = sizeof (buffer);
  205384. DWORD type = 0;
  205385. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205386. exists = true;
  205387. RegCloseKey (k);
  205388. }
  205389. return exists;
  205390. }
  205391. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205392. {
  205393. String valueName;
  205394. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205395. if (k != 0)
  205396. {
  205397. RegDeleteValue (k, valueName.toUTF16());
  205398. RegCloseKey (k);
  205399. }
  205400. }
  205401. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205402. {
  205403. String valueName;
  205404. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205405. if (k != 0)
  205406. {
  205407. RegDeleteKey (k, valueName.toUTF16());
  205408. RegCloseKey (k);
  205409. }
  205410. }
  205411. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205412. const String& symbolicDescription,
  205413. const String& fullDescription,
  205414. const File& targetExecutable,
  205415. int iconResourceNumber)
  205416. {
  205417. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205418. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205419. if (iconResourceNumber != 0)
  205420. setRegistryValue (key + "\\DefaultIcon\\",
  205421. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205422. setRegistryValue (key + "\\", fullDescription);
  205423. setRegistryValue (key + "\\shell\\open\\command\\",
  205424. targetExecutable.getFullPathName() + " %1");
  205425. }
  205426. bool juce_IsRunningInWine()
  205427. {
  205428. HKEY key;
  205429. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205430. {
  205431. RegCloseKey (key);
  205432. return true;
  205433. }
  205434. return false;
  205435. }
  205436. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205437. {
  205438. String s (::GetCommandLineW());
  205439. StringArray tokens;
  205440. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205441. return tokens.joinIntoString (" ", 1);
  205442. }
  205443. static void* currentModuleHandle = 0;
  205444. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205445. {
  205446. if (currentModuleHandle == 0)
  205447. currentModuleHandle = GetModuleHandle (0);
  205448. return currentModuleHandle;
  205449. }
  205450. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205451. {
  205452. currentModuleHandle = newHandle;
  205453. }
  205454. void PlatformUtilities::fpuReset()
  205455. {
  205456. #if JUCE_MSVC
  205457. _clearfp();
  205458. #endif
  205459. }
  205460. void PlatformUtilities::beep()
  205461. {
  205462. MessageBeep (MB_OK);
  205463. }
  205464. #endif
  205465. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205466. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205467. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205468. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205469. // compiled on its own).
  205470. #if JUCE_INCLUDED_FILE
  205471. static const unsigned int specialId = WM_APP + 0x4400;
  205472. static const unsigned int broadcastId = WM_APP + 0x4403;
  205473. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205474. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205475. HWND juce_messageWindowHandle = 0;
  205476. extern long improbableWindowNumber; // defined in windowing.cpp
  205477. #ifndef WM_APPCOMMAND
  205478. #define WM_APPCOMMAND 0x0319
  205479. #endif
  205480. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205481. const UINT message,
  205482. const WPARAM wParam,
  205483. const LPARAM lParam) throw()
  205484. {
  205485. JUCE_TRY
  205486. {
  205487. if (h == juce_messageWindowHandle)
  205488. {
  205489. if (message == specialCallbackId)
  205490. {
  205491. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205492. return (LRESULT) (*func) ((void*) lParam);
  205493. }
  205494. else if (message == specialId)
  205495. {
  205496. // these are trapped early in the dispatch call, but must also be checked
  205497. // here in case there are windows modal dialog boxes doing their own
  205498. // dispatch loop and not calling our version
  205499. Message* const message = reinterpret_cast <Message*> (lParam);
  205500. MessageManager::getInstance()->deliverMessage (message);
  205501. message->decReferenceCount();
  205502. return 0;
  205503. }
  205504. else if (message == broadcastId)
  205505. {
  205506. const ScopedPointer <String> messageString ((String*) lParam);
  205507. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205508. return 0;
  205509. }
  205510. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205511. {
  205512. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205513. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205514. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205515. return 0;
  205516. }
  205517. }
  205518. }
  205519. JUCE_CATCH_EXCEPTION
  205520. return DefWindowProc (h, message, wParam, lParam);
  205521. }
  205522. static bool isEventBlockedByModalComps (MSG& m)
  205523. {
  205524. if (Component::getNumCurrentlyModalComponents() == 0
  205525. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205526. return false;
  205527. switch (m.message)
  205528. {
  205529. case WM_MOUSEMOVE:
  205530. case WM_NCMOUSEMOVE:
  205531. case 0x020A: /* WM_MOUSEWHEEL */
  205532. case 0x020E: /* WM_MOUSEHWHEEL */
  205533. case WM_KEYUP:
  205534. case WM_SYSKEYUP:
  205535. case WM_CHAR:
  205536. case WM_APPCOMMAND:
  205537. case WM_LBUTTONUP:
  205538. case WM_MBUTTONUP:
  205539. case WM_RBUTTONUP:
  205540. case WM_MOUSEACTIVATE:
  205541. case WM_NCMOUSEHOVER:
  205542. case WM_MOUSEHOVER:
  205543. return true;
  205544. case WM_NCLBUTTONDOWN:
  205545. case WM_NCLBUTTONDBLCLK:
  205546. case WM_NCRBUTTONDOWN:
  205547. case WM_NCRBUTTONDBLCLK:
  205548. case WM_NCMBUTTONDOWN:
  205549. case WM_NCMBUTTONDBLCLK:
  205550. case WM_LBUTTONDOWN:
  205551. case WM_LBUTTONDBLCLK:
  205552. case WM_MBUTTONDOWN:
  205553. case WM_MBUTTONDBLCLK:
  205554. case WM_RBUTTONDOWN:
  205555. case WM_RBUTTONDBLCLK:
  205556. case WM_KEYDOWN:
  205557. case WM_SYSKEYDOWN:
  205558. {
  205559. Component* const modal = Component::getCurrentlyModalComponent (0);
  205560. if (modal != 0)
  205561. modal->inputAttemptWhenModal();
  205562. return true;
  205563. }
  205564. default:
  205565. break;
  205566. }
  205567. return false;
  205568. }
  205569. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205570. {
  205571. MSG m;
  205572. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205573. return false;
  205574. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205575. {
  205576. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205577. {
  205578. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205579. MessageManager::getInstance()->deliverMessage (message);
  205580. message->decReferenceCount();
  205581. }
  205582. else if (m.message == WM_QUIT)
  205583. {
  205584. if (JUCEApplication::getInstance() != 0)
  205585. JUCEApplication::getInstance()->systemRequestedQuit();
  205586. }
  205587. else if (! isEventBlockedByModalComps (m))
  205588. {
  205589. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205590. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205591. {
  205592. // if it's someone else's window being clicked on, and the focus is
  205593. // currently on a juce window, pass the kb focus over..
  205594. HWND currentFocus = GetFocus();
  205595. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205596. SetFocus (m.hwnd);
  205597. }
  205598. TranslateMessage (&m);
  205599. DispatchMessage (&m);
  205600. }
  205601. }
  205602. return true;
  205603. }
  205604. bool juce_postMessageToSystemQueue (Message* message)
  205605. {
  205606. message->incReferenceCount();
  205607. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205608. }
  205609. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205610. void* userData)
  205611. {
  205612. if (MessageManager::getInstance()->isThisTheMessageThread())
  205613. {
  205614. return (*callback) (userData);
  205615. }
  205616. else
  205617. {
  205618. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205619. // deadlock because the message manager is blocked from running, and can't
  205620. // call your function..
  205621. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205622. return (void*) SendMessage (juce_messageWindowHandle,
  205623. specialCallbackId,
  205624. (WPARAM) callback,
  205625. (LPARAM) userData);
  205626. }
  205627. }
  205628. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205629. {
  205630. if (hwnd != juce_messageWindowHandle)
  205631. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205632. return TRUE;
  205633. }
  205634. void MessageManager::broadcastMessage (const String& value)
  205635. {
  205636. Array<void*> windows;
  205637. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205638. const String localCopy (value);
  205639. COPYDATASTRUCT data;
  205640. data.dwData = broadcastId;
  205641. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205642. data.lpData = (void*) localCopy.toUTF16().getAddress();
  205643. for (int i = windows.size(); --i >= 0;)
  205644. {
  205645. HWND hwnd = (HWND) windows.getUnchecked(i);
  205646. TCHAR windowName [64]; // no need to read longer strings than this
  205647. GetWindowText (hwnd, windowName, 64);
  205648. windowName [63] = 0;
  205649. if (String (windowName) == messageWindowName)
  205650. {
  205651. DWORD_PTR result;
  205652. SendMessageTimeout (hwnd, WM_COPYDATA,
  205653. (WPARAM) juce_messageWindowHandle,
  205654. (LPARAM) &data,
  205655. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205656. 8000,
  205657. &result);
  205658. }
  205659. }
  205660. }
  205661. static const String getMessageWindowClassName()
  205662. {
  205663. // this name has to be different for each app/dll instance because otherwise
  205664. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205665. // window class).
  205666. static int number = 0;
  205667. if (number == 0)
  205668. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205669. return "JUCEcs_" + String (number);
  205670. }
  205671. void MessageManager::doPlatformSpecificInitialisation()
  205672. {
  205673. OleInitialize (0);
  205674. const String className (getMessageWindowClassName());
  205675. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205676. WNDCLASSEX wc;
  205677. zerostruct (wc);
  205678. wc.cbSize = sizeof (wc);
  205679. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205680. wc.cbWndExtra = 4;
  205681. wc.hInstance = hmod;
  205682. wc.lpszClassName = className.toUTF16();
  205683. RegisterClassEx (&wc);
  205684. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205685. messageWindowName,
  205686. 0, 0, 0, 0, 0, 0, 0,
  205687. hmod, 0);
  205688. }
  205689. void MessageManager::doPlatformSpecificShutdown()
  205690. {
  205691. DestroyWindow (juce_messageWindowHandle);
  205692. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205693. OleUninitialize();
  205694. }
  205695. #endif
  205696. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205697. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205698. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205699. // compiled on its own).
  205700. #if JUCE_INCLUDED_FILE
  205701. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205702. NEWTEXTMETRICEXW*,
  205703. int type,
  205704. LPARAM lParam)
  205705. {
  205706. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205707. {
  205708. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205709. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205710. }
  205711. return 1;
  205712. }
  205713. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205714. NEWTEXTMETRICEXW*,
  205715. int type,
  205716. LPARAM lParam)
  205717. {
  205718. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205719. {
  205720. LOGFONTW lf;
  205721. zerostruct (lf);
  205722. lf.lfWeight = FW_DONTCARE;
  205723. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205724. lf.lfQuality = DEFAULT_QUALITY;
  205725. lf.lfCharSet = DEFAULT_CHARSET;
  205726. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205727. lf.lfPitchAndFamily = FF_DONTCARE;
  205728. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205729. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205730. HDC dc = CreateCompatibleDC (0);
  205731. EnumFontFamiliesEx (dc, &lf,
  205732. (FONTENUMPROCW) &wfontEnum2,
  205733. lParam, 0);
  205734. DeleteDC (dc);
  205735. }
  205736. return 1;
  205737. }
  205738. const StringArray Font::findAllTypefaceNames()
  205739. {
  205740. StringArray results;
  205741. HDC dc = CreateCompatibleDC (0);
  205742. {
  205743. LOGFONTW lf;
  205744. zerostruct (lf);
  205745. lf.lfWeight = FW_DONTCARE;
  205746. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205747. lf.lfQuality = DEFAULT_QUALITY;
  205748. lf.lfCharSet = DEFAULT_CHARSET;
  205749. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205750. lf.lfPitchAndFamily = FF_DONTCARE;
  205751. lf.lfFaceName[0] = 0;
  205752. EnumFontFamiliesEx (dc, &lf,
  205753. (FONTENUMPROCW) &wfontEnum1,
  205754. (LPARAM) &results, 0);
  205755. }
  205756. DeleteDC (dc);
  205757. results.sort (true);
  205758. return results;
  205759. }
  205760. extern bool juce_IsRunningInWine();
  205761. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205762. {
  205763. if (juce_IsRunningInWine())
  205764. {
  205765. // If we're running in Wine, then use fonts that might be available on Linux..
  205766. defaultSans = "Bitstream Vera Sans";
  205767. defaultSerif = "Bitstream Vera Serif";
  205768. defaultFixed = "Bitstream Vera Sans Mono";
  205769. }
  205770. else
  205771. {
  205772. defaultSans = "Verdana";
  205773. defaultSerif = "Times";
  205774. defaultFixed = "Lucida Console";
  205775. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205776. }
  205777. }
  205778. class FontDCHolder : private DeletedAtShutdown
  205779. {
  205780. public:
  205781. FontDCHolder()
  205782. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205783. bold (false), italic (false)
  205784. {
  205785. }
  205786. ~FontDCHolder()
  205787. {
  205788. deleteDCAndFont();
  205789. clearSingletonInstance();
  205790. }
  205791. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205792. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205793. {
  205794. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205795. {
  205796. fontName = fontName_;
  205797. bold = bold_;
  205798. italic = italic_;
  205799. size = size_;
  205800. deleteDCAndFont();
  205801. dc = CreateCompatibleDC (0);
  205802. SetMapperFlags (dc, 0);
  205803. SetMapMode (dc, MM_TEXT);
  205804. LOGFONTW lfw;
  205805. zerostruct (lfw);
  205806. lfw.lfCharSet = DEFAULT_CHARSET;
  205807. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205808. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205809. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205810. lfw.lfQuality = PROOF_QUALITY;
  205811. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205812. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205813. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205814. lfw.lfHeight = size > 0 ? size : -256;
  205815. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205816. if (standardSizedFont != 0)
  205817. {
  205818. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205819. {
  205820. fontH = standardSizedFont;
  205821. if (size == 0)
  205822. {
  205823. OUTLINETEXTMETRIC otm;
  205824. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205825. {
  205826. lfw.lfHeight = -(int) otm.otmEMSquare;
  205827. fontH = CreateFontIndirect (&lfw);
  205828. SelectObject (dc, fontH);
  205829. DeleteObject (standardSizedFont);
  205830. }
  205831. }
  205832. }
  205833. }
  205834. }
  205835. return dc;
  205836. }
  205837. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205838. {
  205839. if (kps == 0)
  205840. {
  205841. numKPs = GetKerningPairs (dc, 0, 0);
  205842. kps.calloc (numKPs);
  205843. GetKerningPairs (dc, numKPs, kps);
  205844. }
  205845. numKPs_ = numKPs;
  205846. return kps;
  205847. }
  205848. private:
  205849. HFONT fontH;
  205850. HGDIOBJ previousFontH;
  205851. HDC dc;
  205852. String fontName;
  205853. HeapBlock <KERNINGPAIR> kps;
  205854. int numKPs, size;
  205855. bool bold, italic;
  205856. void deleteDCAndFont()
  205857. {
  205858. if (dc != 0)
  205859. {
  205860. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205861. DeleteDC (dc);
  205862. dc = 0;
  205863. }
  205864. if (fontH != 0)
  205865. {
  205866. DeleteObject (fontH);
  205867. fontH = 0;
  205868. }
  205869. kps.free();
  205870. }
  205871. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205872. };
  205873. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205874. class WindowsTypeface : public CustomTypeface
  205875. {
  205876. public:
  205877. WindowsTypeface (const Font& font)
  205878. {
  205879. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205880. font.isBold(), font.isItalic(), 0);
  205881. TEXTMETRIC tm;
  205882. tm.tmAscent = tm.tmHeight = 1;
  205883. tm.tmDefaultChar = 0;
  205884. GetTextMetrics (dc, &tm);
  205885. setCharacteristics (font.getTypefaceName(),
  205886. tm.tmAscent / (float) tm.tmHeight,
  205887. font.isBold(), font.isItalic(),
  205888. tm.tmDefaultChar);
  205889. }
  205890. bool loadGlyphIfPossible (juce_wchar character)
  205891. {
  205892. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205893. GLYPHMETRICS gm;
  205894. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205895. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205896. // gets correctly created later on.
  205897. if (! isFallbackFont)
  205898. {
  205899. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205900. WORD index = 0;
  205901. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205902. && index == 0xffff)
  205903. {
  205904. return false;
  205905. }
  205906. }
  205907. Path glyphPath;
  205908. TEXTMETRIC tm;
  205909. if (! GetTextMetrics (dc, &tm))
  205910. {
  205911. addGlyph (character, glyphPath, 0);
  205912. return true;
  205913. }
  205914. const float height = (float) tm.tmHeight;
  205915. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205916. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205917. &gm, 0, 0, &identityMatrix);
  205918. if (bufSize > 0)
  205919. {
  205920. HeapBlock<char> data (bufSize);
  205921. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205922. bufSize, data, &identityMatrix);
  205923. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205924. const float scaleX = 1.0f / height;
  205925. const float scaleY = -1.0f / height;
  205926. while ((char*) pheader < data + bufSize)
  205927. {
  205928. float x = scaleX * pheader->pfxStart.x.value;
  205929. float y = scaleY * pheader->pfxStart.y.value;
  205930. glyphPath.startNewSubPath (x, y);
  205931. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205932. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205933. while ((const char*) curve < curveEnd)
  205934. {
  205935. if (curve->wType == TT_PRIM_LINE)
  205936. {
  205937. for (int i = 0; i < curve->cpfx; ++i)
  205938. {
  205939. x = scaleX * curve->apfx[i].x.value;
  205940. y = scaleY * curve->apfx[i].y.value;
  205941. glyphPath.lineTo (x, y);
  205942. }
  205943. }
  205944. else if (curve->wType == TT_PRIM_QSPLINE)
  205945. {
  205946. for (int i = 0; i < curve->cpfx - 1; ++i)
  205947. {
  205948. const float x2 = scaleX * curve->apfx[i].x.value;
  205949. const float y2 = scaleY * curve->apfx[i].y.value;
  205950. float x3, y3;
  205951. if (i < curve->cpfx - 2)
  205952. {
  205953. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205954. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205955. }
  205956. else
  205957. {
  205958. x3 = scaleX * curve->apfx[i + 1].x.value;
  205959. y3 = scaleY * curve->apfx[i + 1].y.value;
  205960. }
  205961. glyphPath.quadraticTo (x2, y2, x3, y3);
  205962. x = x3;
  205963. y = y3;
  205964. }
  205965. }
  205966. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205967. }
  205968. pheader = (const TTPOLYGONHEADER*) curve;
  205969. glyphPath.closeSubPath();
  205970. }
  205971. }
  205972. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205973. int numKPs;
  205974. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205975. for (int i = 0; i < numKPs; ++i)
  205976. {
  205977. if (kps[i].wFirst == character)
  205978. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205979. kps[i].iKernAmount / height);
  205980. }
  205981. return true;
  205982. }
  205983. private:
  205984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205985. };
  205986. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205987. {
  205988. return new WindowsTypeface (font);
  205989. }
  205990. #endif
  205991. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205992. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205993. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205994. // compiled on its own).
  205995. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205996. class SharedD2DFactory : public DeletedAtShutdown
  205997. {
  205998. public:
  205999. SharedD2DFactory()
  206000. {
  206001. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  206002. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  206003. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  206004. if (directWriteFactory != 0)
  206005. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  206006. }
  206007. ~SharedD2DFactory()
  206008. {
  206009. clearSingletonInstance();
  206010. }
  206011. juce_DeclareSingleton (SharedD2DFactory, false);
  206012. ComSmartPtr <ID2D1Factory> d2dFactory;
  206013. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206014. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206015. };
  206016. juce_ImplementSingleton (SharedD2DFactory)
  206017. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206018. {
  206019. public:
  206020. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206021. : hwnd (hwnd_),
  206022. currentState (0)
  206023. {
  206024. RECT windowRect;
  206025. GetClientRect (hwnd, &windowRect);
  206026. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206027. bounds.setSize (size.width, size.height);
  206028. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206029. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206030. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  206031. // xxx check for error
  206032. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  206033. }
  206034. ~Direct2DLowLevelGraphicsContext()
  206035. {
  206036. states.clear();
  206037. }
  206038. void resized()
  206039. {
  206040. RECT windowRect;
  206041. GetClientRect (hwnd, &windowRect);
  206042. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206043. renderingTarget->Resize (size);
  206044. bounds.setSize (size.width, size.height);
  206045. }
  206046. void clear()
  206047. {
  206048. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206049. }
  206050. void start()
  206051. {
  206052. renderingTarget->BeginDraw();
  206053. saveState();
  206054. }
  206055. void end()
  206056. {
  206057. states.clear();
  206058. currentState = 0;
  206059. renderingTarget->EndDraw();
  206060. renderingTarget->CheckWindowState();
  206061. }
  206062. bool isVectorDevice() const { return false; }
  206063. void setOrigin (int x, int y)
  206064. {
  206065. currentState->origin.addXY (x, y);
  206066. }
  206067. void addTransform (const AffineTransform& transform)
  206068. {
  206069. //xxx todo
  206070. jassertfalse;
  206071. }
  206072. float getScaleFactor()
  206073. {
  206074. jassertfalse; //xxx
  206075. return 1.0f;
  206076. }
  206077. bool clipToRectangle (const Rectangle<int>& r)
  206078. {
  206079. currentState->clipToRectangle (r);
  206080. return ! isClipEmpty();
  206081. }
  206082. bool clipToRectangleList (const RectangleList& clipRegion)
  206083. {
  206084. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206085. return ! isClipEmpty();
  206086. }
  206087. void excludeClipRectangle (const Rectangle<int>&)
  206088. {
  206089. //xxx
  206090. }
  206091. void clipToPath (const Path& path, const AffineTransform& transform)
  206092. {
  206093. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206094. }
  206095. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206096. {
  206097. currentState->clipToImage (sourceImage,transform);
  206098. }
  206099. bool clipRegionIntersects (const Rectangle<int>& r)
  206100. {
  206101. const Rectangle<int> r2 (r + currentState->origin);
  206102. return currentState->clipRect.intersects (r2);
  206103. }
  206104. const Rectangle<int> getClipBounds() const
  206105. {
  206106. // xxx could this take into account complex clip regions?
  206107. return currentState->clipRect - currentState->origin;
  206108. }
  206109. bool isClipEmpty() const
  206110. {
  206111. return currentState->clipRect.isEmpty();
  206112. }
  206113. void saveState()
  206114. {
  206115. states.add (new SavedState (*this));
  206116. currentState = states.getLast();
  206117. }
  206118. void restoreState()
  206119. {
  206120. jassert (states.size() > 1) //you should never pop the last state!
  206121. states.removeLast (1);
  206122. currentState = states.getLast();
  206123. }
  206124. void beginTransparencyLayer (float opacity)
  206125. {
  206126. jassertfalse; //xxx todo
  206127. }
  206128. void endTransparencyLayer()
  206129. {
  206130. jassertfalse; //xxx todo
  206131. }
  206132. void setFill (const FillType& fillType)
  206133. {
  206134. currentState->setFill (fillType);
  206135. }
  206136. void setOpacity (float newOpacity)
  206137. {
  206138. currentState->setOpacity (newOpacity);
  206139. }
  206140. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206141. {
  206142. }
  206143. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206144. {
  206145. currentState->createBrush();
  206146. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206147. }
  206148. void fillPath (const Path& p, const AffineTransform& transform)
  206149. {
  206150. currentState->createBrush();
  206151. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206152. if (renderingTarget != 0)
  206153. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206154. }
  206155. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206156. {
  206157. const int x = currentState->origin.getX();
  206158. const int y = currentState->origin.getY();
  206159. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206160. D2D1_SIZE_U size;
  206161. size.width = image.getWidth();
  206162. size.height = image.getHeight();
  206163. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206164. Image img (image.convertedToFormat (Image::ARGB));
  206165. Image::BitmapData bd (img, Image::BitmapData::readOnly);
  206166. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206167. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206168. {
  206169. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206170. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  206171. if (tempBitmap != 0)
  206172. renderingTarget->DrawBitmap (tempBitmap);
  206173. }
  206174. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206175. }
  206176. void drawLine (const Line <float>& line)
  206177. {
  206178. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206179. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206180. line.getEnd() + currentState->origin.toFloat());
  206181. currentState->createBrush();
  206182. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206183. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206184. currentState->currentBrush);
  206185. }
  206186. void drawVerticalLine (int x, float top, float bottom)
  206187. {
  206188. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206189. currentState->createBrush();
  206190. x += currentState->origin.getX();
  206191. const int y = currentState->origin.getY();
  206192. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206193. D2D1::Point2F (x, y + bottom),
  206194. currentState->currentBrush);
  206195. }
  206196. void drawHorizontalLine (int y, float left, float right)
  206197. {
  206198. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206199. currentState->createBrush();
  206200. y += currentState->origin.getY();
  206201. const int x = currentState->origin.getX();
  206202. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206203. D2D1::Point2F (x + right, y),
  206204. currentState->currentBrush);
  206205. }
  206206. void setFont (const Font& newFont)
  206207. {
  206208. currentState->setFont (newFont);
  206209. }
  206210. const Font getFont()
  206211. {
  206212. return currentState->font;
  206213. }
  206214. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206215. {
  206216. const float x = currentState->origin.getX();
  206217. const float y = currentState->origin.getY();
  206218. currentState->createBrush();
  206219. currentState->createFont();
  206220. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206221. float hScale = currentState->font.getHorizontalScale();
  206222. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206223. float dpiX = 0, dpiY = 0;
  206224. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206225. UINT32 glyphNum = glyphNumber;
  206226. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206227. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206228. DWRITE_GLYPH_OFFSET offset;
  206229. offset.advanceOffset = 0;
  206230. offset.ascenderOffset = 0;
  206231. float glyphAdvances = 0;
  206232. DWRITE_GLYPH_RUN glyph;
  206233. glyph.fontFace = currentState->currentFontFace;
  206234. glyph.glyphCount = 1;
  206235. glyph.glyphIndices = &glyphNum1;
  206236. glyph.isSideways = FALSE;
  206237. glyph.glyphAdvances = &glyphAdvances;
  206238. glyph.glyphOffsets = &offset;
  206239. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206240. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206241. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206242. }
  206243. class SavedState
  206244. {
  206245. public:
  206246. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206247. : owner (owner_), currentBrush (0),
  206248. fontScaling (1.0f), currentFontFace (0),
  206249. clipsRect (false), shouldClipRect (false),
  206250. clipsRectList (false), shouldClipRectList (false),
  206251. clipsComplex (false), shouldClipComplex (false),
  206252. clipsBitmap (false), shouldClipBitmap (false)
  206253. {
  206254. if (owner.currentState != 0)
  206255. {
  206256. // xxx seems like a very slow way to create one of these, and this is a performance
  206257. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206258. setFill (owner.currentState->fillType);
  206259. currentBrush = owner.currentState->currentBrush;
  206260. origin = owner.currentState->origin;
  206261. clipRect = owner.currentState->clipRect;
  206262. font = owner.currentState->font;
  206263. currentFontFace = owner.currentState->currentFontFace;
  206264. }
  206265. else
  206266. {
  206267. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206268. clipRect.setSize (size.width, size.height);
  206269. setFill (FillType (Colours::black));
  206270. }
  206271. }
  206272. ~SavedState()
  206273. {
  206274. clearClip();
  206275. clearFont();
  206276. clearFill();
  206277. clearPathClip();
  206278. clearImageClip();
  206279. complexClipLayer = 0;
  206280. bitmapMaskLayer = 0;
  206281. }
  206282. void clearClip()
  206283. {
  206284. popClips();
  206285. shouldClipRect = false;
  206286. }
  206287. void clipToRectangle (const Rectangle<int>& r)
  206288. {
  206289. clearClip();
  206290. clipRect = r + origin;
  206291. shouldClipRect = true;
  206292. pushClips();
  206293. }
  206294. void clearPathClip()
  206295. {
  206296. popClips();
  206297. if (shouldClipComplex)
  206298. {
  206299. complexClipGeometry = 0;
  206300. shouldClipComplex = false;
  206301. }
  206302. }
  206303. void clipToPath (ID2D1Geometry* geometry)
  206304. {
  206305. clearPathClip();
  206306. if (complexClipLayer == 0)
  206307. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  206308. complexClipGeometry = geometry;
  206309. shouldClipComplex = true;
  206310. pushClips();
  206311. }
  206312. void clearRectListClip()
  206313. {
  206314. popClips();
  206315. if (shouldClipRectList)
  206316. {
  206317. rectListGeometry = 0;
  206318. shouldClipRectList = false;
  206319. }
  206320. }
  206321. void clipToRectList (ID2D1Geometry* geometry)
  206322. {
  206323. clearRectListClip();
  206324. if (rectListLayer == 0)
  206325. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  206326. rectListGeometry = geometry;
  206327. shouldClipRectList = true;
  206328. pushClips();
  206329. }
  206330. void clearImageClip()
  206331. {
  206332. popClips();
  206333. if (shouldClipBitmap)
  206334. {
  206335. maskBitmap = 0;
  206336. bitmapMaskBrush = 0;
  206337. shouldClipBitmap = false;
  206338. }
  206339. }
  206340. void clipToImage (const Image& image, const AffineTransform& transform)
  206341. {
  206342. clearImageClip();
  206343. if (bitmapMaskLayer == 0)
  206344. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  206345. D2D1_BRUSH_PROPERTIES brushProps;
  206346. brushProps.opacity = 1;
  206347. brushProps.transform = transformToMatrix (transform);
  206348. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206349. D2D1_SIZE_U size;
  206350. size.width = image.getWidth();
  206351. size.height = image.getHeight();
  206352. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206353. maskImage = image.convertedToFormat (Image::ARGB);
  206354. Image::BitmapData bd (this->image, Image::BitmapData::readOnly); // xxx should be maskImage?
  206355. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206356. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206357. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  206358. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  206359. imageMaskLayerParams = D2D1::LayerParameters();
  206360. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206361. shouldClipBitmap = true;
  206362. pushClips();
  206363. }
  206364. void popClips()
  206365. {
  206366. if (clipsBitmap)
  206367. {
  206368. owner.renderingTarget->PopLayer();
  206369. clipsBitmap = false;
  206370. }
  206371. if (clipsComplex)
  206372. {
  206373. owner.renderingTarget->PopLayer();
  206374. clipsComplex = false;
  206375. }
  206376. if (clipsRectList)
  206377. {
  206378. owner.renderingTarget->PopLayer();
  206379. clipsRectList = false;
  206380. }
  206381. if (clipsRect)
  206382. {
  206383. owner.renderingTarget->PopAxisAlignedClip();
  206384. clipsRect = false;
  206385. }
  206386. }
  206387. void pushClips()
  206388. {
  206389. if (shouldClipRect && ! clipsRect)
  206390. {
  206391. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206392. clipsRect = true;
  206393. }
  206394. if (shouldClipRectList && ! clipsRectList)
  206395. {
  206396. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206397. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206398. layerParams.geometricMask = rectListGeometry;
  206399. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206400. clipsRectList = true;
  206401. }
  206402. if (shouldClipComplex && ! clipsComplex)
  206403. {
  206404. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206405. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206406. layerParams.geometricMask = complexClipGeometry;
  206407. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206408. clipsComplex = true;
  206409. }
  206410. if (shouldClipBitmap && ! clipsBitmap)
  206411. {
  206412. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206413. clipsBitmap = true;
  206414. }
  206415. }
  206416. void setFill (const FillType& newFillType)
  206417. {
  206418. if (fillType != newFillType)
  206419. {
  206420. fillType = newFillType;
  206421. clearFill();
  206422. }
  206423. }
  206424. void clearFont()
  206425. {
  206426. currentFontFace = localFontFace = 0;
  206427. }
  206428. void setFont (const Font& newFont)
  206429. {
  206430. if (font != newFont)
  206431. {
  206432. font = newFont;
  206433. clearFont();
  206434. }
  206435. }
  206436. void createFont()
  206437. {
  206438. // xxx The font shouldn't be managed by the graphics context.
  206439. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206440. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206441. // WindowsTypeface class.
  206442. if (currentFontFace == 0)
  206443. {
  206444. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206445. fontScaling = systemType->getAscent();
  206446. BOOL fontFound;
  206447. uint32 fontIndex;
  206448. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206449. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206450. if (! fontFound)
  206451. fontIndex = 0;
  206452. ComSmartPtr <IDWriteFontFamily> fontFam;
  206453. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  206454. ComSmartPtr <IDWriteFont> font;
  206455. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206456. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206457. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  206458. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  206459. currentFontFace = localFontFace;
  206460. }
  206461. }
  206462. void setOpacity (float newOpacity)
  206463. {
  206464. fillType.setOpacity (newOpacity);
  206465. if (currentBrush != 0)
  206466. currentBrush->SetOpacity (newOpacity);
  206467. }
  206468. void clearFill()
  206469. {
  206470. gradientStops = 0;
  206471. linearGradient = 0;
  206472. radialGradient = 0;
  206473. bitmap = 0;
  206474. bitmapBrush = 0;
  206475. currentBrush = 0;
  206476. }
  206477. void createBrush()
  206478. {
  206479. if (currentBrush == 0)
  206480. {
  206481. const int x = origin.getX();
  206482. const int y = origin.getY();
  206483. if (fillType.isColour())
  206484. {
  206485. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206486. owner.colourBrush->SetColor (colour);
  206487. currentBrush = owner.colourBrush;
  206488. }
  206489. else if (fillType.isTiledImage())
  206490. {
  206491. D2D1_BRUSH_PROPERTIES brushProps;
  206492. brushProps.opacity = fillType.getOpacity();
  206493. brushProps.transform = transformToMatrix (fillType.transform);
  206494. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206495. image = fillType.image;
  206496. D2D1_SIZE_U size;
  206497. size.width = image.getWidth();
  206498. size.height = image.getHeight();
  206499. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206500. this->image = image.convertedToFormat (Image::ARGB);
  206501. Image::BitmapData bd (this->image, Image::BitmapData::readOnly);
  206502. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206503. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206504. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  206505. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  206506. currentBrush = bitmapBrush;
  206507. }
  206508. else if (fillType.isGradient())
  206509. {
  206510. gradientStops = 0;
  206511. D2D1_BRUSH_PROPERTIES brushProps;
  206512. brushProps.opacity = fillType.getOpacity();
  206513. brushProps.transform = transformToMatrix (fillType.transform);
  206514. const int numColors = fillType.gradient->getNumColours();
  206515. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206516. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206517. {
  206518. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206519. stops[i].position = fillType.gradient->getColourPosition(i);
  206520. }
  206521. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  206522. if (fillType.gradient->isRadial)
  206523. {
  206524. radialGradient = 0;
  206525. const Point<float>& p1 = fillType.gradient->point1;
  206526. const Point<float>& p2 = fillType.gradient->point2;
  206527. float r = p1.getDistanceFrom (p2);
  206528. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206529. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206530. D2D1::Point2F (0, 0),
  206531. r, r);
  206532. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  206533. currentBrush = radialGradient;
  206534. }
  206535. else
  206536. {
  206537. linearGradient = 0;
  206538. const Point<float>& p1 = fillType.gradient->point1;
  206539. const Point<float>& p2 = fillType.gradient->point2;
  206540. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206541. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206542. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206543. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  206544. currentBrush = linearGradient;
  206545. }
  206546. }
  206547. }
  206548. }
  206549. //xxx most of these members should probably be private...
  206550. Direct2DLowLevelGraphicsContext& owner;
  206551. Point<int> origin;
  206552. Font font;
  206553. float fontScaling;
  206554. IDWriteFontFace* currentFontFace;
  206555. ComSmartPtr <IDWriteFontFace> localFontFace;
  206556. FillType fillType;
  206557. Image image;
  206558. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206559. Rectangle<int> clipRect;
  206560. bool clipsRect, shouldClipRect;
  206561. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206562. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206563. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206564. bool clipsComplex, shouldClipComplex;
  206565. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206566. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206567. ComSmartPtr <ID2D1Layer> rectListLayer;
  206568. bool clipsRectList, shouldClipRectList;
  206569. Image maskImage;
  206570. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206571. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206572. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206573. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206574. bool clipsBitmap, shouldClipBitmap;
  206575. ID2D1Brush* currentBrush;
  206576. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206577. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206578. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206579. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206580. private:
  206581. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206582. };
  206583. private:
  206584. HWND hwnd;
  206585. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206586. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206587. Rectangle<int> bounds;
  206588. SavedState* currentState;
  206589. OwnedArray<SavedState> states;
  206590. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206591. {
  206592. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206593. }
  206594. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206595. {
  206596. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206597. }
  206598. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206599. {
  206600. transform.transformPoint (x, y);
  206601. return D2D1::Point2F (x, y);
  206602. }
  206603. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206604. {
  206605. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206606. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206607. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206608. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206609. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206610. }
  206611. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206612. {
  206613. ID2D1PathGeometry* p = 0;
  206614. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206615. ComSmartPtr <ID2D1GeometrySink> sink;
  206616. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206617. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206618. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206619. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206620. hr = sink->Close();
  206621. return p;
  206622. }
  206623. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206624. {
  206625. Path::Iterator it (path);
  206626. while (it.next())
  206627. {
  206628. switch (it.elementType)
  206629. {
  206630. case Path::Iterator::cubicTo:
  206631. {
  206632. D2D1_BEZIER_SEGMENT seg;
  206633. transform.transformPoint (it.x1, it.y1);
  206634. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206635. transform.transformPoint (it.x2, it.y2);
  206636. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206637. transform.transformPoint(it.x3, it.y3);
  206638. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206639. sink->AddBezier (seg);
  206640. break;
  206641. }
  206642. case Path::Iterator::lineTo:
  206643. {
  206644. transform.transformPoint (it.x1, it.y1);
  206645. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206646. break;
  206647. }
  206648. case Path::Iterator::quadraticTo:
  206649. {
  206650. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206651. transform.transformPoint (it.x1, it.y1);
  206652. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206653. transform.transformPoint (it.x2, it.y2);
  206654. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206655. sink->AddQuadraticBezier (seg);
  206656. break;
  206657. }
  206658. case Path::Iterator::closePath:
  206659. {
  206660. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206661. break;
  206662. }
  206663. case Path::Iterator::startNewSubPath:
  206664. {
  206665. transform.transformPoint (it.x1, it.y1);
  206666. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206667. break;
  206668. }
  206669. }
  206670. }
  206671. }
  206672. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206673. {
  206674. ID2D1PathGeometry* p = 0;
  206675. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206676. ComSmartPtr <ID2D1GeometrySink> sink;
  206677. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206678. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206679. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206680. hr = sink->Close();
  206681. return p;
  206682. }
  206683. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206684. {
  206685. D2D1::Matrix3x2F matrix;
  206686. matrix._11 = transform.mat00;
  206687. matrix._12 = transform.mat10;
  206688. matrix._21 = transform.mat01;
  206689. matrix._22 = transform.mat11;
  206690. matrix._31 = transform.mat02;
  206691. matrix._32 = transform.mat12;
  206692. return matrix;
  206693. }
  206694. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206695. };
  206696. #endif
  206697. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206698. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206699. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206700. // compiled on its own).
  206701. #if JUCE_INCLUDED_FILE
  206702. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206703. // these are in the windows SDK, but need to be repeated here for GCC..
  206704. #ifndef GET_APPCOMMAND_LPARAM
  206705. #define FAPPCOMMAND_MASK 0xF000
  206706. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206707. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206708. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206709. #define APPCOMMAND_MEDIA_STOP 13
  206710. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206711. #define WM_APPCOMMAND 0x0319
  206712. #endif
  206713. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206714. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206715. extern bool juce_IsRunningInWine();
  206716. #ifndef ULW_ALPHA
  206717. #define ULW_ALPHA 0x00000002
  206718. #endif
  206719. #ifndef AC_SRC_ALPHA
  206720. #define AC_SRC_ALPHA 0x01
  206721. #endif
  206722. static bool shouldDeactivateTitleBar = true;
  206723. #define WM_TRAYNOTIFY WM_USER + 100
  206724. using ::abs;
  206725. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206726. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206727. bool Desktop::canUseSemiTransparentWindows() throw()
  206728. {
  206729. if (updateLayeredWindow == 0)
  206730. {
  206731. if (! juce_IsRunningInWine())
  206732. {
  206733. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206734. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206735. }
  206736. }
  206737. return updateLayeredWindow != 0;
  206738. }
  206739. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206740. {
  206741. return upright;
  206742. }
  206743. const int extendedKeyModifier = 0x10000;
  206744. const int KeyPress::spaceKey = VK_SPACE;
  206745. const int KeyPress::returnKey = VK_RETURN;
  206746. const int KeyPress::escapeKey = VK_ESCAPE;
  206747. const int KeyPress::backspaceKey = VK_BACK;
  206748. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206749. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206750. const int KeyPress::tabKey = VK_TAB;
  206751. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206752. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206753. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206754. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206755. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206756. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206757. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206758. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206759. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206760. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206761. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206762. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206763. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206764. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206765. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206766. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206767. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206768. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206769. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206770. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206771. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206772. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206773. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206774. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206775. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206776. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206777. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206778. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206779. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206780. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206781. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206782. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206783. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206784. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206785. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206786. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206787. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206788. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206789. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206790. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206791. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206792. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206793. const int KeyPress::playKey = 0x30000;
  206794. const int KeyPress::stopKey = 0x30001;
  206795. const int KeyPress::fastForwardKey = 0x30002;
  206796. const int KeyPress::rewindKey = 0x30003;
  206797. class WindowsBitmapImage : public Image::SharedImage
  206798. {
  206799. public:
  206800. WindowsBitmapImage (const Image::PixelFormat format_,
  206801. const int w, const int h, const bool clearImage)
  206802. : Image::SharedImage (format_, w, h)
  206803. {
  206804. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206805. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206806. lineStride = -((w * pixelStride + 3) & ~3);
  206807. zerostruct (bitmapInfo);
  206808. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206809. bitmapInfo.bV4Width = w;
  206810. bitmapInfo.bV4Height = h;
  206811. bitmapInfo.bV4Planes = 1;
  206812. bitmapInfo.bV4CSType = 1;
  206813. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206814. if (format_ == Image::ARGB)
  206815. {
  206816. bitmapInfo.bV4AlphaMask = 0xff000000;
  206817. bitmapInfo.bV4RedMask = 0xff0000;
  206818. bitmapInfo.bV4GreenMask = 0xff00;
  206819. bitmapInfo.bV4BlueMask = 0xff;
  206820. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206821. }
  206822. else
  206823. {
  206824. bitmapInfo.bV4V4Compression = BI_RGB;
  206825. }
  206826. HDC dc = GetDC (0);
  206827. hdc = CreateCompatibleDC (dc);
  206828. ReleaseDC (0, dc);
  206829. SetMapMode (hdc, MM_TEXT);
  206830. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  206831. (void**) &bitmapData, 0, 0);
  206832. previousBitmap = SelectObject (hdc, hBitmap);
  206833. if (format_ == Image::ARGB && clearImage)
  206834. zeromem (bitmapData, abs (h * lineStride));
  206835. imageData = bitmapData - (lineStride * (h - 1));
  206836. }
  206837. ~WindowsBitmapImage()
  206838. {
  206839. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206840. DeleteDC (hdc);
  206841. DeleteObject (hBitmap);
  206842. }
  206843. Image::ImageType getType() const { return Image::NativeImage; }
  206844. LowLevelGraphicsContext* createLowLevelContext()
  206845. {
  206846. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206847. }
  206848. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  206849. {
  206850. bitmap.data = imageData + x * pixelStride + y * lineStride;
  206851. bitmap.pixelFormat = format;
  206852. bitmap.lineStride = lineStride;
  206853. bitmap.pixelStride = pixelStride;
  206854. }
  206855. Image::SharedImage* clone()
  206856. {
  206857. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206858. for (int i = 0; i < height; ++i)
  206859. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206860. return im;
  206861. }
  206862. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206863. const int x, const int y,
  206864. const RectangleList& maskedRegion,
  206865. const uint8 updateLayeredWindowAlpha) throw()
  206866. {
  206867. static HDRAWDIB hdd = 0;
  206868. static bool needToCreateDrawDib = true;
  206869. if (needToCreateDrawDib)
  206870. {
  206871. needToCreateDrawDib = false;
  206872. HDC dc = GetDC (0);
  206873. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206874. ReleaseDC (0, dc);
  206875. // only open if we're not palettised
  206876. if (n > 8)
  206877. hdd = DrawDibOpen();
  206878. }
  206879. SetMapMode (dc, MM_TEXT);
  206880. if (transparent)
  206881. {
  206882. POINT p, pos;
  206883. SIZE size;
  206884. RECT windowBounds;
  206885. GetWindowRect (hwnd, &windowBounds);
  206886. p.x = -x;
  206887. p.y = -y;
  206888. pos.x = windowBounds.left;
  206889. pos.y = windowBounds.top;
  206890. size.cx = windowBounds.right - windowBounds.left;
  206891. size.cy = windowBounds.bottom - windowBounds.top;
  206892. BLENDFUNCTION bf;
  206893. bf.AlphaFormat = AC_SRC_ALPHA;
  206894. bf.BlendFlags = 0;
  206895. bf.BlendOp = AC_SRC_OVER;
  206896. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206897. if (! maskedRegion.isEmpty())
  206898. {
  206899. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206900. {
  206901. const Rectangle<int>& r = *i.getRectangle();
  206902. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206903. }
  206904. }
  206905. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206906. }
  206907. else
  206908. {
  206909. int savedDC = 0;
  206910. if (! maskedRegion.isEmpty())
  206911. {
  206912. savedDC = SaveDC (dc);
  206913. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206914. {
  206915. const Rectangle<int>& r = *i.getRectangle();
  206916. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206917. }
  206918. }
  206919. if (hdd == 0)
  206920. {
  206921. StretchDIBits (dc,
  206922. x, y, width, height,
  206923. 0, 0, width, height,
  206924. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206925. DIB_RGB_COLORS, SRCCOPY);
  206926. }
  206927. else
  206928. {
  206929. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206930. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206931. 0, 0, width, height, 0);
  206932. }
  206933. if (! maskedRegion.isEmpty())
  206934. RestoreDC (dc, savedDC);
  206935. }
  206936. }
  206937. HBITMAP hBitmap;
  206938. HGDIOBJ previousBitmap;
  206939. BITMAPV4HEADER bitmapInfo;
  206940. HDC hdc;
  206941. uint8* bitmapData;
  206942. int pixelStride, lineStride;
  206943. uint8* imageData;
  206944. private:
  206945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206946. };
  206947. namespace IconConverters
  206948. {
  206949. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206950. {
  206951. Image im;
  206952. if (bitmap != 0)
  206953. {
  206954. BITMAP bm;
  206955. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206956. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206957. {
  206958. HDC tempDC = GetDC (0);
  206959. HDC dc = CreateCompatibleDC (tempDC);
  206960. ReleaseDC (0, tempDC);
  206961. SelectObject (dc, bitmap);
  206962. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206963. Image::BitmapData imageData (im, Image::BitmapData::writeOnly);
  206964. for (int y = bm.bmHeight; --y >= 0;)
  206965. {
  206966. for (int x = bm.bmWidth; --x >= 0;)
  206967. {
  206968. COLORREF col = GetPixel (dc, x, y);
  206969. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206970. (uint8) GetGValue (col),
  206971. (uint8) GetBValue (col)));
  206972. }
  206973. }
  206974. DeleteDC (dc);
  206975. }
  206976. }
  206977. return im;
  206978. }
  206979. const Image createImageFromHICON (HICON icon)
  206980. {
  206981. ICONINFO info;
  206982. if (GetIconInfo (icon, &info))
  206983. {
  206984. Image mask (createImageFromHBITMAP (info.hbmMask));
  206985. Image image (createImageFromHBITMAP (info.hbmColor));
  206986. if (mask.isValid() && image.isValid())
  206987. {
  206988. for (int y = image.getHeight(); --y >= 0;)
  206989. {
  206990. for (int x = image.getWidth(); --x >= 0;)
  206991. {
  206992. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206993. if (brightness > 0.0f)
  206994. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206995. }
  206996. }
  206997. return image;
  206998. }
  206999. }
  207000. return Image::null;
  207001. }
  207002. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  207003. {
  207004. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207005. Image bitmap (nativeBitmap);
  207006. {
  207007. Graphics g (bitmap);
  207008. g.drawImageAt (image, 0, 0);
  207009. }
  207010. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207011. ICONINFO info;
  207012. info.fIcon = isIcon;
  207013. info.xHotspot = hotspotX;
  207014. info.yHotspot = hotspotY;
  207015. info.hbmMask = mask;
  207016. info.hbmColor = nativeBitmap->hBitmap;
  207017. HICON hi = CreateIconIndirect (&info);
  207018. DeleteObject (mask);
  207019. return hi;
  207020. }
  207021. }
  207022. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  207023. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  207024. {
  207025. SHORT k = (SHORT) keyCode;
  207026. if ((keyCode & extendedKeyModifier) == 0
  207027. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  207028. k += (SHORT) 'A' - (SHORT) 'a';
  207029. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  207030. (SHORT) '+', VK_OEM_PLUS,
  207031. (SHORT) '-', VK_OEM_MINUS,
  207032. (SHORT) '.', VK_OEM_PERIOD,
  207033. (SHORT) ';', VK_OEM_1,
  207034. (SHORT) ':', VK_OEM_1,
  207035. (SHORT) '/', VK_OEM_2,
  207036. (SHORT) '?', VK_OEM_2,
  207037. (SHORT) '[', VK_OEM_4,
  207038. (SHORT) ']', VK_OEM_6 };
  207039. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  207040. if (k == translatedValues [i])
  207041. k = translatedValues [i + 1];
  207042. return (GetKeyState (k) & 0x8000) != 0;
  207043. }
  207044. class Win32ComponentPeer : public ComponentPeer
  207045. {
  207046. public:
  207047. enum RenderingEngineType
  207048. {
  207049. softwareRenderingEngine = 0,
  207050. direct2DRenderingEngine
  207051. };
  207052. Win32ComponentPeer (Component* const component,
  207053. const int windowStyleFlags,
  207054. HWND parentToAddTo_)
  207055. : ComponentPeer (component, windowStyleFlags),
  207056. dontRepaint (false),
  207057. #if JUCE_DIRECT2D
  207058. currentRenderingEngine (direct2DRenderingEngine),
  207059. #else
  207060. currentRenderingEngine (softwareRenderingEngine),
  207061. #endif
  207062. fullScreen (false),
  207063. isDragging (false),
  207064. isMouseOver (false),
  207065. hasCreatedCaret (false),
  207066. constrainerIsResizing (false),
  207067. currentWindowIcon (0),
  207068. dropTarget (0),
  207069. parentToAddTo (parentToAddTo_),
  207070. updateLayeredWindowAlpha (255)
  207071. {
  207072. callFunctionIfNotLocked (&createWindowCallback, this);
  207073. setTitle (component->getName());
  207074. if ((windowStyleFlags & windowHasDropShadow) != 0
  207075. && Desktop::canUseSemiTransparentWindows())
  207076. {
  207077. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207078. if (shadower != 0)
  207079. shadower->setOwner (component);
  207080. }
  207081. }
  207082. ~Win32ComponentPeer()
  207083. {
  207084. setTaskBarIcon (Image());
  207085. shadower = 0;
  207086. // do this before the next bit to avoid messages arriving for this window
  207087. // before it's destroyed
  207088. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207089. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207090. if (currentWindowIcon != 0)
  207091. DestroyIcon (currentWindowIcon);
  207092. if (dropTarget != 0)
  207093. {
  207094. dropTarget->Release();
  207095. dropTarget = 0;
  207096. }
  207097. #if JUCE_DIRECT2D
  207098. direct2DContext = 0;
  207099. #endif
  207100. }
  207101. void* getNativeHandle() const
  207102. {
  207103. return hwnd;
  207104. }
  207105. void setVisible (bool shouldBeVisible)
  207106. {
  207107. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207108. if (shouldBeVisible)
  207109. InvalidateRect (hwnd, 0, 0);
  207110. else
  207111. lastPaintTime = 0;
  207112. }
  207113. void setTitle (const String& title)
  207114. {
  207115. SetWindowText (hwnd, title.toUTF16());
  207116. }
  207117. void setPosition (int x, int y)
  207118. {
  207119. offsetWithinParent (x, y);
  207120. SetWindowPos (hwnd, 0,
  207121. x - windowBorder.getLeft(),
  207122. y - windowBorder.getTop(),
  207123. 0, 0,
  207124. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207125. }
  207126. void repaintNowIfTransparent()
  207127. {
  207128. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207129. handlePaintMessage();
  207130. }
  207131. void updateBorderSize()
  207132. {
  207133. WINDOWINFO info;
  207134. info.cbSize = sizeof (info);
  207135. if (GetWindowInfo (hwnd, &info))
  207136. {
  207137. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  207138. info.rcClient.left - info.rcWindow.left,
  207139. info.rcWindow.bottom - info.rcClient.bottom,
  207140. info.rcWindow.right - info.rcClient.right);
  207141. }
  207142. #if JUCE_DIRECT2D
  207143. if (direct2DContext != 0)
  207144. direct2DContext->resized();
  207145. #endif
  207146. }
  207147. void setSize (int w, int h)
  207148. {
  207149. SetWindowPos (hwnd, 0, 0, 0,
  207150. w + windowBorder.getLeftAndRight(),
  207151. h + windowBorder.getTopAndBottom(),
  207152. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207153. updateBorderSize();
  207154. repaintNowIfTransparent();
  207155. }
  207156. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207157. {
  207158. fullScreen = isNowFullScreen;
  207159. offsetWithinParent (x, y);
  207160. SetWindowPos (hwnd, 0,
  207161. x - windowBorder.getLeft(),
  207162. y - windowBorder.getTop(),
  207163. w + windowBorder.getLeftAndRight(),
  207164. h + windowBorder.getTopAndBottom(),
  207165. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207166. updateBorderSize();
  207167. repaintNowIfTransparent();
  207168. }
  207169. const Rectangle<int> getBounds() const
  207170. {
  207171. RECT r;
  207172. GetWindowRect (hwnd, &r);
  207173. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207174. HWND parentH = GetParent (hwnd);
  207175. if (parentH != 0)
  207176. {
  207177. GetWindowRect (parentH, &r);
  207178. bounds.translate (-r.left, -r.top);
  207179. }
  207180. return windowBorder.subtractedFrom (bounds);
  207181. }
  207182. const Point<int> getScreenPosition() const
  207183. {
  207184. RECT r;
  207185. GetWindowRect (hwnd, &r);
  207186. return Point<int> (r.left + windowBorder.getLeft(),
  207187. r.top + windowBorder.getTop());
  207188. }
  207189. const Point<int> localToGlobal (const Point<int>& relativePosition)
  207190. {
  207191. return relativePosition + getScreenPosition();
  207192. }
  207193. const Point<int> globalToLocal (const Point<int>& screenPosition)
  207194. {
  207195. return screenPosition - getScreenPosition();
  207196. }
  207197. void setAlpha (float newAlpha)
  207198. {
  207199. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207200. if (component->isOpaque())
  207201. {
  207202. if (newAlpha < 1.0f)
  207203. {
  207204. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207205. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207206. }
  207207. else
  207208. {
  207209. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207210. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207211. }
  207212. }
  207213. else
  207214. {
  207215. updateLayeredWindowAlpha = intAlpha;
  207216. component->repaint();
  207217. }
  207218. }
  207219. void setMinimised (bool shouldBeMinimised)
  207220. {
  207221. if (shouldBeMinimised != isMinimised())
  207222. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207223. }
  207224. bool isMinimised() const
  207225. {
  207226. WINDOWPLACEMENT wp;
  207227. wp.length = sizeof (WINDOWPLACEMENT);
  207228. GetWindowPlacement (hwnd, &wp);
  207229. return wp.showCmd == SW_SHOWMINIMIZED;
  207230. }
  207231. void setFullScreen (bool shouldBeFullScreen)
  207232. {
  207233. setMinimised (false);
  207234. if (fullScreen != shouldBeFullScreen)
  207235. {
  207236. fullScreen = shouldBeFullScreen;
  207237. const WeakReference<Component> deletionChecker (component);
  207238. if (! fullScreen)
  207239. {
  207240. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207241. if (hasTitleBar())
  207242. ShowWindow (hwnd, SW_SHOWNORMAL);
  207243. if (! boundsCopy.isEmpty())
  207244. {
  207245. setBounds (boundsCopy.getX(),
  207246. boundsCopy.getY(),
  207247. boundsCopy.getWidth(),
  207248. boundsCopy.getHeight(),
  207249. false);
  207250. }
  207251. }
  207252. else
  207253. {
  207254. if (hasTitleBar())
  207255. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207256. else
  207257. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207258. }
  207259. if (deletionChecker != 0)
  207260. handleMovedOrResized();
  207261. }
  207262. }
  207263. bool isFullScreen() const
  207264. {
  207265. if (! hasTitleBar())
  207266. return fullScreen;
  207267. WINDOWPLACEMENT wp;
  207268. wp.length = sizeof (wp);
  207269. GetWindowPlacement (hwnd, &wp);
  207270. return wp.showCmd == SW_SHOWMAXIMIZED;
  207271. }
  207272. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207273. {
  207274. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207275. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207276. return false;
  207277. RECT r;
  207278. GetWindowRect (hwnd, &r);
  207279. POINT p;
  207280. p.x = position.getX() + r.left + windowBorder.getLeft();
  207281. p.y = position.getY() + r.top + windowBorder.getTop();
  207282. HWND w = WindowFromPoint (p);
  207283. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207284. }
  207285. const BorderSize<int> getFrameSize() const
  207286. {
  207287. return windowBorder;
  207288. }
  207289. bool setAlwaysOnTop (bool alwaysOnTop)
  207290. {
  207291. const bool oldDeactivate = shouldDeactivateTitleBar;
  207292. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207293. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207294. 0, 0, 0, 0,
  207295. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207296. shouldDeactivateTitleBar = oldDeactivate;
  207297. if (shadower != 0)
  207298. shadower->componentBroughtToFront (*component);
  207299. return true;
  207300. }
  207301. void toFront (bool makeActive)
  207302. {
  207303. setMinimised (false);
  207304. const bool oldDeactivate = shouldDeactivateTitleBar;
  207305. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207306. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207307. shouldDeactivateTitleBar = oldDeactivate;
  207308. if (! makeActive)
  207309. {
  207310. // in this case a broughttofront call won't have occured, so do it now..
  207311. handleBroughtToFront();
  207312. }
  207313. }
  207314. void toBehind (ComponentPeer* other)
  207315. {
  207316. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207317. jassert (otherPeer != 0); // wrong type of window?
  207318. if (otherPeer != 0)
  207319. {
  207320. setMinimised (false);
  207321. // must be careful not to try to put a topmost window behind a normal one, or win32
  207322. // promotes the normal one to be topmost!
  207323. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207324. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207325. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207326. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207327. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207328. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207329. }
  207330. }
  207331. bool isFocused() const
  207332. {
  207333. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207334. }
  207335. void grabFocus()
  207336. {
  207337. const bool oldDeactivate = shouldDeactivateTitleBar;
  207338. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207339. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207340. shouldDeactivateTitleBar = oldDeactivate;
  207341. }
  207342. void textInputRequired (const Point<int>&)
  207343. {
  207344. if (! hasCreatedCaret)
  207345. {
  207346. hasCreatedCaret = true;
  207347. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207348. }
  207349. ShowCaret (hwnd);
  207350. SetCaretPos (0, 0);
  207351. }
  207352. void repaint (const Rectangle<int>& area)
  207353. {
  207354. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207355. InvalidateRect (hwnd, &r, FALSE);
  207356. }
  207357. void performAnyPendingRepaintsNow()
  207358. {
  207359. MSG m;
  207360. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207361. DispatchMessage (&m);
  207362. }
  207363. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207364. {
  207365. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207366. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207367. return 0;
  207368. }
  207369. void setTaskBarIcon (const Image& image)
  207370. {
  207371. if (image.isValid())
  207372. {
  207373. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207374. if (taskBarIcon == 0)
  207375. {
  207376. taskBarIcon = new NOTIFYICONDATA();
  207377. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207378. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207379. taskBarIcon->hWnd = (HWND) hwnd;
  207380. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207381. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207382. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207383. taskBarIcon->hIcon = hicon;
  207384. taskBarIcon->szTip[0] = 0;
  207385. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207386. }
  207387. else
  207388. {
  207389. HICON oldIcon = taskBarIcon->hIcon;
  207390. taskBarIcon->hIcon = hicon;
  207391. taskBarIcon->uFlags = NIF_ICON;
  207392. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207393. DestroyIcon (oldIcon);
  207394. }
  207395. }
  207396. else if (taskBarIcon != 0)
  207397. {
  207398. taskBarIcon->uFlags = 0;
  207399. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207400. DestroyIcon (taskBarIcon->hIcon);
  207401. taskBarIcon = 0;
  207402. }
  207403. }
  207404. void setTaskBarIconToolTip (const String& toolTip) const
  207405. {
  207406. if (taskBarIcon != 0)
  207407. {
  207408. taskBarIcon->uFlags = NIF_TIP;
  207409. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207410. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207411. }
  207412. }
  207413. void handleTaskBarEvent (const LPARAM lParam)
  207414. {
  207415. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207416. {
  207417. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207418. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207419. {
  207420. Component* const current = Component::getCurrentlyModalComponent();
  207421. if (current != 0)
  207422. current->inputAttemptWhenModal();
  207423. }
  207424. }
  207425. else
  207426. {
  207427. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207428. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207429. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207430. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207431. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207432. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207433. eventMods = eventMods.withoutMouseButtons();
  207434. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207435. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207436. Point<int>(), Time (getMouseEventTime()), 1, false);
  207437. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207438. {
  207439. SetFocus (hwnd);
  207440. SetForegroundWindow (hwnd);
  207441. component->mouseDown (e);
  207442. }
  207443. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207444. {
  207445. component->mouseUp (e);
  207446. }
  207447. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207448. {
  207449. component->mouseDoubleClick (e);
  207450. }
  207451. else if (lParam == WM_MOUSEMOVE)
  207452. {
  207453. component->mouseMove (e);
  207454. }
  207455. }
  207456. }
  207457. bool isInside (HWND h) const
  207458. {
  207459. return GetAncestor (hwnd, GA_ROOT) == h;
  207460. }
  207461. static void updateKeyModifiers() throw()
  207462. {
  207463. int keyMods = 0;
  207464. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207465. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207466. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207467. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207468. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207469. }
  207470. static void updateModifiersFromWParam (const WPARAM wParam)
  207471. {
  207472. int mouseMods = 0;
  207473. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207474. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207475. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207476. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207477. updateKeyModifiers();
  207478. }
  207479. static int64 getMouseEventTime()
  207480. {
  207481. static int64 eventTimeOffset = 0;
  207482. static DWORD lastMessageTime = 0;
  207483. const DWORD thisMessageTime = GetMessageTime();
  207484. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207485. {
  207486. lastMessageTime = thisMessageTime;
  207487. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207488. }
  207489. return eventTimeOffset + thisMessageTime;
  207490. }
  207491. bool dontRepaint;
  207492. static ModifierKeys currentModifiers;
  207493. static ModifierKeys modifiersAtLastCallback;
  207494. private:
  207495. HWND hwnd, parentToAddTo;
  207496. ScopedPointer<DropShadower> shadower;
  207497. RenderingEngineType currentRenderingEngine;
  207498. #if JUCE_DIRECT2D
  207499. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207500. #endif
  207501. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207502. BorderSize<int> windowBorder;
  207503. HICON currentWindowIcon;
  207504. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207505. IDropTarget* dropTarget;
  207506. uint8 updateLayeredWindowAlpha;
  207507. class TemporaryImage : public Timer
  207508. {
  207509. public:
  207510. TemporaryImage() {}
  207511. ~TemporaryImage() {}
  207512. const Image& getImage (const bool transparent, const int w, const int h)
  207513. {
  207514. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207515. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207516. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207517. startTimer (3000);
  207518. return image;
  207519. }
  207520. void timerCallback()
  207521. {
  207522. stopTimer();
  207523. image = Image::null;
  207524. }
  207525. private:
  207526. Image image;
  207527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207528. };
  207529. TemporaryImage offscreenImageGenerator;
  207530. class WindowClassHolder : public DeletedAtShutdown
  207531. {
  207532. public:
  207533. WindowClassHolder()
  207534. : windowClassName ("JUCE_")
  207535. {
  207536. // this name has to be different for each app/dll instance because otherwise
  207537. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207538. // window class).
  207539. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207540. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207541. TCHAR moduleFile [1024];
  207542. moduleFile[0] = 0;
  207543. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207544. WORD iconNum = 0;
  207545. WNDCLASSEX wcex;
  207546. wcex.cbSize = sizeof (wcex);
  207547. wcex.style = CS_OWNDC;
  207548. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207549. wcex.lpszClassName = windowClassName.toUTF16();
  207550. wcex.cbClsExtra = 0;
  207551. wcex.cbWndExtra = 32;
  207552. wcex.hInstance = moduleHandle;
  207553. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207554. iconNum = 1;
  207555. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207556. wcex.hCursor = 0;
  207557. wcex.hbrBackground = 0;
  207558. wcex.lpszMenuName = 0;
  207559. RegisterClassEx (&wcex);
  207560. }
  207561. ~WindowClassHolder()
  207562. {
  207563. if (ComponentPeer::getNumPeers() == 0)
  207564. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207565. clearSingletonInstance();
  207566. }
  207567. String windowClassName;
  207568. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207569. };
  207570. static void* createWindowCallback (void* userData)
  207571. {
  207572. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207573. return 0;
  207574. }
  207575. void createWindow()
  207576. {
  207577. DWORD exstyle = WS_EX_ACCEPTFILES;
  207578. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207579. if (hasTitleBar())
  207580. {
  207581. type |= WS_OVERLAPPED;
  207582. if ((styleFlags & windowHasCloseButton) != 0)
  207583. {
  207584. type |= WS_SYSMENU;
  207585. }
  207586. else
  207587. {
  207588. // annoyingly, windows won't let you have a min/max button without a close button
  207589. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207590. }
  207591. if ((styleFlags & windowIsResizable) != 0)
  207592. type |= WS_THICKFRAME;
  207593. }
  207594. else if (parentToAddTo != 0)
  207595. {
  207596. type |= WS_CHILD;
  207597. }
  207598. else
  207599. {
  207600. type |= WS_POPUP | WS_SYSMENU;
  207601. }
  207602. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207603. exstyle |= WS_EX_TOOLWINDOW;
  207604. else
  207605. exstyle |= WS_EX_APPWINDOW;
  207606. if ((styleFlags & windowHasMinimiseButton) != 0)
  207607. type |= WS_MINIMIZEBOX;
  207608. if ((styleFlags & windowHasMaximiseButton) != 0)
  207609. type |= WS_MAXIMIZEBOX;
  207610. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207611. exstyle |= WS_EX_TRANSPARENT;
  207612. if ((styleFlags & windowIsSemiTransparent) != 0
  207613. && Desktop::canUseSemiTransparentWindows())
  207614. exstyle |= WS_EX_LAYERED;
  207615. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207616. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207617. #if JUCE_DIRECT2D
  207618. updateDirect2DContext();
  207619. #endif
  207620. if (hwnd != 0)
  207621. {
  207622. SetWindowLongPtr (hwnd, 0, 0);
  207623. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207624. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207625. if (dropTarget == 0)
  207626. dropTarget = new JuceDropTarget (this);
  207627. RegisterDragDrop (hwnd, dropTarget);
  207628. updateBorderSize();
  207629. // Calling this function here is (for some reason) necessary to make Windows
  207630. // correctly enable the menu items that we specify in the wm_initmenu message.
  207631. GetSystemMenu (hwnd, false);
  207632. const float alpha = component->getAlpha();
  207633. if (alpha < 1.0f)
  207634. setAlpha (alpha);
  207635. }
  207636. else
  207637. {
  207638. jassertfalse;
  207639. }
  207640. }
  207641. static void* destroyWindowCallback (void* handle)
  207642. {
  207643. RevokeDragDrop ((HWND) handle);
  207644. DestroyWindow ((HWND) handle);
  207645. return 0;
  207646. }
  207647. static void* toFrontCallback1 (void* h)
  207648. {
  207649. SetForegroundWindow ((HWND) h);
  207650. return 0;
  207651. }
  207652. static void* toFrontCallback2 (void* h)
  207653. {
  207654. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207655. return 0;
  207656. }
  207657. static void* setFocusCallback (void* h)
  207658. {
  207659. SetFocus ((HWND) h);
  207660. return 0;
  207661. }
  207662. static void* getFocusCallback (void*)
  207663. {
  207664. return GetFocus();
  207665. }
  207666. void offsetWithinParent (int& x, int& y) const
  207667. {
  207668. if (isUsingUpdateLayeredWindow())
  207669. {
  207670. HWND parentHwnd = GetParent (hwnd);
  207671. if (parentHwnd != 0)
  207672. {
  207673. RECT parentRect;
  207674. GetWindowRect (parentHwnd, &parentRect);
  207675. x += parentRect.left;
  207676. y += parentRect.top;
  207677. }
  207678. }
  207679. }
  207680. bool isUsingUpdateLayeredWindow() const
  207681. {
  207682. return ! component->isOpaque();
  207683. }
  207684. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207685. void setIcon (const Image& newIcon)
  207686. {
  207687. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207688. if (hicon != 0)
  207689. {
  207690. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207691. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207692. if (currentWindowIcon != 0)
  207693. DestroyIcon (currentWindowIcon);
  207694. currentWindowIcon = hicon;
  207695. }
  207696. }
  207697. void handlePaintMessage()
  207698. {
  207699. #if JUCE_DIRECT2D
  207700. if (direct2DContext != 0)
  207701. {
  207702. RECT r;
  207703. if (GetUpdateRect (hwnd, &r, false))
  207704. {
  207705. direct2DContext->start();
  207706. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207707. handlePaint (*direct2DContext);
  207708. direct2DContext->end();
  207709. }
  207710. }
  207711. else
  207712. #endif
  207713. {
  207714. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207715. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207716. PAINTSTRUCT paintStruct;
  207717. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207718. // message and become re-entrant, but that's OK
  207719. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207720. // corrupt the image it's using to paint into, so do a check here.
  207721. static bool reentrant = false;
  207722. if (reentrant)
  207723. {
  207724. DeleteObject (rgn);
  207725. EndPaint (hwnd, &paintStruct);
  207726. return;
  207727. }
  207728. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207729. // this is the rectangle to update..
  207730. int x = paintStruct.rcPaint.left;
  207731. int y = paintStruct.rcPaint.top;
  207732. int w = paintStruct.rcPaint.right - x;
  207733. int h = paintStruct.rcPaint.bottom - y;
  207734. const bool transparent = isUsingUpdateLayeredWindow();
  207735. if (transparent)
  207736. {
  207737. // it's not possible to have a transparent window with a title bar at the moment!
  207738. jassert (! hasTitleBar());
  207739. RECT r;
  207740. GetWindowRect (hwnd, &r);
  207741. x = y = 0;
  207742. w = r.right - r.left;
  207743. h = r.bottom - r.top;
  207744. }
  207745. if (w > 0 && h > 0)
  207746. {
  207747. clearMaskedRegion();
  207748. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207749. RectangleList contextClip;
  207750. const Rectangle<int> clipBounds (0, 0, w, h);
  207751. bool needToPaintAll = true;
  207752. if (regionType == COMPLEXREGION && ! transparent)
  207753. {
  207754. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207755. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207756. DeleteObject (clipRgn);
  207757. char rgnData [8192];
  207758. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207759. if (res > 0 && res <= sizeof (rgnData))
  207760. {
  207761. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207762. if (hdr->iType == RDH_RECTANGLES
  207763. && hdr->rcBound.right - hdr->rcBound.left >= w
  207764. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207765. {
  207766. needToPaintAll = false;
  207767. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207768. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207769. while (--num >= 0)
  207770. {
  207771. if (rects->right <= x + w && rects->bottom <= y + h)
  207772. {
  207773. const int cx = jmax (x, (int) rects->left);
  207774. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207775. .getIntersection (clipBounds));
  207776. }
  207777. else
  207778. {
  207779. needToPaintAll = true;
  207780. break;
  207781. }
  207782. ++rects;
  207783. }
  207784. }
  207785. }
  207786. }
  207787. if (needToPaintAll)
  207788. {
  207789. contextClip.clear();
  207790. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207791. }
  207792. if (transparent)
  207793. {
  207794. RectangleList::Iterator i (contextClip);
  207795. while (i.next())
  207796. offscreenImage.clear (*i.getRectangle());
  207797. }
  207798. // if the component's not opaque, this won't draw properly unless the platform can support this
  207799. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207800. updateCurrentModifiers();
  207801. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207802. handlePaint (context);
  207803. if (! dontRepaint)
  207804. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207805. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207806. }
  207807. DeleteObject (rgn);
  207808. EndPaint (hwnd, &paintStruct);
  207809. }
  207810. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207811. _fpreset(); // because some graphics cards can unmask FP exceptions
  207812. #endif
  207813. lastPaintTime = Time::getMillisecondCounter();
  207814. }
  207815. void doMouseEvent (const Point<int>& position)
  207816. {
  207817. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207818. }
  207819. const StringArray getAvailableRenderingEngines()
  207820. {
  207821. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207822. #if JUCE_DIRECT2D
  207823. // xxx is this correct? Seems to enable it on Vista too??
  207824. OSVERSIONINFO info;
  207825. zerostruct (info);
  207826. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207827. GetVersionEx (&info);
  207828. if (info.dwMajorVersion >= 6)
  207829. s.add ("Direct2D");
  207830. #endif
  207831. return s;
  207832. }
  207833. int getCurrentRenderingEngine() throw()
  207834. {
  207835. return currentRenderingEngine;
  207836. }
  207837. #if JUCE_DIRECT2D
  207838. void updateDirect2DContext()
  207839. {
  207840. if (currentRenderingEngine != direct2DRenderingEngine)
  207841. direct2DContext = 0;
  207842. else if (direct2DContext == 0)
  207843. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207844. }
  207845. #endif
  207846. void setCurrentRenderingEngine (int index)
  207847. {
  207848. (void) index;
  207849. #if JUCE_DIRECT2D
  207850. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207851. updateDirect2DContext();
  207852. repaint (component->getLocalBounds());
  207853. #endif
  207854. }
  207855. void doMouseMove (const Point<int>& position)
  207856. {
  207857. if (! isMouseOver)
  207858. {
  207859. isMouseOver = true;
  207860. updateKeyModifiers();
  207861. TRACKMOUSEEVENT tme;
  207862. tme.cbSize = sizeof (tme);
  207863. tme.dwFlags = TME_LEAVE;
  207864. tme.hwndTrack = hwnd;
  207865. tme.dwHoverTime = 0;
  207866. if (! TrackMouseEvent (&tme))
  207867. jassertfalse;
  207868. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207869. }
  207870. else if (! isDragging)
  207871. {
  207872. if (! contains (position, false))
  207873. return;
  207874. }
  207875. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207876. static uint32 lastMouseTime = 0;
  207877. const uint32 now = Time::getMillisecondCounter();
  207878. const int maxMouseMovesPerSecond = 60;
  207879. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207880. {
  207881. lastMouseTime = now;
  207882. doMouseEvent (position);
  207883. }
  207884. }
  207885. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207886. {
  207887. if (GetCapture() != hwnd)
  207888. SetCapture (hwnd);
  207889. doMouseMove (position);
  207890. updateModifiersFromWParam (wParam);
  207891. isDragging = true;
  207892. doMouseEvent (position);
  207893. }
  207894. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207895. {
  207896. updateModifiersFromWParam (wParam);
  207897. isDragging = false;
  207898. // release the mouse capture if the user has released all buttons
  207899. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207900. ReleaseCapture();
  207901. doMouseEvent (position);
  207902. }
  207903. void doCaptureChanged()
  207904. {
  207905. if (constrainerIsResizing)
  207906. {
  207907. if (constrainer != 0)
  207908. constrainer->resizeEnd();
  207909. constrainerIsResizing = false;
  207910. }
  207911. if (isDragging)
  207912. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207913. }
  207914. void doMouseExit()
  207915. {
  207916. isMouseOver = false;
  207917. doMouseEvent (getCurrentMousePos());
  207918. }
  207919. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207920. {
  207921. updateKeyModifiers();
  207922. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207923. handleMouseWheel (0, position, getMouseEventTime(),
  207924. isVertical ? 0.0f : amount,
  207925. isVertical ? amount : 0.0f);
  207926. }
  207927. void sendModifierKeyChangeIfNeeded()
  207928. {
  207929. if (modifiersAtLastCallback != currentModifiers)
  207930. {
  207931. modifiersAtLastCallback = currentModifiers;
  207932. handleModifierKeysChange();
  207933. }
  207934. }
  207935. bool doKeyUp (const WPARAM key)
  207936. {
  207937. updateKeyModifiers();
  207938. switch (key)
  207939. {
  207940. case VK_SHIFT:
  207941. case VK_CONTROL:
  207942. case VK_MENU:
  207943. case VK_CAPITAL:
  207944. case VK_LWIN:
  207945. case VK_RWIN:
  207946. case VK_APPS:
  207947. case VK_NUMLOCK:
  207948. case VK_SCROLL:
  207949. case VK_LSHIFT:
  207950. case VK_RSHIFT:
  207951. case VK_LCONTROL:
  207952. case VK_LMENU:
  207953. case VK_RCONTROL:
  207954. case VK_RMENU:
  207955. sendModifierKeyChangeIfNeeded();
  207956. }
  207957. return handleKeyUpOrDown (false)
  207958. || Component::getCurrentlyModalComponent() != 0;
  207959. }
  207960. bool doKeyDown (const WPARAM key)
  207961. {
  207962. updateKeyModifiers();
  207963. bool used = false;
  207964. switch (key)
  207965. {
  207966. case VK_SHIFT:
  207967. case VK_LSHIFT:
  207968. case VK_RSHIFT:
  207969. case VK_CONTROL:
  207970. case VK_LCONTROL:
  207971. case VK_RCONTROL:
  207972. case VK_MENU:
  207973. case VK_LMENU:
  207974. case VK_RMENU:
  207975. case VK_LWIN:
  207976. case VK_RWIN:
  207977. case VK_CAPITAL:
  207978. case VK_NUMLOCK:
  207979. case VK_SCROLL:
  207980. case VK_APPS:
  207981. sendModifierKeyChangeIfNeeded();
  207982. break;
  207983. case VK_LEFT:
  207984. case VK_RIGHT:
  207985. case VK_UP:
  207986. case VK_DOWN:
  207987. case VK_PRIOR:
  207988. case VK_NEXT:
  207989. case VK_HOME:
  207990. case VK_END:
  207991. case VK_DELETE:
  207992. case VK_INSERT:
  207993. case VK_F1:
  207994. case VK_F2:
  207995. case VK_F3:
  207996. case VK_F4:
  207997. case VK_F5:
  207998. case VK_F6:
  207999. case VK_F7:
  208000. case VK_F8:
  208001. case VK_F9:
  208002. case VK_F10:
  208003. case VK_F11:
  208004. case VK_F12:
  208005. case VK_F13:
  208006. case VK_F14:
  208007. case VK_F15:
  208008. case VK_F16:
  208009. used = handleKeyUpOrDown (true);
  208010. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  208011. break;
  208012. case VK_ADD:
  208013. case VK_SUBTRACT:
  208014. case VK_MULTIPLY:
  208015. case VK_DIVIDE:
  208016. case VK_SEPARATOR:
  208017. case VK_DECIMAL:
  208018. used = handleKeyUpOrDown (true);
  208019. break;
  208020. default:
  208021. used = handleKeyUpOrDown (true);
  208022. {
  208023. MSG msg;
  208024. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  208025. {
  208026. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  208027. // manually generate the key-press event that matches this key-down.
  208028. const UINT keyChar = MapVirtualKey (key, 2);
  208029. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  208030. }
  208031. }
  208032. break;
  208033. }
  208034. if (Component::getCurrentlyModalComponent() != 0)
  208035. used = true;
  208036. return used;
  208037. }
  208038. bool doKeyChar (int key, const LPARAM flags)
  208039. {
  208040. updateKeyModifiers();
  208041. juce_wchar textChar = (juce_wchar) key;
  208042. const int virtualScanCode = (flags >> 16) & 0xff;
  208043. if (key >= '0' && key <= '9')
  208044. {
  208045. switch (virtualScanCode) // check for a numeric keypad scan-code
  208046. {
  208047. case 0x52:
  208048. case 0x4f:
  208049. case 0x50:
  208050. case 0x51:
  208051. case 0x4b:
  208052. case 0x4c:
  208053. case 0x4d:
  208054. case 0x47:
  208055. case 0x48:
  208056. case 0x49:
  208057. key = (key - '0') + KeyPress::numberPad0;
  208058. break;
  208059. default:
  208060. break;
  208061. }
  208062. }
  208063. else
  208064. {
  208065. // convert the scan code to an unmodified character code..
  208066. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  208067. UINT keyChar = MapVirtualKey (virtualKey, 2);
  208068. keyChar = LOWORD (keyChar);
  208069. if (keyChar != 0)
  208070. key = (int) keyChar;
  208071. // avoid sending junk text characters for some control-key combinations
  208072. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  208073. textChar = 0;
  208074. }
  208075. return handleKeyPress (key, textChar);
  208076. }
  208077. bool doAppCommand (const LPARAM lParam)
  208078. {
  208079. int key = 0;
  208080. switch (GET_APPCOMMAND_LPARAM (lParam))
  208081. {
  208082. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  208083. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  208084. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  208085. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  208086. default: break;
  208087. }
  208088. if (key != 0)
  208089. {
  208090. updateKeyModifiers();
  208091. if (hwnd == GetActiveWindow())
  208092. {
  208093. handleKeyPress (key, 0);
  208094. return true;
  208095. }
  208096. }
  208097. return false;
  208098. }
  208099. bool isConstrainedNativeWindow() const
  208100. {
  208101. return constrainer != 0
  208102. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  208103. }
  208104. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  208105. {
  208106. if (isConstrainedNativeWindow())
  208107. {
  208108. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208109. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208110. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208111. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208112. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208113. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208114. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208115. r->left = pos.getX();
  208116. r->top = pos.getY();
  208117. r->right = pos.getRight();
  208118. r->bottom = pos.getBottom();
  208119. }
  208120. return TRUE;
  208121. }
  208122. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  208123. {
  208124. if (isConstrainedNativeWindow())
  208125. {
  208126. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208127. && ! Component::isMouseButtonDownAnywhere())
  208128. {
  208129. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208130. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208131. constrainer->checkBounds (pos, current,
  208132. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208133. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208134. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208135. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208136. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208137. wp->x = pos.getX();
  208138. wp->y = pos.getY();
  208139. wp->cx = pos.getWidth();
  208140. wp->cy = pos.getHeight();
  208141. }
  208142. }
  208143. return 0;
  208144. }
  208145. void handleAppActivation (const WPARAM wParam)
  208146. {
  208147. modifiersAtLastCallback = -1;
  208148. updateKeyModifiers();
  208149. if (isMinimised())
  208150. {
  208151. component->repaint();
  208152. handleMovedOrResized();
  208153. if (! ComponentPeer::isValidPeer (this))
  208154. return;
  208155. }
  208156. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  208157. {
  208158. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  208159. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208160. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208161. }
  208162. else
  208163. {
  208164. handleBroughtToFront();
  208165. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208166. Component::getCurrentlyModalComponent()->toFront (true);
  208167. }
  208168. }
  208169. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  208170. {
  208171. public:
  208172. JuceDropTarget (Win32ComponentPeer* const owner_)
  208173. : owner (owner_)
  208174. {
  208175. }
  208176. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208177. {
  208178. updateFileList (pDataObject);
  208179. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208180. *pdwEffect = DROPEFFECT_COPY;
  208181. return S_OK;
  208182. }
  208183. HRESULT __stdcall DragLeave()
  208184. {
  208185. owner->handleFileDragExit (files);
  208186. return S_OK;
  208187. }
  208188. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208189. {
  208190. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208191. *pdwEffect = DROPEFFECT_COPY;
  208192. return S_OK;
  208193. }
  208194. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208195. {
  208196. updateFileList (pDataObject);
  208197. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208198. *pdwEffect = DROPEFFECT_COPY;
  208199. return S_OK;
  208200. }
  208201. private:
  208202. Win32ComponentPeer* const owner;
  208203. StringArray files;
  208204. void updateFileList (IDataObject* const pDataObject)
  208205. {
  208206. files.clear();
  208207. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208208. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208209. if (pDataObject->GetData (&format, &medium) == S_OK)
  208210. {
  208211. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208212. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208213. unsigned int i = 0;
  208214. if (pDropFiles->fWide)
  208215. {
  208216. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  208217. for (;;)
  208218. {
  208219. unsigned int len = 0;
  208220. while (i + len < totalLen && fname [i + len] != 0)
  208221. ++len;
  208222. if (len == 0)
  208223. break;
  208224. files.add (String (fname + i, len));
  208225. i += len + 1;
  208226. }
  208227. }
  208228. else
  208229. {
  208230. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  208231. for (;;)
  208232. {
  208233. unsigned int len = 0;
  208234. while (i + len < totalLen && fname [i + len] != 0)
  208235. ++len;
  208236. if (len == 0)
  208237. break;
  208238. files.add (String (fname + i, len));
  208239. i += len + 1;
  208240. }
  208241. }
  208242. GlobalUnlock (medium.hGlobal);
  208243. }
  208244. }
  208245. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  208246. };
  208247. void doSettingChange()
  208248. {
  208249. Desktop::getInstance().refreshMonitorSizes();
  208250. if (fullScreen && ! isMinimised())
  208251. {
  208252. const Rectangle<int> r (component->getParentMonitorArea());
  208253. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208254. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208255. }
  208256. }
  208257. public:
  208258. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208259. {
  208260. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208261. if (peer != 0)
  208262. {
  208263. jassert (isValidPeer (peer));
  208264. return peer->peerWindowProc (h, message, wParam, lParam);
  208265. }
  208266. return DefWindowProcW (h, message, wParam, lParam);
  208267. }
  208268. private:
  208269. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208270. {
  208271. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208272. return callback (userData);
  208273. else
  208274. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208275. }
  208276. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208277. {
  208278. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208279. }
  208280. const Point<int> getCurrentMousePos() throw()
  208281. {
  208282. RECT wr;
  208283. GetWindowRect (hwnd, &wr);
  208284. const DWORD mp = GetMessagePos();
  208285. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208286. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208287. }
  208288. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208289. {
  208290. switch (message)
  208291. {
  208292. case WM_NCHITTEST:
  208293. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208294. return HTTRANSPARENT;
  208295. else if (! hasTitleBar())
  208296. return HTCLIENT;
  208297. break;
  208298. case WM_PAINT:
  208299. handlePaintMessage();
  208300. return 0;
  208301. case WM_NCPAINT:
  208302. if (hasTitleBar())
  208303. break;
  208304. else if (wParam != 1)
  208305. handlePaintMessage();
  208306. return 0;
  208307. case WM_ERASEBKGND:
  208308. case WM_NCCALCSIZE:
  208309. if (hasTitleBar())
  208310. break;
  208311. return 1;
  208312. case WM_MOUSEMOVE:
  208313. doMouseMove (getPointFromLParam (lParam));
  208314. return 0;
  208315. case WM_MOUSELEAVE:
  208316. doMouseExit();
  208317. return 0;
  208318. case WM_LBUTTONDOWN:
  208319. case WM_MBUTTONDOWN:
  208320. case WM_RBUTTONDOWN:
  208321. doMouseDown (getPointFromLParam (lParam), wParam);
  208322. return 0;
  208323. case WM_LBUTTONUP:
  208324. case WM_MBUTTONUP:
  208325. case WM_RBUTTONUP:
  208326. doMouseUp (getPointFromLParam (lParam), wParam);
  208327. return 0;
  208328. case WM_CAPTURECHANGED:
  208329. doCaptureChanged();
  208330. return 0;
  208331. case WM_NCMOUSEMOVE:
  208332. if (hasTitleBar())
  208333. break;
  208334. return 0;
  208335. case 0x020A: /* WM_MOUSEWHEEL */
  208336. case 0x020E: /* WM_MOUSEHWHEEL */
  208337. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208338. return 0;
  208339. case WM_SIZING:
  208340. return handleSizeConstraining ((RECT*) lParam, wParam);
  208341. case WM_WINDOWPOSCHANGING:
  208342. return handlePositionChanging ((WINDOWPOS*) lParam);
  208343. case WM_WINDOWPOSCHANGED:
  208344. {
  208345. const Point<int> pos (getCurrentMousePos());
  208346. if (contains (pos, false))
  208347. doMouseEvent (pos);
  208348. }
  208349. handleMovedOrResized();
  208350. if (dontRepaint)
  208351. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208352. return 0;
  208353. case WM_KEYDOWN:
  208354. case WM_SYSKEYDOWN:
  208355. if (doKeyDown (wParam))
  208356. return 0;
  208357. break;
  208358. case WM_KEYUP:
  208359. case WM_SYSKEYUP:
  208360. if (doKeyUp (wParam))
  208361. return 0;
  208362. break;
  208363. case WM_CHAR:
  208364. if (doKeyChar ((int) wParam, lParam))
  208365. return 0;
  208366. break;
  208367. case WM_APPCOMMAND:
  208368. if (doAppCommand (lParam))
  208369. return TRUE;
  208370. break;
  208371. case WM_SETFOCUS:
  208372. updateKeyModifiers();
  208373. handleFocusGain();
  208374. break;
  208375. case WM_KILLFOCUS:
  208376. if (hasCreatedCaret)
  208377. {
  208378. hasCreatedCaret = false;
  208379. DestroyCaret();
  208380. }
  208381. handleFocusLoss();
  208382. break;
  208383. case WM_ACTIVATEAPP:
  208384. // Windows does weird things to process priority when you swap apps,
  208385. // so this forces an update when the app is brought to the front
  208386. if (wParam != FALSE)
  208387. juce_repeatLastProcessPriority();
  208388. else
  208389. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208390. juce_CheckCurrentlyFocusedTopLevelWindow();
  208391. modifiersAtLastCallback = -1;
  208392. return 0;
  208393. case WM_ACTIVATE:
  208394. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208395. {
  208396. handleAppActivation (wParam);
  208397. return 0;
  208398. }
  208399. break;
  208400. case WM_NCACTIVATE:
  208401. // while a temporary window is being shown, prevent Windows from deactivating the
  208402. // title bars of our main windows.
  208403. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208404. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208405. break;
  208406. case WM_MOUSEACTIVATE:
  208407. if (! component->getMouseClickGrabsKeyboardFocus())
  208408. return MA_NOACTIVATE;
  208409. break;
  208410. case WM_SHOWWINDOW:
  208411. if (wParam != 0)
  208412. handleBroughtToFront();
  208413. break;
  208414. case WM_CLOSE:
  208415. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208416. handleUserClosingWindow();
  208417. return 0;
  208418. case WM_QUERYENDSESSION:
  208419. if (JUCEApplication::getInstance() != 0)
  208420. {
  208421. JUCEApplication::getInstance()->systemRequestedQuit();
  208422. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208423. }
  208424. return TRUE;
  208425. case WM_TRAYNOTIFY:
  208426. handleTaskBarEvent (lParam);
  208427. break;
  208428. case WM_SYNCPAINT:
  208429. return 0;
  208430. case WM_DISPLAYCHANGE:
  208431. InvalidateRect (h, 0, 0);
  208432. // intentional fall-through...
  208433. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208434. doSettingChange();
  208435. break;
  208436. case WM_INITMENU:
  208437. if (! hasTitleBar())
  208438. {
  208439. if (isFullScreen())
  208440. {
  208441. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208442. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208443. }
  208444. else if (! isMinimised())
  208445. {
  208446. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208447. }
  208448. }
  208449. break;
  208450. case WM_SYSCOMMAND:
  208451. switch (wParam & 0xfff0)
  208452. {
  208453. case SC_CLOSE:
  208454. if (sendInputAttemptWhenModalMessage())
  208455. return 0;
  208456. if (hasTitleBar())
  208457. {
  208458. PostMessage (h, WM_CLOSE, 0, 0);
  208459. return 0;
  208460. }
  208461. break;
  208462. case SC_KEYMENU:
  208463. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208464. // situations that can arise if a modal loop is started from an alt-key keypress).
  208465. if (hasTitleBar() && h == GetCapture())
  208466. ReleaseCapture();
  208467. break;
  208468. case SC_MAXIMIZE:
  208469. if (! sendInputAttemptWhenModalMessage())
  208470. setFullScreen (true);
  208471. return 0;
  208472. case SC_MINIMIZE:
  208473. if (sendInputAttemptWhenModalMessage())
  208474. return 0;
  208475. if (! hasTitleBar())
  208476. {
  208477. setMinimised (true);
  208478. return 0;
  208479. }
  208480. break;
  208481. case SC_RESTORE:
  208482. if (sendInputAttemptWhenModalMessage())
  208483. return 0;
  208484. if (hasTitleBar())
  208485. {
  208486. if (isFullScreen())
  208487. {
  208488. setFullScreen (false);
  208489. return 0;
  208490. }
  208491. }
  208492. else
  208493. {
  208494. if (isMinimised())
  208495. setMinimised (false);
  208496. else if (isFullScreen())
  208497. setFullScreen (false);
  208498. return 0;
  208499. }
  208500. break;
  208501. }
  208502. break;
  208503. case WM_NCLBUTTONDOWN:
  208504. if (! sendInputAttemptWhenModalMessage())
  208505. {
  208506. switch (wParam)
  208507. {
  208508. case HTBOTTOM:
  208509. case HTBOTTOMLEFT:
  208510. case HTBOTTOMRIGHT:
  208511. case HTGROWBOX:
  208512. case HTLEFT:
  208513. case HTRIGHT:
  208514. case HTTOP:
  208515. case HTTOPLEFT:
  208516. case HTTOPRIGHT:
  208517. if (isConstrainedNativeWindow())
  208518. {
  208519. constrainerIsResizing = true;
  208520. constrainer->resizeStart();
  208521. }
  208522. break;
  208523. default:
  208524. break;
  208525. };
  208526. }
  208527. break;
  208528. case WM_NCRBUTTONDOWN:
  208529. case WM_NCMBUTTONDOWN:
  208530. sendInputAttemptWhenModalMessage();
  208531. break;
  208532. //case WM_IME_STARTCOMPOSITION;
  208533. // return 0;
  208534. case WM_GETDLGCODE:
  208535. return DLGC_WANTALLKEYS;
  208536. default:
  208537. if (taskBarIcon != 0)
  208538. {
  208539. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208540. if (message == taskbarCreatedMessage)
  208541. {
  208542. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208543. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208544. }
  208545. }
  208546. break;
  208547. }
  208548. return DefWindowProcW (h, message, wParam, lParam);
  208549. }
  208550. bool sendInputAttemptWhenModalMessage()
  208551. {
  208552. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208553. {
  208554. Component* const current = Component::getCurrentlyModalComponent();
  208555. if (current != 0)
  208556. current->inputAttemptWhenModal();
  208557. return true;
  208558. }
  208559. return false;
  208560. }
  208561. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208562. };
  208563. ModifierKeys Win32ComponentPeer::currentModifiers;
  208564. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208565. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208566. {
  208567. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208568. }
  208569. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208570. void ModifierKeys::updateCurrentModifiers() throw()
  208571. {
  208572. currentModifiers = Win32ComponentPeer::currentModifiers;
  208573. }
  208574. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208575. {
  208576. Win32ComponentPeer::updateKeyModifiers();
  208577. int mouseMods = 0;
  208578. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208579. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208580. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208581. Win32ComponentPeer::currentModifiers
  208582. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208583. return Win32ComponentPeer::currentModifiers;
  208584. }
  208585. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208586. {
  208587. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208588. if (wp != 0)
  208589. wp->setTaskBarIcon (newImage);
  208590. }
  208591. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208592. {
  208593. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208594. if (wp != 0)
  208595. wp->setTaskBarIconToolTip (tooltip);
  208596. }
  208597. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208598. {
  208599. DWORD val = GetWindowLong (h, styleType);
  208600. if (bitIsSet)
  208601. val |= feature;
  208602. else
  208603. val &= ~feature;
  208604. SetWindowLongPtr (h, styleType, val);
  208605. SetWindowPos (h, 0, 0, 0, 0, 0,
  208606. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208607. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208608. }
  208609. bool Process::isForegroundProcess()
  208610. {
  208611. HWND fg = GetForegroundWindow();
  208612. if (fg == 0)
  208613. return true;
  208614. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208615. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208616. // have to see if any of our windows are children of the foreground window
  208617. fg = GetAncestor (fg, GA_ROOT);
  208618. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208619. {
  208620. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208621. if (wp != 0 && wp->isInside (fg))
  208622. return true;
  208623. }
  208624. return false;
  208625. }
  208626. bool AlertWindow::showNativeDialogBox (const String& title,
  208627. const String& bodyText,
  208628. bool isOkCancel)
  208629. {
  208630. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208631. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208632. : MB_OK)) == IDOK;
  208633. }
  208634. void Desktop::createMouseInputSources()
  208635. {
  208636. mouseSources.add (new MouseInputSource (0, true));
  208637. }
  208638. const Point<int> MouseInputSource::getCurrentMousePosition()
  208639. {
  208640. POINT mousePos;
  208641. GetCursorPos (&mousePos);
  208642. return Point<int> (mousePos.x, mousePos.y);
  208643. }
  208644. void Desktop::setMousePosition (const Point<int>& newPosition)
  208645. {
  208646. SetCursorPos (newPosition.getX(), newPosition.getY());
  208647. }
  208648. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208649. {
  208650. return createSoftwareImage (format, width, height, clearImage);
  208651. }
  208652. class ScreenSaverDefeater : public Timer,
  208653. public DeletedAtShutdown
  208654. {
  208655. public:
  208656. ScreenSaverDefeater()
  208657. {
  208658. startTimer (10000);
  208659. timerCallback();
  208660. }
  208661. ~ScreenSaverDefeater() {}
  208662. void timerCallback()
  208663. {
  208664. if (Process::isForegroundProcess())
  208665. {
  208666. // simulate a shift key getting pressed..
  208667. INPUT input[2];
  208668. input[0].type = INPUT_KEYBOARD;
  208669. input[0].ki.wVk = VK_SHIFT;
  208670. input[0].ki.dwFlags = 0;
  208671. input[0].ki.dwExtraInfo = 0;
  208672. input[1].type = INPUT_KEYBOARD;
  208673. input[1].ki.wVk = VK_SHIFT;
  208674. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208675. input[1].ki.dwExtraInfo = 0;
  208676. SendInput (2, input, sizeof (INPUT));
  208677. }
  208678. }
  208679. };
  208680. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208681. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208682. {
  208683. if (isEnabled)
  208684. deleteAndZero (screenSaverDefeater);
  208685. else if (screenSaverDefeater == 0)
  208686. screenSaverDefeater = new ScreenSaverDefeater();
  208687. }
  208688. bool Desktop::isScreenSaverEnabled()
  208689. {
  208690. return screenSaverDefeater == 0;
  208691. }
  208692. /* (The code below is the "correct" way to disable the screen saver, but it
  208693. completely fails on winXP when the saver is password-protected...)
  208694. static bool juce_screenSaverEnabled = true;
  208695. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208696. {
  208697. juce_screenSaverEnabled = isEnabled;
  208698. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208699. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208700. }
  208701. bool Desktop::isScreenSaverEnabled() throw()
  208702. {
  208703. return juce_screenSaverEnabled;
  208704. }
  208705. */
  208706. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208707. {
  208708. if (enableOrDisable)
  208709. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208710. }
  208711. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208712. {
  208713. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208714. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208715. return TRUE;
  208716. }
  208717. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208718. {
  208719. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208720. // make sure the first in the list is the main monitor
  208721. for (int i = 1; i < monitorCoords.size(); ++i)
  208722. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208723. monitorCoords.swap (i, 0);
  208724. if (monitorCoords.size() == 0)
  208725. {
  208726. RECT r;
  208727. GetWindowRect (GetDesktopWindow(), &r);
  208728. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208729. }
  208730. if (clipToWorkArea)
  208731. {
  208732. // clip the main monitor to the active non-taskbar area
  208733. RECT r;
  208734. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208735. Rectangle<int>& screen = monitorCoords.getReference (0);
  208736. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208737. jmax (screen.getY(), (int) r.top));
  208738. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208739. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208740. }
  208741. }
  208742. const Image juce_createIconForFile (const File& file)
  208743. {
  208744. Image image;
  208745. WORD iconNum = 0;
  208746. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208747. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208748. if (icon != 0)
  208749. {
  208750. image = IconConverters::createImageFromHICON (icon);
  208751. DestroyIcon (icon);
  208752. }
  208753. return image;
  208754. }
  208755. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208756. {
  208757. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208758. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208759. Image im (image);
  208760. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208761. {
  208762. im = im.rescaled (maxW, maxH);
  208763. hotspotX = (hotspotX * maxW) / image.getWidth();
  208764. hotspotY = (hotspotY * maxH) / image.getHeight();
  208765. }
  208766. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208767. }
  208768. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208769. {
  208770. if (cursorHandle != 0 && ! isStandard)
  208771. DestroyCursor ((HCURSOR) cursorHandle);
  208772. }
  208773. enum
  208774. {
  208775. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208776. };
  208777. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208778. {
  208779. LPCTSTR cursorName = IDC_ARROW;
  208780. switch (type)
  208781. {
  208782. case NormalCursor: break;
  208783. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208784. case WaitCursor: cursorName = IDC_WAIT; break;
  208785. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208786. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208787. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208788. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208789. case LeftRightResizeCursor:
  208790. case LeftEdgeResizeCursor:
  208791. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208792. case UpDownResizeCursor:
  208793. case TopEdgeResizeCursor:
  208794. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208795. case TopLeftCornerResizeCursor:
  208796. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208797. case TopRightCornerResizeCursor:
  208798. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208799. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208800. case DraggingHandCursor:
  208801. {
  208802. static void* dragHandCursor = 0;
  208803. if (dragHandCursor == 0)
  208804. {
  208805. static const unsigned char dragHandData[] =
  208806. { 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,
  208807. 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,
  208808. 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 };
  208809. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208810. }
  208811. return dragHandCursor;
  208812. }
  208813. default:
  208814. jassertfalse; break;
  208815. }
  208816. HCURSOR cursorH = LoadCursor (0, cursorName);
  208817. if (cursorH == 0)
  208818. cursorH = LoadCursor (0, IDC_ARROW);
  208819. return cursorH;
  208820. }
  208821. void MouseCursor::showInWindow (ComponentPeer*) const
  208822. {
  208823. HCURSOR c = (HCURSOR) getHandle();
  208824. if (c == 0)
  208825. c = LoadCursor (0, IDC_ARROW);
  208826. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208827. c = 0;
  208828. SetCursor (c);
  208829. }
  208830. void MouseCursor::showInAllWindows() const
  208831. {
  208832. showInWindow (0);
  208833. }
  208834. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208835. {
  208836. public:
  208837. JuceDropSource() {}
  208838. ~JuceDropSource() {}
  208839. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208840. {
  208841. if (escapePressed)
  208842. return DRAGDROP_S_CANCEL;
  208843. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208844. return DRAGDROP_S_DROP;
  208845. return S_OK;
  208846. }
  208847. HRESULT __stdcall GiveFeedback (DWORD)
  208848. {
  208849. return DRAGDROP_S_USEDEFAULTCURSORS;
  208850. }
  208851. };
  208852. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208853. {
  208854. public:
  208855. JuceEnumFormatEtc (const FORMATETC* const format_)
  208856. : format (format_),
  208857. index (0)
  208858. {
  208859. }
  208860. ~JuceEnumFormatEtc() {}
  208861. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208862. {
  208863. if (result == 0)
  208864. return E_POINTER;
  208865. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208866. newOne->index = index;
  208867. *result = newOne;
  208868. return S_OK;
  208869. }
  208870. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208871. {
  208872. if (pceltFetched != 0)
  208873. *pceltFetched = 0;
  208874. else if (celt != 1)
  208875. return S_FALSE;
  208876. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208877. {
  208878. copyFormatEtc (lpFormatEtc [0], *format);
  208879. ++index;
  208880. if (pceltFetched != 0)
  208881. *pceltFetched = 1;
  208882. return S_OK;
  208883. }
  208884. return S_FALSE;
  208885. }
  208886. HRESULT __stdcall Skip (ULONG celt)
  208887. {
  208888. if (index + (int) celt >= 1)
  208889. return S_FALSE;
  208890. index += celt;
  208891. return S_OK;
  208892. }
  208893. HRESULT __stdcall Reset()
  208894. {
  208895. index = 0;
  208896. return S_OK;
  208897. }
  208898. private:
  208899. const FORMATETC* const format;
  208900. int index;
  208901. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208902. {
  208903. dest = source;
  208904. if (source.ptd != 0)
  208905. {
  208906. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208907. *(dest.ptd) = *(source.ptd);
  208908. }
  208909. }
  208910. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208911. };
  208912. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208913. {
  208914. public:
  208915. JuceDataObject (JuceDropSource* const dropSource_,
  208916. const FORMATETC* const format_,
  208917. const STGMEDIUM* const medium_)
  208918. : dropSource (dropSource_),
  208919. format (format_),
  208920. medium (medium_)
  208921. {
  208922. }
  208923. ~JuceDataObject()
  208924. {
  208925. jassert (refCount == 0);
  208926. }
  208927. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208928. {
  208929. if ((pFormatEtc->tymed & format->tymed) != 0
  208930. && pFormatEtc->cfFormat == format->cfFormat
  208931. && pFormatEtc->dwAspect == format->dwAspect)
  208932. {
  208933. pMedium->tymed = format->tymed;
  208934. pMedium->pUnkForRelease = 0;
  208935. if (format->tymed == TYMED_HGLOBAL)
  208936. {
  208937. const SIZE_T len = GlobalSize (medium->hGlobal);
  208938. void* const src = GlobalLock (medium->hGlobal);
  208939. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208940. memcpy (dst, src, len);
  208941. GlobalUnlock (medium->hGlobal);
  208942. pMedium->hGlobal = dst;
  208943. return S_OK;
  208944. }
  208945. }
  208946. return DV_E_FORMATETC;
  208947. }
  208948. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208949. {
  208950. if (f == 0)
  208951. return E_INVALIDARG;
  208952. if (f->tymed == format->tymed
  208953. && f->cfFormat == format->cfFormat
  208954. && f->dwAspect == format->dwAspect)
  208955. return S_OK;
  208956. return DV_E_FORMATETC;
  208957. }
  208958. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208959. {
  208960. pFormatEtcOut->ptd = 0;
  208961. return E_NOTIMPL;
  208962. }
  208963. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208964. {
  208965. if (result == 0)
  208966. return E_POINTER;
  208967. if (direction == DATADIR_GET)
  208968. {
  208969. *result = new JuceEnumFormatEtc (format);
  208970. return S_OK;
  208971. }
  208972. *result = 0;
  208973. return E_NOTIMPL;
  208974. }
  208975. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208976. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208977. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208978. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208979. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208980. private:
  208981. JuceDropSource* const dropSource;
  208982. const FORMATETC* const format;
  208983. const STGMEDIUM* const medium;
  208984. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208985. };
  208986. static HDROP createHDrop (const StringArray& fileNames)
  208987. {
  208988. int totalBytes = 0;
  208989. for (int i = fileNames.size(); --i >= 0;)
  208990. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  208991. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  208992. if (hDrop != 0)
  208993. {
  208994. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208995. pDropFiles->pFiles = sizeof (DROPFILES);
  208996. pDropFiles->fWide = true;
  208997. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208998. for (int i = 0; i < fileNames.size(); ++i)
  208999. {
  209000. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  209001. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  209002. }
  209003. *fname = 0;
  209004. GlobalUnlock (hDrop);
  209005. }
  209006. return hDrop;
  209007. }
  209008. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  209009. {
  209010. JuceDropSource* const source = new JuceDropSource();
  209011. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  209012. DWORD effect;
  209013. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  209014. data->Release();
  209015. source->Release();
  209016. return res == DRAGDROP_S_DROP;
  209017. }
  209018. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  209019. {
  209020. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209021. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209022. medium.hGlobal = createHDrop (files);
  209023. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  209024. : DROPEFFECT_COPY);
  209025. }
  209026. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  209027. {
  209028. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209029. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209030. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  209031. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  209032. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  209033. text.copyToUTF16 (data, numBytes);
  209034. format.cfFormat = CF_UNICODETEXT;
  209035. GlobalUnlock (medium.hGlobal);
  209036. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  209037. }
  209038. #endif
  209039. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  209040. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  209041. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209042. // compiled on its own).
  209043. #if JUCE_INCLUDED_FILE
  209044. namespace FileChooserHelpers
  209045. {
  209046. static bool areThereAnyAlwaysOnTopWindows()
  209047. {
  209048. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  209049. {
  209050. Component* c = Desktop::getInstance().getComponent (i);
  209051. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  209052. return true;
  209053. }
  209054. return false;
  209055. }
  209056. struct FileChooserCallbackInfo
  209057. {
  209058. String initialPath;
  209059. String returnedString; // need this to get non-existent pathnames from the directory chooser
  209060. ScopedPointer<Component> customComponent;
  209061. };
  209062. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209063. {
  209064. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209065. if (msg == BFFM_INITIALIZED)
  209066. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  209067. else if (msg == BFFM_VALIDATEFAILEDW)
  209068. info->returnedString = (LPCWSTR) lParam;
  209069. else if (msg == BFFM_VALIDATEFAILEDA)
  209070. info->returnedString = (const char*) lParam;
  209071. return 0;
  209072. }
  209073. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209074. {
  209075. if (uiMsg == WM_INITDIALOG)
  209076. {
  209077. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209078. HWND dialogH = GetParent (hdlg);
  209079. jassert (dialogH != 0);
  209080. if (dialogH == 0)
  209081. dialogH = hdlg;
  209082. RECT r, cr;
  209083. GetWindowRect (dialogH, &r);
  209084. GetClientRect (dialogH, &cr);
  209085. SetWindowPos (dialogH, 0,
  209086. r.left, r.top,
  209087. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209088. jmax (150, (int) (r.bottom - r.top)),
  209089. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209090. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209091. customComp->addToDesktop (0, dialogH);
  209092. }
  209093. else if (uiMsg == WM_NOTIFY)
  209094. {
  209095. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209096. if (ofn->hdr.code == CDN_SELCHANGE)
  209097. {
  209098. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209099. FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209100. if (comp != 0)
  209101. {
  209102. WCHAR path [MAX_PATH * 2];
  209103. zerostruct (path);
  209104. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209105. comp->selectedFileChanged (File (path));
  209106. }
  209107. }
  209108. }
  209109. return 0;
  209110. }
  209111. class CustomComponentHolder : public Component
  209112. {
  209113. public:
  209114. CustomComponentHolder (Component* customComp)
  209115. {
  209116. setVisible (true);
  209117. setOpaque (true);
  209118. addAndMakeVisible (customComp);
  209119. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209120. }
  209121. void paint (Graphics& g)
  209122. {
  209123. g.fillAll (Colours::lightgrey);
  209124. }
  209125. void resized()
  209126. {
  209127. Component* const c = getChildComponent(0);
  209128. if (c != 0)
  209129. c->setBounds (getLocalBounds());
  209130. }
  209131. private:
  209132. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  209133. };
  209134. }
  209135. void FileChooser::showPlatformDialog (Array<File>& results, const String& title_, const File& currentFileOrDirectory,
  209136. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209137. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209138. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209139. {
  209140. using namespace FileChooserHelpers;
  209141. const String title (title_);
  209142. HeapBlock<WCHAR> files;
  209143. const int charsAvailableForResult = 32768;
  209144. files.calloc (charsAvailableForResult + 1);
  209145. int filenameOffset = 0;
  209146. FileChooserCallbackInfo info;
  209147. // use a modal window as the parent for this dialog box
  209148. // to block input from other app windows
  209149. Component parentWindow (String::empty);
  209150. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209151. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209152. mainMon.getY() + mainMon.getHeight() / 4,
  209153. 0, 0);
  209154. parentWindow.setOpaque (true);
  209155. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209156. parentWindow.addToDesktop (0);
  209157. if (extraInfoComponent == 0)
  209158. parentWindow.enterModalState();
  209159. if (currentFileOrDirectory.isDirectory())
  209160. {
  209161. info.initialPath = currentFileOrDirectory.getFullPathName();
  209162. }
  209163. else
  209164. {
  209165. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  209166. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209167. }
  209168. if (selectsDirectory)
  209169. {
  209170. BROWSEINFO bi;
  209171. zerostruct (bi);
  209172. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209173. bi.pszDisplayName = files;
  209174. bi.lpszTitle = title.toUTF16();
  209175. bi.lParam = (LPARAM) &info;
  209176. bi.lpfn = browseCallbackProc;
  209177. #ifdef BIF_USENEWUI
  209178. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209179. #else
  209180. bi.ulFlags = 0x50;
  209181. #endif
  209182. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209183. if (! SHGetPathFromIDListW (list, files))
  209184. {
  209185. files[0] = 0;
  209186. info.returnedString = String::empty;
  209187. }
  209188. LPMALLOC al;
  209189. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209190. al->Free (list);
  209191. if (info.returnedString.isNotEmpty())
  209192. {
  209193. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209194. return;
  209195. }
  209196. }
  209197. else
  209198. {
  209199. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209200. if (warnAboutOverwritingExistingFiles)
  209201. flags |= OFN_OVERWRITEPROMPT;
  209202. if (selectMultipleFiles)
  209203. flags |= OFN_ALLOWMULTISELECT;
  209204. if (extraInfoComponent != 0)
  209205. {
  209206. flags |= OFN_ENABLEHOOK;
  209207. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209208. info.customComponent->enterModalState();
  209209. }
  209210. const int filterSpaceNumChars = 2048;
  209211. HeapBlock<WCHAR> filters;
  209212. filters.calloc (filterSpaceNumChars);
  209213. const int bytesWritten = filter.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  209214. filter.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)) + 1,
  209215. (filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten);
  209216. OPENFILENAMEW of;
  209217. zerostruct (of);
  209218. String localPath (info.initialPath);
  209219. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209220. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209221. #else
  209222. of.lStructSize = sizeof (of);
  209223. #endif
  209224. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209225. of.lpstrFilter = filters.getData();
  209226. of.nFilterIndex = 1;
  209227. of.lpstrFile = files;
  209228. of.nMaxFile = charsAvailableForResult;
  209229. of.lpstrInitialDir = localPath.toUTF16();
  209230. of.lpstrTitle = title.toUTF16();
  209231. of.Flags = flags;
  209232. of.lCustData = (LPARAM) &info;
  209233. if (extraInfoComponent != 0)
  209234. of.lpfnHook = &openCallback;
  209235. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209236. : GetOpenFileName (&of)))
  209237. return;
  209238. filenameOffset = of.nFileOffset;
  209239. }
  209240. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209241. {
  209242. const WCHAR* filename = files + filenameOffset;
  209243. while (*filename != 0)
  209244. {
  209245. results.add (File (String (files) + "\\" + String (filename)));
  209246. filename += wcslen (filename) + 1;
  209247. }
  209248. }
  209249. else if (files[0] != 0)
  209250. {
  209251. results.add (File (String (files)));
  209252. }
  209253. }
  209254. #endif
  209255. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209256. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209257. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209258. // compiled on its own).
  209259. #if JUCE_INCLUDED_FILE
  209260. void SystemClipboard::copyTextToClipboard (const String& text)
  209261. {
  209262. if (OpenClipboard (0) != 0)
  209263. {
  209264. if (EmptyClipboard() != 0)
  209265. {
  209266. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  209267. if (bytesNeeded > 0)
  209268. {
  209269. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  209270. if (bufH != 0)
  209271. {
  209272. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209273. text.copyToUTF16 (data, bytesNeeded);
  209274. GlobalUnlock (bufH);
  209275. SetClipboardData (CF_UNICODETEXT, bufH);
  209276. }
  209277. }
  209278. }
  209279. CloseClipboard();
  209280. }
  209281. }
  209282. const String SystemClipboard::getTextFromClipboard()
  209283. {
  209284. String result;
  209285. if (OpenClipboard (0) != 0)
  209286. {
  209287. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209288. if (bufH != 0)
  209289. {
  209290. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  209291. if (data != 0)
  209292. {
  209293. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  209294. GlobalUnlock (bufH);
  209295. }
  209296. }
  209297. CloseClipboard();
  209298. }
  209299. return result;
  209300. }
  209301. #endif
  209302. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209303. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209304. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209305. // compiled on its own).
  209306. #if JUCE_INCLUDED_FILE
  209307. namespace ActiveXHelpers
  209308. {
  209309. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209310. {
  209311. public:
  209312. JuceIStorage() {}
  209313. ~JuceIStorage() {}
  209314. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209315. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209316. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209317. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209318. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209319. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209320. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209321. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209322. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209323. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209324. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209325. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209326. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209327. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209328. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209329. };
  209330. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209331. {
  209332. HWND window;
  209333. public:
  209334. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209335. ~JuceOleInPlaceFrame() {}
  209336. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209337. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209338. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209339. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209340. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209341. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209342. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209343. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209344. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209345. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209346. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209347. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209348. };
  209349. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209350. {
  209351. HWND window;
  209352. JuceOleInPlaceFrame* frame;
  209353. public:
  209354. JuceIOleInPlaceSite (HWND window_)
  209355. : window (window_),
  209356. frame (new JuceOleInPlaceFrame (window))
  209357. {}
  209358. ~JuceIOleInPlaceSite()
  209359. {
  209360. frame->Release();
  209361. }
  209362. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209363. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209364. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209365. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209366. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209367. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209368. {
  209369. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209370. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209371. */
  209372. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209373. if (lplpDoc != 0) *lplpDoc = 0;
  209374. lpFrameInfo->fMDIApp = FALSE;
  209375. lpFrameInfo->hwndFrame = window;
  209376. lpFrameInfo->haccel = 0;
  209377. lpFrameInfo->cAccelEntries = 0;
  209378. return S_OK;
  209379. }
  209380. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209381. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209382. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209383. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209384. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209385. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209386. };
  209387. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209388. {
  209389. JuceIOleInPlaceSite* inplaceSite;
  209390. public:
  209391. JuceIOleClientSite (HWND window)
  209392. : inplaceSite (new JuceIOleInPlaceSite (window))
  209393. {}
  209394. ~JuceIOleClientSite()
  209395. {
  209396. inplaceSite->Release();
  209397. }
  209398. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209399. {
  209400. if (type == IID_IOleInPlaceSite)
  209401. {
  209402. inplaceSite->AddRef();
  209403. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209404. return S_OK;
  209405. }
  209406. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209407. }
  209408. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209409. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209410. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209411. HRESULT __stdcall ShowObject() { return S_OK; }
  209412. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209413. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209414. };
  209415. static Array<ActiveXControlComponent*> activeXComps;
  209416. static HWND getHWND (const ActiveXControlComponent* const component)
  209417. {
  209418. HWND hwnd = 0;
  209419. const IID iid = IID_IOleWindow;
  209420. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209421. if (window != 0)
  209422. {
  209423. window->GetWindow (&hwnd);
  209424. window->Release();
  209425. }
  209426. return hwnd;
  209427. }
  209428. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209429. {
  209430. RECT activeXRect, peerRect;
  209431. GetWindowRect (hwnd, &activeXRect);
  209432. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209433. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209434. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209435. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209436. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209437. switch (message)
  209438. {
  209439. case WM_MOUSEMOVE:
  209440. case WM_LBUTTONDOWN:
  209441. case WM_MBUTTONDOWN:
  209442. case WM_RBUTTONDOWN:
  209443. case WM_LBUTTONUP:
  209444. case WM_MBUTTONUP:
  209445. case WM_RBUTTONUP:
  209446. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209447. break;
  209448. default:
  209449. break;
  209450. }
  209451. }
  209452. }
  209453. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209454. {
  209455. public:
  209456. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209457. : ComponentMovementWatcher (&owner_),
  209458. owner (owner_),
  209459. controlHWND (0),
  209460. storage (new ActiveXHelpers::JuceIStorage()),
  209461. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209462. control (0)
  209463. {
  209464. }
  209465. ~Pimpl()
  209466. {
  209467. if (control != 0)
  209468. {
  209469. control->Close (OLECLOSE_NOSAVE);
  209470. control->Release();
  209471. }
  209472. clientSite->Release();
  209473. storage->Release();
  209474. }
  209475. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209476. {
  209477. Component* const topComp = owner.getTopLevelComponent();
  209478. if (topComp->getPeer() != 0)
  209479. {
  209480. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209481. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209482. }
  209483. }
  209484. void componentPeerChanged()
  209485. {
  209486. componentMovedOrResized (true, true);
  209487. }
  209488. void componentVisibilityChanged()
  209489. {
  209490. owner.setControlVisible (owner.isShowing());
  209491. componentPeerChanged();
  209492. }
  209493. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209494. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209495. {
  209496. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209497. {
  209498. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209499. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209500. {
  209501. switch (message)
  209502. {
  209503. case WM_MOUSEMOVE:
  209504. case WM_LBUTTONDOWN:
  209505. case WM_MBUTTONDOWN:
  209506. case WM_RBUTTONDOWN:
  209507. case WM_LBUTTONUP:
  209508. case WM_MBUTTONUP:
  209509. case WM_RBUTTONUP:
  209510. case WM_LBUTTONDBLCLK:
  209511. case WM_MBUTTONDBLCLK:
  209512. case WM_RBUTTONDBLCLK:
  209513. if (ax->isShowing())
  209514. {
  209515. ComponentPeer* const peer = ax->getPeer();
  209516. if (peer != 0)
  209517. {
  209518. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209519. if (! ax->areMouseEventsAllowed())
  209520. return 0;
  209521. }
  209522. }
  209523. break;
  209524. default:
  209525. break;
  209526. }
  209527. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209528. }
  209529. }
  209530. return DefWindowProc (hwnd, message, wParam, lParam);
  209531. }
  209532. private:
  209533. ActiveXControlComponent& owner;
  209534. public:
  209535. HWND controlHWND;
  209536. IStorage* storage;
  209537. IOleClientSite* clientSite;
  209538. IOleObject* control;
  209539. };
  209540. ActiveXControlComponent::ActiveXControlComponent()
  209541. : originalWndProc (0),
  209542. mouseEventsAllowed (true)
  209543. {
  209544. ActiveXHelpers::activeXComps.add (this);
  209545. }
  209546. ActiveXControlComponent::~ActiveXControlComponent()
  209547. {
  209548. deleteControl();
  209549. ActiveXHelpers::activeXComps.removeValue (this);
  209550. }
  209551. void ActiveXControlComponent::paint (Graphics& g)
  209552. {
  209553. if (control == 0)
  209554. g.fillAll (Colours::lightgrey);
  209555. }
  209556. bool ActiveXControlComponent::createControl (const void* controlIID)
  209557. {
  209558. deleteControl();
  209559. ComponentPeer* const peer = getPeer();
  209560. // the component must have already been added to a real window when you call this!
  209561. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209562. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209563. {
  209564. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209565. HWND hwnd = (HWND) peer->getNativeHandle();
  209566. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209567. HRESULT hr;
  209568. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209569. newControl->clientSite, newControl->storage,
  209570. (void**) &(newControl->control))) == S_OK)
  209571. {
  209572. newControl->control->SetHostNames (L"Juce", 0);
  209573. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209574. {
  209575. RECT rect;
  209576. rect.left = pos.getX();
  209577. rect.top = pos.getY();
  209578. rect.right = pos.getX() + getWidth();
  209579. rect.bottom = pos.getY() + getHeight();
  209580. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209581. {
  209582. control = newControl;
  209583. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209584. control->controlHWND = ActiveXHelpers::getHWND (this);
  209585. if (control->controlHWND != 0)
  209586. {
  209587. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209588. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209589. }
  209590. return true;
  209591. }
  209592. }
  209593. }
  209594. }
  209595. return false;
  209596. }
  209597. void ActiveXControlComponent::deleteControl()
  209598. {
  209599. control = 0;
  209600. originalWndProc = 0;
  209601. }
  209602. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209603. {
  209604. void* result = 0;
  209605. if (control != 0 && control->control != 0
  209606. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209607. return result;
  209608. return 0;
  209609. }
  209610. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209611. {
  209612. if (control->controlHWND != 0)
  209613. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209614. }
  209615. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209616. {
  209617. if (control->controlHWND != 0)
  209618. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209619. }
  209620. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209621. {
  209622. mouseEventsAllowed = eventsCanReachControl;
  209623. }
  209624. #endif
  209625. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209626. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209627. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209628. // compiled on its own).
  209629. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209630. using namespace QTOLibrary;
  209631. using namespace QTOControlLib;
  209632. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209633. static bool isQTAvailable = false;
  209634. class QuickTimeMovieComponent::Pimpl
  209635. {
  209636. public:
  209637. Pimpl() : dataHandle (0)
  209638. {
  209639. }
  209640. ~Pimpl()
  209641. {
  209642. clearHandle();
  209643. }
  209644. void clearHandle()
  209645. {
  209646. if (dataHandle != 0)
  209647. {
  209648. DisposeHandle (dataHandle);
  209649. dataHandle = 0;
  209650. }
  209651. }
  209652. IQTControlPtr qtControl;
  209653. IQTMoviePtr qtMovie;
  209654. Handle dataHandle;
  209655. };
  209656. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209657. : movieLoaded (false),
  209658. controllerVisible (true)
  209659. {
  209660. pimpl = new Pimpl();
  209661. setMouseEventsAllowed (false);
  209662. }
  209663. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209664. {
  209665. closeMovie();
  209666. pimpl->qtControl = 0;
  209667. deleteControl();
  209668. pimpl = 0;
  209669. }
  209670. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209671. {
  209672. if (! isQTAvailable)
  209673. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209674. return isQTAvailable;
  209675. }
  209676. void QuickTimeMovieComponent::createControlIfNeeded()
  209677. {
  209678. if (isShowing() && ! isControlCreated())
  209679. {
  209680. const IID qtIID = __uuidof (QTControl);
  209681. if (createControl (&qtIID))
  209682. {
  209683. const IID qtInterfaceIID = __uuidof (IQTControl);
  209684. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209685. if (pimpl->qtControl != 0)
  209686. {
  209687. pimpl->qtControl->Release(); // it has one ref too many at this point
  209688. pimpl->qtControl->QuickTimeInitialize();
  209689. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209690. if (movieFile != File::nonexistent)
  209691. loadMovie (movieFile, controllerVisible);
  209692. }
  209693. }
  209694. }
  209695. }
  209696. bool QuickTimeMovieComponent::isControlCreated() const
  209697. {
  209698. return isControlOpen();
  209699. }
  209700. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209701. const bool isControllerVisible)
  209702. {
  209703. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209704. movieFile = File::nonexistent;
  209705. movieLoaded = false;
  209706. pimpl->qtMovie = 0;
  209707. controllerVisible = isControllerVisible;
  209708. createControlIfNeeded();
  209709. if (isControlCreated())
  209710. {
  209711. if (pimpl->qtControl != 0)
  209712. {
  209713. pimpl->qtControl->Put_MovieHandle (0);
  209714. pimpl->clearHandle();
  209715. Movie movie;
  209716. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209717. {
  209718. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209719. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209720. if (pimpl->qtMovie != 0)
  209721. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209722. : qtMovieControllerTypeNone);
  209723. }
  209724. if (movie == 0)
  209725. pimpl->clearHandle();
  209726. }
  209727. movieLoaded = (pimpl->qtMovie != 0);
  209728. }
  209729. else
  209730. {
  209731. // You're trying to open a movie when the control hasn't yet been created, probably because
  209732. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209733. jassertfalse;
  209734. }
  209735. return movieLoaded;
  209736. }
  209737. void QuickTimeMovieComponent::closeMovie()
  209738. {
  209739. stop();
  209740. movieFile = File::nonexistent;
  209741. movieLoaded = false;
  209742. pimpl->qtMovie = 0;
  209743. if (pimpl->qtControl != 0)
  209744. pimpl->qtControl->Put_MovieHandle (0);
  209745. pimpl->clearHandle();
  209746. }
  209747. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209748. {
  209749. return movieFile;
  209750. }
  209751. bool QuickTimeMovieComponent::isMovieOpen() const
  209752. {
  209753. return movieLoaded;
  209754. }
  209755. double QuickTimeMovieComponent::getMovieDuration() const
  209756. {
  209757. if (pimpl->qtMovie != 0)
  209758. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209759. return 0.0;
  209760. }
  209761. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209762. {
  209763. if (pimpl->qtMovie != 0)
  209764. {
  209765. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209766. width = r.right - r.left;
  209767. height = r.bottom - r.top;
  209768. }
  209769. else
  209770. {
  209771. width = height = 0;
  209772. }
  209773. }
  209774. void QuickTimeMovieComponent::play()
  209775. {
  209776. if (pimpl->qtMovie != 0)
  209777. pimpl->qtMovie->Play();
  209778. }
  209779. void QuickTimeMovieComponent::stop()
  209780. {
  209781. if (pimpl->qtMovie != 0)
  209782. pimpl->qtMovie->Stop();
  209783. }
  209784. bool QuickTimeMovieComponent::isPlaying() const
  209785. {
  209786. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209787. }
  209788. void QuickTimeMovieComponent::setPosition (const double seconds)
  209789. {
  209790. if (pimpl->qtMovie != 0)
  209791. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209792. }
  209793. double QuickTimeMovieComponent::getPosition() const
  209794. {
  209795. if (pimpl->qtMovie != 0)
  209796. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209797. return 0.0;
  209798. }
  209799. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209800. {
  209801. if (pimpl->qtMovie != 0)
  209802. pimpl->qtMovie->PutRate (newSpeed);
  209803. }
  209804. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209805. {
  209806. if (pimpl->qtMovie != 0)
  209807. {
  209808. pimpl->qtMovie->PutAudioVolume (newVolume);
  209809. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209810. }
  209811. }
  209812. float QuickTimeMovieComponent::getMovieVolume() const
  209813. {
  209814. if (pimpl->qtMovie != 0)
  209815. return pimpl->qtMovie->GetAudioVolume();
  209816. return 0.0f;
  209817. }
  209818. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209819. {
  209820. if (pimpl->qtMovie != 0)
  209821. pimpl->qtMovie->PutLoop (shouldLoop);
  209822. }
  209823. bool QuickTimeMovieComponent::isLooping() const
  209824. {
  209825. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209826. }
  209827. bool QuickTimeMovieComponent::isControllerVisible() const
  209828. {
  209829. return controllerVisible;
  209830. }
  209831. void QuickTimeMovieComponent::parentHierarchyChanged()
  209832. {
  209833. createControlIfNeeded();
  209834. QTCompBaseClass::parentHierarchyChanged();
  209835. }
  209836. void QuickTimeMovieComponent::visibilityChanged()
  209837. {
  209838. createControlIfNeeded();
  209839. QTCompBaseClass::visibilityChanged();
  209840. }
  209841. void QuickTimeMovieComponent::paint (Graphics& g)
  209842. {
  209843. if (! isControlCreated())
  209844. g.fillAll (Colours::black);
  209845. }
  209846. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209847. {
  209848. Handle dataRef = 0;
  209849. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209850. if (err == noErr)
  209851. {
  209852. Str255 suffix;
  209853. strncpy ((char*) suffix, fileName, 128);
  209854. StringPtr name = suffix;
  209855. err = PtrAndHand (name, dataRef, name[0] + 1);
  209856. if (err == noErr)
  209857. {
  209858. long atoms[3];
  209859. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209860. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209861. atoms[2] = EndianU32_NtoB (MovieFileType);
  209862. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209863. if (err == noErr)
  209864. return dataRef;
  209865. }
  209866. DisposeHandle (dataRef);
  209867. }
  209868. return 0;
  209869. }
  209870. static CFStringRef juceStringToCFString (const String& s)
  209871. {
  209872. return CFStringCreateWithCString (kCFAllocatorDefault, s.toUTF8(), kCFStringEncodingUTF8);
  209873. }
  209874. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209875. {
  209876. Boolean trueBool = true;
  209877. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209878. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209879. props[prop].propValueSize = sizeof (trueBool);
  209880. props[prop].propValueAddress = &trueBool;
  209881. ++prop;
  209882. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209883. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209884. props[prop].propValueSize = sizeof (trueBool);
  209885. props[prop].propValueAddress = &trueBool;
  209886. ++prop;
  209887. Boolean isActive = true;
  209888. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209889. props[prop].propID = kQTNewMoviePropertyID_Active;
  209890. props[prop].propValueSize = sizeof (isActive);
  209891. props[prop].propValueAddress = &isActive;
  209892. ++prop;
  209893. MacSetPort (0);
  209894. jassert (prop <= 5);
  209895. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209896. return err == noErr;
  209897. }
  209898. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209899. {
  209900. if (input == 0)
  209901. return false;
  209902. dataHandle = 0;
  209903. bool ok = false;
  209904. QTNewMoviePropertyElement props[5];
  209905. zeromem (props, sizeof (props));
  209906. int prop = 0;
  209907. DataReferenceRecord dr;
  209908. props[prop].propClass = kQTPropertyClass_DataLocation;
  209909. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209910. props[prop].propValueSize = sizeof (dr);
  209911. props[prop].propValueAddress = &dr;
  209912. ++prop;
  209913. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209914. if (fin != 0)
  209915. {
  209916. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209917. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209918. &dr.dataRef, &dr.dataRefType);
  209919. ok = openMovie (props, prop, movie);
  209920. DisposeHandle (dr.dataRef);
  209921. CFRelease (filePath);
  209922. }
  209923. else
  209924. {
  209925. // sanity-check because this currently needs to load the whole stream into memory..
  209926. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209927. dataHandle = NewHandle ((Size) input->getTotalLength());
  209928. HLock (dataHandle);
  209929. // read the entire stream into memory - this is a pain, but can't get it to work
  209930. // properly using a custom callback to supply the data.
  209931. input->read (*dataHandle, (int) input->getTotalLength());
  209932. HUnlock (dataHandle);
  209933. // different types to get QT to try. (We should really be a bit smarter here by
  209934. // working out in advance which one the stream contains, rather than just trying
  209935. // each one)
  209936. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209937. "\04.avi", "\04.m4a" };
  209938. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209939. {
  209940. /* // this fails for some bizarre reason - it can be bodged to work with
  209941. // movies, but can't seem to do it for other file types..
  209942. QTNewMovieUserProcRecord procInfo;
  209943. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209944. procInfo.getMovieUserProcRefcon = this;
  209945. procInfo.defaultDataRef.dataRef = dataRef;
  209946. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209947. props[prop].propClass = kQTPropertyClass_DataLocation;
  209948. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209949. props[prop].propValueSize = sizeof (procInfo);
  209950. props[prop].propValueAddress = (void*) &procInfo;
  209951. ++prop; */
  209952. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209953. dr.dataRefType = HandleDataHandlerSubType;
  209954. ok = openMovie (props, prop, movie);
  209955. DisposeHandle (dr.dataRef);
  209956. }
  209957. }
  209958. return ok;
  209959. }
  209960. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209961. const bool isControllerVisible)
  209962. {
  209963. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209964. movieFile = movieFile_;
  209965. return ok;
  209966. }
  209967. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209968. const bool isControllerVisible)
  209969. {
  209970. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209971. }
  209972. void QuickTimeMovieComponent::goToStart()
  209973. {
  209974. setPosition (0.0);
  209975. }
  209976. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209977. const RectanglePlacement& placement)
  209978. {
  209979. int normalWidth, normalHeight;
  209980. getMovieNormalSize (normalWidth, normalHeight);
  209981. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209982. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209983. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209984. else
  209985. setBounds (spaceToFitWithin);
  209986. }
  209987. #endif
  209988. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209989. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209990. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209991. // compiled on its own).
  209992. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209993. class WebBrowserComponentInternal : public ActiveXControlComponent
  209994. {
  209995. public:
  209996. WebBrowserComponentInternal()
  209997. : browser (0),
  209998. connectionPoint (0),
  209999. adviseCookie (0)
  210000. {
  210001. }
  210002. ~WebBrowserComponentInternal()
  210003. {
  210004. if (connectionPoint != 0)
  210005. connectionPoint->Unadvise (adviseCookie);
  210006. if (browser != 0)
  210007. browser->Release();
  210008. }
  210009. void createBrowser()
  210010. {
  210011. createControl (&CLSID_WebBrowser);
  210012. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210013. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210014. if (connectionPointContainer != 0)
  210015. {
  210016. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210017. &connectionPoint);
  210018. if (connectionPoint != 0)
  210019. {
  210020. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210021. jassert (owner != 0);
  210022. EventHandler* handler = new EventHandler (*owner);
  210023. connectionPoint->Advise (handler, &adviseCookie);
  210024. handler->Release();
  210025. }
  210026. }
  210027. }
  210028. void goToURL (const String& url,
  210029. const StringArray* headers,
  210030. const MemoryBlock* postData)
  210031. {
  210032. if (browser != 0)
  210033. {
  210034. LPSAFEARRAY sa = 0;
  210035. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  210036. VariantInit (&flags);
  210037. VariantInit (&frame);
  210038. VariantInit (&postDataVar);
  210039. VariantInit (&headersVar);
  210040. if (headers != 0)
  210041. {
  210042. V_VT (&headersVar) = VT_BSTR;
  210043. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  210044. }
  210045. if (postData != 0 && postData->getSize() > 0)
  210046. {
  210047. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210048. if (sa != 0)
  210049. {
  210050. void* data = 0;
  210051. SafeArrayAccessData (sa, &data);
  210052. jassert (data != 0);
  210053. if (data != 0)
  210054. {
  210055. postData->copyTo (data, 0, postData->getSize());
  210056. SafeArrayUnaccessData (sa);
  210057. VARIANT postDataVar2;
  210058. VariantInit (&postDataVar2);
  210059. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210060. V_ARRAY (&postDataVar2) = sa;
  210061. postDataVar = postDataVar2;
  210062. }
  210063. }
  210064. }
  210065. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  210066. &flags, &frame,
  210067. &postDataVar, &headersVar);
  210068. if (sa != 0)
  210069. SafeArrayDestroy (sa);
  210070. VariantClear (&flags);
  210071. VariantClear (&frame);
  210072. VariantClear (&postDataVar);
  210073. VariantClear (&headersVar);
  210074. }
  210075. }
  210076. IWebBrowser2* browser;
  210077. private:
  210078. IConnectionPoint* connectionPoint;
  210079. DWORD adviseCookie;
  210080. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210081. public ComponentMovementWatcher
  210082. {
  210083. public:
  210084. EventHandler (WebBrowserComponent& owner_)
  210085. : ComponentMovementWatcher (&owner_),
  210086. owner (owner_)
  210087. {
  210088. }
  210089. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210090. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210091. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210092. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210093. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  210094. {
  210095. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  210096. {
  210097. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210098. String url;
  210099. if ((vurl->vt & VT_BYREF) != 0)
  210100. url = *vurl->pbstrVal;
  210101. else
  210102. url = vurl->bstrVal;
  210103. *pDispParams->rgvarg->pboolVal
  210104. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  210105. : VARIANT_TRUE;
  210106. return S_OK;
  210107. }
  210108. return E_NOTIMPL;
  210109. }
  210110. void componentMovedOrResized (bool, bool ) {}
  210111. void componentPeerChanged() {}
  210112. void componentVisibilityChanged() { owner.visibilityChanged(); }
  210113. private:
  210114. WebBrowserComponent& owner;
  210115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  210116. };
  210117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  210118. };
  210119. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210120. : browser (0),
  210121. blankPageShown (false),
  210122. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210123. {
  210124. setOpaque (true);
  210125. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210126. }
  210127. WebBrowserComponent::~WebBrowserComponent()
  210128. {
  210129. delete browser;
  210130. }
  210131. void WebBrowserComponent::goToURL (const String& url,
  210132. const StringArray* headers,
  210133. const MemoryBlock* postData)
  210134. {
  210135. lastURL = url;
  210136. lastHeaders.clear();
  210137. if (headers != 0)
  210138. lastHeaders = *headers;
  210139. lastPostData.setSize (0);
  210140. if (postData != 0)
  210141. lastPostData = *postData;
  210142. blankPageShown = false;
  210143. browser->goToURL (url, headers, postData);
  210144. }
  210145. void WebBrowserComponent::stop()
  210146. {
  210147. if (browser->browser != 0)
  210148. browser->browser->Stop();
  210149. }
  210150. void WebBrowserComponent::goBack()
  210151. {
  210152. lastURL = String::empty;
  210153. blankPageShown = false;
  210154. if (browser->browser != 0)
  210155. browser->browser->GoBack();
  210156. }
  210157. void WebBrowserComponent::goForward()
  210158. {
  210159. lastURL = String::empty;
  210160. if (browser->browser != 0)
  210161. browser->browser->GoForward();
  210162. }
  210163. void WebBrowserComponent::refresh()
  210164. {
  210165. if (browser->browser != 0)
  210166. browser->browser->Refresh();
  210167. }
  210168. void WebBrowserComponent::paint (Graphics& g)
  210169. {
  210170. if (browser->browser == 0)
  210171. g.fillAll (Colours::white);
  210172. }
  210173. void WebBrowserComponent::checkWindowAssociation()
  210174. {
  210175. if (isShowing())
  210176. {
  210177. if (browser->browser == 0 && getPeer() != 0)
  210178. {
  210179. browser->createBrowser();
  210180. reloadLastURL();
  210181. }
  210182. else
  210183. {
  210184. if (blankPageShown)
  210185. goBack();
  210186. }
  210187. }
  210188. else
  210189. {
  210190. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210191. {
  210192. // when the component becomes invisible, some stuff like flash
  210193. // carries on playing audio, so we need to force it onto a blank
  210194. // page to avoid this..
  210195. blankPageShown = true;
  210196. browser->goToURL ("about:blank", 0, 0);
  210197. }
  210198. }
  210199. }
  210200. void WebBrowserComponent::reloadLastURL()
  210201. {
  210202. if (lastURL.isNotEmpty())
  210203. {
  210204. goToURL (lastURL, &lastHeaders, &lastPostData);
  210205. lastURL = String::empty;
  210206. }
  210207. }
  210208. void WebBrowserComponent::parentHierarchyChanged()
  210209. {
  210210. checkWindowAssociation();
  210211. }
  210212. void WebBrowserComponent::resized()
  210213. {
  210214. browser->setSize (getWidth(), getHeight());
  210215. }
  210216. void WebBrowserComponent::visibilityChanged()
  210217. {
  210218. checkWindowAssociation();
  210219. }
  210220. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210221. {
  210222. return true;
  210223. }
  210224. #endif
  210225. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210226. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210227. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210228. // compiled on its own).
  210229. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210230. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210231. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210232. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210233. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210234. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210235. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210236. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210237. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210238. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210239. #define WGL_ACCELERATION_ARB 0x2003
  210240. #define WGL_SWAP_METHOD_ARB 0x2007
  210241. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210242. #define WGL_PIXEL_TYPE_ARB 0x2013
  210243. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210244. #define WGL_COLOR_BITS_ARB 0x2014
  210245. #define WGL_RED_BITS_ARB 0x2015
  210246. #define WGL_GREEN_BITS_ARB 0x2017
  210247. #define WGL_BLUE_BITS_ARB 0x2019
  210248. #define WGL_ALPHA_BITS_ARB 0x201B
  210249. #define WGL_DEPTH_BITS_ARB 0x2022
  210250. #define WGL_STENCIL_BITS_ARB 0x2023
  210251. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210252. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210253. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210254. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210255. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210256. #define WGL_STEREO_ARB 0x2012
  210257. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210258. #define WGL_SAMPLES_ARB 0x2042
  210259. #define WGL_TYPE_RGBA_ARB 0x202B
  210260. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210261. {
  210262. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210263. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210264. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210265. else
  210266. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210267. }
  210268. class WindowedGLContext : public OpenGLContext
  210269. {
  210270. public:
  210271. WindowedGLContext (Component* const component_,
  210272. HGLRC contextToShareWith,
  210273. const OpenGLPixelFormat& pixelFormat)
  210274. : renderContext (0),
  210275. component (component_),
  210276. dc (0)
  210277. {
  210278. jassert (component != 0);
  210279. createNativeWindow();
  210280. // Use a default pixel format that should be supported everywhere
  210281. PIXELFORMATDESCRIPTOR pfd;
  210282. zerostruct (pfd);
  210283. pfd.nSize = sizeof (pfd);
  210284. pfd.nVersion = 1;
  210285. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210286. pfd.iPixelType = PFD_TYPE_RGBA;
  210287. pfd.cColorBits = 24;
  210288. pfd.cDepthBits = 16;
  210289. const int format = ChoosePixelFormat (dc, &pfd);
  210290. if (format != 0)
  210291. SetPixelFormat (dc, format, &pfd);
  210292. renderContext = wglCreateContext (dc);
  210293. makeActive();
  210294. setPixelFormat (pixelFormat);
  210295. if (contextToShareWith != 0 && renderContext != 0)
  210296. wglShareLists (contextToShareWith, renderContext);
  210297. }
  210298. ~WindowedGLContext()
  210299. {
  210300. deleteContext();
  210301. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210302. nativeWindow = 0;
  210303. }
  210304. void deleteContext()
  210305. {
  210306. makeInactive();
  210307. if (renderContext != 0)
  210308. {
  210309. wglDeleteContext (renderContext);
  210310. renderContext = 0;
  210311. }
  210312. }
  210313. bool makeActive() const throw()
  210314. {
  210315. jassert (renderContext != 0);
  210316. return wglMakeCurrent (dc, renderContext) != 0;
  210317. }
  210318. bool makeInactive() const throw()
  210319. {
  210320. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210321. }
  210322. bool isActive() const throw()
  210323. {
  210324. return wglGetCurrentContext() == renderContext;
  210325. }
  210326. const OpenGLPixelFormat getPixelFormat() const
  210327. {
  210328. OpenGLPixelFormat pf;
  210329. makeActive();
  210330. StringArray availableExtensions;
  210331. getWglExtensions (dc, availableExtensions);
  210332. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210333. return pf;
  210334. }
  210335. void* getRawContext() const throw()
  210336. {
  210337. return renderContext;
  210338. }
  210339. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210340. {
  210341. makeActive();
  210342. PIXELFORMATDESCRIPTOR pfd;
  210343. zerostruct (pfd);
  210344. pfd.nSize = sizeof (pfd);
  210345. pfd.nVersion = 1;
  210346. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210347. pfd.iPixelType = PFD_TYPE_RGBA;
  210348. pfd.iLayerType = PFD_MAIN_PLANE;
  210349. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210350. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210351. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210352. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210353. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210354. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210355. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210356. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210357. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210358. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210359. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210360. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210361. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210362. int format = 0;
  210363. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210364. StringArray availableExtensions;
  210365. getWglExtensions (dc, availableExtensions);
  210366. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210367. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210368. {
  210369. int attributes[64];
  210370. int n = 0;
  210371. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210372. attributes[n++] = GL_TRUE;
  210373. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210374. attributes[n++] = GL_TRUE;
  210375. attributes[n++] = WGL_ACCELERATION_ARB;
  210376. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210377. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210378. attributes[n++] = GL_TRUE;
  210379. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210380. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210381. attributes[n++] = WGL_COLOR_BITS_ARB;
  210382. attributes[n++] = pfd.cColorBits;
  210383. attributes[n++] = WGL_RED_BITS_ARB;
  210384. attributes[n++] = pixelFormat.redBits;
  210385. attributes[n++] = WGL_GREEN_BITS_ARB;
  210386. attributes[n++] = pixelFormat.greenBits;
  210387. attributes[n++] = WGL_BLUE_BITS_ARB;
  210388. attributes[n++] = pixelFormat.blueBits;
  210389. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210390. attributes[n++] = pixelFormat.alphaBits;
  210391. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210392. attributes[n++] = pixelFormat.depthBufferBits;
  210393. if (pixelFormat.stencilBufferBits > 0)
  210394. {
  210395. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210396. attributes[n++] = pixelFormat.stencilBufferBits;
  210397. }
  210398. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210399. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210400. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210401. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210402. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210403. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210404. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210405. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210406. if (availableExtensions.contains ("WGL_ARB_multisample")
  210407. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210408. {
  210409. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210410. attributes[n++] = 1;
  210411. attributes[n++] = WGL_SAMPLES_ARB;
  210412. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210413. }
  210414. attributes[n++] = 0;
  210415. UINT formatsCount;
  210416. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210417. (void) ok;
  210418. jassert (ok);
  210419. }
  210420. else
  210421. {
  210422. format = ChoosePixelFormat (dc, &pfd);
  210423. }
  210424. if (format != 0)
  210425. {
  210426. makeInactive();
  210427. // win32 can't change the pixel format of a window, so need to delete the
  210428. // old one and create a new one..
  210429. jassert (nativeWindow != 0);
  210430. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210431. nativeWindow = 0;
  210432. createNativeWindow();
  210433. if (SetPixelFormat (dc, format, &pfd))
  210434. {
  210435. wglDeleteContext (renderContext);
  210436. renderContext = wglCreateContext (dc);
  210437. jassert (renderContext != 0);
  210438. return renderContext != 0;
  210439. }
  210440. }
  210441. return false;
  210442. }
  210443. void updateWindowPosition (int x, int y, int w, int h, int)
  210444. {
  210445. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210446. x, y, w, h,
  210447. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210448. }
  210449. void repaint()
  210450. {
  210451. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210452. }
  210453. void swapBuffers()
  210454. {
  210455. SwapBuffers (dc);
  210456. }
  210457. bool setSwapInterval (int numFramesPerSwap)
  210458. {
  210459. makeActive();
  210460. StringArray availableExtensions;
  210461. getWglExtensions (dc, availableExtensions);
  210462. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210463. return availableExtensions.contains ("WGL_EXT_swap_control")
  210464. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210465. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210466. }
  210467. int getSwapInterval() const
  210468. {
  210469. makeActive();
  210470. StringArray availableExtensions;
  210471. getWglExtensions (dc, availableExtensions);
  210472. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210473. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210474. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210475. return wglGetSwapIntervalEXT();
  210476. return 0;
  210477. }
  210478. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210479. {
  210480. jassert (isActive());
  210481. StringArray availableExtensions;
  210482. getWglExtensions (dc, availableExtensions);
  210483. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210484. int numTypes = 0;
  210485. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210486. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210487. {
  210488. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210489. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210490. jassertfalse;
  210491. }
  210492. else
  210493. {
  210494. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210495. }
  210496. OpenGLPixelFormat pf;
  210497. for (int i = 0; i < numTypes; ++i)
  210498. {
  210499. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210500. {
  210501. bool alreadyListed = false;
  210502. for (int j = results.size(); --j >= 0;)
  210503. if (pf == *results.getUnchecked(j))
  210504. alreadyListed = true;
  210505. if (! alreadyListed)
  210506. results.add (new OpenGLPixelFormat (pf));
  210507. }
  210508. }
  210509. }
  210510. void* getNativeWindowHandle() const
  210511. {
  210512. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210513. }
  210514. HGLRC renderContext;
  210515. private:
  210516. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210517. Component* const component;
  210518. HDC dc;
  210519. void createNativeWindow()
  210520. {
  210521. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210522. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210523. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210524. nativeWindow->dontRepaint = true;
  210525. nativeWindow->setVisible (true);
  210526. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210527. }
  210528. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210529. OpenGLPixelFormat& result,
  210530. const StringArray& availableExtensions) const throw()
  210531. {
  210532. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210533. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210534. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210535. {
  210536. int attributes[32];
  210537. int numAttributes = 0;
  210538. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210539. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210540. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210541. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210542. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210543. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210544. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210545. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210546. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210547. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210548. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210549. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210550. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210551. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210552. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210553. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210554. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210555. int values[32];
  210556. zeromem (values, sizeof (values));
  210557. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210558. {
  210559. int n = 0;
  210560. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210561. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210562. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210563. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210564. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210565. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210566. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210567. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210568. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210569. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210570. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210571. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210572. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210573. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210574. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210575. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210576. return isValidFormat;
  210577. }
  210578. else
  210579. {
  210580. jassertfalse;
  210581. }
  210582. }
  210583. else
  210584. {
  210585. PIXELFORMATDESCRIPTOR pfd;
  210586. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210587. {
  210588. result.redBits = pfd.cRedBits;
  210589. result.greenBits = pfd.cGreenBits;
  210590. result.blueBits = pfd.cBlueBits;
  210591. result.alphaBits = pfd.cAlphaBits;
  210592. result.depthBufferBits = pfd.cDepthBits;
  210593. result.stencilBufferBits = pfd.cStencilBits;
  210594. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210595. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210596. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210597. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210598. result.fullSceneAntiAliasingNumSamples = 0;
  210599. return true;
  210600. }
  210601. else
  210602. {
  210603. jassertfalse;
  210604. }
  210605. }
  210606. return false;
  210607. }
  210608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210609. };
  210610. OpenGLContext* OpenGLComponent::createContext()
  210611. {
  210612. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210613. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210614. preferredPixelFormat));
  210615. return (c->renderContext != 0) ? c.release() : 0;
  210616. }
  210617. void* OpenGLComponent::getNativeWindowHandle() const
  210618. {
  210619. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210620. }
  210621. void juce_glViewport (const int w, const int h)
  210622. {
  210623. glViewport (0, 0, w, h);
  210624. }
  210625. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210626. OwnedArray <OpenGLPixelFormat>& results)
  210627. {
  210628. Component tempComp;
  210629. {
  210630. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210631. wc.makeActive();
  210632. wc.findAlternativeOpenGLPixelFormats (results);
  210633. }
  210634. }
  210635. #endif
  210636. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210637. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210638. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210639. // compiled on its own).
  210640. #if JUCE_INCLUDED_FILE
  210641. #if JUCE_USE_CDREADER
  210642. namespace CDReaderHelpers
  210643. {
  210644. #define FILE_ANY_ACCESS 0
  210645. #ifndef FILE_READ_ACCESS
  210646. #define FILE_READ_ACCESS 1
  210647. #endif
  210648. #ifndef FILE_WRITE_ACCESS
  210649. #define FILE_WRITE_ACCESS 2
  210650. #endif
  210651. #define METHOD_BUFFERED 0
  210652. #define IOCTL_SCSI_BASE 4
  210653. #define SCSI_IOCTL_DATA_OUT 0
  210654. #define SCSI_IOCTL_DATA_IN 1
  210655. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210656. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210657. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210658. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210659. #define SENSE_LEN 14
  210660. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210661. #define SRB_DIR_IN 0x08
  210662. #define SRB_DIR_OUT 0x10
  210663. #define SRB_EVENT_NOTIFY 0x40
  210664. #define SC_HA_INQUIRY 0x00
  210665. #define SC_GET_DEV_TYPE 0x01
  210666. #define SC_EXEC_SCSI_CMD 0x02
  210667. #define SS_PENDING 0x00
  210668. #define SS_COMP 0x01
  210669. #define SS_ERR 0x04
  210670. enum
  210671. {
  210672. READTYPE_ANY = 0,
  210673. READTYPE_ATAPI1 = 1,
  210674. READTYPE_ATAPI2 = 2,
  210675. READTYPE_READ6 = 3,
  210676. READTYPE_READ10 = 4,
  210677. READTYPE_READ_D8 = 5,
  210678. READTYPE_READ_D4 = 6,
  210679. READTYPE_READ_D4_1 = 7,
  210680. READTYPE_READ10_2 = 8
  210681. };
  210682. struct SCSI_PASS_THROUGH
  210683. {
  210684. USHORT Length;
  210685. UCHAR ScsiStatus;
  210686. UCHAR PathId;
  210687. UCHAR TargetId;
  210688. UCHAR Lun;
  210689. UCHAR CdbLength;
  210690. UCHAR SenseInfoLength;
  210691. UCHAR DataIn;
  210692. ULONG DataTransferLength;
  210693. ULONG TimeOutValue;
  210694. ULONG DataBufferOffset;
  210695. ULONG SenseInfoOffset;
  210696. UCHAR Cdb[16];
  210697. };
  210698. struct SCSI_PASS_THROUGH_DIRECT
  210699. {
  210700. USHORT Length;
  210701. UCHAR ScsiStatus;
  210702. UCHAR PathId;
  210703. UCHAR TargetId;
  210704. UCHAR Lun;
  210705. UCHAR CdbLength;
  210706. UCHAR SenseInfoLength;
  210707. UCHAR DataIn;
  210708. ULONG DataTransferLength;
  210709. ULONG TimeOutValue;
  210710. PVOID DataBuffer;
  210711. ULONG SenseInfoOffset;
  210712. UCHAR Cdb[16];
  210713. };
  210714. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210715. {
  210716. SCSI_PASS_THROUGH_DIRECT spt;
  210717. ULONG Filler;
  210718. UCHAR ucSenseBuf[32];
  210719. };
  210720. struct SCSI_ADDRESS
  210721. {
  210722. ULONG Length;
  210723. UCHAR PortNumber;
  210724. UCHAR PathId;
  210725. UCHAR TargetId;
  210726. UCHAR Lun;
  210727. };
  210728. #pragma pack(1)
  210729. struct SRB_GDEVBlock
  210730. {
  210731. BYTE SRB_Cmd;
  210732. BYTE SRB_Status;
  210733. BYTE SRB_HaID;
  210734. BYTE SRB_Flags;
  210735. DWORD SRB_Hdr_Rsvd;
  210736. BYTE SRB_Target;
  210737. BYTE SRB_Lun;
  210738. BYTE SRB_DeviceType;
  210739. BYTE SRB_Rsvd1;
  210740. BYTE pad[68];
  210741. };
  210742. struct SRB_ExecSCSICmd
  210743. {
  210744. BYTE SRB_Cmd;
  210745. BYTE SRB_Status;
  210746. BYTE SRB_HaID;
  210747. BYTE SRB_Flags;
  210748. DWORD SRB_Hdr_Rsvd;
  210749. BYTE SRB_Target;
  210750. BYTE SRB_Lun;
  210751. WORD SRB_Rsvd1;
  210752. DWORD SRB_BufLen;
  210753. BYTE *SRB_BufPointer;
  210754. BYTE SRB_SenseLen;
  210755. BYTE SRB_CDBLen;
  210756. BYTE SRB_HaStat;
  210757. BYTE SRB_TargStat;
  210758. VOID *SRB_PostProc;
  210759. BYTE SRB_Rsvd2[20];
  210760. BYTE CDBByte[16];
  210761. BYTE SenseArea[SENSE_LEN + 2];
  210762. };
  210763. struct SRB
  210764. {
  210765. BYTE SRB_Cmd;
  210766. BYTE SRB_Status;
  210767. BYTE SRB_HaId;
  210768. BYTE SRB_Flags;
  210769. DWORD SRB_Hdr_Rsvd;
  210770. };
  210771. struct TOCTRACK
  210772. {
  210773. BYTE rsvd;
  210774. BYTE ADR;
  210775. BYTE trackNumber;
  210776. BYTE rsvd2;
  210777. BYTE addr[4];
  210778. };
  210779. struct TOC
  210780. {
  210781. WORD tocLen;
  210782. BYTE firstTrack;
  210783. BYTE lastTrack;
  210784. TOCTRACK tracks[100];
  210785. };
  210786. #pragma pack()
  210787. struct CDDeviceDescription
  210788. {
  210789. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210790. {
  210791. }
  210792. void createDescription (const char* data)
  210793. {
  210794. description << String (data + 8, 8).trim() // vendor
  210795. << ' ' << String (data + 16, 16).trim() // product id
  210796. << ' ' << String (data + 32, 4).trim(); // rev
  210797. }
  210798. String description;
  210799. BYTE ha, tgt, lun;
  210800. char scsiDriveLetter; // will be 0 if not using scsi
  210801. };
  210802. class CDReadBuffer
  210803. {
  210804. public:
  210805. CDReadBuffer (const int numberOfFrames)
  210806. : startFrame (0), numFrames (0), dataStartOffset (0),
  210807. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210808. buffer (bufferSize), wantsIndex (false)
  210809. {
  210810. }
  210811. bool isZero() const throw()
  210812. {
  210813. for (int i = 0; i < dataLength; ++i)
  210814. if (buffer [dataStartOffset + i] != 0)
  210815. return false;
  210816. return true;
  210817. }
  210818. int startFrame, numFrames, dataStartOffset;
  210819. int dataLength, bufferSize, index;
  210820. HeapBlock<BYTE> buffer;
  210821. bool wantsIndex;
  210822. };
  210823. class CDDeviceHandle;
  210824. class CDController
  210825. {
  210826. public:
  210827. CDController() : initialised (false) {}
  210828. virtual ~CDController() {}
  210829. virtual bool read (CDReadBuffer&) = 0;
  210830. virtual void shutDown() {}
  210831. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210832. int getLastIndex();
  210833. public:
  210834. CDDeviceHandle* deviceInfo;
  210835. int framesToCheck, framesOverlap;
  210836. bool initialised;
  210837. void prepare (SRB_ExecSCSICmd& s);
  210838. void perform (SRB_ExecSCSICmd& s);
  210839. void setPaused (bool paused);
  210840. };
  210841. class CDDeviceHandle
  210842. {
  210843. public:
  210844. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210845. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210846. {
  210847. }
  210848. ~CDDeviceHandle()
  210849. {
  210850. if (controller != 0)
  210851. {
  210852. controller->shutDown();
  210853. controller = 0;
  210854. }
  210855. if (scsiHandle != 0)
  210856. CloseHandle (scsiHandle);
  210857. }
  210858. bool readTOC (TOC* lpToc);
  210859. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210860. void openDrawer (bool shouldBeOpen);
  210861. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210862. CDDeviceDescription info;
  210863. HANDLE scsiHandle;
  210864. BYTE readType;
  210865. private:
  210866. ScopedPointer<CDController> controller;
  210867. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210868. };
  210869. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210870. {
  210871. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210872. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210873. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210874. if (h == INVALID_HANDLE_VALUE)
  210875. {
  210876. flags ^= GENERIC_WRITE;
  210877. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210878. }
  210879. return h;
  210880. }
  210881. void findCDDevices (Array<CDDeviceDescription>& list)
  210882. {
  210883. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210884. {
  210885. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210886. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210887. {
  210888. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210889. if (h != INVALID_HANDLE_VALUE)
  210890. {
  210891. char buffer[100];
  210892. zeromem (buffer, sizeof (buffer));
  210893. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210894. zerostruct (p);
  210895. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210896. p.spt.CdbLength = 6;
  210897. p.spt.SenseInfoLength = 24;
  210898. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210899. p.spt.DataTransferLength = sizeof (buffer);
  210900. p.spt.TimeOutValue = 2;
  210901. p.spt.DataBuffer = buffer;
  210902. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210903. p.spt.Cdb[0] = 0x12;
  210904. p.spt.Cdb[4] = 100;
  210905. DWORD bytesReturned = 0;
  210906. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210907. &p, sizeof (p), &p, sizeof (p),
  210908. &bytesReturned, 0) != 0)
  210909. {
  210910. CDDeviceDescription dev;
  210911. dev.scsiDriveLetter = driveLetter;
  210912. dev.createDescription (buffer);
  210913. SCSI_ADDRESS scsiAddr;
  210914. zerostruct (scsiAddr);
  210915. scsiAddr.Length = sizeof (scsiAddr);
  210916. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210917. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210918. &bytesReturned, 0) != 0)
  210919. {
  210920. dev.ha = scsiAddr.PortNumber;
  210921. dev.tgt = scsiAddr.TargetId;
  210922. dev.lun = scsiAddr.Lun;
  210923. list.add (dev);
  210924. }
  210925. }
  210926. CloseHandle (h);
  210927. }
  210928. }
  210929. }
  210930. }
  210931. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210932. HANDLE& deviceHandle, const bool retryOnFailure)
  210933. {
  210934. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210935. zerostruct (s);
  210936. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210937. s.spt.CdbLength = srb->SRB_CDBLen;
  210938. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210939. ? SCSI_IOCTL_DATA_IN
  210940. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210941. ? SCSI_IOCTL_DATA_OUT
  210942. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210943. s.spt.DataTransferLength = srb->SRB_BufLen;
  210944. s.spt.TimeOutValue = 5;
  210945. s.spt.DataBuffer = srb->SRB_BufPointer;
  210946. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210947. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210948. srb->SRB_Status = SS_ERR;
  210949. srb->SRB_TargStat = 0x0004;
  210950. DWORD bytesReturned = 0;
  210951. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210952. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210953. {
  210954. srb->SRB_Status = SS_COMP;
  210955. }
  210956. else if (retryOnFailure)
  210957. {
  210958. const DWORD error = GetLastError();
  210959. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210960. {
  210961. if (error != ERROR_INVALID_HANDLE)
  210962. CloseHandle (deviceHandle);
  210963. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210964. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210965. }
  210966. }
  210967. return srb->SRB_Status;
  210968. }
  210969. // Controller types..
  210970. class ControllerType1 : public CDController
  210971. {
  210972. public:
  210973. ControllerType1() {}
  210974. bool read (CDReadBuffer& rb)
  210975. {
  210976. if (rb.numFrames * 2352 > rb.bufferSize)
  210977. return false;
  210978. SRB_ExecSCSICmd s;
  210979. prepare (s);
  210980. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210981. s.SRB_BufLen = rb.bufferSize;
  210982. s.SRB_BufPointer = rb.buffer;
  210983. s.SRB_CDBLen = 12;
  210984. s.CDBByte[0] = 0xBE;
  210985. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210986. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210987. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210988. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210989. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210990. perform (s);
  210991. if (s.SRB_Status != SS_COMP)
  210992. return false;
  210993. rb.dataLength = rb.numFrames * 2352;
  210994. rb.dataStartOffset = 0;
  210995. return true;
  210996. }
  210997. };
  210998. class ControllerType2 : public CDController
  210999. {
  211000. public:
  211001. ControllerType2() {}
  211002. void shutDown()
  211003. {
  211004. if (initialised)
  211005. {
  211006. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211007. SRB_ExecSCSICmd s;
  211008. prepare (s);
  211009. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211010. s.SRB_BufLen = 0x0C;
  211011. s.SRB_BufPointer = bufPointer;
  211012. s.SRB_CDBLen = 6;
  211013. s.CDBByte[0] = 0x15;
  211014. s.CDBByte[4] = 0x0C;
  211015. perform (s);
  211016. }
  211017. }
  211018. bool init()
  211019. {
  211020. SRB_ExecSCSICmd s;
  211021. s.SRB_Status = SS_ERR;
  211022. if (deviceInfo->readType == READTYPE_READ10_2)
  211023. {
  211024. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211025. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211026. for (int i = 0; i < 2; ++i)
  211027. {
  211028. prepare (s);
  211029. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211030. s.SRB_BufLen = 0x14;
  211031. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211032. s.SRB_CDBLen = 6;
  211033. s.CDBByte[0] = 0x15;
  211034. s.CDBByte[1] = 0x10;
  211035. s.CDBByte[4] = 0x14;
  211036. perform (s);
  211037. if (s.SRB_Status != SS_COMP)
  211038. return false;
  211039. }
  211040. }
  211041. else
  211042. {
  211043. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211044. prepare (s);
  211045. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211046. s.SRB_BufLen = 0x0C;
  211047. s.SRB_BufPointer = bufPointer;
  211048. s.SRB_CDBLen = 6;
  211049. s.CDBByte[0] = 0x15;
  211050. s.CDBByte[4] = 0x0C;
  211051. perform (s);
  211052. }
  211053. return s.SRB_Status == SS_COMP;
  211054. }
  211055. bool read (CDReadBuffer& rb)
  211056. {
  211057. if (rb.numFrames * 2352 > rb.bufferSize)
  211058. return false;
  211059. if (! initialised)
  211060. {
  211061. initialised = init();
  211062. if (! initialised)
  211063. return false;
  211064. }
  211065. SRB_ExecSCSICmd s;
  211066. prepare (s);
  211067. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211068. s.SRB_BufLen = rb.bufferSize;
  211069. s.SRB_BufPointer = rb.buffer;
  211070. s.SRB_CDBLen = 10;
  211071. s.CDBByte[0] = 0x28;
  211072. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211073. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211074. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211075. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211076. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211077. perform (s);
  211078. if (s.SRB_Status != SS_COMP)
  211079. return false;
  211080. rb.dataLength = rb.numFrames * 2352;
  211081. rb.dataStartOffset = 0;
  211082. return true;
  211083. }
  211084. };
  211085. class ControllerType3 : public CDController
  211086. {
  211087. public:
  211088. ControllerType3() {}
  211089. bool read (CDReadBuffer& rb)
  211090. {
  211091. if (rb.numFrames * 2352 > rb.bufferSize)
  211092. return false;
  211093. if (! initialised)
  211094. {
  211095. setPaused (false);
  211096. initialised = true;
  211097. }
  211098. SRB_ExecSCSICmd s;
  211099. prepare (s);
  211100. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211101. s.SRB_BufLen = rb.numFrames * 2352;
  211102. s.SRB_BufPointer = rb.buffer;
  211103. s.SRB_CDBLen = 12;
  211104. s.CDBByte[0] = 0xD8;
  211105. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211106. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211107. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211108. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  211109. perform (s);
  211110. if (s.SRB_Status != SS_COMP)
  211111. return false;
  211112. rb.dataLength = rb.numFrames * 2352;
  211113. rb.dataStartOffset = 0;
  211114. return true;
  211115. }
  211116. };
  211117. class ControllerType4 : public CDController
  211118. {
  211119. public:
  211120. ControllerType4() {}
  211121. bool selectD4Mode()
  211122. {
  211123. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211124. SRB_ExecSCSICmd s;
  211125. prepare (s);
  211126. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211127. s.SRB_CDBLen = 6;
  211128. s.SRB_BufLen = 12;
  211129. s.SRB_BufPointer = bufPointer;
  211130. s.CDBByte[0] = 0x15;
  211131. s.CDBByte[1] = 0x10;
  211132. s.CDBByte[4] = 0x08;
  211133. perform (s);
  211134. return s.SRB_Status == SS_COMP;
  211135. }
  211136. bool read (CDReadBuffer& rb)
  211137. {
  211138. if (rb.numFrames * 2352 > rb.bufferSize)
  211139. return false;
  211140. if (! initialised)
  211141. {
  211142. setPaused (true);
  211143. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211144. selectD4Mode();
  211145. initialised = true;
  211146. }
  211147. SRB_ExecSCSICmd s;
  211148. prepare (s);
  211149. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211150. s.SRB_BufLen = rb.bufferSize;
  211151. s.SRB_BufPointer = rb.buffer;
  211152. s.SRB_CDBLen = 10;
  211153. s.CDBByte[0] = 0xD4;
  211154. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211155. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211156. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211157. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211158. perform (s);
  211159. if (s.SRB_Status != SS_COMP)
  211160. return false;
  211161. rb.dataLength = rb.numFrames * 2352;
  211162. rb.dataStartOffset = 0;
  211163. return true;
  211164. }
  211165. };
  211166. void CDController::prepare (SRB_ExecSCSICmd& s)
  211167. {
  211168. zerostruct (s);
  211169. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211170. s.SRB_HaID = deviceInfo->info.ha;
  211171. s.SRB_Target = deviceInfo->info.tgt;
  211172. s.SRB_Lun = deviceInfo->info.lun;
  211173. s.SRB_SenseLen = SENSE_LEN;
  211174. }
  211175. void CDController::perform (SRB_ExecSCSICmd& s)
  211176. {
  211177. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211178. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  211179. }
  211180. void CDController::setPaused (bool paused)
  211181. {
  211182. SRB_ExecSCSICmd s;
  211183. prepare (s);
  211184. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211185. s.SRB_CDBLen = 10;
  211186. s.CDBByte[0] = 0x4B;
  211187. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211188. perform (s);
  211189. }
  211190. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  211191. {
  211192. if (overlapBuffer != 0)
  211193. {
  211194. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211195. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211196. if (doJitter
  211197. && overlapBuffer->startFrame > 0
  211198. && overlapBuffer->numFrames > 0
  211199. && overlapBuffer->dataLength > 0)
  211200. {
  211201. const int numFrames = rb.numFrames;
  211202. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  211203. {
  211204. rb.startFrame -= framesOverlap;
  211205. if (framesToCheck < framesOverlap
  211206. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  211207. rb.numFrames += framesOverlap;
  211208. }
  211209. else
  211210. {
  211211. overlapBuffer->dataLength = 0;
  211212. overlapBuffer->startFrame = 0;
  211213. overlapBuffer->numFrames = 0;
  211214. }
  211215. }
  211216. if (! read (rb))
  211217. return false;
  211218. if (doJitter)
  211219. {
  211220. const int checkLen = framesToCheck * 2352;
  211221. const int maxToCheck = rb.dataLength - checkLen;
  211222. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211223. return true;
  211224. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211225. bool found = false;
  211226. for (int i = 0; i < maxToCheck; ++i)
  211227. {
  211228. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  211229. {
  211230. i += checkLen;
  211231. rb.dataStartOffset = i;
  211232. rb.dataLength -= i;
  211233. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  211234. found = true;
  211235. break;
  211236. }
  211237. }
  211238. rb.numFrames = rb.dataLength / 2352;
  211239. rb.dataLength = 2352 * rb.numFrames;
  211240. if (! found)
  211241. return false;
  211242. }
  211243. if (canDoJitter)
  211244. {
  211245. memcpy (overlapBuffer->buffer,
  211246. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  211247. 2352 * framesToCheck);
  211248. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  211249. overlapBuffer->numFrames = framesToCheck;
  211250. overlapBuffer->dataLength = 2352 * framesToCheck;
  211251. overlapBuffer->dataStartOffset = 0;
  211252. }
  211253. else
  211254. {
  211255. overlapBuffer->startFrame = 0;
  211256. overlapBuffer->numFrames = 0;
  211257. overlapBuffer->dataLength = 0;
  211258. }
  211259. return true;
  211260. }
  211261. return read (rb);
  211262. }
  211263. int CDController::getLastIndex()
  211264. {
  211265. char qdata[100];
  211266. SRB_ExecSCSICmd s;
  211267. prepare (s);
  211268. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211269. s.SRB_BufLen = sizeof (qdata);
  211270. s.SRB_BufPointer = (BYTE*) qdata;
  211271. s.SRB_CDBLen = 12;
  211272. s.CDBByte[0] = 0x42;
  211273. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211274. s.CDBByte[2] = 64;
  211275. s.CDBByte[3] = 1; // get current position
  211276. s.CDBByte[7] = 0;
  211277. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211278. perform (s);
  211279. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211280. }
  211281. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211282. {
  211283. SRB_ExecSCSICmd s;
  211284. zerostruct (s);
  211285. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211286. s.SRB_HaID = info.ha;
  211287. s.SRB_Target = info.tgt;
  211288. s.SRB_Lun = info.lun;
  211289. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211290. s.SRB_BufLen = 0x324;
  211291. s.SRB_BufPointer = (BYTE*) lpToc;
  211292. s.SRB_SenseLen = 0x0E;
  211293. s.SRB_CDBLen = 0x0A;
  211294. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211295. s.CDBByte[0] = 0x43;
  211296. s.CDBByte[1] = 0x00;
  211297. s.CDBByte[7] = 0x03;
  211298. s.CDBByte[8] = 0x24;
  211299. performScsiCommand (s.SRB_PostProc, s);
  211300. return (s.SRB_Status == SS_COMP);
  211301. }
  211302. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211303. {
  211304. ResetEvent (event);
  211305. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211306. if (status == SS_PENDING)
  211307. WaitForSingleObject (event, 4000);
  211308. CloseHandle (event);
  211309. }
  211310. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211311. {
  211312. if (controller == 0)
  211313. {
  211314. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211315. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211316. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211317. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211318. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211319. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211320. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211321. }
  211322. buffer.index = 0;
  211323. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211324. {
  211325. if (buffer.wantsIndex)
  211326. buffer.index = controller->getLastIndex();
  211327. return true;
  211328. }
  211329. return false;
  211330. }
  211331. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211332. {
  211333. if (shouldBeOpen)
  211334. {
  211335. if (controller != 0)
  211336. {
  211337. controller->shutDown();
  211338. controller = 0;
  211339. }
  211340. if (scsiHandle != 0)
  211341. {
  211342. CloseHandle (scsiHandle);
  211343. scsiHandle = 0;
  211344. }
  211345. }
  211346. SRB_ExecSCSICmd s;
  211347. zerostruct (s);
  211348. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211349. s.SRB_HaID = info.ha;
  211350. s.SRB_Target = info.tgt;
  211351. s.SRB_Lun = info.lun;
  211352. s.SRB_SenseLen = SENSE_LEN;
  211353. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211354. s.SRB_BufLen = 0;
  211355. s.SRB_BufPointer = 0;
  211356. s.SRB_CDBLen = 12;
  211357. s.CDBByte[0] = 0x1b;
  211358. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211359. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211360. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211361. performScsiCommand (s.SRB_PostProc, s);
  211362. }
  211363. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211364. {
  211365. controller = newController;
  211366. readType = (BYTE) type;
  211367. controller->deviceInfo = this;
  211368. controller->framesToCheck = 1;
  211369. controller->framesOverlap = 3;
  211370. bool passed = false;
  211371. memset (rb.buffer, 0xcd, rb.bufferSize);
  211372. if (controller->read (rb))
  211373. {
  211374. passed = true;
  211375. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211376. int wrong = 0;
  211377. for (int i = rb.dataLength / 4; --i >= 0;)
  211378. {
  211379. if (*p++ == (int) 0xcdcdcdcd)
  211380. {
  211381. if (++wrong == 4)
  211382. {
  211383. passed = false;
  211384. break;
  211385. }
  211386. }
  211387. else
  211388. {
  211389. wrong = 0;
  211390. }
  211391. }
  211392. }
  211393. if (! passed)
  211394. {
  211395. controller->shutDown();
  211396. controller = 0;
  211397. }
  211398. return passed;
  211399. }
  211400. struct CDDeviceWrapper
  211401. {
  211402. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211403. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211404. {
  211405. // xxx jitter never seemed to actually be enabled (??)
  211406. }
  211407. CDDeviceHandle deviceHandle;
  211408. CDReadBuffer overlapBuffer;
  211409. bool jitter;
  211410. };
  211411. int getAddressOfTrack (const TOCTRACK& t) throw()
  211412. {
  211413. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211414. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211415. }
  211416. const int samplesPerFrame = 44100 / 75;
  211417. const int bytesPerFrame = samplesPerFrame * 4;
  211418. const int framesPerIndexRead = 4;
  211419. }
  211420. const StringArray AudioCDReader::getAvailableCDNames()
  211421. {
  211422. using namespace CDReaderHelpers;
  211423. StringArray results;
  211424. Array<CDDeviceDescription> list;
  211425. findCDDevices (list);
  211426. for (int i = 0; i < list.size(); ++i)
  211427. {
  211428. String s;
  211429. if (list[i].scsiDriveLetter > 0)
  211430. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211431. s << list[i].description;
  211432. results.add (s);
  211433. }
  211434. return results;
  211435. }
  211436. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211437. {
  211438. using namespace CDReaderHelpers;
  211439. Array<CDDeviceDescription> list;
  211440. findCDDevices (list);
  211441. if (isPositiveAndBelow (deviceIndex, list.size()))
  211442. {
  211443. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211444. if (h != INVALID_HANDLE_VALUE)
  211445. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211446. }
  211447. return 0;
  211448. }
  211449. AudioCDReader::AudioCDReader (void* handle_)
  211450. : AudioFormatReader (0, "CD Audio"),
  211451. handle (handle_),
  211452. indexingEnabled (false),
  211453. lastIndex (0),
  211454. firstFrameInBuffer (0),
  211455. samplesInBuffer (0)
  211456. {
  211457. using namespace CDReaderHelpers;
  211458. jassert (handle_ != 0);
  211459. refreshTrackLengths();
  211460. sampleRate = 44100.0;
  211461. bitsPerSample = 16;
  211462. numChannels = 2;
  211463. usesFloatingPointData = false;
  211464. buffer.setSize (4 * bytesPerFrame, true);
  211465. }
  211466. AudioCDReader::~AudioCDReader()
  211467. {
  211468. using namespace CDReaderHelpers;
  211469. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211470. delete device;
  211471. }
  211472. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211473. int64 startSampleInFile, int numSamples)
  211474. {
  211475. using namespace CDReaderHelpers;
  211476. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211477. bool ok = true;
  211478. while (numSamples > 0)
  211479. {
  211480. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211481. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211482. if (startSampleInFile >= bufferStartSample
  211483. && startSampleInFile < bufferEndSample)
  211484. {
  211485. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211486. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211487. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211488. const short* src = (const short*) buffer.getData();
  211489. src += 2 * (startSampleInFile - bufferStartSample);
  211490. for (int i = 0; i < toDo; ++i)
  211491. {
  211492. l[i] = src [i << 1] << 16;
  211493. if (r != 0)
  211494. r[i] = src [(i << 1) + 1] << 16;
  211495. }
  211496. startOffsetInDestBuffer += toDo;
  211497. startSampleInFile += toDo;
  211498. numSamples -= toDo;
  211499. }
  211500. else
  211501. {
  211502. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211503. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211504. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211505. {
  211506. device->overlapBuffer.dataLength = 0;
  211507. device->overlapBuffer.startFrame = 0;
  211508. device->overlapBuffer.numFrames = 0;
  211509. device->jitter = false;
  211510. }
  211511. firstFrameInBuffer = frameNeeded;
  211512. lastIndex = 0;
  211513. CDReadBuffer readBuffer (framesInBuffer + 4);
  211514. readBuffer.wantsIndex = indexingEnabled;
  211515. int i;
  211516. for (i = 5; --i >= 0;)
  211517. {
  211518. readBuffer.startFrame = frameNeeded;
  211519. readBuffer.numFrames = framesInBuffer;
  211520. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211521. break;
  211522. else
  211523. device->overlapBuffer.dataLength = 0;
  211524. }
  211525. if (i >= 0)
  211526. {
  211527. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211528. samplesInBuffer = readBuffer.dataLength >> 2;
  211529. lastIndex = readBuffer.index;
  211530. }
  211531. else
  211532. {
  211533. int* l = destSamples[0] + startOffsetInDestBuffer;
  211534. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211535. while (--numSamples >= 0)
  211536. {
  211537. *l++ = 0;
  211538. if (r != 0)
  211539. *r++ = 0;
  211540. }
  211541. // sometimes the read fails for just the very last couple of blocks, so
  211542. // we'll ignore and errors in the last half-second of the disk..
  211543. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211544. break;
  211545. }
  211546. }
  211547. }
  211548. return ok;
  211549. }
  211550. bool AudioCDReader::isCDStillPresent() const
  211551. {
  211552. using namespace CDReaderHelpers;
  211553. TOC toc;
  211554. zerostruct (toc);
  211555. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211556. }
  211557. void AudioCDReader::refreshTrackLengths()
  211558. {
  211559. using namespace CDReaderHelpers;
  211560. trackStartSamples.clear();
  211561. zeromem (audioTracks, sizeof (audioTracks));
  211562. TOC toc;
  211563. zerostruct (toc);
  211564. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211565. {
  211566. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211567. for (int i = 0; i <= numTracks; ++i)
  211568. {
  211569. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211570. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211571. }
  211572. }
  211573. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211574. }
  211575. bool AudioCDReader::isTrackAudio (int trackNum) const
  211576. {
  211577. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211578. }
  211579. void AudioCDReader::enableIndexScanning (bool b)
  211580. {
  211581. indexingEnabled = b;
  211582. }
  211583. int AudioCDReader::getLastIndex() const
  211584. {
  211585. return lastIndex;
  211586. }
  211587. int AudioCDReader::getIndexAt (int samplePos)
  211588. {
  211589. using namespace CDReaderHelpers;
  211590. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211591. const int frameNeeded = samplePos / samplesPerFrame;
  211592. device->overlapBuffer.dataLength = 0;
  211593. device->overlapBuffer.startFrame = 0;
  211594. device->overlapBuffer.numFrames = 0;
  211595. device->jitter = false;
  211596. firstFrameInBuffer = 0;
  211597. lastIndex = 0;
  211598. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211599. readBuffer.wantsIndex = true;
  211600. int i;
  211601. for (i = 5; --i >= 0;)
  211602. {
  211603. readBuffer.startFrame = frameNeeded;
  211604. readBuffer.numFrames = framesPerIndexRead;
  211605. if (device->deviceHandle.readAudio (readBuffer))
  211606. break;
  211607. }
  211608. if (i >= 0)
  211609. return readBuffer.index;
  211610. return -1;
  211611. }
  211612. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211613. {
  211614. using namespace CDReaderHelpers;
  211615. Array <int> indexes;
  211616. const int trackStart = getPositionOfTrackStart (trackNumber);
  211617. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211618. bool needToScan = true;
  211619. if (trackEnd - trackStart > 20 * 44100)
  211620. {
  211621. // check the end of the track for indexes before scanning the whole thing
  211622. needToScan = false;
  211623. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211624. bool seenAnIndex = false;
  211625. while (pos <= trackEnd - samplesPerFrame)
  211626. {
  211627. const int index = getIndexAt (pos);
  211628. if (index == 0)
  211629. {
  211630. // lead-out, so skip back a bit if we've not found any indexes yet..
  211631. if (seenAnIndex)
  211632. break;
  211633. pos -= 44100 * 5;
  211634. if (pos < trackStart)
  211635. break;
  211636. }
  211637. else
  211638. {
  211639. if (index > 0)
  211640. seenAnIndex = true;
  211641. if (index > 1)
  211642. {
  211643. needToScan = true;
  211644. break;
  211645. }
  211646. pos += samplesPerFrame * framesPerIndexRead;
  211647. }
  211648. }
  211649. }
  211650. if (needToScan)
  211651. {
  211652. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211653. int pos = trackStart;
  211654. int last = -1;
  211655. while (pos < trackEnd - samplesPerFrame * 10)
  211656. {
  211657. const int frameNeeded = pos / samplesPerFrame;
  211658. device->overlapBuffer.dataLength = 0;
  211659. device->overlapBuffer.startFrame = 0;
  211660. device->overlapBuffer.numFrames = 0;
  211661. device->jitter = false;
  211662. firstFrameInBuffer = 0;
  211663. CDReadBuffer readBuffer (4);
  211664. readBuffer.wantsIndex = true;
  211665. int i;
  211666. for (i = 5; --i >= 0;)
  211667. {
  211668. readBuffer.startFrame = frameNeeded;
  211669. readBuffer.numFrames = framesPerIndexRead;
  211670. if (device->deviceHandle.readAudio (readBuffer))
  211671. break;
  211672. }
  211673. if (i < 0)
  211674. break;
  211675. if (readBuffer.index > last && readBuffer.index > 1)
  211676. {
  211677. last = readBuffer.index;
  211678. indexes.add (pos);
  211679. }
  211680. pos += samplesPerFrame * framesPerIndexRead;
  211681. }
  211682. indexes.removeValue (trackStart);
  211683. }
  211684. return indexes;
  211685. }
  211686. void AudioCDReader::ejectDisk()
  211687. {
  211688. using namespace CDReaderHelpers;
  211689. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211690. }
  211691. #endif
  211692. #if JUCE_USE_CDBURNER
  211693. namespace CDBurnerHelpers
  211694. {
  211695. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211696. {
  211697. CoInitialize (0);
  211698. IDiscMaster* dm;
  211699. IDiscRecorder* result = 0;
  211700. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211701. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211702. IID_IDiscMaster,
  211703. (void**) &dm)))
  211704. {
  211705. if (SUCCEEDED (dm->Open()))
  211706. {
  211707. IEnumDiscRecorders* drEnum = 0;
  211708. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211709. {
  211710. IDiscRecorder* dr = 0;
  211711. DWORD dummy;
  211712. int index = 0;
  211713. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211714. {
  211715. if (indexToOpen == index)
  211716. {
  211717. result = dr;
  211718. break;
  211719. }
  211720. else if (list != 0)
  211721. {
  211722. BSTR path;
  211723. if (SUCCEEDED (dr->GetPath (&path)))
  211724. list->add ((const WCHAR*) path);
  211725. }
  211726. ++index;
  211727. dr->Release();
  211728. }
  211729. drEnum->Release();
  211730. }
  211731. if (master == 0)
  211732. dm->Close();
  211733. }
  211734. if (master != 0)
  211735. *master = dm;
  211736. else
  211737. dm->Release();
  211738. }
  211739. return result;
  211740. }
  211741. }
  211742. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211743. public Timer
  211744. {
  211745. public:
  211746. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211747. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211748. listener (0), progress (0), shouldCancel (false)
  211749. {
  211750. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211751. jassert (SUCCEEDED (hr));
  211752. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211753. //jassert (SUCCEEDED (hr));
  211754. lastState = getDiskState();
  211755. startTimer (2000);
  211756. }
  211757. ~Pimpl() {}
  211758. void releaseObjects()
  211759. {
  211760. discRecorder->Close();
  211761. if (redbook != 0)
  211762. redbook->Release();
  211763. discRecorder->Release();
  211764. discMaster->Release();
  211765. Release();
  211766. }
  211767. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211768. {
  211769. if (listener != 0 && ! shouldCancel)
  211770. shouldCancel = listener->audioCDBurnProgress (progress);
  211771. *pbCancel = shouldCancel;
  211772. return S_OK;
  211773. }
  211774. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211775. {
  211776. progress = nCompleted / (float) nTotal;
  211777. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211778. return E_NOTIMPL;
  211779. }
  211780. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211781. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211782. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211783. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211784. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211785. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211786. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211787. class ScopedDiscOpener
  211788. {
  211789. public:
  211790. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211791. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211792. private:
  211793. Pimpl& pimpl;
  211794. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211795. };
  211796. DiskState getDiskState()
  211797. {
  211798. const ScopedDiscOpener opener (*this);
  211799. long type, flags;
  211800. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211801. if (FAILED (hr))
  211802. return unknown;
  211803. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211804. return writableDiskPresent;
  211805. if (type == 0)
  211806. return noDisc;
  211807. else
  211808. return readOnlyDiskPresent;
  211809. }
  211810. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211811. {
  211812. ComSmartPtr<IPropertyStorage> prop;
  211813. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211814. return defaultReturn;
  211815. PROPSPEC iPropSpec;
  211816. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211817. iPropSpec.lpwstr = name;
  211818. PROPVARIANT iPropVariant;
  211819. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211820. ? defaultReturn : (int) iPropVariant.lVal;
  211821. }
  211822. bool setIntProperty (const LPOLESTR name, const int value) const
  211823. {
  211824. ComSmartPtr<IPropertyStorage> prop;
  211825. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211826. return false;
  211827. PROPSPEC iPropSpec;
  211828. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211829. iPropSpec.lpwstr = name;
  211830. PROPVARIANT iPropVariant;
  211831. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211832. return false;
  211833. iPropVariant.lVal = (long) value;
  211834. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211835. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211836. }
  211837. void timerCallback()
  211838. {
  211839. const DiskState state = getDiskState();
  211840. if (state != lastState)
  211841. {
  211842. lastState = state;
  211843. owner.sendChangeMessage();
  211844. }
  211845. }
  211846. AudioCDBurner& owner;
  211847. DiskState lastState;
  211848. IDiscMaster* discMaster;
  211849. IDiscRecorder* discRecorder;
  211850. IRedbookDiscMaster* redbook;
  211851. AudioCDBurner::BurnProgressListener* listener;
  211852. float progress;
  211853. bool shouldCancel;
  211854. };
  211855. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211856. {
  211857. IDiscMaster* discMaster = 0;
  211858. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211859. if (discRecorder != 0)
  211860. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211861. }
  211862. AudioCDBurner::~AudioCDBurner()
  211863. {
  211864. if (pimpl != 0)
  211865. pimpl.release()->releaseObjects();
  211866. }
  211867. const StringArray AudioCDBurner::findAvailableDevices()
  211868. {
  211869. StringArray devs;
  211870. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211871. return devs;
  211872. }
  211873. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211874. {
  211875. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211876. if (b->pimpl == 0)
  211877. b = 0;
  211878. return b.release();
  211879. }
  211880. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211881. {
  211882. return pimpl->getDiskState();
  211883. }
  211884. bool AudioCDBurner::isDiskPresent() const
  211885. {
  211886. return getDiskState() == writableDiskPresent;
  211887. }
  211888. bool AudioCDBurner::openTray()
  211889. {
  211890. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211891. return SUCCEEDED (pimpl->discRecorder->Eject());
  211892. }
  211893. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211894. {
  211895. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211896. DiskState oldState = getDiskState();
  211897. DiskState newState = oldState;
  211898. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211899. {
  211900. newState = getDiskState();
  211901. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211902. }
  211903. return newState;
  211904. }
  211905. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211906. {
  211907. Array<int> results;
  211908. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211909. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211910. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211911. if (speeds[i] <= maxSpeed)
  211912. results.add (speeds[i]);
  211913. results.addIfNotAlreadyThere (maxSpeed);
  211914. return results;
  211915. }
  211916. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211917. {
  211918. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211919. return false;
  211920. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211921. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211922. }
  211923. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211924. {
  211925. long blocksFree = 0;
  211926. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211927. return blocksFree;
  211928. }
  211929. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211930. bool performFakeBurnForTesting, int writeSpeed)
  211931. {
  211932. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211933. pimpl->listener = listener;
  211934. pimpl->progress = 0;
  211935. pimpl->shouldCancel = false;
  211936. UINT_PTR cookie;
  211937. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211938. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211939. ejectDiscAfterwards);
  211940. String error;
  211941. if (hr != S_OK)
  211942. {
  211943. const char* e = "Couldn't open or write to the CD device";
  211944. if (hr == IMAPI_E_USERABORT)
  211945. e = "User cancelled the write operation";
  211946. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211947. e = "No Disk present";
  211948. error = e;
  211949. }
  211950. pimpl->discMaster->ProgressUnadvise (cookie);
  211951. pimpl->listener = 0;
  211952. return error;
  211953. }
  211954. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211955. {
  211956. if (audioSource == 0)
  211957. return false;
  211958. ScopedPointer<AudioSource> source (audioSource);
  211959. long bytesPerBlock;
  211960. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211961. const int samplesPerBlock = bytesPerBlock / 4;
  211962. bool ok = true;
  211963. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211964. HeapBlock <byte> buffer (bytesPerBlock);
  211965. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211966. int samplesDone = 0;
  211967. source->prepareToPlay (samplesPerBlock, 44100.0);
  211968. while (ok)
  211969. {
  211970. {
  211971. AudioSourceChannelInfo info;
  211972. info.buffer = &sourceBuffer;
  211973. info.numSamples = samplesPerBlock;
  211974. info.startSample = 0;
  211975. sourceBuffer.clear();
  211976. source->getNextAudioBlock (info);
  211977. }
  211978. zeromem (buffer, bytesPerBlock);
  211979. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211980. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211981. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211982. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211983. CDSampleFormat left (buffer, 2);
  211984. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211985. CDSampleFormat right (buffer + 2, 2);
  211986. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211987. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211988. if (FAILED (hr))
  211989. ok = false;
  211990. samplesDone += samplesPerBlock;
  211991. if (samplesDone >= numSamples)
  211992. break;
  211993. }
  211994. hr = pimpl->redbook->CloseAudioTrack();
  211995. return ok && hr == S_OK;
  211996. }
  211997. #endif
  211998. #endif
  211999. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212000. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212001. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212002. // compiled on its own).
  212003. #if JUCE_INCLUDED_FILE
  212004. class MidiInCollector
  212005. {
  212006. public:
  212007. MidiInCollector (MidiInput* const input_,
  212008. MidiInputCallback& callback_)
  212009. : deviceHandle (0),
  212010. input (input_),
  212011. callback (callback_),
  212012. concatenator (4096),
  212013. isStarted (false),
  212014. startTime (0)
  212015. {
  212016. }
  212017. ~MidiInCollector()
  212018. {
  212019. stop();
  212020. if (deviceHandle != 0)
  212021. {
  212022. int count = 5;
  212023. while (--count >= 0)
  212024. {
  212025. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212026. break;
  212027. Sleep (20);
  212028. }
  212029. }
  212030. }
  212031. void handleMessage (const uint32 message, const uint32 timeStamp)
  212032. {
  212033. if ((message & 0xff) >= 0x80 && isStarted)
  212034. {
  212035. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212036. writeFinishedBlocks();
  212037. }
  212038. }
  212039. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212040. {
  212041. if (isStarted)
  212042. {
  212043. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212044. writeFinishedBlocks();
  212045. }
  212046. }
  212047. void start()
  212048. {
  212049. jassert (deviceHandle != 0);
  212050. if (deviceHandle != 0 && ! isStarted)
  212051. {
  212052. activeMidiCollectors.addIfNotAlreadyThere (this);
  212053. for (int i = 0; i < (int) numHeaders; ++i)
  212054. headers[i].write (deviceHandle);
  212055. startTime = Time::getMillisecondCounter();
  212056. MMRESULT res = midiInStart (deviceHandle);
  212057. if (res == MMSYSERR_NOERROR)
  212058. {
  212059. concatenator.reset();
  212060. isStarted = true;
  212061. }
  212062. else
  212063. {
  212064. unprepareAllHeaders();
  212065. }
  212066. }
  212067. }
  212068. void stop()
  212069. {
  212070. if (isStarted)
  212071. {
  212072. isStarted = false;
  212073. midiInReset (deviceHandle);
  212074. midiInStop (deviceHandle);
  212075. activeMidiCollectors.removeValue (this);
  212076. unprepareAllHeaders();
  212077. concatenator.reset();
  212078. }
  212079. }
  212080. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212081. {
  212082. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212083. if (activeMidiCollectors.contains (collector))
  212084. {
  212085. if (uMsg == MIM_DATA)
  212086. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212087. else if (uMsg == MIM_LONGDATA)
  212088. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212089. }
  212090. }
  212091. HMIDIIN deviceHandle;
  212092. private:
  212093. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212094. MidiInput* input;
  212095. MidiInputCallback& callback;
  212096. MidiDataConcatenator concatenator;
  212097. bool volatile isStarted;
  212098. uint32 startTime;
  212099. class MidiHeader
  212100. {
  212101. public:
  212102. MidiHeader()
  212103. {
  212104. zerostruct (hdr);
  212105. hdr.lpData = data;
  212106. hdr.dwBufferLength = numElementsInArray (data);
  212107. }
  212108. void write (HMIDIIN deviceHandle)
  212109. {
  212110. hdr.dwBytesRecorded = 0;
  212111. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212112. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212113. }
  212114. void writeIfFinished (HMIDIIN deviceHandle)
  212115. {
  212116. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212117. {
  212118. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212119. (void) res;
  212120. write (deviceHandle);
  212121. }
  212122. }
  212123. void unprepare (HMIDIIN deviceHandle)
  212124. {
  212125. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212126. {
  212127. int c = 10;
  212128. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212129. Thread::sleep (20);
  212130. jassert (c >= 0);
  212131. }
  212132. }
  212133. private:
  212134. MIDIHDR hdr;
  212135. char data [256];
  212136. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  212137. };
  212138. enum { numHeaders = 32 };
  212139. MidiHeader headers [numHeaders];
  212140. void writeFinishedBlocks()
  212141. {
  212142. for (int i = 0; i < (int) numHeaders; ++i)
  212143. headers[i].writeIfFinished (deviceHandle);
  212144. }
  212145. void unprepareAllHeaders()
  212146. {
  212147. for (int i = 0; i < (int) numHeaders; ++i)
  212148. headers[i].unprepare (deviceHandle);
  212149. }
  212150. double convertTimeStamp (uint32 timeStamp)
  212151. {
  212152. timeStamp += startTime;
  212153. const uint32 now = Time::getMillisecondCounter();
  212154. if (timeStamp > now)
  212155. {
  212156. if (timeStamp > now + 2)
  212157. --startTime;
  212158. timeStamp = now;
  212159. }
  212160. return timeStamp * 0.001;
  212161. }
  212162. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  212163. };
  212164. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212165. const StringArray MidiInput::getDevices()
  212166. {
  212167. StringArray s;
  212168. const int num = midiInGetNumDevs();
  212169. for (int i = 0; i < num; ++i)
  212170. {
  212171. MIDIINCAPS mc;
  212172. zerostruct (mc);
  212173. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212174. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212175. }
  212176. return s;
  212177. }
  212178. int MidiInput::getDefaultDeviceIndex()
  212179. {
  212180. return 0;
  212181. }
  212182. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212183. {
  212184. if (callback == 0)
  212185. return 0;
  212186. UINT deviceId = MIDI_MAPPER;
  212187. int n = 0;
  212188. String name;
  212189. const int num = midiInGetNumDevs();
  212190. for (int i = 0; i < num; ++i)
  212191. {
  212192. MIDIINCAPS mc;
  212193. zerostruct (mc);
  212194. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212195. {
  212196. if (index == n)
  212197. {
  212198. deviceId = i;
  212199. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212200. break;
  212201. }
  212202. ++n;
  212203. }
  212204. }
  212205. ScopedPointer <MidiInput> in (new MidiInput (name));
  212206. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212207. HMIDIIN h;
  212208. HRESULT err = midiInOpen (&h, deviceId,
  212209. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212210. (DWORD_PTR) (MidiInCollector*) collector,
  212211. CALLBACK_FUNCTION);
  212212. if (err == MMSYSERR_NOERROR)
  212213. {
  212214. collector->deviceHandle = h;
  212215. in->internal = collector.release();
  212216. return in.release();
  212217. }
  212218. return 0;
  212219. }
  212220. MidiInput::MidiInput (const String& name_)
  212221. : name (name_),
  212222. internal (0)
  212223. {
  212224. }
  212225. MidiInput::~MidiInput()
  212226. {
  212227. delete static_cast <MidiInCollector*> (internal);
  212228. }
  212229. void MidiInput::start()
  212230. {
  212231. static_cast <MidiInCollector*> (internal)->start();
  212232. }
  212233. void MidiInput::stop()
  212234. {
  212235. static_cast <MidiInCollector*> (internal)->stop();
  212236. }
  212237. struct MidiOutHandle
  212238. {
  212239. int refCount;
  212240. UINT deviceId;
  212241. HMIDIOUT handle;
  212242. static Array<MidiOutHandle*> activeHandles;
  212243. private:
  212244. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212245. };
  212246. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212247. const StringArray MidiOutput::getDevices()
  212248. {
  212249. StringArray s;
  212250. const int num = midiOutGetNumDevs();
  212251. for (int i = 0; i < num; ++i)
  212252. {
  212253. MIDIOUTCAPS mc;
  212254. zerostruct (mc);
  212255. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212256. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212257. }
  212258. return s;
  212259. }
  212260. int MidiOutput::getDefaultDeviceIndex()
  212261. {
  212262. const int num = midiOutGetNumDevs();
  212263. int n = 0;
  212264. for (int i = 0; i < num; ++i)
  212265. {
  212266. MIDIOUTCAPS mc;
  212267. zerostruct (mc);
  212268. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212269. {
  212270. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212271. return n;
  212272. ++n;
  212273. }
  212274. }
  212275. return 0;
  212276. }
  212277. MidiOutput* MidiOutput::openDevice (int index)
  212278. {
  212279. UINT deviceId = MIDI_MAPPER;
  212280. const int num = midiOutGetNumDevs();
  212281. int i, n = 0;
  212282. for (i = 0; i < num; ++i)
  212283. {
  212284. MIDIOUTCAPS mc;
  212285. zerostruct (mc);
  212286. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212287. {
  212288. // use the microsoft sw synth as a default - best not to allow deviceId
  212289. // to be MIDI_MAPPER, or else device sharing breaks
  212290. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212291. deviceId = i;
  212292. if (index == n)
  212293. {
  212294. deviceId = i;
  212295. break;
  212296. }
  212297. ++n;
  212298. }
  212299. }
  212300. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212301. {
  212302. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212303. if (han != 0 && han->deviceId == deviceId)
  212304. {
  212305. han->refCount++;
  212306. MidiOutput* const out = new MidiOutput();
  212307. out->internal = han;
  212308. return out;
  212309. }
  212310. }
  212311. for (i = 4; --i >= 0;)
  212312. {
  212313. HMIDIOUT h = 0;
  212314. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212315. if (res == MMSYSERR_NOERROR)
  212316. {
  212317. MidiOutHandle* const han = new MidiOutHandle();
  212318. han->deviceId = deviceId;
  212319. han->refCount = 1;
  212320. han->handle = h;
  212321. MidiOutHandle::activeHandles.add (han);
  212322. MidiOutput* const out = new MidiOutput();
  212323. out->internal = han;
  212324. return out;
  212325. }
  212326. else if (res == MMSYSERR_ALLOCATED)
  212327. {
  212328. Sleep (100);
  212329. }
  212330. else
  212331. {
  212332. break;
  212333. }
  212334. }
  212335. return 0;
  212336. }
  212337. MidiOutput::~MidiOutput()
  212338. {
  212339. stopBackgroundThread();
  212340. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212341. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212342. {
  212343. midiOutClose (h->handle);
  212344. MidiOutHandle::activeHandles.removeValue (h);
  212345. delete h;
  212346. }
  212347. }
  212348. void MidiOutput::reset()
  212349. {
  212350. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212351. midiOutReset (h->handle);
  212352. }
  212353. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212354. {
  212355. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212356. DWORD n;
  212357. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212358. {
  212359. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212360. rightVol = nn[0] / (float) 0xffff;
  212361. leftVol = nn[1] / (float) 0xffff;
  212362. return true;
  212363. }
  212364. else
  212365. {
  212366. rightVol = leftVol = 1.0f;
  212367. return false;
  212368. }
  212369. }
  212370. void MidiOutput::setVolume (float leftVol, float rightVol)
  212371. {
  212372. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212373. DWORD n;
  212374. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212375. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212376. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212377. midiOutSetVolume (handle->handle, n);
  212378. }
  212379. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212380. {
  212381. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212382. if (message.getRawDataSize() > 3
  212383. || message.isSysEx())
  212384. {
  212385. MIDIHDR h;
  212386. zerostruct (h);
  212387. h.lpData = (char*) message.getRawData();
  212388. h.dwBufferLength = message.getRawDataSize();
  212389. h.dwBytesRecorded = message.getRawDataSize();
  212390. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212391. {
  212392. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212393. if (res == MMSYSERR_NOERROR)
  212394. {
  212395. while ((h.dwFlags & MHDR_DONE) == 0)
  212396. Sleep (1);
  212397. int count = 500; // 1 sec timeout
  212398. while (--count >= 0)
  212399. {
  212400. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212401. if (res == MIDIERR_STILLPLAYING)
  212402. Sleep (2);
  212403. else
  212404. break;
  212405. }
  212406. }
  212407. }
  212408. }
  212409. else
  212410. {
  212411. midiOutShortMsg (handle->handle,
  212412. *(unsigned int*) message.getRawData());
  212413. }
  212414. }
  212415. #endif
  212416. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212417. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212418. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212419. // compiled on its own).
  212420. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212421. #undef WINDOWS
  212422. // #define ASIO_DEBUGGING 1
  212423. #undef log
  212424. #if ASIO_DEBUGGING
  212425. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212426. #else
  212427. #define log(a) {}
  212428. #endif
  212429. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212430. to be pretty random about whether or not they do this. If you hit an error using these functions
  212431. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212432. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212433. */
  212434. #define JUCE_ASIOCALLBACK __cdecl
  212435. namespace ASIODebugging
  212436. {
  212437. #if ASIO_DEBUGGING
  212438. static void log (const String& context, long error)
  212439. {
  212440. String err ("unknown error");
  212441. if (error == ASE_NotPresent) err = "Not Present";
  212442. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212443. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212444. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212445. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212446. else if (error == ASE_NoClock) err = "No Clock";
  212447. else if (error == ASE_NoMemory) err = "Out of memory";
  212448. log ("!!error: " + context + " - " + err);
  212449. }
  212450. #define logError(a, b) ASIODebugging::log ((a), (b))
  212451. #else
  212452. #define logError(a, b) {}
  212453. #endif
  212454. }
  212455. class ASIOAudioIODevice;
  212456. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212457. static const int maxASIOChannels = 160;
  212458. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212459. private Timer
  212460. {
  212461. public:
  212462. Component ourWindow;
  212463. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212464. const String& optionalDllForDirectLoading_)
  212465. : AudioIODevice (name_, "ASIO"),
  212466. asioObject (0),
  212467. classId (classId_),
  212468. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212469. currentBitDepth (16),
  212470. currentSampleRate (0),
  212471. isOpen_ (false),
  212472. isStarted (false),
  212473. postOutput (true),
  212474. insideControlPanelModalLoop (false),
  212475. shouldUsePreferredSize (false)
  212476. {
  212477. name = name_;
  212478. ourWindow.addToDesktop (0);
  212479. windowHandle = ourWindow.getWindowHandle();
  212480. jassert (currentASIODev [slotNumber] == 0);
  212481. currentASIODev [slotNumber] = this;
  212482. openDevice();
  212483. }
  212484. ~ASIOAudioIODevice()
  212485. {
  212486. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212487. if (currentASIODev[i] == this)
  212488. currentASIODev[i] = 0;
  212489. close();
  212490. log ("ASIO - exiting");
  212491. removeCurrentDriver();
  212492. }
  212493. void updateSampleRates()
  212494. {
  212495. // find a list of sample rates..
  212496. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212497. sampleRates.clear();
  212498. if (asioObject != 0)
  212499. {
  212500. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212501. {
  212502. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212503. if (err == 0)
  212504. {
  212505. sampleRates.add ((int) possibleSampleRates[index]);
  212506. log ("rate: " + String ((int) possibleSampleRates[index]));
  212507. }
  212508. else if (err != ASE_NoClock)
  212509. {
  212510. logError ("CanSampleRate", err);
  212511. }
  212512. }
  212513. if (sampleRates.size() == 0)
  212514. {
  212515. double cr = 0;
  212516. const long err = asioObject->getSampleRate (&cr);
  212517. log ("No sample rates supported - current rate: " + String ((int) cr));
  212518. if (err == 0)
  212519. sampleRates.add ((int) cr);
  212520. }
  212521. }
  212522. }
  212523. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212524. const StringArray getInputChannelNames() { return inputChannelNames; }
  212525. int getNumSampleRates() { return sampleRates.size(); }
  212526. double getSampleRate (int index) { return sampleRates [index]; }
  212527. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212528. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212529. int getDefaultBufferSize() { return preferredSize; }
  212530. const String open (const BigInteger& inputChannels,
  212531. const BigInteger& outputChannels,
  212532. double sr,
  212533. int bufferSizeSamples)
  212534. {
  212535. close();
  212536. currentCallback = 0;
  212537. if (bufferSizeSamples <= 0)
  212538. shouldUsePreferredSize = true;
  212539. if (asioObject == 0 || ! isASIOOpen)
  212540. {
  212541. log ("Warning: device not open");
  212542. const String err (openDevice());
  212543. if (asioObject == 0 || ! isASIOOpen)
  212544. return err;
  212545. }
  212546. isStarted = false;
  212547. bufferIndex = -1;
  212548. long err = 0;
  212549. long newPreferredSize = 0;
  212550. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212551. minSize = 0;
  212552. maxSize = 0;
  212553. newPreferredSize = 0;
  212554. granularity = 0;
  212555. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212556. {
  212557. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212558. shouldUsePreferredSize = true;
  212559. preferredSize = newPreferredSize;
  212560. }
  212561. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212562. // dynamic changes to the buffer size...
  212563. shouldUsePreferredSize = shouldUsePreferredSize
  212564. || getName().containsIgnoreCase ("Digidesign");
  212565. if (shouldUsePreferredSize)
  212566. {
  212567. log ("Using preferred size for buffer..");
  212568. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212569. {
  212570. bufferSizeSamples = preferredSize;
  212571. }
  212572. else
  212573. {
  212574. bufferSizeSamples = 1024;
  212575. logError ("GetBufferSize1", err);
  212576. }
  212577. shouldUsePreferredSize = false;
  212578. }
  212579. int sampleRate = roundDoubleToInt (sr);
  212580. currentSampleRate = sampleRate;
  212581. currentBlockSizeSamples = bufferSizeSamples;
  212582. currentChansOut.clear();
  212583. currentChansIn.clear();
  212584. zeromem (inBuffers, sizeof (inBuffers));
  212585. zeromem (outBuffers, sizeof (outBuffers));
  212586. updateSampleRates();
  212587. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212588. sampleRate = sampleRates[0];
  212589. jassert (sampleRate != 0);
  212590. if (sampleRate == 0)
  212591. sampleRate = 44100;
  212592. long numSources = 32;
  212593. ASIOClockSource clocks[32];
  212594. zeromem (clocks, sizeof (clocks));
  212595. asioObject->getClockSources (clocks, &numSources);
  212596. bool isSourceSet = false;
  212597. // careful not to remove this loop because it does more than just logging!
  212598. int i;
  212599. for (i = 0; i < numSources; ++i)
  212600. {
  212601. String s ("clock: ");
  212602. s += clocks[i].name;
  212603. if (clocks[i].isCurrentSource)
  212604. {
  212605. isSourceSet = true;
  212606. s << " (cur)";
  212607. }
  212608. log (s);
  212609. }
  212610. if (numSources > 1 && ! isSourceSet)
  212611. {
  212612. log ("setting clock source");
  212613. asioObject->setClockSource (clocks[0].index);
  212614. Thread::sleep (20);
  212615. }
  212616. else
  212617. {
  212618. if (numSources == 0)
  212619. {
  212620. log ("ASIO - no clock sources!");
  212621. }
  212622. }
  212623. double cr = 0;
  212624. err = asioObject->getSampleRate (&cr);
  212625. if (err == 0)
  212626. {
  212627. currentSampleRate = cr;
  212628. }
  212629. else
  212630. {
  212631. logError ("GetSampleRate", err);
  212632. currentSampleRate = 0;
  212633. }
  212634. error = String::empty;
  212635. needToReset = false;
  212636. isReSync = false;
  212637. err = 0;
  212638. bool buffersCreated = false;
  212639. if (currentSampleRate != sampleRate)
  212640. {
  212641. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212642. err = asioObject->setSampleRate (sampleRate);
  212643. if (err == ASE_NoClock && numSources > 0)
  212644. {
  212645. log ("trying to set a clock source..");
  212646. Thread::sleep (10);
  212647. err = asioObject->setClockSource (clocks[0].index);
  212648. if (err != 0)
  212649. {
  212650. logError ("SetClock", err);
  212651. }
  212652. Thread::sleep (10);
  212653. err = asioObject->setSampleRate (sampleRate);
  212654. }
  212655. }
  212656. if (err == 0)
  212657. {
  212658. currentSampleRate = sampleRate;
  212659. if (needToReset)
  212660. {
  212661. if (isReSync)
  212662. {
  212663. log ("Resync request");
  212664. }
  212665. log ("! Resetting ASIO after sample rate change");
  212666. removeCurrentDriver();
  212667. loadDriver();
  212668. const String error (initDriver());
  212669. if (error.isNotEmpty())
  212670. {
  212671. log ("ASIOInit: " + error);
  212672. }
  212673. needToReset = false;
  212674. isReSync = false;
  212675. }
  212676. numActiveInputChans = 0;
  212677. numActiveOutputChans = 0;
  212678. ASIOBufferInfo* info = bufferInfos;
  212679. int i;
  212680. for (i = 0; i < totalNumInputChans; ++i)
  212681. {
  212682. if (inputChannels[i])
  212683. {
  212684. currentChansIn.setBit (i);
  212685. info->isInput = 1;
  212686. info->channelNum = i;
  212687. info->buffers[0] = info->buffers[1] = 0;
  212688. ++info;
  212689. ++numActiveInputChans;
  212690. }
  212691. }
  212692. for (i = 0; i < totalNumOutputChans; ++i)
  212693. {
  212694. if (outputChannels[i])
  212695. {
  212696. currentChansOut.setBit (i);
  212697. info->isInput = 0;
  212698. info->channelNum = i;
  212699. info->buffers[0] = info->buffers[1] = 0;
  212700. ++info;
  212701. ++numActiveOutputChans;
  212702. }
  212703. }
  212704. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212705. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212706. if (currentASIODev[0] == this)
  212707. {
  212708. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212709. callbacks.asioMessage = &asioMessagesCallback0;
  212710. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212711. }
  212712. else if (currentASIODev[1] == this)
  212713. {
  212714. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212715. callbacks.asioMessage = &asioMessagesCallback1;
  212716. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212717. }
  212718. else if (currentASIODev[2] == this)
  212719. {
  212720. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212721. callbacks.asioMessage = &asioMessagesCallback2;
  212722. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212723. }
  212724. else
  212725. {
  212726. jassertfalse;
  212727. }
  212728. log ("disposing buffers");
  212729. err = asioObject->disposeBuffers();
  212730. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212731. err = asioObject->createBuffers (bufferInfos,
  212732. totalBuffers,
  212733. currentBlockSizeSamples,
  212734. &callbacks);
  212735. if (err != 0)
  212736. {
  212737. currentBlockSizeSamples = preferredSize;
  212738. logError ("create buffers 2", err);
  212739. asioObject->disposeBuffers();
  212740. err = asioObject->createBuffers (bufferInfos,
  212741. totalBuffers,
  212742. currentBlockSizeSamples,
  212743. &callbacks);
  212744. }
  212745. if (err == 0)
  212746. {
  212747. buffersCreated = true;
  212748. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212749. int n = 0;
  212750. Array <int> types;
  212751. currentBitDepth = 16;
  212752. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212753. {
  212754. if (inputChannels[i])
  212755. {
  212756. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212757. ASIOChannelInfo channelInfo;
  212758. zerostruct (channelInfo);
  212759. channelInfo.channel = i;
  212760. channelInfo.isInput = 1;
  212761. asioObject->getChannelInfo (&channelInfo);
  212762. types.addIfNotAlreadyThere (channelInfo.type);
  212763. typeToFormatParameters (channelInfo.type,
  212764. inputChannelBitDepths[n],
  212765. inputChannelBytesPerSample[n],
  212766. inputChannelIsFloat[n],
  212767. inputChannelLittleEndian[n]);
  212768. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212769. ++n;
  212770. }
  212771. }
  212772. jassert (numActiveInputChans == n);
  212773. n = 0;
  212774. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212775. {
  212776. if (outputChannels[i])
  212777. {
  212778. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212779. ASIOChannelInfo channelInfo;
  212780. zerostruct (channelInfo);
  212781. channelInfo.channel = i;
  212782. channelInfo.isInput = 0;
  212783. asioObject->getChannelInfo (&channelInfo);
  212784. types.addIfNotAlreadyThere (channelInfo.type);
  212785. typeToFormatParameters (channelInfo.type,
  212786. outputChannelBitDepths[n],
  212787. outputChannelBytesPerSample[n],
  212788. outputChannelIsFloat[n],
  212789. outputChannelLittleEndian[n]);
  212790. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212791. ++n;
  212792. }
  212793. }
  212794. jassert (numActiveOutputChans == n);
  212795. for (i = types.size(); --i >= 0;)
  212796. {
  212797. log ("channel format: " + String (types[i]));
  212798. }
  212799. jassert (n <= totalBuffers);
  212800. for (i = 0; i < numActiveOutputChans; ++i)
  212801. {
  212802. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212803. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212804. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212805. {
  212806. log ("!! Null buffers");
  212807. }
  212808. else
  212809. {
  212810. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212811. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212812. }
  212813. }
  212814. inputLatency = outputLatency = 0;
  212815. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212816. {
  212817. log ("ASIO - no latencies");
  212818. }
  212819. else
  212820. {
  212821. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212822. }
  212823. isOpen_ = true;
  212824. log ("starting ASIO");
  212825. calledback = false;
  212826. err = asioObject->start();
  212827. if (err != 0)
  212828. {
  212829. isOpen_ = false;
  212830. log ("ASIO - stop on failure");
  212831. Thread::sleep (10);
  212832. asioObject->stop();
  212833. error = "Can't start device";
  212834. Thread::sleep (10);
  212835. }
  212836. else
  212837. {
  212838. int count = 300;
  212839. while (--count > 0 && ! calledback)
  212840. Thread::sleep (10);
  212841. isStarted = true;
  212842. if (! calledback)
  212843. {
  212844. error = "Device didn't start correctly";
  212845. log ("ASIO didn't callback - stopping..");
  212846. asioObject->stop();
  212847. }
  212848. }
  212849. }
  212850. else
  212851. {
  212852. error = "Can't create i/o buffers";
  212853. }
  212854. }
  212855. else
  212856. {
  212857. error = "Can't set sample rate: ";
  212858. error << sampleRate;
  212859. }
  212860. if (error.isNotEmpty())
  212861. {
  212862. logError (error, err);
  212863. if (asioObject != 0 && buffersCreated)
  212864. asioObject->disposeBuffers();
  212865. Thread::sleep (20);
  212866. isStarted = false;
  212867. isOpen_ = false;
  212868. const String errorCopy (error);
  212869. close(); // (this resets the error string)
  212870. error = errorCopy;
  212871. }
  212872. needToReset = false;
  212873. isReSync = false;
  212874. return error;
  212875. }
  212876. void close()
  212877. {
  212878. error = String::empty;
  212879. stopTimer();
  212880. stop();
  212881. if (isASIOOpen && isOpen_)
  212882. {
  212883. const ScopedLock sl (callbackLock);
  212884. isOpen_ = false;
  212885. isStarted = false;
  212886. needToReset = false;
  212887. isReSync = false;
  212888. log ("ASIO - stopping");
  212889. if (asioObject != 0)
  212890. {
  212891. Thread::sleep (20);
  212892. asioObject->stop();
  212893. Thread::sleep (10);
  212894. asioObject->disposeBuffers();
  212895. }
  212896. Thread::sleep (10);
  212897. }
  212898. }
  212899. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212900. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212901. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212902. double getCurrentSampleRate() { return currentSampleRate; }
  212903. int getCurrentBitDepth() { return currentBitDepth; }
  212904. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212905. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212906. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212907. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212908. void start (AudioIODeviceCallback* callback)
  212909. {
  212910. if (callback != 0)
  212911. {
  212912. callback->audioDeviceAboutToStart (this);
  212913. const ScopedLock sl (callbackLock);
  212914. currentCallback = callback;
  212915. }
  212916. }
  212917. void stop()
  212918. {
  212919. AudioIODeviceCallback* const lastCallback = currentCallback;
  212920. {
  212921. const ScopedLock sl (callbackLock);
  212922. currentCallback = 0;
  212923. }
  212924. if (lastCallback != 0)
  212925. lastCallback->audioDeviceStopped();
  212926. }
  212927. const String getLastError() { return error; }
  212928. bool hasControlPanel() const { return true; }
  212929. bool showControlPanel()
  212930. {
  212931. log ("ASIO - showing control panel");
  212932. Component modalWindow (String::empty);
  212933. modalWindow.setOpaque (true);
  212934. modalWindow.addToDesktop (0);
  212935. modalWindow.enterModalState();
  212936. bool done = false;
  212937. JUCE_TRY
  212938. {
  212939. // are there are devices that need to be closed before showing their control panel?
  212940. // close();
  212941. insideControlPanelModalLoop = true;
  212942. const uint32 started = Time::getMillisecondCounter();
  212943. if (asioObject != 0)
  212944. {
  212945. asioObject->controlPanel();
  212946. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212947. log ("spent: " + String (spent));
  212948. if (spent > 300)
  212949. {
  212950. shouldUsePreferredSize = true;
  212951. done = true;
  212952. }
  212953. }
  212954. }
  212955. JUCE_CATCH_ALL
  212956. insideControlPanelModalLoop = false;
  212957. return done;
  212958. }
  212959. void resetRequest() throw()
  212960. {
  212961. needToReset = true;
  212962. }
  212963. void resyncRequest() throw()
  212964. {
  212965. needToReset = true;
  212966. isReSync = true;
  212967. }
  212968. void timerCallback()
  212969. {
  212970. if (! insideControlPanelModalLoop)
  212971. {
  212972. stopTimer();
  212973. // used to cause a reset
  212974. log ("! ASIO restart request!");
  212975. if (isOpen_)
  212976. {
  212977. AudioIODeviceCallback* const oldCallback = currentCallback;
  212978. close();
  212979. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212980. currentSampleRate, currentBlockSizeSamples);
  212981. if (oldCallback != 0)
  212982. start (oldCallback);
  212983. }
  212984. }
  212985. else
  212986. {
  212987. startTimer (100);
  212988. }
  212989. }
  212990. private:
  212991. IASIO* volatile asioObject;
  212992. ASIOCallbacks callbacks;
  212993. void* windowHandle;
  212994. CLSID classId;
  212995. const String optionalDllForDirectLoading;
  212996. String error;
  212997. long totalNumInputChans, totalNumOutputChans;
  212998. StringArray inputChannelNames, outputChannelNames;
  212999. Array<int> sampleRates, bufferSizes;
  213000. long inputLatency, outputLatency;
  213001. long minSize, maxSize, preferredSize, granularity;
  213002. int volatile currentBlockSizeSamples;
  213003. int volatile currentBitDepth;
  213004. double volatile currentSampleRate;
  213005. BigInteger currentChansOut, currentChansIn;
  213006. AudioIODeviceCallback* volatile currentCallback;
  213007. CriticalSection callbackLock;
  213008. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213009. float* inBuffers [maxASIOChannels];
  213010. float* outBuffers [maxASIOChannels];
  213011. int inputChannelBitDepths [maxASIOChannels];
  213012. int outputChannelBitDepths [maxASIOChannels];
  213013. int inputChannelBytesPerSample [maxASIOChannels];
  213014. int outputChannelBytesPerSample [maxASIOChannels];
  213015. bool inputChannelIsFloat [maxASIOChannels];
  213016. bool outputChannelIsFloat [maxASIOChannels];
  213017. bool inputChannelLittleEndian [maxASIOChannels];
  213018. bool outputChannelLittleEndian [maxASIOChannels];
  213019. WaitableEvent event1;
  213020. HeapBlock <float> tempBuffer;
  213021. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213022. bool isOpen_, isStarted;
  213023. bool volatile isASIOOpen;
  213024. bool volatile calledback;
  213025. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213026. bool volatile insideControlPanelModalLoop;
  213027. bool volatile shouldUsePreferredSize;
  213028. void removeCurrentDriver()
  213029. {
  213030. if (asioObject != 0)
  213031. {
  213032. asioObject->Release();
  213033. asioObject = 0;
  213034. }
  213035. }
  213036. bool loadDriver()
  213037. {
  213038. removeCurrentDriver();
  213039. JUCE_TRY
  213040. {
  213041. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213042. classId, (void**) &asioObject) == S_OK)
  213043. {
  213044. return true;
  213045. }
  213046. // If a class isn't registered but we have a path for it, we can fallback to
  213047. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213048. if (optionalDllForDirectLoading.isNotEmpty())
  213049. {
  213050. HMODULE h = LoadLibrary (optionalDllForDirectLoading.toUTF16());
  213051. if (h != 0)
  213052. {
  213053. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213054. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213055. if (dllGetClassObject != 0)
  213056. {
  213057. IClassFactory* classFactory = 0;
  213058. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213059. if (classFactory != 0)
  213060. {
  213061. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213062. classFactory->Release();
  213063. }
  213064. return asioObject != 0;
  213065. }
  213066. }
  213067. }
  213068. }
  213069. JUCE_CATCH_ALL
  213070. asioObject = 0;
  213071. return false;
  213072. }
  213073. const String initDriver()
  213074. {
  213075. if (asioObject != 0)
  213076. {
  213077. char buffer [256];
  213078. zeromem (buffer, sizeof (buffer));
  213079. if (! asioObject->init (windowHandle))
  213080. {
  213081. asioObject->getErrorMessage (buffer);
  213082. return String (buffer, sizeof (buffer) - 1);
  213083. }
  213084. // just in case any daft drivers expect this to be called..
  213085. asioObject->getDriverName (buffer);
  213086. return String::empty;
  213087. }
  213088. return "No Driver";
  213089. }
  213090. const String openDevice()
  213091. {
  213092. // use this in case the driver starts opening dialog boxes..
  213093. Component modalWindow (String::empty);
  213094. modalWindow.setOpaque (true);
  213095. modalWindow.addToDesktop (0);
  213096. modalWindow.enterModalState();
  213097. // open the device and get its info..
  213098. log ("opening ASIO device: " + getName());
  213099. needToReset = false;
  213100. isReSync = false;
  213101. outputChannelNames.clear();
  213102. inputChannelNames.clear();
  213103. bufferSizes.clear();
  213104. sampleRates.clear();
  213105. isASIOOpen = false;
  213106. isOpen_ = false;
  213107. totalNumInputChans = 0;
  213108. totalNumOutputChans = 0;
  213109. numActiveInputChans = 0;
  213110. numActiveOutputChans = 0;
  213111. currentCallback = 0;
  213112. error = String::empty;
  213113. if (getName().isEmpty())
  213114. return error;
  213115. long err = 0;
  213116. if (loadDriver())
  213117. {
  213118. if ((error = initDriver()).isEmpty())
  213119. {
  213120. numActiveInputChans = 0;
  213121. numActiveOutputChans = 0;
  213122. totalNumInputChans = 0;
  213123. totalNumOutputChans = 0;
  213124. if (asioObject != 0
  213125. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213126. {
  213127. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213128. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213129. {
  213130. // find a list of buffer sizes..
  213131. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213132. if (granularity >= 0)
  213133. {
  213134. granularity = jmax (1, (int) granularity);
  213135. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213136. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213137. }
  213138. else if (granularity < 0)
  213139. {
  213140. for (int i = 0; i < 18; ++i)
  213141. {
  213142. const int s = (1 << i);
  213143. if (s >= minSize && s <= maxSize)
  213144. bufferSizes.add (s);
  213145. }
  213146. }
  213147. if (! bufferSizes.contains (preferredSize))
  213148. bufferSizes.insert (0, preferredSize);
  213149. double currentRate = 0;
  213150. asioObject->getSampleRate (&currentRate);
  213151. if (currentRate <= 0.0 || currentRate > 192001.0)
  213152. {
  213153. log ("setting sample rate");
  213154. err = asioObject->setSampleRate (44100.0);
  213155. if (err != 0)
  213156. {
  213157. logError ("setting sample rate", err);
  213158. }
  213159. asioObject->getSampleRate (&currentRate);
  213160. }
  213161. currentSampleRate = currentRate;
  213162. postOutput = (asioObject->outputReady() == 0);
  213163. if (postOutput)
  213164. {
  213165. log ("ASIO outputReady = ok");
  213166. }
  213167. updateSampleRates();
  213168. // ..because cubase does it at this point
  213169. inputLatency = outputLatency = 0;
  213170. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213171. {
  213172. log ("ASIO - no latencies");
  213173. }
  213174. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213175. // create some dummy buffers now.. because cubase does..
  213176. numActiveInputChans = 0;
  213177. numActiveOutputChans = 0;
  213178. ASIOBufferInfo* info = bufferInfos;
  213179. int i, numChans = 0;
  213180. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213181. {
  213182. info->isInput = 1;
  213183. info->channelNum = i;
  213184. info->buffers[0] = info->buffers[1] = 0;
  213185. ++info;
  213186. ++numChans;
  213187. }
  213188. const int outputBufferIndex = numChans;
  213189. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213190. {
  213191. info->isInput = 0;
  213192. info->channelNum = i;
  213193. info->buffers[0] = info->buffers[1] = 0;
  213194. ++info;
  213195. ++numChans;
  213196. }
  213197. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213198. if (currentASIODev[0] == this)
  213199. {
  213200. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213201. callbacks.asioMessage = &asioMessagesCallback0;
  213202. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213203. }
  213204. else if (currentASIODev[1] == this)
  213205. {
  213206. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213207. callbacks.asioMessage = &asioMessagesCallback1;
  213208. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213209. }
  213210. else if (currentASIODev[2] == this)
  213211. {
  213212. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213213. callbacks.asioMessage = &asioMessagesCallback2;
  213214. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213215. }
  213216. else
  213217. {
  213218. jassertfalse;
  213219. }
  213220. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213221. if (preferredSize > 0)
  213222. {
  213223. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213224. if (err != 0)
  213225. {
  213226. logError ("dummy buffers", err);
  213227. }
  213228. }
  213229. long newInps = 0, newOuts = 0;
  213230. asioObject->getChannels (&newInps, &newOuts);
  213231. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213232. {
  213233. totalNumInputChans = newInps;
  213234. totalNumOutputChans = newOuts;
  213235. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213236. }
  213237. updateSampleRates();
  213238. ASIOChannelInfo channelInfo;
  213239. channelInfo.type = 0;
  213240. for (i = 0; i < totalNumInputChans; ++i)
  213241. {
  213242. zerostruct (channelInfo);
  213243. channelInfo.channel = i;
  213244. channelInfo.isInput = 1;
  213245. asioObject->getChannelInfo (&channelInfo);
  213246. inputChannelNames.add (String (channelInfo.name));
  213247. }
  213248. for (i = 0; i < totalNumOutputChans; ++i)
  213249. {
  213250. zerostruct (channelInfo);
  213251. channelInfo.channel = i;
  213252. channelInfo.isInput = 0;
  213253. asioObject->getChannelInfo (&channelInfo);
  213254. outputChannelNames.add (String (channelInfo.name));
  213255. typeToFormatParameters (channelInfo.type,
  213256. outputChannelBitDepths[i],
  213257. outputChannelBytesPerSample[i],
  213258. outputChannelIsFloat[i],
  213259. outputChannelLittleEndian[i]);
  213260. if (i < 2)
  213261. {
  213262. // clear the channels that are used with the dummy stuff
  213263. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213264. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213265. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213266. }
  213267. }
  213268. outputChannelNames.trim();
  213269. inputChannelNames.trim();
  213270. outputChannelNames.appendNumbersToDuplicates (false, true);
  213271. inputChannelNames.appendNumbersToDuplicates (false, true);
  213272. // start and stop because cubase does it..
  213273. asioObject->getLatencies (&inputLatency, &outputLatency);
  213274. if ((err = asioObject->start()) != 0)
  213275. {
  213276. // ignore an error here, as it might start later after setting other stuff up
  213277. logError ("ASIO start", err);
  213278. }
  213279. Thread::sleep (100);
  213280. asioObject->stop();
  213281. }
  213282. else
  213283. {
  213284. error = "Can't detect buffer sizes";
  213285. }
  213286. }
  213287. else
  213288. {
  213289. error = "Can't detect asio channels";
  213290. }
  213291. }
  213292. }
  213293. else
  213294. {
  213295. error = "No such device";
  213296. }
  213297. if (error.isNotEmpty())
  213298. {
  213299. logError (error, err);
  213300. if (asioObject != 0)
  213301. asioObject->disposeBuffers();
  213302. removeCurrentDriver();
  213303. isASIOOpen = false;
  213304. }
  213305. else
  213306. {
  213307. isASIOOpen = true;
  213308. log ("ASIO device open");
  213309. }
  213310. isOpen_ = false;
  213311. needToReset = false;
  213312. isReSync = false;
  213313. return error;
  213314. }
  213315. void JUCE_ASIOCALLBACK callback (const long index)
  213316. {
  213317. if (isStarted)
  213318. {
  213319. bufferIndex = index;
  213320. processBuffer();
  213321. }
  213322. else
  213323. {
  213324. if (postOutput && (asioObject != 0))
  213325. asioObject->outputReady();
  213326. }
  213327. calledback = true;
  213328. }
  213329. void processBuffer()
  213330. {
  213331. const ASIOBufferInfo* const infos = bufferInfos;
  213332. const int bi = bufferIndex;
  213333. const ScopedLock sl (callbackLock);
  213334. if (needToReset)
  213335. {
  213336. needToReset = false;
  213337. if (isReSync)
  213338. {
  213339. log ("! ASIO resync");
  213340. isReSync = false;
  213341. }
  213342. else
  213343. {
  213344. startTimer (20);
  213345. }
  213346. }
  213347. if (bi >= 0)
  213348. {
  213349. const int samps = currentBlockSizeSamples;
  213350. if (currentCallback != 0)
  213351. {
  213352. int i;
  213353. for (i = 0; i < numActiveInputChans; ++i)
  213354. {
  213355. float* const dst = inBuffers[i];
  213356. jassert (dst != 0);
  213357. const char* const src = (const char*) (infos[i].buffers[bi]);
  213358. if (inputChannelIsFloat[i])
  213359. {
  213360. memcpy (dst, src, samps * sizeof (float));
  213361. }
  213362. else
  213363. {
  213364. jassert (dst == tempBuffer + (samps * i));
  213365. switch (inputChannelBitDepths[i])
  213366. {
  213367. case 16:
  213368. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213369. samps, inputChannelLittleEndian[i]);
  213370. break;
  213371. case 24:
  213372. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213373. samps, inputChannelLittleEndian[i]);
  213374. break;
  213375. case 32:
  213376. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213377. samps, inputChannelLittleEndian[i]);
  213378. break;
  213379. case 64:
  213380. jassertfalse;
  213381. break;
  213382. }
  213383. }
  213384. }
  213385. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213386. outBuffers, numActiveOutputChans, samps);
  213387. for (i = 0; i < numActiveOutputChans; ++i)
  213388. {
  213389. float* const src = outBuffers[i];
  213390. jassert (src != 0);
  213391. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213392. if (outputChannelIsFloat[i])
  213393. {
  213394. memcpy (dst, src, samps * sizeof (float));
  213395. }
  213396. else
  213397. {
  213398. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213399. switch (outputChannelBitDepths[i])
  213400. {
  213401. case 16:
  213402. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213403. samps, outputChannelLittleEndian[i]);
  213404. break;
  213405. case 24:
  213406. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213407. samps, outputChannelLittleEndian[i]);
  213408. break;
  213409. case 32:
  213410. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213411. samps, outputChannelLittleEndian[i]);
  213412. break;
  213413. case 64:
  213414. jassertfalse;
  213415. break;
  213416. }
  213417. }
  213418. }
  213419. }
  213420. else
  213421. {
  213422. for (int i = 0; i < numActiveOutputChans; ++i)
  213423. {
  213424. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213425. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213426. }
  213427. }
  213428. }
  213429. if (postOutput)
  213430. asioObject->outputReady();
  213431. }
  213432. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213433. {
  213434. if (currentASIODev[0] != 0)
  213435. currentASIODev[0]->callback (index);
  213436. return 0;
  213437. }
  213438. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213439. {
  213440. if (currentASIODev[1] != 0)
  213441. currentASIODev[1]->callback (index);
  213442. return 0;
  213443. }
  213444. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213445. {
  213446. if (currentASIODev[2] != 0)
  213447. currentASIODev[2]->callback (index);
  213448. return 0;
  213449. }
  213450. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213451. {
  213452. if (currentASIODev[0] != 0)
  213453. currentASIODev[0]->callback (index);
  213454. }
  213455. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213456. {
  213457. if (currentASIODev[1] != 0)
  213458. currentASIODev[1]->callback (index);
  213459. }
  213460. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213461. {
  213462. if (currentASIODev[2] != 0)
  213463. currentASIODev[2]->callback (index);
  213464. }
  213465. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213466. {
  213467. return asioMessagesCallback (selector, value, 0);
  213468. }
  213469. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213470. {
  213471. return asioMessagesCallback (selector, value, 1);
  213472. }
  213473. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213474. {
  213475. return asioMessagesCallback (selector, value, 2);
  213476. }
  213477. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213478. {
  213479. switch (selector)
  213480. {
  213481. case kAsioSelectorSupported:
  213482. if (value == kAsioResetRequest
  213483. || value == kAsioEngineVersion
  213484. || value == kAsioResyncRequest
  213485. || value == kAsioLatenciesChanged
  213486. || value == kAsioSupportsInputMonitor)
  213487. return 1;
  213488. break;
  213489. case kAsioBufferSizeChange:
  213490. break;
  213491. case kAsioResetRequest:
  213492. if (currentASIODev[deviceIndex] != 0)
  213493. currentASIODev[deviceIndex]->resetRequest();
  213494. return 1;
  213495. case kAsioResyncRequest:
  213496. if (currentASIODev[deviceIndex] != 0)
  213497. currentASIODev[deviceIndex]->resyncRequest();
  213498. return 1;
  213499. case kAsioLatenciesChanged:
  213500. return 1;
  213501. case kAsioEngineVersion:
  213502. return 2;
  213503. case kAsioSupportsTimeInfo:
  213504. case kAsioSupportsTimeCode:
  213505. return 0;
  213506. }
  213507. return 0;
  213508. }
  213509. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213510. {
  213511. }
  213512. static void convertInt16ToFloat (const char* src,
  213513. float* dest,
  213514. const int srcStrideBytes,
  213515. int numSamples,
  213516. const bool littleEndian) throw()
  213517. {
  213518. const double g = 1.0 / 32768.0;
  213519. if (littleEndian)
  213520. {
  213521. while (--numSamples >= 0)
  213522. {
  213523. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213524. src += srcStrideBytes;
  213525. }
  213526. }
  213527. else
  213528. {
  213529. while (--numSamples >= 0)
  213530. {
  213531. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213532. src += srcStrideBytes;
  213533. }
  213534. }
  213535. }
  213536. static void convertFloatToInt16 (const float* src,
  213537. char* dest,
  213538. const int dstStrideBytes,
  213539. int numSamples,
  213540. const bool littleEndian) throw()
  213541. {
  213542. const double maxVal = (double) 0x7fff;
  213543. if (littleEndian)
  213544. {
  213545. while (--numSamples >= 0)
  213546. {
  213547. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213548. dest += dstStrideBytes;
  213549. }
  213550. }
  213551. else
  213552. {
  213553. while (--numSamples >= 0)
  213554. {
  213555. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213556. dest += dstStrideBytes;
  213557. }
  213558. }
  213559. }
  213560. static void convertInt24ToFloat (const char* src,
  213561. float* dest,
  213562. const int srcStrideBytes,
  213563. int numSamples,
  213564. const bool littleEndian) throw()
  213565. {
  213566. const double g = 1.0 / 0x7fffff;
  213567. if (littleEndian)
  213568. {
  213569. while (--numSamples >= 0)
  213570. {
  213571. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213572. src += srcStrideBytes;
  213573. }
  213574. }
  213575. else
  213576. {
  213577. while (--numSamples >= 0)
  213578. {
  213579. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213580. src += srcStrideBytes;
  213581. }
  213582. }
  213583. }
  213584. static void convertFloatToInt24 (const float* src,
  213585. char* dest,
  213586. const int dstStrideBytes,
  213587. int numSamples,
  213588. const bool littleEndian) throw()
  213589. {
  213590. const double maxVal = (double) 0x7fffff;
  213591. if (littleEndian)
  213592. {
  213593. while (--numSamples >= 0)
  213594. {
  213595. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213596. dest += dstStrideBytes;
  213597. }
  213598. }
  213599. else
  213600. {
  213601. while (--numSamples >= 0)
  213602. {
  213603. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213604. dest += dstStrideBytes;
  213605. }
  213606. }
  213607. }
  213608. static void convertInt32ToFloat (const char* src,
  213609. float* dest,
  213610. const int srcStrideBytes,
  213611. int numSamples,
  213612. const bool littleEndian) throw()
  213613. {
  213614. const double g = 1.0 / 0x7fffffff;
  213615. if (littleEndian)
  213616. {
  213617. while (--numSamples >= 0)
  213618. {
  213619. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213620. src += srcStrideBytes;
  213621. }
  213622. }
  213623. else
  213624. {
  213625. while (--numSamples >= 0)
  213626. {
  213627. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213628. src += srcStrideBytes;
  213629. }
  213630. }
  213631. }
  213632. static void convertFloatToInt32 (const float* src,
  213633. char* dest,
  213634. const int dstStrideBytes,
  213635. int numSamples,
  213636. const bool littleEndian) throw()
  213637. {
  213638. const double maxVal = (double) 0x7fffffff;
  213639. if (littleEndian)
  213640. {
  213641. while (--numSamples >= 0)
  213642. {
  213643. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213644. dest += dstStrideBytes;
  213645. }
  213646. }
  213647. else
  213648. {
  213649. while (--numSamples >= 0)
  213650. {
  213651. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213652. dest += dstStrideBytes;
  213653. }
  213654. }
  213655. }
  213656. static void typeToFormatParameters (const long type,
  213657. int& bitDepth,
  213658. int& byteStride,
  213659. bool& formatIsFloat,
  213660. bool& littleEndian) throw()
  213661. {
  213662. bitDepth = 0;
  213663. littleEndian = false;
  213664. formatIsFloat = false;
  213665. switch (type)
  213666. {
  213667. case ASIOSTInt16MSB:
  213668. case ASIOSTInt16LSB:
  213669. case ASIOSTInt32MSB16:
  213670. case ASIOSTInt32LSB16:
  213671. bitDepth = 16; break;
  213672. case ASIOSTFloat32MSB:
  213673. case ASIOSTFloat32LSB:
  213674. formatIsFloat = true;
  213675. bitDepth = 32; break;
  213676. case ASIOSTInt32MSB:
  213677. case ASIOSTInt32LSB:
  213678. bitDepth = 32; break;
  213679. case ASIOSTInt24MSB:
  213680. case ASIOSTInt24LSB:
  213681. case ASIOSTInt32MSB24:
  213682. case ASIOSTInt32LSB24:
  213683. case ASIOSTInt32MSB18:
  213684. case ASIOSTInt32MSB20:
  213685. case ASIOSTInt32LSB18:
  213686. case ASIOSTInt32LSB20:
  213687. bitDepth = 24; break;
  213688. case ASIOSTFloat64MSB:
  213689. case ASIOSTFloat64LSB:
  213690. default:
  213691. bitDepth = 64;
  213692. break;
  213693. }
  213694. switch (type)
  213695. {
  213696. case ASIOSTInt16MSB:
  213697. case ASIOSTInt32MSB16:
  213698. case ASIOSTFloat32MSB:
  213699. case ASIOSTFloat64MSB:
  213700. case ASIOSTInt32MSB:
  213701. case ASIOSTInt32MSB18:
  213702. case ASIOSTInt32MSB20:
  213703. case ASIOSTInt32MSB24:
  213704. case ASIOSTInt24MSB:
  213705. littleEndian = false; break;
  213706. case ASIOSTInt16LSB:
  213707. case ASIOSTInt32LSB16:
  213708. case ASIOSTFloat32LSB:
  213709. case ASIOSTFloat64LSB:
  213710. case ASIOSTInt32LSB:
  213711. case ASIOSTInt32LSB18:
  213712. case ASIOSTInt32LSB20:
  213713. case ASIOSTInt32LSB24:
  213714. case ASIOSTInt24LSB:
  213715. littleEndian = true; break;
  213716. default:
  213717. break;
  213718. }
  213719. switch (type)
  213720. {
  213721. case ASIOSTInt16LSB:
  213722. case ASIOSTInt16MSB:
  213723. byteStride = 2; break;
  213724. case ASIOSTInt24LSB:
  213725. case ASIOSTInt24MSB:
  213726. byteStride = 3; break;
  213727. case ASIOSTInt32MSB16:
  213728. case ASIOSTInt32LSB16:
  213729. case ASIOSTInt32MSB:
  213730. case ASIOSTInt32MSB18:
  213731. case ASIOSTInt32MSB20:
  213732. case ASIOSTInt32MSB24:
  213733. case ASIOSTInt32LSB:
  213734. case ASIOSTInt32LSB18:
  213735. case ASIOSTInt32LSB20:
  213736. case ASIOSTInt32LSB24:
  213737. case ASIOSTFloat32LSB:
  213738. case ASIOSTFloat32MSB:
  213739. byteStride = 4; break;
  213740. case ASIOSTFloat64MSB:
  213741. case ASIOSTFloat64LSB:
  213742. byteStride = 8; break;
  213743. default:
  213744. break;
  213745. }
  213746. }
  213747. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213748. };
  213749. class ASIOAudioIODeviceType : public AudioIODeviceType
  213750. {
  213751. public:
  213752. ASIOAudioIODeviceType()
  213753. : AudioIODeviceType ("ASIO"),
  213754. hasScanned (false)
  213755. {
  213756. CoInitialize (0);
  213757. }
  213758. ~ASIOAudioIODeviceType()
  213759. {
  213760. }
  213761. void scanForDevices()
  213762. {
  213763. hasScanned = true;
  213764. deviceNames.clear();
  213765. classIds.clear();
  213766. HKEY hk = 0;
  213767. int index = 0;
  213768. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213769. {
  213770. for (;;)
  213771. {
  213772. char name [256];
  213773. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213774. {
  213775. addDriverInfo (name, hk);
  213776. }
  213777. else
  213778. {
  213779. break;
  213780. }
  213781. }
  213782. RegCloseKey (hk);
  213783. }
  213784. }
  213785. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213786. {
  213787. jassert (hasScanned); // need to call scanForDevices() before doing this
  213788. return deviceNames;
  213789. }
  213790. int getDefaultDeviceIndex (bool) const
  213791. {
  213792. jassert (hasScanned); // need to call scanForDevices() before doing this
  213793. for (int i = deviceNames.size(); --i >= 0;)
  213794. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213795. return i; // asio4all is a safe choice for a default..
  213796. #if JUCE_DEBUG
  213797. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213798. return 1; // (the digi m-box driver crashes the app when you run
  213799. // it in the debugger, which can be a bit annoying)
  213800. #endif
  213801. return 0;
  213802. }
  213803. static int findFreeSlot()
  213804. {
  213805. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213806. if (currentASIODev[i] == 0)
  213807. return i;
  213808. jassertfalse; // unfortunately you can only have a finite number
  213809. // of ASIO devices open at the same time..
  213810. return -1;
  213811. }
  213812. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213813. {
  213814. jassert (hasScanned); // need to call scanForDevices() before doing this
  213815. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213816. }
  213817. bool hasSeparateInputsAndOutputs() const { return false; }
  213818. AudioIODevice* createDevice (const String& outputDeviceName,
  213819. const String& inputDeviceName)
  213820. {
  213821. // ASIO can't open two different devices for input and output - they must be the same one.
  213822. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213823. jassert (hasScanned); // need to call scanForDevices() before doing this
  213824. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213825. : inputDeviceName);
  213826. if (index >= 0)
  213827. {
  213828. const int freeSlot = findFreeSlot();
  213829. if (freeSlot >= 0)
  213830. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213831. }
  213832. return 0;
  213833. }
  213834. private:
  213835. StringArray deviceNames;
  213836. OwnedArray <CLSID> classIds;
  213837. bool hasScanned;
  213838. static bool checkClassIsOk (const String& classId)
  213839. {
  213840. HKEY hk = 0;
  213841. bool ok = false;
  213842. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213843. {
  213844. int index = 0;
  213845. for (;;)
  213846. {
  213847. WCHAR buf [512];
  213848. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213849. {
  213850. if (classId.equalsIgnoreCase (buf))
  213851. {
  213852. HKEY subKey, pathKey;
  213853. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213854. {
  213855. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213856. {
  213857. WCHAR pathName [1024];
  213858. DWORD dtype = REG_SZ;
  213859. DWORD dsize = sizeof (pathName);
  213860. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213861. ok = File (pathName).exists();
  213862. RegCloseKey (pathKey);
  213863. }
  213864. RegCloseKey (subKey);
  213865. }
  213866. break;
  213867. }
  213868. }
  213869. else
  213870. {
  213871. break;
  213872. }
  213873. }
  213874. RegCloseKey (hk);
  213875. }
  213876. return ok;
  213877. }
  213878. void addDriverInfo (const String& keyName, HKEY hk)
  213879. {
  213880. HKEY subKey;
  213881. if (RegOpenKeyEx (hk, keyName.toUTF16(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213882. {
  213883. WCHAR buf [256];
  213884. zerostruct (buf);
  213885. DWORD dtype = REG_SZ;
  213886. DWORD dsize = sizeof (buf);
  213887. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213888. {
  213889. if (dsize > 0 && checkClassIsOk (buf))
  213890. {
  213891. CLSID classId;
  213892. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213893. {
  213894. dtype = REG_SZ;
  213895. dsize = sizeof (buf);
  213896. String deviceName;
  213897. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213898. deviceName = buf;
  213899. else
  213900. deviceName = keyName;
  213901. log ("found " + deviceName);
  213902. deviceNames.add (deviceName);
  213903. classIds.add (new CLSID (classId));
  213904. }
  213905. }
  213906. RegCloseKey (subKey);
  213907. }
  213908. }
  213909. }
  213910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213911. };
  213912. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
  213913. {
  213914. return new ASIOAudioIODeviceType();
  213915. }
  213916. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213917. void* guid,
  213918. const String& optionalDllForDirectLoading)
  213919. {
  213920. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213921. if (freeSlot < 0)
  213922. return 0;
  213923. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213924. }
  213925. #undef logError
  213926. #undef log
  213927. #endif
  213928. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213929. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213930. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213931. // compiled on its own).
  213932. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213933. END_JUCE_NAMESPACE
  213934. extern "C"
  213935. {
  213936. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213937. typedef struct typeDSBUFFERDESC
  213938. {
  213939. DWORD dwSize;
  213940. DWORD dwFlags;
  213941. DWORD dwBufferBytes;
  213942. DWORD dwReserved;
  213943. LPWAVEFORMATEX lpwfxFormat;
  213944. GUID guid3DAlgorithm;
  213945. } DSBUFFERDESC;
  213946. struct IDirectSoundBuffer;
  213947. #undef INTERFACE
  213948. #define INTERFACE IDirectSound
  213949. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213950. {
  213951. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213952. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213953. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213954. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213955. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213956. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213957. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213958. STDMETHOD(Compact) (THIS) PURE;
  213959. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213960. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213961. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213962. };
  213963. #undef INTERFACE
  213964. #define INTERFACE IDirectSoundBuffer
  213965. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213966. {
  213967. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213968. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213969. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213970. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213971. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213972. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213973. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213974. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213975. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213976. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213977. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213978. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213979. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213980. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213981. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213982. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213983. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213984. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213985. STDMETHOD(Stop) (THIS) PURE;
  213986. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213987. STDMETHOD(Restore) (THIS) PURE;
  213988. };
  213989. typedef struct typeDSCBUFFERDESC
  213990. {
  213991. DWORD dwSize;
  213992. DWORD dwFlags;
  213993. DWORD dwBufferBytes;
  213994. DWORD dwReserved;
  213995. LPWAVEFORMATEX lpwfxFormat;
  213996. } DSCBUFFERDESC;
  213997. struct IDirectSoundCaptureBuffer;
  213998. #undef INTERFACE
  213999. #define INTERFACE IDirectSoundCapture
  214000. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214001. {
  214002. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214003. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214004. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214005. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214006. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214007. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214008. };
  214009. #undef INTERFACE
  214010. #define INTERFACE IDirectSoundCaptureBuffer
  214011. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214012. {
  214013. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214014. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214015. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214016. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214017. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214018. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214019. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214020. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214021. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214022. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214023. STDMETHOD(Stop) (THIS) PURE;
  214024. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214025. };
  214026. };
  214027. BEGIN_JUCE_NAMESPACE
  214028. namespace
  214029. {
  214030. const String getDSErrorMessage (HRESULT hr)
  214031. {
  214032. const char* result = 0;
  214033. switch (hr)
  214034. {
  214035. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214036. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214037. case E_INVALIDARG: result = "Invalid parameter"; break;
  214038. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214039. case E_FAIL: result = "Generic error"; break;
  214040. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214041. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214042. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214043. case E_NOTIMPL: result = "Unsupported function"; break;
  214044. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214045. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214046. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214047. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214048. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214049. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214050. case E_NOINTERFACE: result = "No interface"; break;
  214051. case S_OK: result = "No error"; break;
  214052. default: return "Unknown error: " + String ((int) hr);
  214053. }
  214054. return result;
  214055. }
  214056. #define DS_DEBUGGING 1
  214057. #ifdef DS_DEBUGGING
  214058. #define CATCH JUCE_CATCH_EXCEPTION
  214059. #undef log
  214060. #define log(a) Logger::writeToLog(a);
  214061. #undef logError
  214062. #define logError(a) logDSError(a, __LINE__);
  214063. static void logDSError (HRESULT hr, int lineNum)
  214064. {
  214065. if (hr != S_OK)
  214066. {
  214067. String error ("DS error at line ");
  214068. error << lineNum << " - " << getDSErrorMessage (hr);
  214069. log (error);
  214070. }
  214071. }
  214072. #else
  214073. #define CATCH JUCE_CATCH_ALL
  214074. #define log(a)
  214075. #define logError(a)
  214076. #endif
  214077. #define DSOUND_FUNCTION(functionName, params) \
  214078. typedef HRESULT (WINAPI *type##functionName) params; \
  214079. static type##functionName ds##functionName = 0;
  214080. #define DSOUND_FUNCTION_LOAD(functionName) \
  214081. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214082. jassert (ds##functionName != 0);
  214083. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214084. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214085. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214086. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214087. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214088. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214089. void initialiseDSoundFunctions()
  214090. {
  214091. if (dsDirectSoundCreate == 0)
  214092. {
  214093. HMODULE h = LoadLibraryA ("dsound.dll");
  214094. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214095. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214096. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214097. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214098. }
  214099. }
  214100. }
  214101. class DSoundInternalOutChannel
  214102. {
  214103. public:
  214104. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  214105. int bufferSize, float* left, float* right)
  214106. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214107. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214108. pDirectSound (0), pOutputBuffer (0)
  214109. {
  214110. }
  214111. ~DSoundInternalOutChannel()
  214112. {
  214113. close();
  214114. }
  214115. void close()
  214116. {
  214117. HRESULT hr;
  214118. if (pOutputBuffer != 0)
  214119. {
  214120. log ("closing dsound out: " + name);
  214121. hr = pOutputBuffer->Stop();
  214122. logError (hr);
  214123. hr = pOutputBuffer->Release();
  214124. pOutputBuffer = 0;
  214125. logError (hr);
  214126. }
  214127. if (pDirectSound != 0)
  214128. {
  214129. hr = pDirectSound->Release();
  214130. pDirectSound = 0;
  214131. logError (hr);
  214132. }
  214133. }
  214134. const String open()
  214135. {
  214136. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214137. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214138. pDirectSound = 0;
  214139. pOutputBuffer = 0;
  214140. writeOffset = 0;
  214141. String error;
  214142. HRESULT hr = E_NOINTERFACE;
  214143. if (dsDirectSoundCreate != 0)
  214144. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214145. if (hr == S_OK)
  214146. {
  214147. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214148. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214149. const int numChannels = 2;
  214150. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214151. logError (hr);
  214152. if (hr == S_OK)
  214153. {
  214154. IDirectSoundBuffer* pPrimaryBuffer;
  214155. DSBUFFERDESC primaryDesc;
  214156. zerostruct (primaryDesc);
  214157. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214158. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214159. primaryDesc.dwBufferBytes = 0;
  214160. primaryDesc.lpwfxFormat = 0;
  214161. log ("opening dsound out step 2");
  214162. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214163. logError (hr);
  214164. if (hr == S_OK)
  214165. {
  214166. WAVEFORMATEX wfFormat;
  214167. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214168. wfFormat.nChannels = (unsigned short) numChannels;
  214169. wfFormat.nSamplesPerSec = sampleRate;
  214170. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214171. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214172. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214173. wfFormat.cbSize = 0;
  214174. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214175. logError (hr);
  214176. if (hr == S_OK)
  214177. {
  214178. DSBUFFERDESC secondaryDesc;
  214179. zerostruct (secondaryDesc);
  214180. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214181. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214182. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214183. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214184. secondaryDesc.lpwfxFormat = &wfFormat;
  214185. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214186. logError (hr);
  214187. if (hr == S_OK)
  214188. {
  214189. log ("opening dsound out step 3");
  214190. DWORD dwDataLen;
  214191. unsigned char* pDSBuffData;
  214192. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214193. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214194. logError (hr);
  214195. if (hr == S_OK)
  214196. {
  214197. zeromem (pDSBuffData, dwDataLen);
  214198. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214199. if (hr == S_OK)
  214200. {
  214201. hr = pOutputBuffer->SetCurrentPosition (0);
  214202. if (hr == S_OK)
  214203. {
  214204. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214205. if (hr == S_OK)
  214206. return String::empty;
  214207. }
  214208. }
  214209. }
  214210. }
  214211. }
  214212. }
  214213. }
  214214. }
  214215. error = getDSErrorMessage (hr);
  214216. close();
  214217. return error;
  214218. }
  214219. void synchronisePosition()
  214220. {
  214221. if (pOutputBuffer != 0)
  214222. {
  214223. DWORD playCursor;
  214224. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214225. }
  214226. }
  214227. bool service()
  214228. {
  214229. if (pOutputBuffer == 0)
  214230. return true;
  214231. DWORD playCursor, writeCursor;
  214232. for (;;)
  214233. {
  214234. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214235. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214236. {
  214237. pOutputBuffer->Restore();
  214238. continue;
  214239. }
  214240. if (hr == S_OK)
  214241. break;
  214242. logError (hr);
  214243. jassertfalse;
  214244. return true;
  214245. }
  214246. int playWriteGap = writeCursor - playCursor;
  214247. if (playWriteGap < 0)
  214248. playWriteGap += totalBytesPerBuffer;
  214249. int bytesEmpty = playCursor - writeOffset;
  214250. if (bytesEmpty < 0)
  214251. bytesEmpty += totalBytesPerBuffer;
  214252. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214253. {
  214254. writeOffset = writeCursor;
  214255. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214256. }
  214257. if (bytesEmpty >= bytesPerBuffer)
  214258. {
  214259. void* lpbuf1 = 0;
  214260. void* lpbuf2 = 0;
  214261. DWORD dwSize1 = 0;
  214262. DWORD dwSize2 = 0;
  214263. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214264. &lpbuf1, &dwSize1,
  214265. &lpbuf2, &dwSize2, 0);
  214266. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214267. {
  214268. pOutputBuffer->Restore();
  214269. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214270. &lpbuf1, &dwSize1,
  214271. &lpbuf2, &dwSize2, 0);
  214272. }
  214273. if (hr == S_OK)
  214274. {
  214275. if (bitDepth == 16)
  214276. {
  214277. int* dest = static_cast<int*> (lpbuf1);
  214278. const float* left = leftBuffer;
  214279. const float* right = rightBuffer;
  214280. int samples1 = dwSize1 >> 2;
  214281. int samples2 = dwSize2 >> 2;
  214282. if (left == 0)
  214283. {
  214284. while (--samples1 >= 0)
  214285. *dest++ = (convertInputValue (*right++) << 16);
  214286. dest = static_cast<int*> (lpbuf2);
  214287. while (--samples2 >= 0)
  214288. *dest++ = (convertInputValue (*right++) << 16);
  214289. }
  214290. else if (right == 0)
  214291. {
  214292. while (--samples1 >= 0)
  214293. *dest++ = (0xffff & convertInputValue (*left++));
  214294. dest = static_cast<int*> (lpbuf2);
  214295. while (--samples2 >= 0)
  214296. *dest++ = (0xffff & convertInputValue (*left++));
  214297. }
  214298. else
  214299. {
  214300. while (--samples1 >= 0)
  214301. {
  214302. const int l = convertInputValue (*left++);
  214303. const int r = convertInputValue (*right++);
  214304. *dest++ = (r << 16) | (0xffff & l);
  214305. }
  214306. dest = static_cast<int*> (lpbuf2);
  214307. while (--samples2 >= 0)
  214308. {
  214309. const int l = convertInputValue (*left++);
  214310. const int r = convertInputValue (*right++);
  214311. *dest++ = (r << 16) | (0xffff & l);
  214312. }
  214313. }
  214314. }
  214315. else
  214316. {
  214317. jassertfalse;
  214318. }
  214319. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214320. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214321. }
  214322. else
  214323. {
  214324. jassertfalse;
  214325. logError (hr);
  214326. }
  214327. bytesEmpty -= bytesPerBuffer;
  214328. return true;
  214329. }
  214330. else
  214331. {
  214332. return false;
  214333. }
  214334. }
  214335. int bitDepth;
  214336. bool doneFlag;
  214337. private:
  214338. String name;
  214339. LPGUID guid;
  214340. int sampleRate, bufferSizeSamples;
  214341. float* leftBuffer;
  214342. float* rightBuffer;
  214343. IDirectSound* pDirectSound;
  214344. IDirectSoundBuffer* pOutputBuffer;
  214345. DWORD writeOffset;
  214346. int totalBytesPerBuffer, bytesPerBuffer;
  214347. unsigned int lastPlayCursor;
  214348. static inline int convertInputValue (const float v) throw()
  214349. {
  214350. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214351. }
  214352. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214353. };
  214354. struct DSoundInternalInChannel
  214355. {
  214356. public:
  214357. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214358. int bufferSize, float* left, float* right)
  214359. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214360. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214361. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214362. {
  214363. }
  214364. ~DSoundInternalInChannel()
  214365. {
  214366. close();
  214367. }
  214368. void close()
  214369. {
  214370. HRESULT hr;
  214371. if (pInputBuffer != 0)
  214372. {
  214373. log ("closing dsound in: " + name);
  214374. hr = pInputBuffer->Stop();
  214375. logError (hr);
  214376. hr = pInputBuffer->Release();
  214377. pInputBuffer = 0;
  214378. logError (hr);
  214379. }
  214380. if (pDirectSoundCapture != 0)
  214381. {
  214382. hr = pDirectSoundCapture->Release();
  214383. pDirectSoundCapture = 0;
  214384. logError (hr);
  214385. }
  214386. if (pDirectSound != 0)
  214387. {
  214388. hr = pDirectSound->Release();
  214389. pDirectSound = 0;
  214390. logError (hr);
  214391. }
  214392. }
  214393. const String open()
  214394. {
  214395. log ("opening dsound in device: " + name
  214396. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214397. pDirectSound = 0;
  214398. pDirectSoundCapture = 0;
  214399. pInputBuffer = 0;
  214400. readOffset = 0;
  214401. totalBytesPerBuffer = 0;
  214402. String error;
  214403. HRESULT hr = E_NOINTERFACE;
  214404. if (dsDirectSoundCaptureCreate != 0)
  214405. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214406. logError (hr);
  214407. if (hr == S_OK)
  214408. {
  214409. const int numChannels = 2;
  214410. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214411. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214412. WAVEFORMATEX wfFormat;
  214413. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214414. wfFormat.nChannels = (unsigned short)numChannels;
  214415. wfFormat.nSamplesPerSec = sampleRate;
  214416. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214417. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214418. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214419. wfFormat.cbSize = 0;
  214420. DSCBUFFERDESC captureDesc;
  214421. zerostruct (captureDesc);
  214422. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214423. captureDesc.dwFlags = 0;
  214424. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214425. captureDesc.lpwfxFormat = &wfFormat;
  214426. log ("opening dsound in step 2");
  214427. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214428. logError (hr);
  214429. if (hr == S_OK)
  214430. {
  214431. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214432. logError (hr);
  214433. if (hr == S_OK)
  214434. return String::empty;
  214435. }
  214436. }
  214437. error = getDSErrorMessage (hr);
  214438. close();
  214439. return error;
  214440. }
  214441. void synchronisePosition()
  214442. {
  214443. if (pInputBuffer != 0)
  214444. {
  214445. DWORD capturePos;
  214446. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214447. }
  214448. }
  214449. bool service()
  214450. {
  214451. if (pInputBuffer == 0)
  214452. return true;
  214453. DWORD capturePos, readPos;
  214454. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214455. logError (hr);
  214456. if (hr != S_OK)
  214457. return true;
  214458. int bytesFilled = readPos - readOffset;
  214459. if (bytesFilled < 0)
  214460. bytesFilled += totalBytesPerBuffer;
  214461. if (bytesFilled >= bytesPerBuffer)
  214462. {
  214463. LPBYTE lpbuf1 = 0;
  214464. LPBYTE lpbuf2 = 0;
  214465. DWORD dwsize1 = 0;
  214466. DWORD dwsize2 = 0;
  214467. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214468. (void**) &lpbuf1, &dwsize1,
  214469. (void**) &lpbuf2, &dwsize2, 0);
  214470. if (hr == S_OK)
  214471. {
  214472. if (bitDepth == 16)
  214473. {
  214474. const float g = 1.0f / 32768.0f;
  214475. float* destL = leftBuffer;
  214476. float* destR = rightBuffer;
  214477. int samples1 = dwsize1 >> 2;
  214478. int samples2 = dwsize2 >> 2;
  214479. const short* src = (const short*)lpbuf1;
  214480. if (destL == 0)
  214481. {
  214482. while (--samples1 >= 0)
  214483. {
  214484. ++src;
  214485. *destR++ = *src++ * g;
  214486. }
  214487. src = (const short*)lpbuf2;
  214488. while (--samples2 >= 0)
  214489. {
  214490. ++src;
  214491. *destR++ = *src++ * g;
  214492. }
  214493. }
  214494. else if (destR == 0)
  214495. {
  214496. while (--samples1 >= 0)
  214497. {
  214498. *destL++ = *src++ * g;
  214499. ++src;
  214500. }
  214501. src = (const short*)lpbuf2;
  214502. while (--samples2 >= 0)
  214503. {
  214504. *destL++ = *src++ * g;
  214505. ++src;
  214506. }
  214507. }
  214508. else
  214509. {
  214510. while (--samples1 >= 0)
  214511. {
  214512. *destL++ = *src++ * g;
  214513. *destR++ = *src++ * g;
  214514. }
  214515. src = (const short*)lpbuf2;
  214516. while (--samples2 >= 0)
  214517. {
  214518. *destL++ = *src++ * g;
  214519. *destR++ = *src++ * g;
  214520. }
  214521. }
  214522. }
  214523. else
  214524. {
  214525. jassertfalse;
  214526. }
  214527. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214528. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214529. }
  214530. else
  214531. {
  214532. logError (hr);
  214533. jassertfalse;
  214534. }
  214535. bytesFilled -= bytesPerBuffer;
  214536. return true;
  214537. }
  214538. else
  214539. {
  214540. return false;
  214541. }
  214542. }
  214543. unsigned int readOffset;
  214544. int bytesPerBuffer, totalBytesPerBuffer;
  214545. int bitDepth;
  214546. bool doneFlag;
  214547. private:
  214548. String name;
  214549. LPGUID guid;
  214550. int sampleRate, bufferSizeSamples;
  214551. float* leftBuffer;
  214552. float* rightBuffer;
  214553. IDirectSound* pDirectSound;
  214554. IDirectSoundCapture* pDirectSoundCapture;
  214555. IDirectSoundCaptureBuffer* pInputBuffer;
  214556. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214557. };
  214558. class DSoundAudioIODevice : public AudioIODevice,
  214559. public Thread
  214560. {
  214561. public:
  214562. DSoundAudioIODevice (const String& deviceName,
  214563. const int outputDeviceIndex_,
  214564. const int inputDeviceIndex_)
  214565. : AudioIODevice (deviceName, "DirectSound"),
  214566. Thread ("Juce DSound"),
  214567. outputDeviceIndex (outputDeviceIndex_),
  214568. inputDeviceIndex (inputDeviceIndex_),
  214569. isOpen_ (false),
  214570. isStarted (false),
  214571. bufferSizeSamples (0),
  214572. totalSamplesOut (0),
  214573. sampleRate (0.0),
  214574. inputBuffers (1, 1),
  214575. outputBuffers (1, 1),
  214576. callback (0)
  214577. {
  214578. if (outputDeviceIndex_ >= 0)
  214579. {
  214580. outChannels.add (TRANS("Left"));
  214581. outChannels.add (TRANS("Right"));
  214582. }
  214583. if (inputDeviceIndex_ >= 0)
  214584. {
  214585. inChannels.add (TRANS("Left"));
  214586. inChannels.add (TRANS("Right"));
  214587. }
  214588. }
  214589. ~DSoundAudioIODevice()
  214590. {
  214591. close();
  214592. }
  214593. const String open (const BigInteger& inputChannels,
  214594. const BigInteger& outputChannels,
  214595. double sampleRate, int bufferSizeSamples)
  214596. {
  214597. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214598. isOpen_ = lastError.isEmpty();
  214599. return lastError;
  214600. }
  214601. void close()
  214602. {
  214603. stop();
  214604. if (isOpen_)
  214605. {
  214606. closeDevice();
  214607. isOpen_ = false;
  214608. }
  214609. }
  214610. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214611. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214612. double getCurrentSampleRate() { return sampleRate; }
  214613. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214614. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214615. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214616. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214617. const StringArray getOutputChannelNames() { return outChannels; }
  214618. const StringArray getInputChannelNames() { return inChannels; }
  214619. int getNumSampleRates() { return 4; }
  214620. int getDefaultBufferSize() { return 2560; }
  214621. int getNumBufferSizesAvailable() { return 50; }
  214622. double getSampleRate (int index)
  214623. {
  214624. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214625. return samps [jlimit (0, 3, index)];
  214626. }
  214627. int getBufferSizeSamples (int index)
  214628. {
  214629. int n = 64;
  214630. for (int i = 0; i < index; ++i)
  214631. n += (n < 512) ? 32
  214632. : ((n < 1024) ? 64
  214633. : ((n < 2048) ? 128 : 256));
  214634. return n;
  214635. }
  214636. int getCurrentBitDepth()
  214637. {
  214638. int i, bits = 256;
  214639. for (i = inChans.size(); --i >= 0;)
  214640. bits = jmin (bits, inChans[i]->bitDepth);
  214641. for (i = outChans.size(); --i >= 0;)
  214642. bits = jmin (bits, outChans[i]->bitDepth);
  214643. if (bits > 32)
  214644. bits = 16;
  214645. return bits;
  214646. }
  214647. void start (AudioIODeviceCallback* call)
  214648. {
  214649. if (isOpen_ && call != 0 && ! isStarted)
  214650. {
  214651. if (! isThreadRunning())
  214652. {
  214653. // something gone wrong and the thread's stopped..
  214654. isOpen_ = false;
  214655. return;
  214656. }
  214657. call->audioDeviceAboutToStart (this);
  214658. const ScopedLock sl (startStopLock);
  214659. callback = call;
  214660. isStarted = true;
  214661. }
  214662. }
  214663. void stop()
  214664. {
  214665. if (isStarted)
  214666. {
  214667. AudioIODeviceCallback* const callbackLocal = callback;
  214668. {
  214669. const ScopedLock sl (startStopLock);
  214670. isStarted = false;
  214671. }
  214672. if (callbackLocal != 0)
  214673. callbackLocal->audioDeviceStopped();
  214674. }
  214675. }
  214676. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214677. const String getLastError() { return lastError; }
  214678. StringArray inChannels, outChannels;
  214679. int outputDeviceIndex, inputDeviceIndex;
  214680. private:
  214681. bool isOpen_;
  214682. bool isStarted;
  214683. String lastError;
  214684. OwnedArray <DSoundInternalInChannel> inChans;
  214685. OwnedArray <DSoundInternalOutChannel> outChans;
  214686. WaitableEvent startEvent;
  214687. int bufferSizeSamples;
  214688. int volatile totalSamplesOut;
  214689. int64 volatile lastBlockTime;
  214690. double sampleRate;
  214691. BigInteger enabledInputs, enabledOutputs;
  214692. AudioSampleBuffer inputBuffers, outputBuffers;
  214693. AudioIODeviceCallback* callback;
  214694. CriticalSection startStopLock;
  214695. const String openDevice (const BigInteger& inputChannels,
  214696. const BigInteger& outputChannels,
  214697. double sampleRate_, int bufferSizeSamples_);
  214698. void closeDevice()
  214699. {
  214700. isStarted = false;
  214701. stopThread (5000);
  214702. inChans.clear();
  214703. outChans.clear();
  214704. inputBuffers.setSize (1, 1);
  214705. outputBuffers.setSize (1, 1);
  214706. }
  214707. void resync()
  214708. {
  214709. if (! threadShouldExit())
  214710. {
  214711. sleep (5);
  214712. int i;
  214713. for (i = 0; i < outChans.size(); ++i)
  214714. outChans.getUnchecked(i)->synchronisePosition();
  214715. for (i = 0; i < inChans.size(); ++i)
  214716. inChans.getUnchecked(i)->synchronisePosition();
  214717. }
  214718. }
  214719. public:
  214720. void run()
  214721. {
  214722. while (! threadShouldExit())
  214723. {
  214724. if (wait (100))
  214725. break;
  214726. }
  214727. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214728. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214729. while (! threadShouldExit())
  214730. {
  214731. int numToDo = 0;
  214732. uint32 startTime = Time::getMillisecondCounter();
  214733. int i;
  214734. for (i = inChans.size(); --i >= 0;)
  214735. {
  214736. inChans.getUnchecked(i)->doneFlag = false;
  214737. ++numToDo;
  214738. }
  214739. for (i = outChans.size(); --i >= 0;)
  214740. {
  214741. outChans.getUnchecked(i)->doneFlag = false;
  214742. ++numToDo;
  214743. }
  214744. if (numToDo > 0)
  214745. {
  214746. const int maxCount = 3;
  214747. int count = maxCount;
  214748. for (;;)
  214749. {
  214750. for (i = inChans.size(); --i >= 0;)
  214751. {
  214752. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214753. if ((! in->doneFlag) && in->service())
  214754. {
  214755. in->doneFlag = true;
  214756. --numToDo;
  214757. }
  214758. }
  214759. for (i = outChans.size(); --i >= 0;)
  214760. {
  214761. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214762. if ((! out->doneFlag) && out->service())
  214763. {
  214764. out->doneFlag = true;
  214765. --numToDo;
  214766. }
  214767. }
  214768. if (numToDo <= 0)
  214769. break;
  214770. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214771. {
  214772. resync();
  214773. break;
  214774. }
  214775. if (--count <= 0)
  214776. {
  214777. Sleep (1);
  214778. count = maxCount;
  214779. }
  214780. if (threadShouldExit())
  214781. return;
  214782. }
  214783. }
  214784. else
  214785. {
  214786. sleep (1);
  214787. }
  214788. const ScopedLock sl (startStopLock);
  214789. if (isStarted)
  214790. {
  214791. JUCE_TRY
  214792. {
  214793. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214794. inputBuffers.getNumChannels(),
  214795. outputBuffers.getArrayOfChannels(),
  214796. outputBuffers.getNumChannels(),
  214797. bufferSizeSamples);
  214798. }
  214799. JUCE_CATCH_EXCEPTION
  214800. totalSamplesOut += bufferSizeSamples;
  214801. }
  214802. else
  214803. {
  214804. outputBuffers.clear();
  214805. totalSamplesOut = 0;
  214806. sleep (1);
  214807. }
  214808. }
  214809. }
  214810. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214811. };
  214812. class DSoundAudioIODeviceType : public AudioIODeviceType
  214813. {
  214814. public:
  214815. DSoundAudioIODeviceType()
  214816. : AudioIODeviceType ("DirectSound"),
  214817. hasScanned (false)
  214818. {
  214819. initialiseDSoundFunctions();
  214820. }
  214821. void scanForDevices()
  214822. {
  214823. hasScanned = true;
  214824. outputDeviceNames.clear();
  214825. outputGuids.clear();
  214826. inputDeviceNames.clear();
  214827. inputGuids.clear();
  214828. if (dsDirectSoundEnumerateW != 0)
  214829. {
  214830. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214831. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214832. }
  214833. }
  214834. const StringArray getDeviceNames (bool wantInputNames) const
  214835. {
  214836. jassert (hasScanned); // need to call scanForDevices() before doing this
  214837. return wantInputNames ? inputDeviceNames
  214838. : outputDeviceNames;
  214839. }
  214840. int getDefaultDeviceIndex (bool /*forInput*/) const
  214841. {
  214842. jassert (hasScanned); // need to call scanForDevices() before doing this
  214843. return 0;
  214844. }
  214845. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214846. {
  214847. jassert (hasScanned); // need to call scanForDevices() before doing this
  214848. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214849. if (d == 0)
  214850. return -1;
  214851. return asInput ? d->inputDeviceIndex
  214852. : d->outputDeviceIndex;
  214853. }
  214854. bool hasSeparateInputsAndOutputs() const { return true; }
  214855. AudioIODevice* createDevice (const String& outputDeviceName,
  214856. const String& inputDeviceName)
  214857. {
  214858. jassert (hasScanned); // need to call scanForDevices() before doing this
  214859. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214860. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214861. if (outputIndex >= 0 || inputIndex >= 0)
  214862. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214863. : inputDeviceName,
  214864. outputIndex, inputIndex);
  214865. return 0;
  214866. }
  214867. StringArray outputDeviceNames, inputDeviceNames;
  214868. OwnedArray <GUID> outputGuids, inputGuids;
  214869. private:
  214870. bool hasScanned;
  214871. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214872. {
  214873. desc = desc.trim();
  214874. if (desc.isNotEmpty())
  214875. {
  214876. const String origDesc (desc);
  214877. int n = 2;
  214878. while (outputDeviceNames.contains (desc))
  214879. desc = origDesc + " (" + String (n++) + ")";
  214880. outputDeviceNames.add (desc);
  214881. if (lpGUID != 0)
  214882. outputGuids.add (new GUID (*lpGUID));
  214883. else
  214884. outputGuids.add (0);
  214885. }
  214886. return TRUE;
  214887. }
  214888. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214889. {
  214890. return ((DSoundAudioIODeviceType*) object)
  214891. ->outputEnumProc (lpGUID, String (description));
  214892. }
  214893. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214894. {
  214895. return ((DSoundAudioIODeviceType*) object)
  214896. ->outputEnumProc (lpGUID, String (description));
  214897. }
  214898. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214899. {
  214900. desc = desc.trim();
  214901. if (desc.isNotEmpty())
  214902. {
  214903. const String origDesc (desc);
  214904. int n = 2;
  214905. while (inputDeviceNames.contains (desc))
  214906. desc = origDesc + " (" + String (n++) + ")";
  214907. inputDeviceNames.add (desc);
  214908. if (lpGUID != 0)
  214909. inputGuids.add (new GUID (*lpGUID));
  214910. else
  214911. inputGuids.add (0);
  214912. }
  214913. return TRUE;
  214914. }
  214915. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214916. {
  214917. return ((DSoundAudioIODeviceType*) object)
  214918. ->inputEnumProc (lpGUID, String (description));
  214919. }
  214920. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214921. {
  214922. return ((DSoundAudioIODeviceType*) object)
  214923. ->inputEnumProc (lpGUID, String (description));
  214924. }
  214925. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214926. };
  214927. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214928. const BigInteger& outputChannels,
  214929. double sampleRate_, int bufferSizeSamples_)
  214930. {
  214931. closeDevice();
  214932. totalSamplesOut = 0;
  214933. sampleRate = sampleRate_;
  214934. if (bufferSizeSamples_ <= 0)
  214935. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214936. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214937. DSoundAudioIODeviceType dlh;
  214938. dlh.scanForDevices();
  214939. enabledInputs = inputChannels;
  214940. enabledInputs.setRange (inChannels.size(),
  214941. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214942. false);
  214943. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214944. inputBuffers.clear();
  214945. int i, numIns = 0;
  214946. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214947. {
  214948. float* left = 0;
  214949. if (enabledInputs[i])
  214950. left = inputBuffers.getSampleData (numIns++);
  214951. float* right = 0;
  214952. if (enabledInputs[i + 1])
  214953. right = inputBuffers.getSampleData (numIns++);
  214954. if (left != 0 || right != 0)
  214955. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214956. dlh.inputGuids [inputDeviceIndex],
  214957. (int) sampleRate, bufferSizeSamples,
  214958. left, right));
  214959. }
  214960. enabledOutputs = outputChannels;
  214961. enabledOutputs.setRange (outChannels.size(),
  214962. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214963. false);
  214964. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214965. outputBuffers.clear();
  214966. int numOuts = 0;
  214967. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214968. {
  214969. float* left = 0;
  214970. if (enabledOutputs[i])
  214971. left = outputBuffers.getSampleData (numOuts++);
  214972. float* right = 0;
  214973. if (enabledOutputs[i + 1])
  214974. right = outputBuffers.getSampleData (numOuts++);
  214975. if (left != 0 || right != 0)
  214976. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214977. dlh.outputGuids [outputDeviceIndex],
  214978. (int) sampleRate, bufferSizeSamples,
  214979. left, right));
  214980. }
  214981. String error;
  214982. // boost our priority while opening the devices to try to get better sync between them
  214983. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214984. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214985. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214986. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214987. for (i = 0; i < outChans.size(); ++i)
  214988. {
  214989. error = outChans[i]->open();
  214990. if (error.isNotEmpty())
  214991. {
  214992. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214993. break;
  214994. }
  214995. }
  214996. if (error.isEmpty())
  214997. {
  214998. for (i = 0; i < inChans.size(); ++i)
  214999. {
  215000. error = inChans[i]->open();
  215001. if (error.isNotEmpty())
  215002. {
  215003. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215004. break;
  215005. }
  215006. }
  215007. }
  215008. if (error.isEmpty())
  215009. {
  215010. totalSamplesOut = 0;
  215011. for (i = 0; i < outChans.size(); ++i)
  215012. outChans.getUnchecked(i)->synchronisePosition();
  215013. for (i = 0; i < inChans.size(); ++i)
  215014. inChans.getUnchecked(i)->synchronisePosition();
  215015. startThread (9);
  215016. sleep (10);
  215017. notify();
  215018. }
  215019. else
  215020. {
  215021. log (error);
  215022. }
  215023. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215024. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215025. return error;
  215026. }
  215027. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()
  215028. {
  215029. return new DSoundAudioIODeviceType();
  215030. }
  215031. #undef log
  215032. #endif
  215033. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215034. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215035. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215036. // compiled on its own).
  215037. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215038. #ifndef WASAPI_ENABLE_LOGGING
  215039. #define WASAPI_ENABLE_LOGGING 0
  215040. #endif
  215041. namespace WasapiClasses
  215042. {
  215043. void logFailure (HRESULT hr)
  215044. {
  215045. (void) hr;
  215046. #if WASAPI_ENABLE_LOGGING
  215047. if (FAILED (hr))
  215048. {
  215049. String e;
  215050. e << Time::getCurrentTime().toString (true, true, true, true)
  215051. << " -- WASAPI error: ";
  215052. switch (hr)
  215053. {
  215054. case E_POINTER: e << "E_POINTER"; break;
  215055. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215056. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215057. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215058. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215059. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215060. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215061. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215062. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215063. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215064. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215065. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215066. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215067. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215068. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215069. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215070. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215071. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215072. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215073. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215074. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215075. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215076. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215077. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215078. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215079. default: e << String::toHexString ((int) hr); break;
  215080. }
  215081. DBG (e);
  215082. jassertfalse;
  215083. }
  215084. #endif
  215085. }
  215086. #undef check
  215087. bool check (HRESULT hr)
  215088. {
  215089. logFailure (hr);
  215090. return SUCCEEDED (hr);
  215091. }
  215092. const String getDeviceID (IMMDevice* const device)
  215093. {
  215094. String s;
  215095. WCHAR* deviceId = 0;
  215096. if (check (device->GetId (&deviceId)))
  215097. {
  215098. s = String (deviceId);
  215099. CoTaskMemFree (deviceId);
  215100. }
  215101. return s;
  215102. }
  215103. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215104. {
  215105. EDataFlow flow = eRender;
  215106. ComSmartPtr <IMMEndpoint> endPoint;
  215107. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215108. (void) check (endPoint->GetDataFlow (&flow));
  215109. return flow;
  215110. }
  215111. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215112. {
  215113. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215114. }
  215115. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215116. {
  215117. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215118. : sizeof (WAVEFORMATEX));
  215119. }
  215120. class WASAPIDeviceBase
  215121. {
  215122. public:
  215123. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215124. : device (device_),
  215125. sampleRate (0),
  215126. defaultSampleRate (0),
  215127. numChannels (0),
  215128. actualNumChannels (0),
  215129. minBufferSize (0),
  215130. defaultBufferSize (0),
  215131. latencySamples (0),
  215132. useExclusiveMode (useExclusiveMode_)
  215133. {
  215134. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215135. ComSmartPtr <IAudioClient> tempClient (createClient());
  215136. if (tempClient == 0)
  215137. return;
  215138. REFERENCE_TIME defaultPeriod, minPeriod;
  215139. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215140. return;
  215141. WAVEFORMATEX* mixFormat = 0;
  215142. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215143. return;
  215144. WAVEFORMATEXTENSIBLE format;
  215145. copyWavFormat (format, mixFormat);
  215146. CoTaskMemFree (mixFormat);
  215147. actualNumChannels = numChannels = format.Format.nChannels;
  215148. defaultSampleRate = format.Format.nSamplesPerSec;
  215149. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215150. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215151. rates.addUsingDefaultSort (defaultSampleRate);
  215152. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215153. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215154. {
  215155. if (ratesToTest[i] == defaultSampleRate)
  215156. continue;
  215157. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215158. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215159. (WAVEFORMATEX*) &format, 0)))
  215160. if (! rates.contains (ratesToTest[i]))
  215161. rates.addUsingDefaultSort (ratesToTest[i]);
  215162. }
  215163. }
  215164. ~WASAPIDeviceBase()
  215165. {
  215166. device = 0;
  215167. CloseHandle (clientEvent);
  215168. }
  215169. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215170. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215171. {
  215172. sampleRate = newSampleRate;
  215173. channels = newChannels;
  215174. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215175. numChannels = channels.getHighestBit() + 1;
  215176. if (numChannels == 0)
  215177. return true;
  215178. client = createClient();
  215179. if (client != 0
  215180. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215181. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215182. {
  215183. channelMaps.clear();
  215184. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215185. if (channels[i])
  215186. channelMaps.add (i);
  215187. REFERENCE_TIME latency;
  215188. if (check (client->GetStreamLatency (&latency)))
  215189. latencySamples = refTimeToSamples (latency, sampleRate);
  215190. (void) check (client->GetBufferSize (&actualBufferSize));
  215191. return check (client->SetEventHandle (clientEvent));
  215192. }
  215193. return false;
  215194. }
  215195. void closeClient()
  215196. {
  215197. if (client != 0)
  215198. client->Stop();
  215199. client = 0;
  215200. ResetEvent (clientEvent);
  215201. }
  215202. ComSmartPtr <IMMDevice> device;
  215203. ComSmartPtr <IAudioClient> client;
  215204. double sampleRate, defaultSampleRate;
  215205. int numChannels, actualNumChannels;
  215206. int minBufferSize, defaultBufferSize, latencySamples;
  215207. const bool useExclusiveMode;
  215208. Array <double> rates;
  215209. HANDLE clientEvent;
  215210. BigInteger channels;
  215211. Array <int> channelMaps;
  215212. UINT32 actualBufferSize;
  215213. int bytesPerSample;
  215214. virtual void updateFormat (bool isFloat) = 0;
  215215. private:
  215216. const ComSmartPtr <IAudioClient> createClient()
  215217. {
  215218. ComSmartPtr <IAudioClient> client;
  215219. if (device != 0)
  215220. {
  215221. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215222. logFailure (hr);
  215223. }
  215224. return client;
  215225. }
  215226. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215227. {
  215228. WAVEFORMATEXTENSIBLE format;
  215229. zerostruct (format);
  215230. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215231. {
  215232. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215233. }
  215234. else
  215235. {
  215236. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215237. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215238. }
  215239. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215240. format.Format.nChannels = (WORD) numChannels;
  215241. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215242. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215243. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215244. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215245. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215246. switch (numChannels)
  215247. {
  215248. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215249. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215250. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215251. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215252. 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;
  215253. default: break;
  215254. }
  215255. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215256. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215257. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215258. logFailure (hr);
  215259. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215260. {
  215261. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215262. hr = S_OK;
  215263. }
  215264. CoTaskMemFree (nearestFormat);
  215265. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215266. if (useExclusiveMode)
  215267. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215268. GUID session;
  215269. if (hr == S_OK
  215270. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215271. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215272. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215273. {
  215274. actualNumChannels = format.Format.nChannels;
  215275. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215276. bytesPerSample = format.Format.wBitsPerSample / 8;
  215277. updateFormat (isFloat);
  215278. return true;
  215279. }
  215280. return false;
  215281. }
  215282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215283. };
  215284. class WASAPIInputDevice : public WASAPIDeviceBase
  215285. {
  215286. public:
  215287. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215288. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215289. reservoir (1, 1)
  215290. {
  215291. }
  215292. ~WASAPIInputDevice()
  215293. {
  215294. close();
  215295. }
  215296. bool open (const double newSampleRate, const BigInteger& newChannels)
  215297. {
  215298. reservoirSize = 0;
  215299. reservoirCapacity = 16384;
  215300. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215301. return openClient (newSampleRate, newChannels)
  215302. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215303. (void**) captureClient.resetAndGetPointerAddress())));
  215304. }
  215305. void close()
  215306. {
  215307. closeClient();
  215308. captureClient = 0;
  215309. reservoir.setSize (0);
  215310. }
  215311. template <class SourceType>
  215312. void updateFormatWithType (SourceType*)
  215313. {
  215314. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215315. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215316. }
  215317. void updateFormat (bool isFloat)
  215318. {
  215319. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215320. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215321. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215322. else updateFormatWithType ((AudioData::Int16*) 0);
  215323. }
  215324. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215325. {
  215326. if (numChannels <= 0)
  215327. return;
  215328. int offset = 0;
  215329. while (bufferSize > 0)
  215330. {
  215331. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215332. {
  215333. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215334. for (int i = 0; i < numDestBuffers; ++i)
  215335. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215336. bufferSize -= samplesToDo;
  215337. offset += samplesToDo;
  215338. reservoirSize = 0;
  215339. }
  215340. else
  215341. {
  215342. UINT32 packetLength = 0;
  215343. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215344. break;
  215345. if (packetLength == 0)
  215346. {
  215347. if (thread.threadShouldExit()
  215348. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215349. break;
  215350. continue;
  215351. }
  215352. uint8* inputData;
  215353. UINT32 numSamplesAvailable;
  215354. DWORD flags;
  215355. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215356. {
  215357. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215358. for (int i = 0; i < numDestBuffers; ++i)
  215359. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215360. bufferSize -= samplesToDo;
  215361. offset += samplesToDo;
  215362. if (samplesToDo < (int) numSamplesAvailable)
  215363. {
  215364. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215365. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215366. bytesPerSample * actualNumChannels * reservoirSize);
  215367. }
  215368. captureClient->ReleaseBuffer (numSamplesAvailable);
  215369. }
  215370. }
  215371. }
  215372. }
  215373. ComSmartPtr <IAudioCaptureClient> captureClient;
  215374. MemoryBlock reservoir;
  215375. int reservoirSize, reservoirCapacity;
  215376. ScopedPointer <AudioData::Converter> converter;
  215377. private:
  215378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215379. };
  215380. class WASAPIOutputDevice : public WASAPIDeviceBase
  215381. {
  215382. public:
  215383. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215384. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215385. {
  215386. }
  215387. ~WASAPIOutputDevice()
  215388. {
  215389. close();
  215390. }
  215391. bool open (const double newSampleRate, const BigInteger& newChannels)
  215392. {
  215393. return openClient (newSampleRate, newChannels)
  215394. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215395. }
  215396. void close()
  215397. {
  215398. closeClient();
  215399. renderClient = 0;
  215400. }
  215401. template <class DestType>
  215402. void updateFormatWithType (DestType*)
  215403. {
  215404. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215405. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215406. }
  215407. void updateFormat (bool isFloat)
  215408. {
  215409. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215410. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215411. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215412. else updateFormatWithType ((AudioData::Int16*) 0);
  215413. }
  215414. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215415. {
  215416. if (numChannels <= 0)
  215417. return;
  215418. int offset = 0;
  215419. while (bufferSize > 0)
  215420. {
  215421. UINT32 padding = 0;
  215422. if (! check (client->GetCurrentPadding (&padding)))
  215423. return;
  215424. int samplesToDo = useExclusiveMode ? bufferSize
  215425. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215426. if (samplesToDo <= 0)
  215427. {
  215428. if (thread.threadShouldExit()
  215429. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215430. break;
  215431. continue;
  215432. }
  215433. uint8* outputData = 0;
  215434. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215435. {
  215436. for (int i = 0; i < numSrcBuffers; ++i)
  215437. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215438. renderClient->ReleaseBuffer (samplesToDo, 0);
  215439. offset += samplesToDo;
  215440. bufferSize -= samplesToDo;
  215441. }
  215442. }
  215443. }
  215444. ComSmartPtr <IAudioRenderClient> renderClient;
  215445. ScopedPointer <AudioData::Converter> converter;
  215446. private:
  215447. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215448. };
  215449. class WASAPIAudioIODevice : public AudioIODevice,
  215450. public Thread
  215451. {
  215452. public:
  215453. WASAPIAudioIODevice (const String& deviceName,
  215454. const String& outputDeviceId_,
  215455. const String& inputDeviceId_,
  215456. const bool useExclusiveMode_)
  215457. : AudioIODevice (deviceName, "Windows Audio"),
  215458. Thread ("Juce WASAPI"),
  215459. outputDeviceId (outputDeviceId_),
  215460. inputDeviceId (inputDeviceId_),
  215461. useExclusiveMode (useExclusiveMode_),
  215462. isOpen_ (false),
  215463. isStarted (false),
  215464. currentBufferSizeSamples (0),
  215465. currentSampleRate (0),
  215466. callback (0)
  215467. {
  215468. }
  215469. ~WASAPIAudioIODevice()
  215470. {
  215471. close();
  215472. }
  215473. bool initialise()
  215474. {
  215475. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215476. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215477. latencyIn = latencyOut = 0;
  215478. Array <double> ratesIn, ratesOut;
  215479. if (createDevices())
  215480. {
  215481. jassert (inputDevice != 0 || outputDevice != 0);
  215482. if (inputDevice != 0 && outputDevice != 0)
  215483. {
  215484. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215485. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215486. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215487. sampleRates = inputDevice->rates;
  215488. sampleRates.removeValuesNotIn (outputDevice->rates);
  215489. }
  215490. else
  215491. {
  215492. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215493. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215494. defaultSampleRate = d->defaultSampleRate;
  215495. minBufferSize = d->minBufferSize;
  215496. defaultBufferSize = d->defaultBufferSize;
  215497. sampleRates = d->rates;
  215498. }
  215499. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215500. if (minBufferSize != defaultBufferSize)
  215501. bufferSizes.addUsingDefaultSort (minBufferSize);
  215502. int n = 64;
  215503. for (int i = 0; i < 40; ++i)
  215504. {
  215505. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215506. bufferSizes.addUsingDefaultSort (n);
  215507. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215508. }
  215509. return true;
  215510. }
  215511. return false;
  215512. }
  215513. const StringArray getOutputChannelNames()
  215514. {
  215515. StringArray outChannels;
  215516. if (outputDevice != 0)
  215517. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215518. outChannels.add ("Output channel " + String (i));
  215519. return outChannels;
  215520. }
  215521. const StringArray getInputChannelNames()
  215522. {
  215523. StringArray inChannels;
  215524. if (inputDevice != 0)
  215525. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215526. inChannels.add ("Input channel " + String (i));
  215527. return inChannels;
  215528. }
  215529. int getNumSampleRates() { return sampleRates.size(); }
  215530. double getSampleRate (int index) { return sampleRates [index]; }
  215531. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215532. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215533. int getDefaultBufferSize() { return defaultBufferSize; }
  215534. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215535. double getCurrentSampleRate() { return currentSampleRate; }
  215536. int getCurrentBitDepth() { return 32; }
  215537. int getOutputLatencyInSamples() { return latencyOut; }
  215538. int getInputLatencyInSamples() { return latencyIn; }
  215539. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215540. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215541. const String getLastError() { return lastError; }
  215542. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215543. double sampleRate, int bufferSizeSamples)
  215544. {
  215545. close();
  215546. lastError = String::empty;
  215547. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215548. {
  215549. lastError = "The input and output devices don't share a common sample rate!";
  215550. return lastError;
  215551. }
  215552. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215553. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215554. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215555. {
  215556. lastError = "Couldn't open the input device!";
  215557. return lastError;
  215558. }
  215559. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215560. {
  215561. close();
  215562. lastError = "Couldn't open the output device!";
  215563. return lastError;
  215564. }
  215565. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215566. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215567. startThread (8);
  215568. Thread::sleep (5);
  215569. if (inputDevice != 0 && inputDevice->client != 0)
  215570. {
  215571. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215572. HRESULT hr = inputDevice->client->Start();
  215573. logFailure (hr); //xxx handle this
  215574. }
  215575. if (outputDevice != 0 && outputDevice->client != 0)
  215576. {
  215577. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215578. HRESULT hr = outputDevice->client->Start();
  215579. logFailure (hr); //xxx handle this
  215580. }
  215581. isOpen_ = true;
  215582. return lastError;
  215583. }
  215584. void close()
  215585. {
  215586. stop();
  215587. signalThreadShouldExit();
  215588. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215589. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215590. stopThread (5000);
  215591. if (inputDevice != 0) inputDevice->close();
  215592. if (outputDevice != 0) outputDevice->close();
  215593. isOpen_ = false;
  215594. }
  215595. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215596. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215597. void start (AudioIODeviceCallback* call)
  215598. {
  215599. if (isOpen_ && call != 0 && ! isStarted)
  215600. {
  215601. if (! isThreadRunning())
  215602. {
  215603. // something's gone wrong and the thread's stopped..
  215604. isOpen_ = false;
  215605. return;
  215606. }
  215607. call->audioDeviceAboutToStart (this);
  215608. const ScopedLock sl (startStopLock);
  215609. callback = call;
  215610. isStarted = true;
  215611. }
  215612. }
  215613. void stop()
  215614. {
  215615. if (isStarted)
  215616. {
  215617. AudioIODeviceCallback* const callbackLocal = callback;
  215618. {
  215619. const ScopedLock sl (startStopLock);
  215620. isStarted = false;
  215621. }
  215622. if (callbackLocal != 0)
  215623. callbackLocal->audioDeviceStopped();
  215624. }
  215625. }
  215626. void setMMThreadPriority()
  215627. {
  215628. DynamicLibraryLoader dll ("avrt.dll");
  215629. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215630. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215631. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215632. {
  215633. DWORD dummy = 0;
  215634. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215635. if (h != 0)
  215636. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215637. }
  215638. }
  215639. void run()
  215640. {
  215641. setMMThreadPriority();
  215642. const int bufferSize = currentBufferSizeSamples;
  215643. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215644. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215645. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215646. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215647. float** const inputBuffers = ins.getArrayOfChannels();
  215648. float** const outputBuffers = outs.getArrayOfChannels();
  215649. ins.clear();
  215650. while (! threadShouldExit())
  215651. {
  215652. if (inputDevice != 0)
  215653. {
  215654. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215655. if (threadShouldExit())
  215656. break;
  215657. }
  215658. JUCE_TRY
  215659. {
  215660. const ScopedLock sl (startStopLock);
  215661. if (isStarted)
  215662. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215663. outputBuffers, numOutputBuffers, bufferSize);
  215664. else
  215665. outs.clear();
  215666. }
  215667. JUCE_CATCH_EXCEPTION
  215668. if (outputDevice != 0)
  215669. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215670. }
  215671. }
  215672. String outputDeviceId, inputDeviceId;
  215673. String lastError;
  215674. private:
  215675. // Device stats...
  215676. ScopedPointer<WASAPIInputDevice> inputDevice;
  215677. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215678. const bool useExclusiveMode;
  215679. double defaultSampleRate;
  215680. int minBufferSize, defaultBufferSize;
  215681. int latencyIn, latencyOut;
  215682. Array <double> sampleRates;
  215683. Array <int> bufferSizes;
  215684. // Active state...
  215685. bool isOpen_, isStarted;
  215686. int currentBufferSizeSamples;
  215687. double currentSampleRate;
  215688. AudioIODeviceCallback* callback;
  215689. CriticalSection startStopLock;
  215690. bool createDevices()
  215691. {
  215692. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215693. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215694. return false;
  215695. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215696. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215697. return false;
  215698. UINT32 numDevices = 0;
  215699. if (! check (deviceCollection->GetCount (&numDevices)))
  215700. return false;
  215701. for (UINT32 i = 0; i < numDevices; ++i)
  215702. {
  215703. ComSmartPtr <IMMDevice> device;
  215704. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215705. continue;
  215706. const String deviceId (getDeviceID (device));
  215707. if (deviceId.isEmpty())
  215708. continue;
  215709. const EDataFlow flow = getDataFlow (device);
  215710. if (deviceId == inputDeviceId && flow == eCapture)
  215711. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215712. else if (deviceId == outputDeviceId && flow == eRender)
  215713. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215714. }
  215715. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215716. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215717. }
  215718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215719. };
  215720. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215721. {
  215722. public:
  215723. WASAPIAudioIODeviceType()
  215724. : AudioIODeviceType ("Windows Audio"),
  215725. hasScanned (false)
  215726. {
  215727. }
  215728. ~WASAPIAudioIODeviceType()
  215729. {
  215730. }
  215731. void scanForDevices()
  215732. {
  215733. hasScanned = true;
  215734. outputDeviceNames.clear();
  215735. inputDeviceNames.clear();
  215736. outputDeviceIds.clear();
  215737. inputDeviceIds.clear();
  215738. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215739. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215740. return;
  215741. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215742. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215743. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215744. UINT32 numDevices = 0;
  215745. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215746. && check (deviceCollection->GetCount (&numDevices))))
  215747. return;
  215748. for (UINT32 i = 0; i < numDevices; ++i)
  215749. {
  215750. ComSmartPtr <IMMDevice> device;
  215751. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215752. continue;
  215753. const String deviceId (getDeviceID (device));
  215754. DWORD state = 0;
  215755. if (! check (device->GetState (&state)))
  215756. continue;
  215757. if (state != DEVICE_STATE_ACTIVE)
  215758. continue;
  215759. String name;
  215760. {
  215761. ComSmartPtr <IPropertyStore> properties;
  215762. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215763. continue;
  215764. PROPVARIANT value;
  215765. PropVariantInit (&value);
  215766. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215767. name = value.pwszVal;
  215768. PropVariantClear (&value);
  215769. }
  215770. const EDataFlow flow = getDataFlow (device);
  215771. if (flow == eRender)
  215772. {
  215773. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215774. outputDeviceIds.insert (index, deviceId);
  215775. outputDeviceNames.insert (index, name);
  215776. }
  215777. else if (flow == eCapture)
  215778. {
  215779. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215780. inputDeviceIds.insert (index, deviceId);
  215781. inputDeviceNames.insert (index, name);
  215782. }
  215783. }
  215784. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215785. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215786. }
  215787. const StringArray getDeviceNames (bool wantInputNames) const
  215788. {
  215789. jassert (hasScanned); // need to call scanForDevices() before doing this
  215790. return wantInputNames ? inputDeviceNames
  215791. : outputDeviceNames;
  215792. }
  215793. int getDefaultDeviceIndex (bool /*forInput*/) const
  215794. {
  215795. jassert (hasScanned); // need to call scanForDevices() before doing this
  215796. return 0;
  215797. }
  215798. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215799. {
  215800. jassert (hasScanned); // need to call scanForDevices() before doing this
  215801. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215802. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215803. : outputDeviceIds.indexOf (d->outputDeviceId));
  215804. }
  215805. bool hasSeparateInputsAndOutputs() const { return true; }
  215806. AudioIODevice* createDevice (const String& outputDeviceName,
  215807. const String& inputDeviceName)
  215808. {
  215809. jassert (hasScanned); // need to call scanForDevices() before doing this
  215810. const bool useExclusiveMode = false;
  215811. ScopedPointer<WASAPIAudioIODevice> device;
  215812. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215813. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215814. if (outputIndex >= 0 || inputIndex >= 0)
  215815. {
  215816. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215817. : inputDeviceName,
  215818. outputDeviceIds [outputIndex],
  215819. inputDeviceIds [inputIndex],
  215820. useExclusiveMode);
  215821. if (! device->initialise())
  215822. device = 0;
  215823. }
  215824. return device.release();
  215825. }
  215826. StringArray outputDeviceNames, outputDeviceIds;
  215827. StringArray inputDeviceNames, inputDeviceIds;
  215828. private:
  215829. bool hasScanned;
  215830. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215831. {
  215832. String s;
  215833. IMMDevice* dev = 0;
  215834. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215835. eMultimedia, &dev)))
  215836. {
  215837. WCHAR* deviceId = 0;
  215838. if (check (dev->GetId (&deviceId)))
  215839. {
  215840. s = String (deviceId);
  215841. CoTaskMemFree (deviceId);
  215842. }
  215843. dev->Release();
  215844. }
  215845. return s;
  215846. }
  215847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215848. };
  215849. }
  215850. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()
  215851. {
  215852. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  215853. return new WasapiClasses::WASAPIAudioIODeviceType();
  215854. return 0;
  215855. }
  215856. #endif
  215857. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215858. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215859. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215860. // compiled on its own).
  215861. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215862. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215863. {
  215864. public:
  215865. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215866. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215867. const ComSmartPtr <IBaseFilter>& filter_,
  215868. int minWidth, int minHeight,
  215869. int maxWidth, int maxHeight)
  215870. : owner (owner_),
  215871. captureGraphBuilder (captureGraphBuilder_),
  215872. filter (filter_),
  215873. ok (false),
  215874. imageNeedsFlipping (false),
  215875. width (0),
  215876. height (0),
  215877. activeUsers (0),
  215878. recordNextFrameTime (false),
  215879. previewMaxFPS (60)
  215880. {
  215881. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215882. if (FAILED (hr))
  215883. return;
  215884. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215885. if (FAILED (hr))
  215886. return;
  215887. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215888. if (FAILED (hr))
  215889. return;
  215890. {
  215891. ComSmartPtr <IAMStreamConfig> streamConfig;
  215892. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215893. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215894. if (streamConfig != 0)
  215895. {
  215896. getVideoSizes (streamConfig);
  215897. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215898. return;
  215899. }
  215900. }
  215901. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215902. if (FAILED (hr))
  215903. return;
  215904. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215905. if (FAILED (hr))
  215906. return;
  215907. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215908. if (FAILED (hr))
  215909. return;
  215910. if (! connectFilters (filter, smartTee))
  215911. return;
  215912. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215913. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215914. if (FAILED (hr))
  215915. return;
  215916. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215917. if (FAILED (hr))
  215918. return;
  215919. AM_MEDIA_TYPE mt;
  215920. zerostruct (mt);
  215921. mt.majortype = MEDIATYPE_Video;
  215922. mt.subtype = MEDIASUBTYPE_RGB24;
  215923. mt.formattype = FORMAT_VideoInfo;
  215924. sampleGrabber->SetMediaType (&mt);
  215925. callback = new GrabberCallback (*this);
  215926. hr = sampleGrabber->SetCallback (callback, 1);
  215927. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215928. if (FAILED (hr))
  215929. return;
  215930. ComSmartPtr <IPin> grabberInputPin;
  215931. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215932. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215933. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215934. return;
  215935. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215936. if (FAILED (hr))
  215937. return;
  215938. zerostruct (mt);
  215939. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215940. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215941. width = pVih->bmiHeader.biWidth;
  215942. height = pVih->bmiHeader.biHeight;
  215943. ComSmartPtr <IBaseFilter> nullFilter;
  215944. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215945. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215946. if (connectFilters (sampleGrabberBase, nullFilter)
  215947. && addGraphToRot())
  215948. {
  215949. activeImage = Image (Image::RGB, width, height, true);
  215950. loadingImage = Image (Image::RGB, width, height, true);
  215951. ok = true;
  215952. }
  215953. }
  215954. ~DShowCameraDeviceInteral()
  215955. {
  215956. if (mediaControl != 0)
  215957. mediaControl->Stop();
  215958. removeGraphFromRot();
  215959. for (int i = viewerComps.size(); --i >= 0;)
  215960. viewerComps.getUnchecked(i)->ownerDeleted();
  215961. callback = 0;
  215962. graphBuilder = 0;
  215963. sampleGrabber = 0;
  215964. mediaControl = 0;
  215965. filter = 0;
  215966. captureGraphBuilder = 0;
  215967. smartTee = 0;
  215968. smartTeePreviewOutputPin = 0;
  215969. smartTeeCaptureOutputPin = 0;
  215970. asfWriter = 0;
  215971. }
  215972. void addUser()
  215973. {
  215974. if (ok && activeUsers++ == 0)
  215975. mediaControl->Run();
  215976. }
  215977. void removeUser()
  215978. {
  215979. if (ok && --activeUsers == 0)
  215980. mediaControl->Stop();
  215981. }
  215982. int getPreviewMaxFPS() const
  215983. {
  215984. return previewMaxFPS;
  215985. }
  215986. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215987. {
  215988. if (recordNextFrameTime)
  215989. {
  215990. const double defaultCameraLatency = 0.1;
  215991. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215992. recordNextFrameTime = false;
  215993. ComSmartPtr <IPin> pin;
  215994. if (getPin (filter, PINDIR_OUTPUT, pin))
  215995. {
  215996. ComSmartPtr <IAMPushSource> pushSource;
  215997. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215998. if (pushSource != 0)
  215999. {
  216000. REFERENCE_TIME latency = 0;
  216001. hr = pushSource->GetLatency (&latency);
  216002. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216003. }
  216004. }
  216005. }
  216006. {
  216007. const int lineStride = width * 3;
  216008. const ScopedLock sl (imageSwapLock);
  216009. {
  216010. const Image::BitmapData destData (loadingImage, 0, 0, width, height, Image::BitmapData::writeOnly);
  216011. for (int i = 0; i < height; ++i)
  216012. memcpy (destData.getLinePointer ((height - 1) - i),
  216013. buffer + lineStride * i,
  216014. lineStride);
  216015. }
  216016. imageNeedsFlipping = true;
  216017. }
  216018. if (listeners.size() > 0)
  216019. callListeners (loadingImage);
  216020. sendChangeMessage();
  216021. }
  216022. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216023. {
  216024. if (imageNeedsFlipping)
  216025. {
  216026. const ScopedLock sl (imageSwapLock);
  216027. swapVariables (loadingImage, activeImage);
  216028. imageNeedsFlipping = false;
  216029. }
  216030. RectanglePlacement rp (RectanglePlacement::centred);
  216031. double dx = 0, dy = 0, dw = width, dh = height;
  216032. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216033. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216034. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216035. {
  216036. Graphics::ScopedSaveState ss (g);
  216037. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216038. g.fillAll (Colours::black);
  216039. }
  216040. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216041. }
  216042. bool createFileCaptureFilter (const File& file, int quality)
  216043. {
  216044. removeFileCaptureFilter();
  216045. file.deleteFile();
  216046. mediaControl->Stop();
  216047. firstRecordedTime = Time();
  216048. recordNextFrameTime = true;
  216049. previewMaxFPS = 60;
  216050. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216051. if (SUCCEEDED (hr))
  216052. {
  216053. ComSmartPtr <IFileSinkFilter> fileSink;
  216054. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216055. if (SUCCEEDED (hr))
  216056. {
  216057. hr = fileSink->SetFileName (file.getFullPathName().toUTF16(), 0);
  216058. if (SUCCEEDED (hr))
  216059. {
  216060. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216061. if (SUCCEEDED (hr))
  216062. {
  216063. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216064. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216065. asfConfig->SetIndexMode (true);
  216066. ComSmartPtr <IWMProfileManager> profileManager;
  216067. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216068. // This gibberish is the DirectShow profile for a video-only wmv file.
  216069. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216070. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216071. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216072. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216073. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216074. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216075. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216076. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216077. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216078. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216079. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216080. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216081. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216082. "</videoinfoheader>"
  216083. "</wmmediatype>"
  216084. "</streamconfig>"
  216085. "</profile>");
  216086. const int fps[] = { 10, 15, 30 };
  216087. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216088. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216089. maxFramesPerSecond = (quality >> 24) & 0xff;
  216090. prof = prof.replace ("$WIDTH", String (width))
  216091. .replace ("$HEIGHT", String (height))
  216092. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216093. ComSmartPtr <IWMProfile> currentProfile;
  216094. hr = profileManager->LoadProfileByData (prof.toUTF16(), currentProfile.resetAndGetPointerAddress());
  216095. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216096. if (SUCCEEDED (hr))
  216097. {
  216098. ComSmartPtr <IPin> asfWriterInputPin;
  216099. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216100. {
  216101. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216102. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216103. && SUCCEEDED (mediaControl->Run()))
  216104. {
  216105. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216106. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216107. previewMaxFPS = (quality >> 16) & 0xff;
  216108. return true;
  216109. }
  216110. }
  216111. }
  216112. }
  216113. }
  216114. }
  216115. }
  216116. removeFileCaptureFilter();
  216117. if (ok && activeUsers > 0)
  216118. mediaControl->Run();
  216119. return false;
  216120. }
  216121. void removeFileCaptureFilter()
  216122. {
  216123. mediaControl->Stop();
  216124. if (asfWriter != 0)
  216125. {
  216126. graphBuilder->RemoveFilter (asfWriter);
  216127. asfWriter = 0;
  216128. }
  216129. if (ok && activeUsers > 0)
  216130. mediaControl->Run();
  216131. previewMaxFPS = 60;
  216132. }
  216133. void addListener (CameraDevice::Listener* listenerToAdd)
  216134. {
  216135. const ScopedLock sl (listenerLock);
  216136. if (listeners.size() == 0)
  216137. addUser();
  216138. listeners.addIfNotAlreadyThere (listenerToAdd);
  216139. }
  216140. void removeListener (CameraDevice::Listener* listenerToRemove)
  216141. {
  216142. const ScopedLock sl (listenerLock);
  216143. listeners.removeValue (listenerToRemove);
  216144. if (listeners.size() == 0)
  216145. removeUser();
  216146. }
  216147. void callListeners (const Image& image)
  216148. {
  216149. const ScopedLock sl (listenerLock);
  216150. for (int i = listeners.size(); --i >= 0;)
  216151. {
  216152. CameraDevice::Listener* const l = listeners[i];
  216153. if (l != 0)
  216154. l->imageReceived (image);
  216155. }
  216156. }
  216157. class DShowCaptureViewerComp : public Component,
  216158. public ChangeListener
  216159. {
  216160. public:
  216161. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216162. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216163. {
  216164. setOpaque (true);
  216165. owner->addChangeListener (this);
  216166. owner->addUser();
  216167. owner->viewerComps.add (this);
  216168. setSize (owner->width, owner->height);
  216169. }
  216170. ~DShowCaptureViewerComp()
  216171. {
  216172. if (owner != 0)
  216173. {
  216174. owner->viewerComps.removeValue (this);
  216175. owner->removeUser();
  216176. owner->removeChangeListener (this);
  216177. }
  216178. }
  216179. void ownerDeleted()
  216180. {
  216181. owner = 0;
  216182. }
  216183. void paint (Graphics& g)
  216184. {
  216185. g.setColour (Colours::black);
  216186. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216187. if (owner != 0)
  216188. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216189. else
  216190. g.fillAll (Colours::black);
  216191. }
  216192. void changeListenerCallback (ChangeBroadcaster*)
  216193. {
  216194. const int64 now = Time::currentTimeMillis();
  216195. if (now >= lastRepaintTime + (1000 / maxFPS))
  216196. {
  216197. lastRepaintTime = now;
  216198. repaint();
  216199. if (owner != 0)
  216200. maxFPS = owner->getPreviewMaxFPS();
  216201. }
  216202. }
  216203. private:
  216204. DShowCameraDeviceInteral* owner;
  216205. int maxFPS;
  216206. int64 lastRepaintTime;
  216207. };
  216208. bool ok;
  216209. int width, height;
  216210. Time firstRecordedTime;
  216211. Array <DShowCaptureViewerComp*> viewerComps;
  216212. private:
  216213. CameraDevice* const owner;
  216214. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216215. ComSmartPtr <IBaseFilter> filter;
  216216. ComSmartPtr <IBaseFilter> smartTee;
  216217. ComSmartPtr <IGraphBuilder> graphBuilder;
  216218. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216219. ComSmartPtr <IMediaControl> mediaControl;
  216220. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216221. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216222. ComSmartPtr <IBaseFilter> asfWriter;
  216223. int activeUsers;
  216224. Array <int> widths, heights;
  216225. DWORD graphRegistrationID;
  216226. CriticalSection imageSwapLock;
  216227. bool imageNeedsFlipping;
  216228. Image loadingImage;
  216229. Image activeImage;
  216230. bool recordNextFrameTime;
  216231. int previewMaxFPS;
  216232. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216233. {
  216234. widths.clear();
  216235. heights.clear();
  216236. int count = 0, size = 0;
  216237. streamConfig->GetNumberOfCapabilities (&count, &size);
  216238. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216239. {
  216240. for (int i = 0; i < count; ++i)
  216241. {
  216242. VIDEO_STREAM_CONFIG_CAPS scc;
  216243. AM_MEDIA_TYPE* config;
  216244. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216245. if (SUCCEEDED (hr))
  216246. {
  216247. const int w = scc.InputSize.cx;
  216248. const int h = scc.InputSize.cy;
  216249. bool duplicate = false;
  216250. for (int j = widths.size(); --j >= 0;)
  216251. {
  216252. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216253. {
  216254. duplicate = true;
  216255. break;
  216256. }
  216257. }
  216258. if (! duplicate)
  216259. {
  216260. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216261. widths.add (w);
  216262. heights.add (h);
  216263. }
  216264. deleteMediaType (config);
  216265. }
  216266. }
  216267. }
  216268. }
  216269. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216270. const int minWidth, const int minHeight,
  216271. const int maxWidth, const int maxHeight)
  216272. {
  216273. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216274. streamConfig->GetNumberOfCapabilities (&count, &size);
  216275. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216276. {
  216277. AM_MEDIA_TYPE* config;
  216278. VIDEO_STREAM_CONFIG_CAPS scc;
  216279. for (int i = 0; i < count; ++i)
  216280. {
  216281. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216282. if (SUCCEEDED (hr))
  216283. {
  216284. if (scc.InputSize.cx >= minWidth
  216285. && scc.InputSize.cy >= minHeight
  216286. && scc.InputSize.cx <= maxWidth
  216287. && scc.InputSize.cy <= maxHeight)
  216288. {
  216289. int area = scc.InputSize.cx * scc.InputSize.cy;
  216290. if (area > bestArea)
  216291. {
  216292. bestIndex = i;
  216293. bestArea = area;
  216294. }
  216295. }
  216296. deleteMediaType (config);
  216297. }
  216298. }
  216299. if (bestIndex >= 0)
  216300. {
  216301. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216302. hr = streamConfig->SetFormat (config);
  216303. deleteMediaType (config);
  216304. return SUCCEEDED (hr);
  216305. }
  216306. }
  216307. return false;
  216308. }
  216309. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216310. {
  216311. ComSmartPtr <IEnumPins> enumerator;
  216312. ComSmartPtr <IPin> pin;
  216313. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216314. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216315. {
  216316. PIN_DIRECTION dir;
  216317. pin->QueryDirection (&dir);
  216318. if (wantedDirection == dir)
  216319. {
  216320. PIN_INFO info;
  216321. zerostruct (info);
  216322. pin->QueryPinInfo (&info);
  216323. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216324. {
  216325. result = pin;
  216326. return true;
  216327. }
  216328. }
  216329. }
  216330. return false;
  216331. }
  216332. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216333. {
  216334. ComSmartPtr <IPin> in, out;
  216335. return getPin (first, PINDIR_OUTPUT, out)
  216336. && getPin (second, PINDIR_INPUT, in)
  216337. && SUCCEEDED (graphBuilder->Connect (out, in));
  216338. }
  216339. bool addGraphToRot()
  216340. {
  216341. ComSmartPtr <IRunningObjectTable> rot;
  216342. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216343. return false;
  216344. ComSmartPtr <IMoniker> moniker;
  216345. WCHAR buffer[128];
  216346. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216347. if (FAILED (hr))
  216348. return false;
  216349. graphRegistrationID = 0;
  216350. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216351. }
  216352. void removeGraphFromRot()
  216353. {
  216354. ComSmartPtr <IRunningObjectTable> rot;
  216355. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216356. rot->Revoke (graphRegistrationID);
  216357. }
  216358. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216359. {
  216360. if (pmt->cbFormat != 0)
  216361. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216362. if (pmt->pUnk != 0)
  216363. pmt->pUnk->Release();
  216364. CoTaskMemFree (pmt);
  216365. }
  216366. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216367. {
  216368. public:
  216369. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216370. : owner (owner_)
  216371. {
  216372. }
  216373. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216374. {
  216375. return E_FAIL;
  216376. }
  216377. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216378. {
  216379. owner.handleFrame (time, buffer, bufferSize);
  216380. return S_OK;
  216381. }
  216382. private:
  216383. DShowCameraDeviceInteral& owner;
  216384. GrabberCallback (const GrabberCallback&);
  216385. GrabberCallback& operator= (const GrabberCallback&);
  216386. };
  216387. ComSmartPtr <GrabberCallback> callback;
  216388. Array <CameraDevice::Listener*> listeners;
  216389. CriticalSection listenerLock;
  216390. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216391. };
  216392. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216393. : name (name_)
  216394. {
  216395. isRecording = false;
  216396. }
  216397. CameraDevice::~CameraDevice()
  216398. {
  216399. stopRecording();
  216400. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216401. internal = 0;
  216402. }
  216403. Component* CameraDevice::createViewerComponent()
  216404. {
  216405. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216406. }
  216407. const String CameraDevice::getFileExtension()
  216408. {
  216409. return ".wmv";
  216410. }
  216411. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216412. {
  216413. stopRecording();
  216414. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216415. d->addUser();
  216416. isRecording = d->createFileCaptureFilter (file, quality);
  216417. }
  216418. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216419. {
  216420. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216421. return d->firstRecordedTime;
  216422. }
  216423. void CameraDevice::stopRecording()
  216424. {
  216425. if (isRecording)
  216426. {
  216427. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216428. d->removeFileCaptureFilter();
  216429. d->removeUser();
  216430. isRecording = false;
  216431. }
  216432. }
  216433. void CameraDevice::addListener (Listener* listenerToAdd)
  216434. {
  216435. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216436. if (listenerToAdd != 0)
  216437. d->addListener (listenerToAdd);
  216438. }
  216439. void CameraDevice::removeListener (Listener* listenerToRemove)
  216440. {
  216441. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216442. if (listenerToRemove != 0)
  216443. d->removeListener (listenerToRemove);
  216444. }
  216445. namespace
  216446. {
  216447. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216448. const int deviceIndexToOpen,
  216449. String& name)
  216450. {
  216451. int index = 0;
  216452. ComSmartPtr <IBaseFilter> result;
  216453. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216454. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216455. if (SUCCEEDED (hr))
  216456. {
  216457. ComSmartPtr <IEnumMoniker> enumerator;
  216458. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216459. if (SUCCEEDED (hr) && enumerator != 0)
  216460. {
  216461. ComSmartPtr <IMoniker> moniker;
  216462. ULONG fetched;
  216463. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216464. {
  216465. ComSmartPtr <IBaseFilter> captureFilter;
  216466. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216467. if (SUCCEEDED (hr))
  216468. {
  216469. ComSmartPtr <IPropertyBag> propertyBag;
  216470. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216471. if (SUCCEEDED (hr))
  216472. {
  216473. VARIANT var;
  216474. var.vt = VT_BSTR;
  216475. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216476. propertyBag = 0;
  216477. if (SUCCEEDED (hr))
  216478. {
  216479. if (names != 0)
  216480. names->add (var.bstrVal);
  216481. if (index == deviceIndexToOpen)
  216482. {
  216483. name = var.bstrVal;
  216484. result = captureFilter;
  216485. break;
  216486. }
  216487. ++index;
  216488. }
  216489. }
  216490. }
  216491. }
  216492. }
  216493. }
  216494. return result;
  216495. }
  216496. }
  216497. const StringArray CameraDevice::getAvailableDevices()
  216498. {
  216499. StringArray devs;
  216500. String dummy;
  216501. enumerateCameras (&devs, -1, dummy);
  216502. return devs;
  216503. }
  216504. CameraDevice* CameraDevice::openDevice (int index,
  216505. int minWidth, int minHeight,
  216506. int maxWidth, int maxHeight)
  216507. {
  216508. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216509. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216510. if (SUCCEEDED (hr))
  216511. {
  216512. String name;
  216513. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216514. if (filter != 0)
  216515. {
  216516. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216517. DShowCameraDeviceInteral* const intern
  216518. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216519. minWidth, minHeight, maxWidth, maxHeight);
  216520. cam->internal = intern;
  216521. if (intern->ok)
  216522. return cam.release();
  216523. }
  216524. }
  216525. return 0;
  216526. }
  216527. #endif
  216528. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216529. #endif
  216530. // Auto-link the other win32 libs that are needed by library calls..
  216531. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216532. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216533. // Auto-links to various win32 libs that are needed by library calls..
  216534. #pragma comment(lib, "kernel32.lib")
  216535. #pragma comment(lib, "user32.lib")
  216536. #pragma comment(lib, "shell32.lib")
  216537. #pragma comment(lib, "gdi32.lib")
  216538. #pragma comment(lib, "vfw32.lib")
  216539. #pragma comment(lib, "comdlg32.lib")
  216540. #pragma comment(lib, "winmm.lib")
  216541. #pragma comment(lib, "wininet.lib")
  216542. #pragma comment(lib, "ole32.lib")
  216543. #pragma comment(lib, "oleaut32.lib")
  216544. #pragma comment(lib, "advapi32.lib")
  216545. #pragma comment(lib, "ws2_32.lib")
  216546. #pragma comment(lib, "version.lib")
  216547. #pragma comment(lib, "shlwapi.lib")
  216548. #ifdef _NATIVE_WCHAR_T_DEFINED
  216549. #ifdef _DEBUG
  216550. #pragma comment(lib, "comsuppwd.lib")
  216551. #else
  216552. #pragma comment(lib, "comsuppw.lib")
  216553. #endif
  216554. #else
  216555. #ifdef _DEBUG
  216556. #pragma comment(lib, "comsuppd.lib")
  216557. #else
  216558. #pragma comment(lib, "comsupp.lib")
  216559. #endif
  216560. #endif
  216561. #if JUCE_OPENGL
  216562. #pragma comment(lib, "OpenGL32.Lib")
  216563. #pragma comment(lib, "GlU32.Lib")
  216564. #endif
  216565. #if JUCE_QUICKTIME
  216566. #pragma comment (lib, "QTMLClient.lib")
  216567. #endif
  216568. #if JUCE_USE_CAMERA
  216569. #pragma comment (lib, "Strmiids.lib")
  216570. #pragma comment (lib, "wmvcore.lib")
  216571. #endif
  216572. #if JUCE_DIRECT2D
  216573. #pragma comment (lib, "Dwrite.lib")
  216574. #pragma comment (lib, "D2d1.lib")
  216575. #endif
  216576. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216577. #endif
  216578. END_JUCE_NAMESPACE
  216579. #endif
  216580. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216581. #elif JUCE_LINUX
  216582. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216583. /*
  216584. This file wraps together all the mac-specific code, so that
  216585. we can include all the native headers just once, and compile all our
  216586. platform-specific stuff in one big lump, keeping it out of the way of
  216587. the rest of the codebase.
  216588. */
  216589. #if JUCE_LINUX
  216590. #undef JUCE_BUILD_NATIVE
  216591. #define JUCE_BUILD_NATIVE 1
  216592. BEGIN_JUCE_NAMESPACE
  216593. #define JUCE_INCLUDED_FILE 1
  216594. // Now include the actual code files..
  216595. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216596. /*
  216597. This file contains posix routines that are common to both the Linux and Mac builds.
  216598. It gets included directly in the cpp files for these platforms.
  216599. */
  216600. CriticalSection::CriticalSection() throw()
  216601. {
  216602. pthread_mutexattr_t atts;
  216603. pthread_mutexattr_init (&atts);
  216604. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216605. #if ! JUCE_ANDROID
  216606. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216607. #endif
  216608. pthread_mutex_init (&internal, &atts);
  216609. }
  216610. CriticalSection::~CriticalSection() throw()
  216611. {
  216612. pthread_mutex_destroy (&internal);
  216613. }
  216614. void CriticalSection::enter() const throw()
  216615. {
  216616. pthread_mutex_lock (&internal);
  216617. }
  216618. bool CriticalSection::tryEnter() const throw()
  216619. {
  216620. return pthread_mutex_trylock (&internal) == 0;
  216621. }
  216622. void CriticalSection::exit() const throw()
  216623. {
  216624. pthread_mutex_unlock (&internal);
  216625. }
  216626. class WaitableEventImpl
  216627. {
  216628. public:
  216629. WaitableEventImpl (const bool manualReset_)
  216630. : triggered (false),
  216631. manualReset (manualReset_)
  216632. {
  216633. pthread_cond_init (&condition, 0);
  216634. pthread_mutexattr_t atts;
  216635. pthread_mutexattr_init (&atts);
  216636. #if ! JUCE_ANDROID
  216637. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216638. #endif
  216639. pthread_mutex_init (&mutex, &atts);
  216640. }
  216641. ~WaitableEventImpl()
  216642. {
  216643. pthread_cond_destroy (&condition);
  216644. pthread_mutex_destroy (&mutex);
  216645. }
  216646. bool wait (const int timeOutMillisecs) throw()
  216647. {
  216648. pthread_mutex_lock (&mutex);
  216649. if (! triggered)
  216650. {
  216651. if (timeOutMillisecs < 0)
  216652. {
  216653. do
  216654. {
  216655. pthread_cond_wait (&condition, &mutex);
  216656. }
  216657. while (! triggered);
  216658. }
  216659. else
  216660. {
  216661. struct timeval now;
  216662. gettimeofday (&now, 0);
  216663. struct timespec time;
  216664. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216665. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216666. if (time.tv_nsec >= 1000000000)
  216667. {
  216668. time.tv_nsec -= 1000000000;
  216669. time.tv_sec++;
  216670. }
  216671. do
  216672. {
  216673. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216674. {
  216675. pthread_mutex_unlock (&mutex);
  216676. return false;
  216677. }
  216678. }
  216679. while (! triggered);
  216680. }
  216681. }
  216682. if (! manualReset)
  216683. triggered = false;
  216684. pthread_mutex_unlock (&mutex);
  216685. return true;
  216686. }
  216687. void signal() throw()
  216688. {
  216689. pthread_mutex_lock (&mutex);
  216690. triggered = true;
  216691. pthread_cond_broadcast (&condition);
  216692. pthread_mutex_unlock (&mutex);
  216693. }
  216694. void reset() throw()
  216695. {
  216696. pthread_mutex_lock (&mutex);
  216697. triggered = false;
  216698. pthread_mutex_unlock (&mutex);
  216699. }
  216700. private:
  216701. pthread_cond_t condition;
  216702. pthread_mutex_t mutex;
  216703. bool triggered;
  216704. const bool manualReset;
  216705. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216706. };
  216707. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216708. : internal (new WaitableEventImpl (manualReset))
  216709. {
  216710. }
  216711. WaitableEvent::~WaitableEvent() throw()
  216712. {
  216713. delete static_cast <WaitableEventImpl*> (internal);
  216714. }
  216715. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216716. {
  216717. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216718. }
  216719. void WaitableEvent::signal() const throw()
  216720. {
  216721. static_cast <WaitableEventImpl*> (internal)->signal();
  216722. }
  216723. void WaitableEvent::reset() const throw()
  216724. {
  216725. static_cast <WaitableEventImpl*> (internal)->reset();
  216726. }
  216727. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216728. {
  216729. struct timespec time;
  216730. time.tv_sec = millisecs / 1000;
  216731. time.tv_nsec = (millisecs % 1000) * 1000000;
  216732. nanosleep (&time, 0);
  216733. }
  216734. const juce_wchar File::separator = '/';
  216735. const String File::separatorString ("/");
  216736. const File File::getCurrentWorkingDirectory()
  216737. {
  216738. HeapBlock<char> heapBuffer;
  216739. char localBuffer [1024];
  216740. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216741. int bufferSize = 4096;
  216742. while (cwd == 0 && errno == ERANGE)
  216743. {
  216744. heapBuffer.malloc (bufferSize);
  216745. cwd = getcwd (heapBuffer, bufferSize - 1);
  216746. bufferSize += 1024;
  216747. }
  216748. return File (String::fromUTF8 (cwd));
  216749. }
  216750. bool File::setAsCurrentWorkingDirectory() const
  216751. {
  216752. return chdir (getFullPathName().toUTF8()) == 0;
  216753. }
  216754. namespace
  216755. {
  216756. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216757. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216758. #else
  216759. typedef struct stat juce_statStruct;
  216760. #endif
  216761. bool juce_stat (const String& fileName, juce_statStruct& info)
  216762. {
  216763. return fileName.isNotEmpty()
  216764. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216765. && (stat64 (fileName.toUTF8(), &info) == 0);
  216766. #else
  216767. && (stat (fileName.toUTF8(), &info) == 0);
  216768. #endif
  216769. }
  216770. // if this file doesn't exist, find a parent of it that does..
  216771. bool juce_doStatFS (File f, struct statfs& result)
  216772. {
  216773. for (int i = 5; --i >= 0;)
  216774. {
  216775. if (f.exists())
  216776. break;
  216777. f = f.getParentDirectory();
  216778. }
  216779. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216780. }
  216781. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216782. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216783. {
  216784. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216785. {
  216786. juce_statStruct info;
  216787. const bool statOk = juce_stat (path, info);
  216788. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216789. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216790. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216791. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216792. }
  216793. if (isReadOnly != 0)
  216794. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216795. }
  216796. }
  216797. bool File::isDirectory() const
  216798. {
  216799. juce_statStruct info;
  216800. return fullPath.isEmpty()
  216801. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216802. }
  216803. bool File::exists() const
  216804. {
  216805. juce_statStruct info;
  216806. return fullPath.isNotEmpty()
  216807. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216808. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216809. #else
  216810. && (lstat (fullPath.toUTF8(), &info) == 0);
  216811. #endif
  216812. }
  216813. bool File::existsAsFile() const
  216814. {
  216815. return exists() && ! isDirectory();
  216816. }
  216817. int64 File::getSize() const
  216818. {
  216819. juce_statStruct info;
  216820. return juce_stat (fullPath, info) ? info.st_size : 0;
  216821. }
  216822. bool File::hasWriteAccess() const
  216823. {
  216824. if (exists())
  216825. return access (fullPath.toUTF8(), W_OK) == 0;
  216826. if ((! isDirectory()) && fullPath.containsChar (separator))
  216827. return getParentDirectory().hasWriteAccess();
  216828. return false;
  216829. }
  216830. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216831. {
  216832. juce_statStruct info;
  216833. if (! juce_stat (fullPath, info))
  216834. return false;
  216835. info.st_mode &= 0777; // Just permissions
  216836. if (shouldBeReadOnly)
  216837. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216838. else
  216839. // Give everybody write permission?
  216840. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216841. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216842. }
  216843. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216844. {
  216845. modificationTime = 0;
  216846. accessTime = 0;
  216847. creationTime = 0;
  216848. juce_statStruct info;
  216849. if (juce_stat (fullPath, info))
  216850. {
  216851. modificationTime = (int64) info.st_mtime * 1000;
  216852. accessTime = (int64) info.st_atime * 1000;
  216853. creationTime = (int64) info.st_ctime * 1000;
  216854. }
  216855. }
  216856. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216857. {
  216858. juce_statStruct info;
  216859. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216860. {
  216861. struct utimbuf times;
  216862. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216863. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216864. return utime (fullPath.toUTF8(), &times) == 0;
  216865. }
  216866. return false;
  216867. }
  216868. bool File::deleteFile() const
  216869. {
  216870. if (! exists())
  216871. return true;
  216872. if (isDirectory())
  216873. return rmdir (fullPath.toUTF8()) == 0;
  216874. return remove (fullPath.toUTF8()) == 0;
  216875. }
  216876. bool File::moveInternal (const File& dest) const
  216877. {
  216878. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216879. return true;
  216880. if (hasWriteAccess() && copyInternal (dest))
  216881. {
  216882. if (deleteFile())
  216883. return true;
  216884. dest.deleteFile();
  216885. }
  216886. return false;
  216887. }
  216888. void File::createDirectoryInternal (const String& fileName) const
  216889. {
  216890. mkdir (fileName.toUTF8(), 0777);
  216891. }
  216892. int64 juce_fileSetPosition (void* handle, int64 pos)
  216893. {
  216894. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216895. return pos;
  216896. return -1;
  216897. }
  216898. void FileInputStream::openHandle()
  216899. {
  216900. totalSize = file.getSize();
  216901. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216902. if (f != -1)
  216903. fileHandle = (void*) f;
  216904. }
  216905. void FileInputStream::closeHandle()
  216906. {
  216907. if (fileHandle != 0)
  216908. {
  216909. close ((int) (pointer_sized_int) fileHandle);
  216910. fileHandle = 0;
  216911. }
  216912. }
  216913. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216914. {
  216915. if (fileHandle != 0)
  216916. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216917. return 0;
  216918. }
  216919. void FileOutputStream::openHandle()
  216920. {
  216921. if (file.exists())
  216922. {
  216923. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216924. if (f != -1)
  216925. {
  216926. currentPosition = lseek (f, 0, SEEK_END);
  216927. if (currentPosition >= 0)
  216928. fileHandle = (void*) f;
  216929. else
  216930. close (f);
  216931. }
  216932. }
  216933. else
  216934. {
  216935. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216936. if (f != -1)
  216937. fileHandle = (void*) f;
  216938. }
  216939. }
  216940. void FileOutputStream::closeHandle()
  216941. {
  216942. if (fileHandle != 0)
  216943. {
  216944. close ((int) (pointer_sized_int) fileHandle);
  216945. fileHandle = 0;
  216946. }
  216947. }
  216948. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216949. {
  216950. if (fileHandle != 0)
  216951. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216952. return 0;
  216953. }
  216954. void FileOutputStream::flushInternal()
  216955. {
  216956. if (fileHandle != 0)
  216957. fsync ((int) (pointer_sized_int) fileHandle);
  216958. }
  216959. const File juce_getExecutableFile()
  216960. {
  216961. #if JUCE_ANDROID
  216962. return File (android.appFile);
  216963. #else
  216964. Dl_info exeInfo;
  216965. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216966. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216967. #endif
  216968. }
  216969. int64 File::getBytesFreeOnVolume() const
  216970. {
  216971. struct statfs buf;
  216972. if (juce_doStatFS (*this, buf))
  216973. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216974. return 0;
  216975. }
  216976. int64 File::getVolumeTotalSize() const
  216977. {
  216978. struct statfs buf;
  216979. if (juce_doStatFS (*this, buf))
  216980. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216981. return 0;
  216982. }
  216983. const String File::getVolumeLabel() const
  216984. {
  216985. #if JUCE_MAC
  216986. struct VolAttrBuf
  216987. {
  216988. u_int32_t length;
  216989. attrreference_t mountPointRef;
  216990. char mountPointSpace [MAXPATHLEN];
  216991. } attrBuf;
  216992. struct attrlist attrList;
  216993. zerostruct (attrList);
  216994. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216995. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216996. File f (*this);
  216997. for (;;)
  216998. {
  216999. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217000. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217001. (int) attrBuf.mountPointRef.attr_length);
  217002. const File parent (f.getParentDirectory());
  217003. if (f == parent)
  217004. break;
  217005. f = parent;
  217006. }
  217007. #endif
  217008. return String::empty;
  217009. }
  217010. int File::getVolumeSerialNumber() const
  217011. {
  217012. int result = 0;
  217013. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  217014. char info [512];
  217015. #ifndef HDIO_GET_IDENTITY
  217016. #define HDIO_GET_IDENTITY 0x030d
  217017. #endif
  217018. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  217019. {
  217020. DBG (String (info + 20, 20));
  217021. result = String (info + 20, 20).trim().getIntValue();
  217022. }
  217023. close (fd);*/
  217024. return result;
  217025. }
  217026. void juce_runSystemCommand (const String& command)
  217027. {
  217028. int result = system (command.toUTF8());
  217029. (void) result;
  217030. }
  217031. const String juce_getOutputFromCommand (const String& command)
  217032. {
  217033. // slight bodge here, as we just pipe the output into a temp file and read it...
  217034. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217035. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217036. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217037. String result (tempFile.loadFileAsString());
  217038. tempFile.deleteFile();
  217039. return result;
  217040. }
  217041. class InterProcessLock::Pimpl
  217042. {
  217043. public:
  217044. Pimpl (const String& name, const int timeOutMillisecs)
  217045. : handle (0), refCount (1)
  217046. {
  217047. #if JUCE_MAC
  217048. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217049. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217050. #else
  217051. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217052. #endif
  217053. temp.create();
  217054. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217055. if (handle != 0)
  217056. {
  217057. struct flock fl;
  217058. zerostruct (fl);
  217059. fl.l_whence = SEEK_SET;
  217060. fl.l_type = F_WRLCK;
  217061. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217062. for (;;)
  217063. {
  217064. const int result = fcntl (handle, F_SETLK, &fl);
  217065. if (result >= 0)
  217066. return;
  217067. if (errno != EINTR)
  217068. {
  217069. if (timeOutMillisecs == 0
  217070. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217071. break;
  217072. Thread::sleep (10);
  217073. }
  217074. }
  217075. }
  217076. closeFile();
  217077. }
  217078. ~Pimpl()
  217079. {
  217080. closeFile();
  217081. }
  217082. void closeFile()
  217083. {
  217084. if (handle != 0)
  217085. {
  217086. struct flock fl;
  217087. zerostruct (fl);
  217088. fl.l_whence = SEEK_SET;
  217089. fl.l_type = F_UNLCK;
  217090. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217091. {}
  217092. close (handle);
  217093. handle = 0;
  217094. }
  217095. }
  217096. int handle, refCount;
  217097. };
  217098. InterProcessLock::InterProcessLock (const String& name_)
  217099. : name (name_)
  217100. {
  217101. }
  217102. InterProcessLock::~InterProcessLock()
  217103. {
  217104. }
  217105. bool InterProcessLock::enter (const int timeOutMillisecs)
  217106. {
  217107. const ScopedLock sl (lock);
  217108. if (pimpl == 0)
  217109. {
  217110. pimpl = new Pimpl (name, timeOutMillisecs);
  217111. if (pimpl->handle == 0)
  217112. pimpl = 0;
  217113. }
  217114. else
  217115. {
  217116. pimpl->refCount++;
  217117. }
  217118. return pimpl != 0;
  217119. }
  217120. void InterProcessLock::exit()
  217121. {
  217122. const ScopedLock sl (lock);
  217123. // Trying to release the lock too many times!
  217124. jassert (pimpl != 0);
  217125. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217126. pimpl = 0;
  217127. }
  217128. void JUCE_API juce_threadEntryPoint (void*);
  217129. void* threadEntryProc (void* userData)
  217130. {
  217131. JUCE_AUTORELEASEPOOL
  217132. #if JUCE_ANDROID
  217133. const AndroidThreadScope androidEnv;
  217134. #endif
  217135. juce_threadEntryPoint (userData);
  217136. return 0;
  217137. }
  217138. void Thread::launchThread()
  217139. {
  217140. threadHandle_ = 0;
  217141. pthread_t handle = 0;
  217142. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  217143. {
  217144. pthread_detach (handle);
  217145. threadHandle_ = (void*) handle;
  217146. threadId_ = (ThreadID) threadHandle_;
  217147. }
  217148. }
  217149. void Thread::closeThreadHandle()
  217150. {
  217151. threadId_ = 0;
  217152. threadHandle_ = 0;
  217153. }
  217154. void Thread::killThread()
  217155. {
  217156. if (threadHandle_ != 0)
  217157. {
  217158. #if JUCE_ANDROID
  217159. jassertfalse; // pthread_cancel not available!
  217160. #else
  217161. pthread_cancel ((pthread_t) threadHandle_);
  217162. #endif
  217163. }
  217164. }
  217165. void Thread::setCurrentThreadName (const String& name)
  217166. {
  217167. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  217168. pthread_setname_np (name.toUTF8());
  217169. #elif JUCE_LINUX
  217170. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  217171. #endif
  217172. }
  217173. bool Thread::setThreadPriority (void* handle, int priority)
  217174. {
  217175. struct sched_param param;
  217176. int policy;
  217177. priority = jlimit (0, 10, priority);
  217178. if (handle == 0)
  217179. handle = (void*) pthread_self();
  217180. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217181. return false;
  217182. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217183. const int minPriority = sched_get_priority_min (policy);
  217184. const int maxPriority = sched_get_priority_max (policy);
  217185. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217186. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217187. }
  217188. Thread::ThreadID Thread::getCurrentThreadId()
  217189. {
  217190. return (ThreadID) pthread_self();
  217191. }
  217192. void Thread::yield()
  217193. {
  217194. sched_yield();
  217195. }
  217196. /* Remove this macro if you're having problems compiling the cpu affinity
  217197. calls (the API for these has changed about quite a bit in various Linux
  217198. versions, and a lot of distros seem to ship with obsolete versions)
  217199. */
  217200. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217201. #define SUPPORT_AFFINITIES 1
  217202. #endif
  217203. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217204. {
  217205. #if SUPPORT_AFFINITIES
  217206. cpu_set_t affinity;
  217207. CPU_ZERO (&affinity);
  217208. for (int i = 0; i < 32; ++i)
  217209. if ((affinityMask & (1 << i)) != 0)
  217210. CPU_SET (i, &affinity);
  217211. /*
  217212. N.B. If this line causes a compile error, then you've probably not got the latest
  217213. version of glibc installed.
  217214. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217215. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217216. */
  217217. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217218. sched_yield();
  217219. #else
  217220. /* affinities aren't supported because either the appropriate header files weren't found,
  217221. or the SUPPORT_AFFINITIES macro was turned off
  217222. */
  217223. jassertfalse;
  217224. (void) affinityMask;
  217225. #endif
  217226. }
  217227. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217228. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217229. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217230. // compiled on its own).
  217231. #if JUCE_INCLUDED_FILE
  217232. enum
  217233. {
  217234. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217235. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217236. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217237. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217238. };
  217239. bool File::copyInternal (const File& dest) const
  217240. {
  217241. FileInputStream in (*this);
  217242. if (dest.deleteFile())
  217243. {
  217244. {
  217245. FileOutputStream out (dest);
  217246. if (out.failedToOpen())
  217247. return false;
  217248. if (out.writeFromInputStream (in, -1) == getSize())
  217249. return true;
  217250. }
  217251. dest.deleteFile();
  217252. }
  217253. return false;
  217254. }
  217255. void File::findFileSystemRoots (Array<File>& destArray)
  217256. {
  217257. destArray.add (File ("/"));
  217258. }
  217259. bool File::isOnCDRomDrive() const
  217260. {
  217261. struct statfs buf;
  217262. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217263. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217264. }
  217265. bool File::isOnHardDisk() const
  217266. {
  217267. struct statfs buf;
  217268. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217269. {
  217270. switch (buf.f_type)
  217271. {
  217272. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217273. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217274. case U_NFS_SUPER_MAGIC: // Network NFS
  217275. case U_SMB_SUPER_MAGIC: // Network Samba
  217276. return false;
  217277. default:
  217278. // Assume anything else is a hard-disk (but note it could
  217279. // be a RAM disk. There isn't a good way of determining
  217280. // this for sure)
  217281. return true;
  217282. }
  217283. }
  217284. // Assume so if this fails for some reason
  217285. return true;
  217286. }
  217287. bool File::isOnRemovableDrive() const
  217288. {
  217289. jassertfalse; // xxx not implemented for linux!
  217290. return false;
  217291. }
  217292. bool File::isHidden() const
  217293. {
  217294. return getFileName().startsWithChar ('.');
  217295. }
  217296. namespace
  217297. {
  217298. const File juce_readlink (const String& file, const File& defaultFile)
  217299. {
  217300. const int size = 8192;
  217301. HeapBlock<char> buffer;
  217302. buffer.malloc (size + 4);
  217303. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217304. if (numBytes > 0 && numBytes <= size)
  217305. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217306. return defaultFile;
  217307. }
  217308. }
  217309. const File File::getLinkedTarget() const
  217310. {
  217311. return juce_readlink (getFullPathName().toUTF8(), *this);
  217312. }
  217313. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217314. const File File::getSpecialLocation (const SpecialLocationType type)
  217315. {
  217316. switch (type)
  217317. {
  217318. case userHomeDirectory:
  217319. {
  217320. const char* homeDir = getenv ("HOME");
  217321. if (homeDir == 0)
  217322. {
  217323. struct passwd* const pw = getpwuid (getuid());
  217324. if (pw != 0)
  217325. homeDir = pw->pw_dir;
  217326. }
  217327. return File (String::fromUTF8 (homeDir));
  217328. }
  217329. case userDocumentsDirectory:
  217330. case userMusicDirectory:
  217331. case userMoviesDirectory:
  217332. case userApplicationDataDirectory:
  217333. return File ("~");
  217334. case userDesktopDirectory:
  217335. return File ("~/Desktop");
  217336. case commonApplicationDataDirectory:
  217337. return File ("/var");
  217338. case globalApplicationsDirectory:
  217339. return File ("/usr");
  217340. case tempDirectory:
  217341. {
  217342. File tmp ("/var/tmp");
  217343. if (! tmp.isDirectory())
  217344. {
  217345. tmp = "/tmp";
  217346. if (! tmp.isDirectory())
  217347. tmp = File::getCurrentWorkingDirectory();
  217348. }
  217349. return tmp;
  217350. }
  217351. case invokedExecutableFile:
  217352. if (juce_Argv0 != 0)
  217353. return File (String::fromUTF8 (juce_Argv0));
  217354. // deliberate fall-through...
  217355. case currentExecutableFile:
  217356. case currentApplicationFile:
  217357. return juce_getExecutableFile();
  217358. case hostApplicationPath:
  217359. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217360. default:
  217361. jassertfalse; // unknown type?
  217362. break;
  217363. }
  217364. return File::nonexistent;
  217365. }
  217366. const String File::getVersion() const
  217367. {
  217368. return String::empty; // xxx not yet implemented
  217369. }
  217370. bool File::moveToTrash() const
  217371. {
  217372. if (! exists())
  217373. return true;
  217374. File trashCan ("~/.Trash");
  217375. if (! trashCan.isDirectory())
  217376. trashCan = "~/.local/share/Trash/files";
  217377. if (! trashCan.isDirectory())
  217378. return false;
  217379. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217380. getFileExtension()));
  217381. }
  217382. class DirectoryIterator::NativeIterator::Pimpl
  217383. {
  217384. public:
  217385. Pimpl (const File& directory, const String& wildCard_)
  217386. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217387. wildCard (wildCard_),
  217388. dir (opendir (directory.getFullPathName().toUTF8()))
  217389. {
  217390. wildcardUTF8 = wildCard.toUTF8();
  217391. }
  217392. ~Pimpl()
  217393. {
  217394. if (dir != 0)
  217395. closedir (dir);
  217396. }
  217397. bool next (String& filenameFound,
  217398. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217399. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217400. {
  217401. if (dir != 0)
  217402. {
  217403. for (;;)
  217404. {
  217405. struct dirent* const de = readdir (dir);
  217406. if (de == 0)
  217407. break;
  217408. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217409. {
  217410. filenameFound = String::fromUTF8 (de->d_name);
  217411. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  217412. if (isHidden != 0)
  217413. *isHidden = filenameFound.startsWithChar ('.');
  217414. return true;
  217415. }
  217416. }
  217417. }
  217418. return false;
  217419. }
  217420. private:
  217421. String parentDir, wildCard;
  217422. const char* wildcardUTF8;
  217423. DIR* dir;
  217424. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217425. };
  217426. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217427. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217428. {
  217429. }
  217430. DirectoryIterator::NativeIterator::~NativeIterator()
  217431. {
  217432. }
  217433. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217434. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217435. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217436. {
  217437. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217438. }
  217439. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217440. {
  217441. String cmdString (fileName.replace (" ", "\\ ",false));
  217442. cmdString << " " << parameters;
  217443. if (URL::isProbablyAWebsiteURL (fileName)
  217444. || cmdString.startsWithIgnoreCase ("file:")
  217445. || URL::isProbablyAnEmailAddress (fileName))
  217446. {
  217447. // create a command that tries to launch a bunch of likely browsers
  217448. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217449. StringArray cmdLines;
  217450. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217451. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217452. cmdString = cmdLines.joinIntoString (" || ");
  217453. }
  217454. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217455. const int cpid = fork();
  217456. if (cpid == 0)
  217457. {
  217458. setsid();
  217459. // Child process
  217460. execve (argv[0], (char**) argv, environ);
  217461. exit (0);
  217462. }
  217463. return cpid >= 0;
  217464. }
  217465. void File::revealToUser() const
  217466. {
  217467. if (isDirectory())
  217468. startAsProcess();
  217469. else if (getParentDirectory().exists())
  217470. getParentDirectory().startAsProcess();
  217471. }
  217472. #endif
  217473. /*** End of inlined file: juce_linux_Files.cpp ***/
  217474. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217475. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217476. // compiled on its own).
  217477. #if JUCE_INCLUDED_FILE
  217478. struct NamedPipeInternal
  217479. {
  217480. String pipeInName, pipeOutName;
  217481. int pipeIn, pipeOut;
  217482. bool volatile createdPipe, blocked, stopReadOperation;
  217483. static void signalHandler (int) {}
  217484. };
  217485. void NamedPipe::cancelPendingReads()
  217486. {
  217487. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217488. {
  217489. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217490. intern->stopReadOperation = true;
  217491. char buffer [1] = { 0 };
  217492. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217493. (void) bytesWritten;
  217494. int timeout = 2000;
  217495. while (intern->blocked && --timeout >= 0)
  217496. Thread::sleep (2);
  217497. intern->stopReadOperation = false;
  217498. }
  217499. }
  217500. void NamedPipe::close()
  217501. {
  217502. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217503. if (intern != 0)
  217504. {
  217505. internal = 0;
  217506. if (intern->pipeIn != -1)
  217507. ::close (intern->pipeIn);
  217508. if (intern->pipeOut != -1)
  217509. ::close (intern->pipeOut);
  217510. if (intern->createdPipe)
  217511. {
  217512. unlink (intern->pipeInName.toUTF8());
  217513. unlink (intern->pipeOutName.toUTF8());
  217514. }
  217515. delete intern;
  217516. }
  217517. }
  217518. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217519. {
  217520. close();
  217521. NamedPipeInternal* const intern = new NamedPipeInternal();
  217522. internal = intern;
  217523. intern->createdPipe = createPipe;
  217524. intern->blocked = false;
  217525. intern->stopReadOperation = false;
  217526. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217527. siginterrupt (SIGPIPE, 1);
  217528. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217529. intern->pipeInName = pipePath + "_in";
  217530. intern->pipeOutName = pipePath + "_out";
  217531. intern->pipeIn = -1;
  217532. intern->pipeOut = -1;
  217533. if (createPipe)
  217534. {
  217535. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217536. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217537. {
  217538. delete intern;
  217539. internal = 0;
  217540. return false;
  217541. }
  217542. }
  217543. return true;
  217544. }
  217545. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217546. {
  217547. int bytesRead = -1;
  217548. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217549. if (intern != 0)
  217550. {
  217551. intern->blocked = true;
  217552. if (intern->pipeIn == -1)
  217553. {
  217554. if (intern->createdPipe)
  217555. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217556. else
  217557. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217558. if (intern->pipeIn == -1)
  217559. {
  217560. intern->blocked = false;
  217561. return -1;
  217562. }
  217563. }
  217564. bytesRead = 0;
  217565. char* p = static_cast<char*> (destBuffer);
  217566. while (bytesRead < maxBytesToRead)
  217567. {
  217568. const int bytesThisTime = maxBytesToRead - bytesRead;
  217569. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217570. if (numRead <= 0 || intern->stopReadOperation)
  217571. {
  217572. bytesRead = -1;
  217573. break;
  217574. }
  217575. bytesRead += numRead;
  217576. p += bytesRead;
  217577. }
  217578. intern->blocked = false;
  217579. }
  217580. return bytesRead;
  217581. }
  217582. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217583. {
  217584. int bytesWritten = -1;
  217585. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217586. if (intern != 0)
  217587. {
  217588. if (intern->pipeOut == -1)
  217589. {
  217590. if (intern->createdPipe)
  217591. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217592. else
  217593. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217594. if (intern->pipeOut == -1)
  217595. {
  217596. return -1;
  217597. }
  217598. }
  217599. const char* p = static_cast<const char*> (sourceBuffer);
  217600. bytesWritten = 0;
  217601. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217602. while (bytesWritten < numBytesToWrite
  217603. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217604. {
  217605. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217606. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217607. if (numWritten <= 0)
  217608. {
  217609. bytesWritten = -1;
  217610. break;
  217611. }
  217612. bytesWritten += numWritten;
  217613. p += bytesWritten;
  217614. }
  217615. }
  217616. return bytesWritten;
  217617. }
  217618. #endif
  217619. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217620. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217621. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217622. // compiled on its own).
  217623. #if JUCE_INCLUDED_FILE
  217624. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217625. {
  217626. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217627. if (s != -1)
  217628. {
  217629. char buf [1024];
  217630. struct ifconf ifc;
  217631. ifc.ifc_len = sizeof (buf);
  217632. ifc.ifc_buf = buf;
  217633. ioctl (s, SIOCGIFCONF, &ifc);
  217634. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217635. {
  217636. struct ifreq ifr;
  217637. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217638. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217639. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217640. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217641. {
  217642. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217643. }
  217644. }
  217645. close (s);
  217646. }
  217647. }
  217648. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217649. const String& emailSubject,
  217650. const String& bodyText,
  217651. const StringArray& filesToAttach)
  217652. {
  217653. jassertfalse; // xxx todo
  217654. return false;
  217655. }
  217656. class WebInputStream : public InputStream
  217657. {
  217658. public:
  217659. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217660. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217661. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217662. : socketHandle (-1), levelsOfRedirection (0),
  217663. address (address_), headers (headers_), postData (postData_), position (0),
  217664. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217665. {
  217666. createConnection (progressCallback, progressCallbackContext);
  217667. if (responseHeaders != 0 && ! isError())
  217668. {
  217669. for (int i = 0; i < headerLines.size(); ++i)
  217670. {
  217671. const String& headersEntry = headerLines[i];
  217672. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217673. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217674. const String previousValue ((*responseHeaders) [key]);
  217675. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217676. }
  217677. }
  217678. }
  217679. ~WebInputStream()
  217680. {
  217681. closeSocket();
  217682. }
  217683. bool isError() const { return socketHandle < 0; }
  217684. bool isExhausted() { return finished; }
  217685. int64 getPosition() { return position; }
  217686. int64 getTotalLength()
  217687. {
  217688. jassertfalse; //xxx to do
  217689. return -1;
  217690. }
  217691. int read (void* buffer, int bytesToRead)
  217692. {
  217693. if (finished || isError())
  217694. return 0;
  217695. fd_set readbits;
  217696. FD_ZERO (&readbits);
  217697. FD_SET (socketHandle, &readbits);
  217698. struct timeval tv;
  217699. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217700. tv.tv_usec = 0;
  217701. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217702. return 0; // (timeout)
  217703. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217704. if (bytesRead == 0)
  217705. finished = true;
  217706. position += bytesRead;
  217707. return bytesRead;
  217708. }
  217709. bool setPosition (int64 wantedPos)
  217710. {
  217711. if (isError())
  217712. return false;
  217713. if (wantedPos != position)
  217714. {
  217715. finished = false;
  217716. if (wantedPos < position)
  217717. {
  217718. closeSocket();
  217719. position = 0;
  217720. createConnection (0, 0);
  217721. }
  217722. skipNextBytes (wantedPos - position);
  217723. }
  217724. return true;
  217725. }
  217726. private:
  217727. int socketHandle, levelsOfRedirection;
  217728. StringArray headerLines;
  217729. String address, headers;
  217730. MemoryBlock postData;
  217731. int64 position;
  217732. bool finished;
  217733. const bool isPost;
  217734. const int timeOutMs;
  217735. void closeSocket()
  217736. {
  217737. if (socketHandle >= 0)
  217738. close (socketHandle);
  217739. socketHandle = -1;
  217740. levelsOfRedirection = 0;
  217741. }
  217742. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217743. {
  217744. closeSocket();
  217745. uint32 timeOutTime = Time::getMillisecondCounter();
  217746. if (timeOutMs == 0)
  217747. timeOutTime += 60000;
  217748. else if (timeOutMs < 0)
  217749. timeOutTime = 0xffffffff;
  217750. else
  217751. timeOutTime += timeOutMs;
  217752. String hostName, hostPath;
  217753. int hostPort;
  217754. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217755. return;
  217756. const struct hostent* host = 0;
  217757. int port = 0;
  217758. String proxyName, proxyPath;
  217759. int proxyPort = 0;
  217760. String proxyURL (getenv ("http_proxy"));
  217761. if (proxyURL.startsWithIgnoreCase ("http://"))
  217762. {
  217763. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217764. return;
  217765. host = gethostbyname (proxyName.toUTF8());
  217766. port = proxyPort;
  217767. }
  217768. else
  217769. {
  217770. host = gethostbyname (hostName.toUTF8());
  217771. port = hostPort;
  217772. }
  217773. if (host == 0)
  217774. return;
  217775. {
  217776. struct sockaddr_in socketAddress;
  217777. zerostruct (socketAddress);
  217778. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217779. socketAddress.sin_family = host->h_addrtype;
  217780. socketAddress.sin_port = htons (port);
  217781. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217782. if (socketHandle == -1)
  217783. return;
  217784. int receiveBufferSize = 16384;
  217785. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217786. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217787. #if JUCE_MAC
  217788. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217789. #endif
  217790. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217791. {
  217792. closeSocket();
  217793. return;
  217794. }
  217795. }
  217796. {
  217797. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217798. hostPath, address, headers, postData, isPost));
  217799. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217800. {
  217801. closeSocket();
  217802. return;
  217803. }
  217804. }
  217805. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217806. if (responseHeader.isNotEmpty())
  217807. {
  217808. headerLines.clear();
  217809. headerLines.addLines (responseHeader);
  217810. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217811. .substring (0, 3).getIntValue();
  217812. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217813. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217814. String location (findHeaderItem (headerLines, "Location:"));
  217815. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217816. {
  217817. if (! location.startsWithIgnoreCase ("http://"))
  217818. location = "http://" + location;
  217819. if (++levelsOfRedirection <= 3)
  217820. {
  217821. address = location;
  217822. createConnection (progressCallback, progressCallbackContext);
  217823. return;
  217824. }
  217825. }
  217826. else
  217827. {
  217828. levelsOfRedirection = 0;
  217829. return;
  217830. }
  217831. }
  217832. closeSocket();
  217833. }
  217834. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217835. {
  217836. int bytesRead = 0, numConsecutiveLFs = 0;
  217837. MemoryBlock buffer (1024, true);
  217838. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217839. && Time::getMillisecondCounter() <= timeOutTime)
  217840. {
  217841. fd_set readbits;
  217842. FD_ZERO (&readbits);
  217843. FD_SET (socketHandle, &readbits);
  217844. struct timeval tv;
  217845. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217846. tv.tv_usec = 0;
  217847. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217848. return String::empty; // (timeout)
  217849. buffer.ensureSize (bytesRead + 8, true);
  217850. char* const dest = (char*) buffer.getData() + bytesRead;
  217851. if (recv (socketHandle, dest, 1, 0) == -1)
  217852. return String::empty;
  217853. const char lastByte = *dest;
  217854. ++bytesRead;
  217855. if (lastByte == '\n')
  217856. ++numConsecutiveLFs;
  217857. else if (lastByte != '\r')
  217858. numConsecutiveLFs = 0;
  217859. }
  217860. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217861. if (header.startsWithIgnoreCase ("HTTP/"))
  217862. return header.trimEnd();
  217863. return String::empty;
  217864. }
  217865. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217866. const String& proxyName, const int proxyPort,
  217867. const String& hostPath, const String& originalURL,
  217868. const String& headers, const MemoryBlock& postData,
  217869. const bool isPost)
  217870. {
  217871. String header (isPost ? "POST " : "GET ");
  217872. if (proxyName.isEmpty())
  217873. {
  217874. header << hostPath << " HTTP/1.0\r\nHost: "
  217875. << hostName << ':' << hostPort;
  217876. }
  217877. else
  217878. {
  217879. header << originalURL << " HTTP/1.0\r\nHost: "
  217880. << proxyName << ':' << proxyPort;
  217881. }
  217882. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217883. << "\r\nConnection: Close\r\nContent-Length: "
  217884. << (int) postData.getSize() << "\r\n"
  217885. << headers << "\r\n";
  217886. MemoryBlock mb;
  217887. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217888. mb.append (postData.getData(), postData.getSize());
  217889. return mb;
  217890. }
  217891. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217892. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217893. {
  217894. size_t totalHeaderSent = 0;
  217895. while (totalHeaderSent < requestHeader.getSize())
  217896. {
  217897. if (Time::getMillisecondCounter() > timeOutTime)
  217898. return false;
  217899. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217900. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217901. return false;
  217902. totalHeaderSent += numToSend;
  217903. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217904. return false;
  217905. }
  217906. return true;
  217907. }
  217908. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217909. {
  217910. if (! url.startsWithIgnoreCase ("http://"))
  217911. return false;
  217912. const int nextSlash = url.indexOfChar (7, '/');
  217913. int nextColon = url.indexOfChar (7, ':');
  217914. if (nextColon > nextSlash && nextSlash > 0)
  217915. nextColon = -1;
  217916. if (nextColon >= 0)
  217917. {
  217918. host = url.substring (7, nextColon);
  217919. if (nextSlash >= 0)
  217920. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217921. else
  217922. port = url.substring (nextColon + 1).getIntValue();
  217923. }
  217924. else
  217925. {
  217926. port = 80;
  217927. if (nextSlash >= 0)
  217928. host = url.substring (7, nextSlash);
  217929. else
  217930. host = url.substring (7);
  217931. }
  217932. if (nextSlash >= 0)
  217933. path = url.substring (nextSlash);
  217934. else
  217935. path = "/";
  217936. return true;
  217937. }
  217938. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217939. {
  217940. for (int i = 0; i < lines.size(); ++i)
  217941. if (lines[i].startsWithIgnoreCase (itemName))
  217942. return lines[i].substring (itemName.length()).trim();
  217943. return String::empty;
  217944. }
  217945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217946. };
  217947. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217948. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217949. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217950. {
  217951. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217952. progressCallback, progressCallbackContext,
  217953. headers, timeOutMs, responseHeaders));
  217954. return wi->isError() ? 0 : wi.release();
  217955. }
  217956. #endif
  217957. /*** End of inlined file: juce_linux_Network.cpp ***/
  217958. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217959. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217960. // compiled on its own).
  217961. #if JUCE_INCLUDED_FILE
  217962. void Logger::outputDebugString (const String& text)
  217963. {
  217964. std::cerr << text << std::endl;
  217965. }
  217966. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217967. {
  217968. return Linux;
  217969. }
  217970. const String SystemStats::getOperatingSystemName()
  217971. {
  217972. return "Linux";
  217973. }
  217974. bool SystemStats::isOperatingSystem64Bit()
  217975. {
  217976. #if JUCE_64BIT
  217977. return true;
  217978. #else
  217979. //xxx not sure how to find this out?..
  217980. return false;
  217981. #endif
  217982. }
  217983. namespace LinuxStatsHelpers
  217984. {
  217985. const String getCpuInfo (const char* const key)
  217986. {
  217987. StringArray lines;
  217988. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217989. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217990. if (lines[i].startsWithIgnoreCase (key))
  217991. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217992. return String::empty;
  217993. }
  217994. }
  217995. const String SystemStats::getCpuVendor()
  217996. {
  217997. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217998. }
  217999. int SystemStats::getCpuSpeedInMegaherz()
  218000. {
  218001. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218002. }
  218003. int SystemStats::getMemorySizeInMegabytes()
  218004. {
  218005. struct sysinfo sysi;
  218006. if (sysinfo (&sysi) == 0)
  218007. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218008. return 0;
  218009. }
  218010. int SystemStats::getPageSize()
  218011. {
  218012. return sysconf (_SC_PAGESIZE);
  218013. }
  218014. const String SystemStats::getLogonName()
  218015. {
  218016. const char* user = getenv ("USER");
  218017. if (user == 0)
  218018. {
  218019. struct passwd* const pw = getpwuid (getuid());
  218020. if (pw != 0)
  218021. user = pw->pw_name;
  218022. }
  218023. return String::fromUTF8 (user);
  218024. }
  218025. const String SystemStats::getFullUserName()
  218026. {
  218027. return getLogonName();
  218028. }
  218029. void SystemStats::initialiseStats()
  218030. {
  218031. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218032. cpuFlags.hasMMX = flags.contains ("mmx");
  218033. cpuFlags.hasSSE = flags.contains ("sse");
  218034. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218035. cpuFlags.has3DNow = flags.contains ("3dnow");
  218036. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218037. }
  218038. void PlatformUtilities::fpuReset()
  218039. {
  218040. }
  218041. uint32 juce_millisecondsSinceStartup() throw()
  218042. {
  218043. timespec t;
  218044. clock_gettime (CLOCK_MONOTONIC, &t);
  218045. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  218046. }
  218047. int64 Time::getHighResolutionTicks() throw()
  218048. {
  218049. timespec t;
  218050. clock_gettime (CLOCK_MONOTONIC, &t);
  218051. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  218052. }
  218053. int64 Time::getHighResolutionTicksPerSecond() throw()
  218054. {
  218055. return 1000000; // (microseconds)
  218056. }
  218057. double Time::getMillisecondCounterHiRes() throw()
  218058. {
  218059. return getHighResolutionTicks() * 0.001;
  218060. }
  218061. bool Time::setSystemTimeToThisTime() const
  218062. {
  218063. timeval t;
  218064. t.tv_sec = millisSinceEpoch / 1000;
  218065. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  218066. return settimeofday (&t, 0) == 0;
  218067. }
  218068. #endif
  218069. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218070. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218071. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218072. // compiled on its own).
  218073. #if JUCE_INCLUDED_FILE
  218074. /*
  218075. Note that a lot of methods that you'd expect to find in this file actually
  218076. live in juce_posix_SharedCode.h!
  218077. */
  218078. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218079. void Process::setPriority (ProcessPriority prior)
  218080. {
  218081. struct sched_param param;
  218082. int policy, maxp, minp;
  218083. const int p = (int) prior;
  218084. if (p <= 1)
  218085. policy = SCHED_OTHER;
  218086. else
  218087. policy = SCHED_RR;
  218088. minp = sched_get_priority_min (policy);
  218089. maxp = sched_get_priority_max (policy);
  218090. if (p < 2)
  218091. param.sched_priority = 0;
  218092. else if (p == 2 )
  218093. // Set to middle of lower realtime priority range
  218094. param.sched_priority = minp + (maxp - minp) / 4;
  218095. else
  218096. // Set to middle of higher realtime priority range
  218097. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218098. pthread_setschedparam (pthread_self(), policy, &param);
  218099. }
  218100. void Process::terminate()
  218101. {
  218102. exit (0);
  218103. }
  218104. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218105. {
  218106. static char testResult = 0;
  218107. if (testResult == 0)
  218108. {
  218109. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218110. if (testResult >= 0)
  218111. {
  218112. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218113. testResult = 1;
  218114. }
  218115. }
  218116. return testResult < 0;
  218117. }
  218118. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218119. {
  218120. return juce_isRunningUnderDebugger();
  218121. }
  218122. void Process::raisePrivilege()
  218123. {
  218124. // If running suid root, change effective user
  218125. // to root
  218126. if (geteuid() != 0 && getuid() == 0)
  218127. {
  218128. setreuid (geteuid(), getuid());
  218129. setregid (getegid(), getgid());
  218130. }
  218131. }
  218132. void Process::lowerPrivilege()
  218133. {
  218134. // If runing suid root, change effective user
  218135. // back to real user
  218136. if (geteuid() == 0 && getuid() != 0)
  218137. {
  218138. setreuid (geteuid(), getuid());
  218139. setregid (getegid(), getgid());
  218140. }
  218141. }
  218142. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218143. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218144. {
  218145. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218146. }
  218147. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218148. {
  218149. dlclose(handle);
  218150. }
  218151. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218152. {
  218153. return dlsym (libraryHandle, procedureName.toCString());
  218154. }
  218155. #endif
  218156. #endif
  218157. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218158. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218159. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218160. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218161. // compiled on its own).
  218162. #if JUCE_INCLUDED_FILE
  218163. extern Display* display;
  218164. extern Window juce_messageWindowHandle;
  218165. namespace ClipboardHelpers
  218166. {
  218167. static String localClipboardContent;
  218168. static Atom atom_UTF8_STRING;
  218169. static Atom atom_CLIPBOARD;
  218170. static Atom atom_TARGETS;
  218171. static void initSelectionAtoms()
  218172. {
  218173. static bool isInitialised = false;
  218174. if (! isInitialised)
  218175. {
  218176. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218177. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218178. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218179. }
  218180. }
  218181. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218182. // works only for strings shorter than 1000000 bytes
  218183. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218184. {
  218185. String returnData;
  218186. char* clipData;
  218187. Atom actualType;
  218188. int actualFormat;
  218189. unsigned long numItems, bytesLeft;
  218190. if (XGetWindowProperty (display, window, prop,
  218191. 0L /* offset */, 1000000 /* length (max) */, False,
  218192. AnyPropertyType /* format */,
  218193. &actualType, &actualFormat, &numItems, &bytesLeft,
  218194. (unsigned char**) &clipData) == Success)
  218195. {
  218196. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218197. returnData = String::fromUTF8 (clipData, numItems);
  218198. else if (actualType == XA_STRING && actualFormat == 8)
  218199. returnData = String (clipData, numItems);
  218200. if (clipData != 0)
  218201. XFree (clipData);
  218202. jassert (bytesLeft == 0 || numItems == 1000000);
  218203. }
  218204. XDeleteProperty (display, window, prop);
  218205. return returnData;
  218206. }
  218207. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218208. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218209. {
  218210. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218211. // The selection owner will be asked to set the JUCE_SEL property on the
  218212. // juce_messageWindowHandle with the selection content
  218213. XConvertSelection (display, selection, requestedFormat, property_name,
  218214. juce_messageWindowHandle, CurrentTime);
  218215. int count = 50; // will wait at most for 200 ms
  218216. while (--count >= 0)
  218217. {
  218218. XEvent event;
  218219. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218220. {
  218221. if (event.xselection.property == property_name)
  218222. {
  218223. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218224. selectionContent = readWindowProperty (event.xselection.requestor,
  218225. event.xselection.property,
  218226. requestedFormat);
  218227. return true;
  218228. }
  218229. else
  218230. {
  218231. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218232. }
  218233. }
  218234. // not very elegant.. we could do a select() or something like that...
  218235. // however clipboard content requesting is inherently slow on x11, it
  218236. // often takes 50ms or more so...
  218237. Thread::sleep (4);
  218238. }
  218239. return false;
  218240. }
  218241. }
  218242. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218243. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218244. {
  218245. ClipboardHelpers::initSelectionAtoms();
  218246. // the selection content is sent to the target window as a window property
  218247. XSelectionEvent reply;
  218248. reply.type = SelectionNotify;
  218249. reply.display = evt.display;
  218250. reply.requestor = evt.requestor;
  218251. reply.selection = evt.selection;
  218252. reply.target = evt.target;
  218253. reply.property = None; // == "fail"
  218254. reply.time = evt.time;
  218255. HeapBlock <char> data;
  218256. int propertyFormat = 0, numDataItems = 0;
  218257. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218258. {
  218259. if (evt.target == XA_STRING)
  218260. {
  218261. // format data according to system locale
  218262. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218263. data.calloc (numDataItems + 1);
  218264. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218265. propertyFormat = 8; // bits/item
  218266. }
  218267. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218268. {
  218269. // translate to utf8
  218270. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218271. data.calloc (numDataItems + 1);
  218272. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218273. propertyFormat = 8; // bits/item
  218274. }
  218275. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218276. {
  218277. // another application wants to know what we are able to send
  218278. numDataItems = 2;
  218279. propertyFormat = 32; // atoms are 32-bit
  218280. data.calloc (numDataItems * 4);
  218281. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218282. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218283. atoms[1] = XA_STRING;
  218284. }
  218285. }
  218286. else
  218287. {
  218288. DBG ("requested unsupported clipboard");
  218289. }
  218290. if (data != 0)
  218291. {
  218292. const int maxReasonableSelectionSize = 1000000;
  218293. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218294. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218295. {
  218296. XChangeProperty (evt.display, evt.requestor,
  218297. evt.property, evt.target,
  218298. propertyFormat /* 8 or 32 */, PropModeReplace,
  218299. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218300. reply.property = evt.property; // " == success"
  218301. }
  218302. }
  218303. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218304. }
  218305. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218306. {
  218307. ClipboardHelpers::initSelectionAtoms();
  218308. ClipboardHelpers::localClipboardContent = clipText;
  218309. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218310. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218311. }
  218312. const String SystemClipboard::getTextFromClipboard()
  218313. {
  218314. ClipboardHelpers::initSelectionAtoms();
  218315. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218316. level" clipboard that is supposed to be filled by ctrl-C
  218317. etc). When a clipboard manager is running, the content of this
  218318. selection is preserved even when the original selection owner
  218319. exits.
  218320. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218321. filled by good old x11 apps such as xterm)
  218322. */
  218323. String content;
  218324. Atom selection = XA_PRIMARY;
  218325. Window selectionOwner = None;
  218326. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218327. {
  218328. selection = ClipboardHelpers::atom_CLIPBOARD;
  218329. selectionOwner = XGetSelectionOwner (display, selection);
  218330. }
  218331. if (selectionOwner != None)
  218332. {
  218333. if (selectionOwner == juce_messageWindowHandle)
  218334. {
  218335. content = ClipboardHelpers::localClipboardContent;
  218336. }
  218337. else
  218338. {
  218339. // first try: we want an utf8 string
  218340. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218341. if (! ok)
  218342. {
  218343. // second chance, ask for a good old locale-dependent string ..
  218344. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218345. }
  218346. }
  218347. }
  218348. return content;
  218349. }
  218350. #endif
  218351. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218352. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218353. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218354. // compiled on its own).
  218355. #if JUCE_INCLUDED_FILE
  218356. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218357. #define JUCE_DEBUG_XERRORS 1
  218358. #endif
  218359. Display* display = 0;
  218360. Window juce_messageWindowHandle = None;
  218361. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218362. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218363. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218364. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218365. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218366. class InternalMessageQueue
  218367. {
  218368. public:
  218369. InternalMessageQueue()
  218370. : bytesInSocket (0),
  218371. totalEventCount (0)
  218372. {
  218373. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218374. (void) ret; jassert (ret == 0);
  218375. //setNonBlocking (fd[0]);
  218376. //setNonBlocking (fd[1]);
  218377. }
  218378. ~InternalMessageQueue()
  218379. {
  218380. close (fd[0]);
  218381. close (fd[1]);
  218382. clearSingletonInstance();
  218383. }
  218384. void postMessage (Message* msg)
  218385. {
  218386. const int maxBytesInSocketQueue = 128;
  218387. ScopedLock sl (lock);
  218388. queue.add (msg);
  218389. if (bytesInSocket < maxBytesInSocketQueue)
  218390. {
  218391. ++bytesInSocket;
  218392. ScopedUnlock ul (lock);
  218393. const unsigned char x = 0xff;
  218394. size_t bytesWritten = write (fd[0], &x, 1);
  218395. (void) bytesWritten;
  218396. }
  218397. }
  218398. bool isEmpty() const
  218399. {
  218400. ScopedLock sl (lock);
  218401. return queue.size() == 0;
  218402. }
  218403. bool dispatchNextEvent()
  218404. {
  218405. // This alternates between giving priority to XEvents or internal messages,
  218406. // to keep everything running smoothly..
  218407. if ((++totalEventCount & 1) != 0)
  218408. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218409. else
  218410. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218411. }
  218412. // Wait for an event (either XEvent, or an internal Message)
  218413. bool sleepUntilEvent (const int timeoutMs)
  218414. {
  218415. if (! isEmpty())
  218416. return true;
  218417. if (display != 0)
  218418. {
  218419. ScopedXLock xlock;
  218420. if (XPending (display))
  218421. return true;
  218422. }
  218423. struct timeval tv;
  218424. tv.tv_sec = 0;
  218425. tv.tv_usec = timeoutMs * 1000;
  218426. int fd0 = getWaitHandle();
  218427. int fdmax = fd0;
  218428. fd_set readset;
  218429. FD_ZERO (&readset);
  218430. FD_SET (fd0, &readset);
  218431. if (display != 0)
  218432. {
  218433. ScopedXLock xlock;
  218434. int fd1 = XConnectionNumber (display);
  218435. FD_SET (fd1, &readset);
  218436. fdmax = jmax (fd0, fd1);
  218437. }
  218438. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218439. return (ret > 0); // ret <= 0 if error or timeout
  218440. }
  218441. struct MessageThreadFuncCall
  218442. {
  218443. enum { uniqueID = 0x73774623 };
  218444. MessageCallbackFunction* func;
  218445. void* parameter;
  218446. void* result;
  218447. CriticalSection lock;
  218448. WaitableEvent event;
  218449. };
  218450. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218451. private:
  218452. CriticalSection lock;
  218453. ReferenceCountedArray <Message> queue;
  218454. int fd[2];
  218455. int bytesInSocket;
  218456. int totalEventCount;
  218457. int getWaitHandle() const throw() { return fd[1]; }
  218458. static bool setNonBlocking (int handle)
  218459. {
  218460. int socketFlags = fcntl (handle, F_GETFL, 0);
  218461. if (socketFlags == -1)
  218462. return false;
  218463. socketFlags |= O_NONBLOCK;
  218464. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218465. }
  218466. static bool dispatchNextXEvent()
  218467. {
  218468. if (display == 0)
  218469. return false;
  218470. XEvent evt;
  218471. {
  218472. ScopedXLock xlock;
  218473. if (! XPending (display))
  218474. return false;
  218475. XNextEvent (display, &evt);
  218476. }
  218477. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218478. juce_handleSelectionRequest (evt.xselectionrequest);
  218479. else if (evt.xany.window != juce_messageWindowHandle)
  218480. juce_windowMessageReceive (&evt);
  218481. return true;
  218482. }
  218483. const Message::Ptr popNextMessage()
  218484. {
  218485. const ScopedLock sl (lock);
  218486. if (bytesInSocket > 0)
  218487. {
  218488. --bytesInSocket;
  218489. const ScopedUnlock ul (lock);
  218490. unsigned char x;
  218491. size_t numBytes = read (fd[1], &x, 1);
  218492. (void) numBytes;
  218493. }
  218494. return queue.removeAndReturn (0);
  218495. }
  218496. bool dispatchNextInternalMessage()
  218497. {
  218498. const Message::Ptr msg (popNextMessage());
  218499. if (msg == 0)
  218500. return false;
  218501. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218502. {
  218503. // Handle callback message
  218504. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218505. call->result = (*(call->func)) (call->parameter);
  218506. call->event.signal();
  218507. }
  218508. else
  218509. {
  218510. // Handle "normal" messages
  218511. MessageManager::getInstance()->deliverMessage (msg);
  218512. }
  218513. return true;
  218514. }
  218515. };
  218516. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218517. namespace LinuxErrorHandling
  218518. {
  218519. static bool errorOccurred = false;
  218520. static bool keyboardBreakOccurred = false;
  218521. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218522. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218523. // Usually happens when client-server connection is broken
  218524. static int ioErrorHandler (Display* display)
  218525. {
  218526. DBG ("ERROR: connection to X server broken.. terminating.");
  218527. if (JUCEApplication::isStandaloneApp())
  218528. MessageManager::getInstance()->stopDispatchLoop();
  218529. errorOccurred = true;
  218530. return 0;
  218531. }
  218532. // A protocol error has occurred
  218533. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218534. {
  218535. #if JUCE_DEBUG_XERRORS
  218536. char errorStr[64] = { 0 };
  218537. char requestStr[64] = { 0 };
  218538. XGetErrorText (display, event->error_code, errorStr, 64);
  218539. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218540. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218541. #endif
  218542. return 0;
  218543. }
  218544. static void installXErrorHandlers()
  218545. {
  218546. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218547. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218548. }
  218549. static void removeXErrorHandlers()
  218550. {
  218551. if (JUCEApplication::isStandaloneApp())
  218552. {
  218553. XSetIOErrorHandler (oldIOErrorHandler);
  218554. oldIOErrorHandler = 0;
  218555. XSetErrorHandler (oldErrorHandler);
  218556. oldErrorHandler = 0;
  218557. }
  218558. }
  218559. static void keyboardBreakSignalHandler (int sig)
  218560. {
  218561. if (sig == SIGINT)
  218562. keyboardBreakOccurred = true;
  218563. }
  218564. static void installKeyboardBreakHandler()
  218565. {
  218566. struct sigaction saction;
  218567. sigset_t maskSet;
  218568. sigemptyset (&maskSet);
  218569. saction.sa_handler = keyboardBreakSignalHandler;
  218570. saction.sa_mask = maskSet;
  218571. saction.sa_flags = 0;
  218572. sigaction (SIGINT, &saction, 0);
  218573. }
  218574. }
  218575. void MessageManager::doPlatformSpecificInitialisation()
  218576. {
  218577. if (JUCEApplication::isStandaloneApp())
  218578. {
  218579. // Initialise xlib for multiple thread support
  218580. static bool initThreadCalled = false;
  218581. if (! initThreadCalled)
  218582. {
  218583. if (! XInitThreads())
  218584. {
  218585. // This is fatal! Print error and closedown
  218586. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218587. Process::terminate();
  218588. return;
  218589. }
  218590. initThreadCalled = true;
  218591. }
  218592. LinuxErrorHandling::installXErrorHandlers();
  218593. LinuxErrorHandling::installKeyboardBreakHandler();
  218594. }
  218595. // Create the internal message queue
  218596. InternalMessageQueue::getInstance();
  218597. // Try to connect to a display
  218598. String displayName (getenv ("DISPLAY"));
  218599. if (displayName.isEmpty())
  218600. displayName = ":0.0";
  218601. display = XOpenDisplay (displayName.toCString());
  218602. if (display != 0) // This is not fatal! we can run headless.
  218603. {
  218604. // Create a context to store user data associated with Windows we create in WindowDriver
  218605. windowHandleXContext = XUniqueContext();
  218606. // We're only interested in client messages for this window, which are always sent
  218607. XSetWindowAttributes swa;
  218608. swa.event_mask = NoEventMask;
  218609. // Create our message window (this will never be mapped)
  218610. const int screen = DefaultScreen (display);
  218611. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218612. 0, 0, 1, 1, 0, 0, InputOnly,
  218613. DefaultVisual (display, screen),
  218614. CWEventMask, &swa);
  218615. }
  218616. }
  218617. void MessageManager::doPlatformSpecificShutdown()
  218618. {
  218619. InternalMessageQueue::deleteInstance();
  218620. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218621. {
  218622. XDestroyWindow (display, juce_messageWindowHandle);
  218623. XCloseDisplay (display);
  218624. juce_messageWindowHandle = 0;
  218625. display = 0;
  218626. LinuxErrorHandling::removeXErrorHandlers();
  218627. }
  218628. }
  218629. bool juce_postMessageToSystemQueue (Message* message)
  218630. {
  218631. if (LinuxErrorHandling::errorOccurred)
  218632. return false;
  218633. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218634. return true;
  218635. }
  218636. void MessageManager::broadcastMessage (const String& value)
  218637. {
  218638. /* TODO */
  218639. }
  218640. class AsyncFunctionCaller : public AsyncUpdater
  218641. {
  218642. public:
  218643. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218644. {
  218645. if (MessageManager::getInstance()->isThisTheMessageThread())
  218646. return func_ (parameter_);
  218647. AsyncFunctionCaller caller (func_, parameter_);
  218648. caller.triggerAsyncUpdate();
  218649. caller.finished.wait();
  218650. return caller.result;
  218651. }
  218652. void handleAsyncUpdate()
  218653. {
  218654. result = (*func) (parameter);
  218655. finished.signal();
  218656. }
  218657. private:
  218658. WaitableEvent finished;
  218659. MessageCallbackFunction* func;
  218660. void* parameter;
  218661. void* volatile result;
  218662. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218663. : result (0), func (func_), parameter (parameter_)
  218664. {}
  218665. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218666. };
  218667. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218668. {
  218669. if (LinuxErrorHandling::errorOccurred)
  218670. return 0;
  218671. return AsyncFunctionCaller::call (func, parameter);
  218672. }
  218673. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218674. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218675. {
  218676. while (! LinuxErrorHandling::errorOccurred)
  218677. {
  218678. if (LinuxErrorHandling::keyboardBreakOccurred)
  218679. {
  218680. LinuxErrorHandling::errorOccurred = true;
  218681. if (JUCEApplication::isStandaloneApp())
  218682. Process::terminate();
  218683. break;
  218684. }
  218685. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218686. return true;
  218687. if (returnIfNoPendingMessages)
  218688. break;
  218689. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218690. }
  218691. return false;
  218692. }
  218693. #endif
  218694. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218695. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218696. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218697. // compiled on its own).
  218698. #if JUCE_INCLUDED_FILE
  218699. class FreeTypeFontFace
  218700. {
  218701. public:
  218702. enum FontStyle
  218703. {
  218704. Plain = 0,
  218705. Bold = 1,
  218706. Italic = 2
  218707. };
  218708. FreeTypeFontFace (const String& familyName)
  218709. : hasSerif (false),
  218710. monospaced (false)
  218711. {
  218712. family = familyName;
  218713. }
  218714. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218715. {
  218716. if (names [(int) style].fileName.isEmpty())
  218717. {
  218718. names [(int) style].fileName = name;
  218719. names [(int) style].faceIndex = faceIndex;
  218720. }
  218721. }
  218722. const String& getFamilyName() const throw() { return family; }
  218723. const String& getFileName (const int style, int& faceIndex) const throw()
  218724. {
  218725. faceIndex = names[style].faceIndex;
  218726. return names[style].fileName;
  218727. }
  218728. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218729. bool getMonospaced() const throw() { return monospaced; }
  218730. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218731. bool getSerif() const throw() { return hasSerif; }
  218732. private:
  218733. String family;
  218734. struct FontNameIndex
  218735. {
  218736. String fileName;
  218737. int faceIndex;
  218738. };
  218739. FontNameIndex names[4];
  218740. bool hasSerif, monospaced;
  218741. };
  218742. class FreeTypeInterface : public DeletedAtShutdown
  218743. {
  218744. public:
  218745. FreeTypeInterface()
  218746. : ftLib (0),
  218747. lastFace (0),
  218748. lastBold (false),
  218749. lastItalic (false)
  218750. {
  218751. if (FT_Init_FreeType (&ftLib) != 0)
  218752. {
  218753. ftLib = 0;
  218754. DBG ("Failed to initialize FreeType");
  218755. }
  218756. StringArray fontDirs;
  218757. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218758. fontDirs.removeEmptyStrings (true);
  218759. if (fontDirs.size() == 0)
  218760. {
  218761. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218762. if (fontsInfo != 0)
  218763. {
  218764. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218765. {
  218766. fontDirs.add (e->getAllSubText().trim());
  218767. }
  218768. }
  218769. }
  218770. if (fontDirs.size() == 0)
  218771. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218772. for (int i = 0; i < fontDirs.size(); ++i)
  218773. enumerateFaces (fontDirs[i]);
  218774. }
  218775. ~FreeTypeInterface()
  218776. {
  218777. if (lastFace != 0)
  218778. FT_Done_Face (lastFace);
  218779. if (ftLib != 0)
  218780. FT_Done_FreeType (ftLib);
  218781. clearSingletonInstance();
  218782. }
  218783. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218784. {
  218785. for (int i = 0; i < faces.size(); i++)
  218786. if (faces[i]->getFamilyName() == familyName)
  218787. return faces[i];
  218788. if (! create)
  218789. return 0;
  218790. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218791. faces.add (newFace);
  218792. return newFace;
  218793. }
  218794. // Enumerate all font faces available in a given directory
  218795. void enumerateFaces (const String& path)
  218796. {
  218797. File dirPath (path);
  218798. if (path.isEmpty() || ! dirPath.isDirectory())
  218799. return;
  218800. DirectoryIterator di (dirPath, true);
  218801. while (di.next())
  218802. {
  218803. File possible (di.getFile());
  218804. if (possible.hasFileExtension ("ttf")
  218805. || possible.hasFileExtension ("pfb")
  218806. || possible.hasFileExtension ("pcf"))
  218807. {
  218808. FT_Face face;
  218809. int faceIndex = 0;
  218810. int numFaces = 0;
  218811. do
  218812. {
  218813. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218814. faceIndex, &face) == 0)
  218815. {
  218816. if (faceIndex == 0)
  218817. numFaces = face->num_faces;
  218818. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218819. {
  218820. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218821. int style = (int) FreeTypeFontFace::Plain;
  218822. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218823. style |= (int) FreeTypeFontFace::Bold;
  218824. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218825. style |= (int) FreeTypeFontFace::Italic;
  218826. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218827. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218828. // Surely there must be a better way to do this?
  218829. const String name (face->family_name);
  218830. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218831. || name.containsIgnoreCase ("Verdana")
  218832. || name.containsIgnoreCase ("Arial")));
  218833. }
  218834. FT_Done_Face (face);
  218835. }
  218836. ++faceIndex;
  218837. }
  218838. while (faceIndex < numFaces);
  218839. }
  218840. }
  218841. }
  218842. // Create a FreeType face object for a given font
  218843. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218844. {
  218845. FT_Face face = 0;
  218846. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218847. {
  218848. face = lastFace;
  218849. }
  218850. else
  218851. {
  218852. if (lastFace != 0)
  218853. {
  218854. FT_Done_Face (lastFace);
  218855. lastFace = 0;
  218856. }
  218857. lastFontName = fontName;
  218858. lastBold = bold;
  218859. lastItalic = italic;
  218860. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218861. if (ftFace != 0)
  218862. {
  218863. int style = (int) FreeTypeFontFace::Plain;
  218864. if (bold)
  218865. style |= (int) FreeTypeFontFace::Bold;
  218866. if (italic)
  218867. style |= (int) FreeTypeFontFace::Italic;
  218868. int faceIndex;
  218869. String fileName (ftFace->getFileName (style, faceIndex));
  218870. if (fileName.isEmpty())
  218871. {
  218872. style ^= (int) FreeTypeFontFace::Bold;
  218873. fileName = ftFace->getFileName (style, faceIndex);
  218874. if (fileName.isEmpty())
  218875. {
  218876. style ^= (int) FreeTypeFontFace::Bold;
  218877. style ^= (int) FreeTypeFontFace::Italic;
  218878. fileName = ftFace->getFileName (style, faceIndex);
  218879. if (! fileName.length())
  218880. {
  218881. style ^= (int) FreeTypeFontFace::Bold;
  218882. fileName = ftFace->getFileName (style, faceIndex);
  218883. }
  218884. }
  218885. }
  218886. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218887. {
  218888. face = lastFace;
  218889. // If there isn't a unicode charmap then select the first one.
  218890. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218891. FT_Set_Charmap (face, face->charmaps[0]);
  218892. }
  218893. }
  218894. }
  218895. return face;
  218896. }
  218897. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218898. {
  218899. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218900. const float height = (float) (face->ascender - face->descender);
  218901. const float scaleX = 1.0f / height;
  218902. const float scaleY = -1.0f / height;
  218903. Path destShape;
  218904. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218905. || face->glyph->format != ft_glyph_format_outline)
  218906. {
  218907. return false;
  218908. }
  218909. const FT_Outline* const outline = &face->glyph->outline;
  218910. const short* const contours = outline->contours;
  218911. const char* const tags = outline->tags;
  218912. FT_Vector* const points = outline->points;
  218913. for (int c = 0; c < outline->n_contours; c++)
  218914. {
  218915. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218916. const int endPoint = contours[c];
  218917. for (int p = startPoint; p <= endPoint; p++)
  218918. {
  218919. const float x = scaleX * points[p].x;
  218920. const float y = scaleY * points[p].y;
  218921. if (p == startPoint)
  218922. {
  218923. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218924. {
  218925. float x2 = scaleX * points [endPoint].x;
  218926. float y2 = scaleY * points [endPoint].y;
  218927. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218928. {
  218929. x2 = (x + x2) * 0.5f;
  218930. y2 = (y + y2) * 0.5f;
  218931. }
  218932. destShape.startNewSubPath (x2, y2);
  218933. }
  218934. else
  218935. {
  218936. destShape.startNewSubPath (x, y);
  218937. }
  218938. }
  218939. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218940. {
  218941. if (p != startPoint)
  218942. destShape.lineTo (x, y);
  218943. }
  218944. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218945. {
  218946. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218947. float x2 = scaleX * points [nextIndex].x;
  218948. float y2 = scaleY * points [nextIndex].y;
  218949. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218950. {
  218951. x2 = (x + x2) * 0.5f;
  218952. y2 = (y + y2) * 0.5f;
  218953. }
  218954. else
  218955. {
  218956. ++p;
  218957. }
  218958. destShape.quadraticTo (x, y, x2, y2);
  218959. }
  218960. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218961. {
  218962. if (p >= endPoint)
  218963. return false;
  218964. const int next1 = p + 1;
  218965. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218966. const float x2 = scaleX * points [next1].x;
  218967. const float y2 = scaleY * points [next1].y;
  218968. const float x3 = scaleX * points [next2].x;
  218969. const float y3 = scaleY * points [next2].y;
  218970. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218971. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218972. return false;
  218973. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218974. p += 2;
  218975. }
  218976. }
  218977. destShape.closeSubPath();
  218978. }
  218979. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218980. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218981. addKerning (face, dest, character, glyphIndex);
  218982. return true;
  218983. }
  218984. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218985. {
  218986. const float height = (float) (face->ascender - face->descender);
  218987. uint32 rightGlyphIndex;
  218988. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218989. while (rightGlyphIndex != 0)
  218990. {
  218991. FT_Vector kerning;
  218992. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218993. {
  218994. if (kerning.x != 0)
  218995. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218996. }
  218997. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218998. }
  218999. }
  219000. // Add a glyph to a font
  219001. bool addGlyphToFont (const uint32 character, const String& fontName,
  219002. bool bold, bool italic, CustomTypeface& dest)
  219003. {
  219004. FT_Face face = createFT_Face (fontName, bold, italic);
  219005. return face != 0 && addGlyph (face, dest, character);
  219006. }
  219007. void getFamilyNames (StringArray& familyNames) const
  219008. {
  219009. for (int i = 0; i < faces.size(); i++)
  219010. familyNames.add (faces[i]->getFamilyName());
  219011. }
  219012. void getMonospacedNames (StringArray& monoSpaced) const
  219013. {
  219014. for (int i = 0; i < faces.size(); i++)
  219015. if (faces[i]->getMonospaced())
  219016. monoSpaced.add (faces[i]->getFamilyName());
  219017. }
  219018. void getSerifNames (StringArray& serif) const
  219019. {
  219020. for (int i = 0; i < faces.size(); i++)
  219021. if (faces[i]->getSerif())
  219022. serif.add (faces[i]->getFamilyName());
  219023. }
  219024. void getSansSerifNames (StringArray& sansSerif) const
  219025. {
  219026. for (int i = 0; i < faces.size(); i++)
  219027. if (! faces[i]->getSerif())
  219028. sansSerif.add (faces[i]->getFamilyName());
  219029. }
  219030. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219031. private:
  219032. FT_Library ftLib;
  219033. FT_Face lastFace;
  219034. String lastFontName;
  219035. bool lastBold, lastItalic;
  219036. OwnedArray<FreeTypeFontFace> faces;
  219037. };
  219038. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219039. class FreetypeTypeface : public CustomTypeface
  219040. {
  219041. public:
  219042. FreetypeTypeface (const Font& font)
  219043. {
  219044. FT_Face face = FreeTypeInterface::getInstance()
  219045. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219046. if (face == 0)
  219047. {
  219048. #if JUCE_DEBUG
  219049. String msg ("Failed to create typeface: ");
  219050. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219051. DBG (msg);
  219052. #endif
  219053. }
  219054. else
  219055. {
  219056. setCharacteristics (font.getTypefaceName(),
  219057. face->ascender / (float) (face->ascender - face->descender),
  219058. font.isBold(), font.isItalic(),
  219059. L' ');
  219060. }
  219061. }
  219062. bool loadGlyphIfPossible (juce_wchar character)
  219063. {
  219064. return FreeTypeInterface::getInstance()
  219065. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219066. }
  219067. };
  219068. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219069. {
  219070. return new FreetypeTypeface (font);
  219071. }
  219072. const StringArray Font::findAllTypefaceNames()
  219073. {
  219074. StringArray s;
  219075. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219076. s.sort (true);
  219077. return s;
  219078. }
  219079. namespace
  219080. {
  219081. const String pickBestFont (const StringArray& names,
  219082. const char* const choicesString)
  219083. {
  219084. StringArray choices;
  219085. choices.addTokens (String (choicesString), ",", String::empty);
  219086. choices.trim();
  219087. choices.removeEmptyStrings();
  219088. int i, j;
  219089. for (j = 0; j < choices.size(); ++j)
  219090. if (names.contains (choices[j], true))
  219091. return choices[j];
  219092. for (j = 0; j < choices.size(); ++j)
  219093. for (i = 0; i < names.size(); i++)
  219094. if (names[i].startsWithIgnoreCase (choices[j]))
  219095. return names[i];
  219096. for (j = 0; j < choices.size(); ++j)
  219097. for (i = 0; i < names.size(); i++)
  219098. if (names[i].containsIgnoreCase (choices[j]))
  219099. return names[i];
  219100. return names[0];
  219101. }
  219102. const String linux_getDefaultSansSerifFontName()
  219103. {
  219104. StringArray allFonts;
  219105. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219106. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219107. }
  219108. const String linux_getDefaultSerifFontName()
  219109. {
  219110. StringArray allFonts;
  219111. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219112. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219113. }
  219114. const String linux_getDefaultMonospacedFontName()
  219115. {
  219116. StringArray allFonts;
  219117. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219118. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219119. }
  219120. }
  219121. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219122. {
  219123. defaultSans = linux_getDefaultSansSerifFontName();
  219124. defaultSerif = linux_getDefaultSerifFontName();
  219125. defaultFixed = linux_getDefaultMonospacedFontName();
  219126. }
  219127. #endif
  219128. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219129. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219130. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219131. // compiled on its own).
  219132. #if JUCE_INCLUDED_FILE
  219133. // These are defined in juce_linux_Messaging.cpp
  219134. extern Display* display;
  219135. extern XContext windowHandleXContext;
  219136. namespace Atoms
  219137. {
  219138. enum ProtocolItems
  219139. {
  219140. TAKE_FOCUS = 0,
  219141. DELETE_WINDOW = 1,
  219142. PING = 2
  219143. };
  219144. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219145. ActiveWin, Pid, WindowType, WindowState,
  219146. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219147. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219148. XdndActionDescription, XdndActionCopy,
  219149. allowedActions[5],
  219150. allowedMimeTypes[2];
  219151. const unsigned long DndVersion = 3;
  219152. static void initialiseAtoms()
  219153. {
  219154. static bool atomsInitialised = false;
  219155. if (! atomsInitialised)
  219156. {
  219157. atomsInitialised = true;
  219158. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219159. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219160. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219161. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219162. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219163. State = XInternAtom (display, "WM_STATE", True);
  219164. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219165. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219166. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219167. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219168. XdndAware = XInternAtom (display, "XdndAware", False);
  219169. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219170. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219171. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219172. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219173. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219174. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219175. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219176. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219177. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219178. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219179. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219180. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219181. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219182. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219183. allowedActions[1] = XdndActionCopy;
  219184. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219185. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219186. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219187. }
  219188. }
  219189. }
  219190. namespace Keys
  219191. {
  219192. enum MouseButtons
  219193. {
  219194. NoButton = 0,
  219195. LeftButton = 1,
  219196. MiddleButton = 2,
  219197. RightButton = 3,
  219198. WheelUp = 4,
  219199. WheelDown = 5
  219200. };
  219201. static int AltMask = 0;
  219202. static int NumLockMask = 0;
  219203. static bool numLock = false;
  219204. static bool capsLock = false;
  219205. static char keyStates [32];
  219206. static const int extendedKeyModifier = 0x10000000;
  219207. }
  219208. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219209. {
  219210. int keysym;
  219211. if (keyCode & Keys::extendedKeyModifier)
  219212. {
  219213. keysym = 0xff00 | (keyCode & 0xff);
  219214. }
  219215. else
  219216. {
  219217. keysym = keyCode;
  219218. if (keysym == (XK_Tab & 0xff)
  219219. || keysym == (XK_Return & 0xff)
  219220. || keysym == (XK_Escape & 0xff)
  219221. || keysym == (XK_BackSpace & 0xff))
  219222. {
  219223. keysym |= 0xff00;
  219224. }
  219225. }
  219226. ScopedXLock xlock;
  219227. const int keycode = XKeysymToKeycode (display, keysym);
  219228. const int keybyte = keycode >> 3;
  219229. const int keybit = (1 << (keycode & 7));
  219230. return (Keys::keyStates [keybyte] & keybit) != 0;
  219231. }
  219232. #if JUCE_USE_XSHM
  219233. namespace XSHMHelpers
  219234. {
  219235. static int trappedErrorCode = 0;
  219236. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219237. {
  219238. trappedErrorCode = err->error_code;
  219239. return 0;
  219240. }
  219241. static bool isShmAvailable() throw()
  219242. {
  219243. static bool isChecked = false;
  219244. static bool isAvailable = false;
  219245. if (! isChecked)
  219246. {
  219247. isChecked = true;
  219248. int major, minor;
  219249. Bool pixmaps;
  219250. ScopedXLock xlock;
  219251. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219252. {
  219253. trappedErrorCode = 0;
  219254. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219255. XShmSegmentInfo segmentInfo;
  219256. zerostruct (segmentInfo);
  219257. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219258. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219259. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219260. xImage->bytes_per_line * xImage->height,
  219261. IPC_CREAT | 0777)) >= 0)
  219262. {
  219263. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219264. if (segmentInfo.shmaddr != (void*) -1)
  219265. {
  219266. segmentInfo.readOnly = False;
  219267. xImage->data = segmentInfo.shmaddr;
  219268. XSync (display, False);
  219269. if (XShmAttach (display, &segmentInfo) != 0)
  219270. {
  219271. XSync (display, False);
  219272. XShmDetach (display, &segmentInfo);
  219273. isAvailable = true;
  219274. }
  219275. }
  219276. XFlush (display);
  219277. XDestroyImage (xImage);
  219278. shmdt (segmentInfo.shmaddr);
  219279. }
  219280. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219281. XSetErrorHandler (oldHandler);
  219282. if (trappedErrorCode != 0)
  219283. isAvailable = false;
  219284. }
  219285. }
  219286. return isAvailable;
  219287. }
  219288. }
  219289. #endif
  219290. #if JUCE_USE_XRENDER
  219291. namespace XRender
  219292. {
  219293. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219294. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219295. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219296. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219297. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219298. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219299. static tXRenderFindFormat xRenderFindFormat = 0;
  219300. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219301. static bool isAvailable()
  219302. {
  219303. static bool hasLoaded = false;
  219304. if (! hasLoaded)
  219305. {
  219306. ScopedXLock xlock;
  219307. hasLoaded = true;
  219308. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219309. if (h != 0)
  219310. {
  219311. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219312. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219313. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219314. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219315. }
  219316. if (xRenderQueryVersion != 0
  219317. && xRenderFindStandardFormat != 0
  219318. && xRenderFindFormat != 0
  219319. && xRenderFindVisualFormat != 0)
  219320. {
  219321. int major, minor;
  219322. if (xRenderQueryVersion (display, &major, &minor))
  219323. return true;
  219324. }
  219325. xRenderQueryVersion = 0;
  219326. }
  219327. return xRenderQueryVersion != 0;
  219328. }
  219329. static XRenderPictFormat* findPictureFormat()
  219330. {
  219331. ScopedXLock xlock;
  219332. XRenderPictFormat* pictFormat = 0;
  219333. if (isAvailable())
  219334. {
  219335. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219336. if (pictFormat == 0)
  219337. {
  219338. XRenderPictFormat desiredFormat;
  219339. desiredFormat.type = PictTypeDirect;
  219340. desiredFormat.depth = 32;
  219341. desiredFormat.direct.alphaMask = 0xff;
  219342. desiredFormat.direct.redMask = 0xff;
  219343. desiredFormat.direct.greenMask = 0xff;
  219344. desiredFormat.direct.blueMask = 0xff;
  219345. desiredFormat.direct.alpha = 24;
  219346. desiredFormat.direct.red = 16;
  219347. desiredFormat.direct.green = 8;
  219348. desiredFormat.direct.blue = 0;
  219349. pictFormat = xRenderFindFormat (display,
  219350. PictFormatType | PictFormatDepth
  219351. | PictFormatRedMask | PictFormatRed
  219352. | PictFormatGreenMask | PictFormatGreen
  219353. | PictFormatBlueMask | PictFormatBlue
  219354. | PictFormatAlphaMask | PictFormatAlpha,
  219355. &desiredFormat,
  219356. 0);
  219357. }
  219358. }
  219359. return pictFormat;
  219360. }
  219361. }
  219362. #endif
  219363. namespace Visuals
  219364. {
  219365. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219366. {
  219367. ScopedXLock xlock;
  219368. Visual* visual = 0;
  219369. int numVisuals = 0;
  219370. long desiredMask = VisualNoMask;
  219371. XVisualInfo desiredVisual;
  219372. desiredVisual.screen = DefaultScreen (display);
  219373. desiredVisual.depth = desiredDepth;
  219374. desiredMask = VisualScreenMask | VisualDepthMask;
  219375. if (desiredDepth == 32)
  219376. {
  219377. desiredVisual.c_class = TrueColor;
  219378. desiredVisual.red_mask = 0x00FF0000;
  219379. desiredVisual.green_mask = 0x0000FF00;
  219380. desiredVisual.blue_mask = 0x000000FF;
  219381. desiredVisual.bits_per_rgb = 8;
  219382. desiredMask |= VisualClassMask;
  219383. desiredMask |= VisualRedMaskMask;
  219384. desiredMask |= VisualGreenMaskMask;
  219385. desiredMask |= VisualBlueMaskMask;
  219386. desiredMask |= VisualBitsPerRGBMask;
  219387. }
  219388. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219389. desiredMask,
  219390. &desiredVisual,
  219391. &numVisuals);
  219392. if (xvinfos != 0)
  219393. {
  219394. for (int i = 0; i < numVisuals; i++)
  219395. {
  219396. if (xvinfos[i].depth == desiredDepth)
  219397. {
  219398. visual = xvinfos[i].visual;
  219399. break;
  219400. }
  219401. }
  219402. XFree (xvinfos);
  219403. }
  219404. return visual;
  219405. }
  219406. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219407. {
  219408. Visual* visual = 0;
  219409. if (desiredDepth == 32)
  219410. {
  219411. #if JUCE_USE_XSHM
  219412. if (XSHMHelpers::isShmAvailable())
  219413. {
  219414. #if JUCE_USE_XRENDER
  219415. if (XRender::isAvailable())
  219416. {
  219417. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219418. if (pictFormat != 0)
  219419. {
  219420. int numVisuals = 0;
  219421. XVisualInfo desiredVisual;
  219422. desiredVisual.screen = DefaultScreen (display);
  219423. desiredVisual.depth = 32;
  219424. desiredVisual.bits_per_rgb = 8;
  219425. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219426. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219427. &desiredVisual, &numVisuals);
  219428. if (xvinfos != 0)
  219429. {
  219430. for (int i = 0; i < numVisuals; ++i)
  219431. {
  219432. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219433. if (pictVisualFormat != 0
  219434. && pictVisualFormat->type == PictTypeDirect
  219435. && pictVisualFormat->direct.alphaMask)
  219436. {
  219437. visual = xvinfos[i].visual;
  219438. matchedDepth = 32;
  219439. break;
  219440. }
  219441. }
  219442. XFree (xvinfos);
  219443. }
  219444. }
  219445. }
  219446. #endif
  219447. if (visual == 0)
  219448. {
  219449. visual = findVisualWithDepth (32);
  219450. if (visual != 0)
  219451. matchedDepth = 32;
  219452. }
  219453. }
  219454. #endif
  219455. }
  219456. if (visual == 0 && desiredDepth >= 24)
  219457. {
  219458. visual = findVisualWithDepth (24);
  219459. if (visual != 0)
  219460. matchedDepth = 24;
  219461. }
  219462. if (visual == 0 && desiredDepth >= 16)
  219463. {
  219464. visual = findVisualWithDepth (16);
  219465. if (visual != 0)
  219466. matchedDepth = 16;
  219467. }
  219468. return visual;
  219469. }
  219470. }
  219471. class XBitmapImage : public Image::SharedImage
  219472. {
  219473. public:
  219474. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219475. const bool clearImage, const int imageDepth_, Visual* visual)
  219476. : Image::SharedImage (format_, w, h),
  219477. imageDepth (imageDepth_),
  219478. gc (None)
  219479. {
  219480. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219481. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219482. lineStride = ((w * pixelStride + 3) & ~3);
  219483. ScopedXLock xlock;
  219484. #if JUCE_USE_XSHM
  219485. usingXShm = false;
  219486. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219487. {
  219488. zerostruct (segmentInfo);
  219489. segmentInfo.shmid = -1;
  219490. segmentInfo.shmaddr = (char *) -1;
  219491. segmentInfo.readOnly = False;
  219492. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219493. if (xImage != 0)
  219494. {
  219495. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219496. xImage->bytes_per_line * xImage->height,
  219497. IPC_CREAT | 0777)) >= 0)
  219498. {
  219499. if (segmentInfo.shmid != -1)
  219500. {
  219501. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219502. if (segmentInfo.shmaddr != (void*) -1)
  219503. {
  219504. segmentInfo.readOnly = False;
  219505. xImage->data = segmentInfo.shmaddr;
  219506. imageData = (uint8*) segmentInfo.shmaddr;
  219507. if (XShmAttach (display, &segmentInfo) != 0)
  219508. usingXShm = true;
  219509. else
  219510. jassertfalse;
  219511. }
  219512. else
  219513. {
  219514. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219515. }
  219516. }
  219517. }
  219518. }
  219519. }
  219520. if (! usingXShm)
  219521. #endif
  219522. {
  219523. imageDataAllocated.malloc (lineStride * h);
  219524. imageData = imageDataAllocated;
  219525. if (format_ == Image::ARGB && clearImage)
  219526. zeromem (imageData, h * lineStride);
  219527. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219528. xImage->width = w;
  219529. xImage->height = h;
  219530. xImage->xoffset = 0;
  219531. xImage->format = ZPixmap;
  219532. xImage->data = (char*) imageData;
  219533. xImage->byte_order = ImageByteOrder (display);
  219534. xImage->bitmap_unit = BitmapUnit (display);
  219535. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219536. xImage->bitmap_pad = 32;
  219537. xImage->depth = pixelStride * 8;
  219538. xImage->bytes_per_line = lineStride;
  219539. xImage->bits_per_pixel = pixelStride * 8;
  219540. xImage->red_mask = 0x00FF0000;
  219541. xImage->green_mask = 0x0000FF00;
  219542. xImage->blue_mask = 0x000000FF;
  219543. if (imageDepth == 16)
  219544. {
  219545. const int pixelStride = 2;
  219546. const int lineStride = ((w * pixelStride + 3) & ~3);
  219547. imageData16Bit.malloc (lineStride * h);
  219548. xImage->data = imageData16Bit;
  219549. xImage->bitmap_pad = 16;
  219550. xImage->depth = pixelStride * 8;
  219551. xImage->bytes_per_line = lineStride;
  219552. xImage->bits_per_pixel = pixelStride * 8;
  219553. xImage->red_mask = visual->red_mask;
  219554. xImage->green_mask = visual->green_mask;
  219555. xImage->blue_mask = visual->blue_mask;
  219556. }
  219557. if (! XInitImage (xImage))
  219558. jassertfalse;
  219559. }
  219560. }
  219561. ~XBitmapImage()
  219562. {
  219563. ScopedXLock xlock;
  219564. if (gc != None)
  219565. XFreeGC (display, gc);
  219566. #if JUCE_USE_XSHM
  219567. if (usingXShm)
  219568. {
  219569. XShmDetach (display, &segmentInfo);
  219570. XFlush (display);
  219571. XDestroyImage (xImage);
  219572. shmdt (segmentInfo.shmaddr);
  219573. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219574. }
  219575. else
  219576. #endif
  219577. {
  219578. xImage->data = 0;
  219579. XDestroyImage (xImage);
  219580. }
  219581. }
  219582. Image::ImageType getType() const { return Image::NativeImage; }
  219583. LowLevelGraphicsContext* createLowLevelContext()
  219584. {
  219585. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219586. }
  219587. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  219588. {
  219589. bitmap.data = imageData + x * pixelStride + y * lineStride;
  219590. bitmap.pixelFormat = format;
  219591. bitmap.lineStride = lineStride;
  219592. bitmap.pixelStride = pixelStride;
  219593. }
  219594. SharedImage* clone()
  219595. {
  219596. jassertfalse;
  219597. return 0;
  219598. }
  219599. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219600. {
  219601. ScopedXLock xlock;
  219602. if (gc == None)
  219603. {
  219604. XGCValues gcvalues;
  219605. gcvalues.foreground = None;
  219606. gcvalues.background = None;
  219607. gcvalues.function = GXcopy;
  219608. gcvalues.plane_mask = AllPlanes;
  219609. gcvalues.clip_mask = None;
  219610. gcvalues.graphics_exposures = False;
  219611. gc = XCreateGC (display, window,
  219612. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219613. &gcvalues);
  219614. }
  219615. if (imageDepth == 16)
  219616. {
  219617. const uint32 rMask = xImage->red_mask;
  219618. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219619. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219620. const uint32 gMask = xImage->green_mask;
  219621. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219622. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219623. const uint32 bMask = xImage->blue_mask;
  219624. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219625. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219626. const Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
  219627. for (int y = sy; y < sy + dh; ++y)
  219628. {
  219629. const uint8* p = srcData.getPixelPointer (sx, y);
  219630. for (int x = sx; x < sx + dw; ++x)
  219631. {
  219632. const PixelRGB* const pixel = (const PixelRGB*) p;
  219633. p += srcData.pixelStride;
  219634. XPutPixel (xImage, x, y,
  219635. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219636. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219637. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219638. }
  219639. }
  219640. }
  219641. // blit results to screen.
  219642. #if JUCE_USE_XSHM
  219643. if (usingXShm)
  219644. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219645. else
  219646. #endif
  219647. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219648. }
  219649. private:
  219650. XImage* xImage;
  219651. const int imageDepth;
  219652. HeapBlock <uint8> imageDataAllocated;
  219653. HeapBlock <char> imageData16Bit;
  219654. int pixelStride, lineStride;
  219655. uint8* imageData;
  219656. GC gc;
  219657. #if JUCE_USE_XSHM
  219658. XShmSegmentInfo segmentInfo;
  219659. bool usingXShm;
  219660. #endif
  219661. static int getShiftNeeded (const uint32 mask) throw()
  219662. {
  219663. for (int i = 32; --i >= 0;)
  219664. if (((mask >> i) & 1) != 0)
  219665. return i - 7;
  219666. jassertfalse;
  219667. return 0;
  219668. }
  219669. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219670. };
  219671. namespace PixmapHelpers
  219672. {
  219673. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219674. {
  219675. ScopedXLock xlock;
  219676. const int width = image.getWidth();
  219677. const int height = image.getHeight();
  219678. HeapBlock <uint32> colour (width * height);
  219679. int index = 0;
  219680. for (int y = 0; y < height; ++y)
  219681. for (int x = 0; x < width; ++x)
  219682. colour[index++] = image.getPixelAt (x, y).getARGB();
  219683. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219684. 0, reinterpret_cast<char*> (colour.getData()),
  219685. width, height, 32, 0);
  219686. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219687. width, height, 24);
  219688. GC gc = XCreateGC (display, pixmap, 0, 0);
  219689. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219690. XFreeGC (display, gc);
  219691. return pixmap;
  219692. }
  219693. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219694. {
  219695. ScopedXLock xlock;
  219696. const int width = image.getWidth();
  219697. const int height = image.getHeight();
  219698. const int stride = (width + 7) >> 3;
  219699. HeapBlock <char> mask;
  219700. mask.calloc (stride * height);
  219701. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219702. for (int y = 0; y < height; ++y)
  219703. {
  219704. for (int x = 0; x < width; ++x)
  219705. {
  219706. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219707. const int offset = y * stride + (x >> 3);
  219708. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219709. mask[offset] |= bit;
  219710. }
  219711. }
  219712. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219713. mask.getData(), width, height, 1, 0, 1);
  219714. }
  219715. }
  219716. class LinuxComponentPeer : public ComponentPeer
  219717. {
  219718. public:
  219719. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219720. : ComponentPeer (component, windowStyleFlags),
  219721. windowH (0),
  219722. parentWindow (0),
  219723. wx (0),
  219724. wy (0),
  219725. ww (0),
  219726. wh (0),
  219727. fullScreen (false),
  219728. mapped (false),
  219729. visual (0),
  219730. depth (0)
  219731. {
  219732. // it's dangerous to create a window on a thread other than the message thread..
  219733. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219734. repainter = new LinuxRepaintManager (this);
  219735. createWindow();
  219736. setTitle (component->getName());
  219737. }
  219738. ~LinuxComponentPeer()
  219739. {
  219740. // it's dangerous to delete a window on a thread other than the message thread..
  219741. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219742. deleteIconPixmaps();
  219743. destroyWindow();
  219744. windowH = 0;
  219745. }
  219746. void* getNativeHandle() const
  219747. {
  219748. return (void*) windowH;
  219749. }
  219750. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219751. {
  219752. XPointer peer = 0;
  219753. ScopedXLock xlock;
  219754. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219755. {
  219756. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219757. peer = 0;
  219758. }
  219759. return (LinuxComponentPeer*) peer;
  219760. }
  219761. void setVisible (bool shouldBeVisible)
  219762. {
  219763. ScopedXLock xlock;
  219764. if (shouldBeVisible)
  219765. XMapWindow (display, windowH);
  219766. else
  219767. XUnmapWindow (display, windowH);
  219768. }
  219769. void setTitle (const String& title)
  219770. {
  219771. XTextProperty nameProperty;
  219772. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219773. ScopedXLock xlock;
  219774. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219775. {
  219776. XSetWMName (display, windowH, &nameProperty);
  219777. XSetWMIconName (display, windowH, &nameProperty);
  219778. XFree (nameProperty.value);
  219779. }
  219780. }
  219781. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219782. {
  219783. fullScreen = isNowFullScreen;
  219784. if (windowH != 0)
  219785. {
  219786. WeakReference<Component> deletionChecker (component);
  219787. wx = x;
  219788. wy = y;
  219789. ww = jmax (1, w);
  219790. wh = jmax (1, h);
  219791. ScopedXLock xlock;
  219792. // Make sure the Window manager does what we want
  219793. XSizeHints* hints = XAllocSizeHints();
  219794. hints->flags = USSize | USPosition;
  219795. hints->width = ww;
  219796. hints->height = wh;
  219797. hints->x = wx;
  219798. hints->y = wy;
  219799. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219800. {
  219801. hints->min_width = hints->max_width = hints->width;
  219802. hints->min_height = hints->max_height = hints->height;
  219803. hints->flags |= PMinSize | PMaxSize;
  219804. }
  219805. XSetWMNormalHints (display, windowH, hints);
  219806. XFree (hints);
  219807. XMoveResizeWindow (display, windowH,
  219808. wx - windowBorder.getLeft(),
  219809. wy - windowBorder.getTop(), ww, wh);
  219810. if (deletionChecker != 0)
  219811. {
  219812. updateBorderSize();
  219813. handleMovedOrResized();
  219814. }
  219815. }
  219816. }
  219817. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219818. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219819. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219820. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219821. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219822. {
  219823. return relativePosition + getScreenPosition();
  219824. }
  219825. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219826. {
  219827. return screenPosition - getScreenPosition();
  219828. }
  219829. void setAlpha (float newAlpha)
  219830. {
  219831. //xxx todo!
  219832. }
  219833. void setMinimised (bool shouldBeMinimised)
  219834. {
  219835. if (shouldBeMinimised)
  219836. {
  219837. Window root = RootWindow (display, DefaultScreen (display));
  219838. XClientMessageEvent clientMsg;
  219839. clientMsg.display = display;
  219840. clientMsg.window = windowH;
  219841. clientMsg.type = ClientMessage;
  219842. clientMsg.format = 32;
  219843. clientMsg.message_type = Atoms::ChangeState;
  219844. clientMsg.data.l[0] = IconicState;
  219845. ScopedXLock xlock;
  219846. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219847. }
  219848. else
  219849. {
  219850. setVisible (true);
  219851. }
  219852. }
  219853. bool isMinimised() const
  219854. {
  219855. bool minimised = false;
  219856. unsigned char* stateProp;
  219857. unsigned long nitems, bytesLeft;
  219858. Atom actualType;
  219859. int actualFormat;
  219860. ScopedXLock xlock;
  219861. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219862. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219863. &stateProp) == Success
  219864. && actualType == Atoms::State
  219865. && actualFormat == 32
  219866. && nitems > 0)
  219867. {
  219868. if (((unsigned long*) stateProp)[0] == IconicState)
  219869. minimised = true;
  219870. XFree (stateProp);
  219871. }
  219872. return minimised;
  219873. }
  219874. void setFullScreen (const bool shouldBeFullScreen)
  219875. {
  219876. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219877. setMinimised (false);
  219878. if (fullScreen != shouldBeFullScreen)
  219879. {
  219880. if (shouldBeFullScreen)
  219881. r = Desktop::getInstance().getMainMonitorArea();
  219882. if (! r.isEmpty())
  219883. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219884. getComponent()->repaint();
  219885. }
  219886. }
  219887. bool isFullScreen() const
  219888. {
  219889. return fullScreen;
  219890. }
  219891. bool isChildWindowOf (Window possibleParent) const
  219892. {
  219893. Window* windowList = 0;
  219894. uint32 windowListSize = 0;
  219895. Window parent, root;
  219896. ScopedXLock xlock;
  219897. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219898. {
  219899. if (windowList != 0)
  219900. XFree (windowList);
  219901. return parent == possibleParent;
  219902. }
  219903. return false;
  219904. }
  219905. bool isFrontWindow() const
  219906. {
  219907. Window* windowList = 0;
  219908. uint32 windowListSize = 0;
  219909. bool result = false;
  219910. ScopedXLock xlock;
  219911. Window parent, root = RootWindow (display, DefaultScreen (display));
  219912. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219913. {
  219914. for (int i = windowListSize; --i >= 0;)
  219915. {
  219916. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219917. if (peer != 0)
  219918. {
  219919. result = (peer == this);
  219920. break;
  219921. }
  219922. }
  219923. }
  219924. if (windowList != 0)
  219925. XFree (windowList);
  219926. return result;
  219927. }
  219928. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219929. {
  219930. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219931. return false;
  219932. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219933. {
  219934. Component* const c = Desktop::getInstance().getComponent (i);
  219935. if (c == getComponent())
  219936. break;
  219937. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219938. return false;
  219939. }
  219940. if (trueIfInAChildWindow)
  219941. return true;
  219942. ::Window root, child;
  219943. unsigned int bw, depth;
  219944. int wx, wy, w, h;
  219945. ScopedXLock xlock;
  219946. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219947. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219948. &bw, &depth))
  219949. {
  219950. return false;
  219951. }
  219952. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219953. return false;
  219954. return child == None;
  219955. }
  219956. const BorderSize<int> getFrameSize() const
  219957. {
  219958. return BorderSize<int>();
  219959. }
  219960. bool setAlwaysOnTop (bool alwaysOnTop)
  219961. {
  219962. return false;
  219963. }
  219964. void toFront (bool makeActive)
  219965. {
  219966. if (makeActive)
  219967. {
  219968. setVisible (true);
  219969. grabFocus();
  219970. }
  219971. XEvent ev;
  219972. ev.xclient.type = ClientMessage;
  219973. ev.xclient.serial = 0;
  219974. ev.xclient.send_event = True;
  219975. ev.xclient.message_type = Atoms::ActiveWin;
  219976. ev.xclient.window = windowH;
  219977. ev.xclient.format = 32;
  219978. ev.xclient.data.l[0] = 2;
  219979. ev.xclient.data.l[1] = CurrentTime;
  219980. ev.xclient.data.l[2] = 0;
  219981. ev.xclient.data.l[3] = 0;
  219982. ev.xclient.data.l[4] = 0;
  219983. {
  219984. ScopedXLock xlock;
  219985. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219986. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219987. XWindowAttributes attr;
  219988. XGetWindowAttributes (display, windowH, &attr);
  219989. if (component->isAlwaysOnTop())
  219990. XRaiseWindow (display, windowH);
  219991. XSync (display, False);
  219992. }
  219993. handleBroughtToFront();
  219994. }
  219995. void toBehind (ComponentPeer* other)
  219996. {
  219997. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219998. jassert (otherPeer != 0); // wrong type of window?
  219999. if (otherPeer != 0)
  220000. {
  220001. setMinimised (false);
  220002. Window newStack[] = { otherPeer->windowH, windowH };
  220003. ScopedXLock xlock;
  220004. XRestackWindows (display, newStack, 2);
  220005. }
  220006. }
  220007. bool isFocused() const
  220008. {
  220009. int revert = 0;
  220010. Window focusedWindow = 0;
  220011. ScopedXLock xlock;
  220012. XGetInputFocus (display, &focusedWindow, &revert);
  220013. return focusedWindow == windowH;
  220014. }
  220015. void grabFocus()
  220016. {
  220017. XWindowAttributes atts;
  220018. ScopedXLock xlock;
  220019. if (windowH != 0
  220020. && XGetWindowAttributes (display, windowH, &atts)
  220021. && atts.map_state == IsViewable
  220022. && ! isFocused())
  220023. {
  220024. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220025. isActiveApplication = true;
  220026. }
  220027. }
  220028. void textInputRequired (const Point<int>&)
  220029. {
  220030. }
  220031. void repaint (const Rectangle<int>& area)
  220032. {
  220033. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220034. }
  220035. void performAnyPendingRepaintsNow()
  220036. {
  220037. repainter->performAnyPendingRepaintsNow();
  220038. }
  220039. void setIcon (const Image& newIcon)
  220040. {
  220041. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220042. HeapBlock <unsigned long> data (dataSize);
  220043. int index = 0;
  220044. data[index++] = newIcon.getWidth();
  220045. data[index++] = newIcon.getHeight();
  220046. for (int y = 0; y < newIcon.getHeight(); ++y)
  220047. for (int x = 0; x < newIcon.getWidth(); ++x)
  220048. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220049. ScopedXLock xlock;
  220050. XChangeProperty (display, windowH,
  220051. XInternAtom (display, "_NET_WM_ICON", False),
  220052. XA_CARDINAL, 32, PropModeReplace,
  220053. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220054. deleteIconPixmaps();
  220055. XWMHints* wmHints = XGetWMHints (display, windowH);
  220056. if (wmHints == 0)
  220057. wmHints = XAllocWMHints();
  220058. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220059. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  220060. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  220061. XSetWMHints (display, windowH, wmHints);
  220062. XFree (wmHints);
  220063. XSync (display, False);
  220064. }
  220065. void deleteIconPixmaps()
  220066. {
  220067. ScopedXLock xlock;
  220068. XWMHints* wmHints = XGetWMHints (display, windowH);
  220069. if (wmHints != 0)
  220070. {
  220071. if ((wmHints->flags & IconPixmapHint) != 0)
  220072. {
  220073. wmHints->flags &= ~IconPixmapHint;
  220074. XFreePixmap (display, wmHints->icon_pixmap);
  220075. }
  220076. if ((wmHints->flags & IconMaskHint) != 0)
  220077. {
  220078. wmHints->flags &= ~IconMaskHint;
  220079. XFreePixmap (display, wmHints->icon_mask);
  220080. }
  220081. XSetWMHints (display, windowH, wmHints);
  220082. XFree (wmHints);
  220083. }
  220084. }
  220085. void handleWindowMessage (XEvent* event)
  220086. {
  220087. switch (event->xany.type)
  220088. {
  220089. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  220090. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  220091. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  220092. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  220093. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  220094. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  220095. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  220096. case FocusIn: handleFocusInEvent(); break;
  220097. case FocusOut: handleFocusOutEvent(); break;
  220098. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  220099. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  220100. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  220101. case SelectionNotify: handleDragAndDropSelection (event); break;
  220102. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  220103. case ReparentNotify: handleReparentNotifyEvent(); break;
  220104. case GravityNotify: handleGravityNotify(); break;
  220105. case CirculateNotify:
  220106. case CreateNotify:
  220107. case DestroyNotify:
  220108. // Think we can ignore these
  220109. break;
  220110. case MapNotify:
  220111. mapped = true;
  220112. handleBroughtToFront();
  220113. break;
  220114. case UnmapNotify:
  220115. mapped = false;
  220116. break;
  220117. case SelectionClear:
  220118. case SelectionRequest:
  220119. break;
  220120. default:
  220121. #if JUCE_USE_XSHM
  220122. {
  220123. ScopedXLock xlock;
  220124. if (event->xany.type == XShmGetEventBase (display))
  220125. repainter->notifyPaintCompleted();
  220126. }
  220127. #endif
  220128. break;
  220129. }
  220130. }
  220131. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  220132. {
  220133. char utf8 [64] = { 0 };
  220134. juce_wchar unicodeChar = 0;
  220135. int keyCode = 0;
  220136. bool keyDownChange = false;
  220137. KeySym sym;
  220138. {
  220139. ScopedXLock xlock;
  220140. updateKeyStates (keyEvent->keycode, true);
  220141. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220142. ::setlocale (LC_ALL, "");
  220143. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220144. ::setlocale (LC_ALL, oldLocale);
  220145. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220146. keyCode = (int) unicodeChar;
  220147. if (keyCode < 0x20)
  220148. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220149. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220150. }
  220151. const ModifierKeys oldMods (currentModifiers);
  220152. bool keyPressed = false;
  220153. if ((sym & 0xff00) == 0xff00)
  220154. {
  220155. switch (sym) // Translate keypad
  220156. {
  220157. case XK_KP_Divide: keyCode = XK_slash; break;
  220158. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  220159. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  220160. case XK_KP_Add: keyCode = XK_plus; break;
  220161. case XK_KP_Enter: keyCode = XK_Return; break;
  220162. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  220163. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  220164. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  220165. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  220166. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  220167. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  220168. case XK_KP_5: keyCode = XK_5; break;
  220169. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  220170. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  220171. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  220172. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  220173. default: break;
  220174. }
  220175. switch (sym)
  220176. {
  220177. case XK_Left:
  220178. case XK_Right:
  220179. case XK_Up:
  220180. case XK_Down:
  220181. case XK_Page_Up:
  220182. case XK_Page_Down:
  220183. case XK_End:
  220184. case XK_Home:
  220185. case XK_Delete:
  220186. case XK_Insert:
  220187. keyPressed = true;
  220188. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220189. break;
  220190. case XK_Tab:
  220191. case XK_Return:
  220192. case XK_Escape:
  220193. case XK_BackSpace:
  220194. keyPressed = true;
  220195. keyCode &= 0xff;
  220196. break;
  220197. default:
  220198. if (sym >= XK_F1 && sym <= XK_F16)
  220199. {
  220200. keyPressed = true;
  220201. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220202. }
  220203. break;
  220204. }
  220205. }
  220206. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220207. keyPressed = true;
  220208. if (oldMods != currentModifiers)
  220209. handleModifierKeysChange();
  220210. if (keyDownChange)
  220211. handleKeyUpOrDown (true);
  220212. if (keyPressed)
  220213. handleKeyPress (keyCode, unicodeChar);
  220214. }
  220215. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  220216. {
  220217. updateKeyStates (keyEvent->keycode, false);
  220218. KeySym sym;
  220219. {
  220220. ScopedXLock xlock;
  220221. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220222. }
  220223. const ModifierKeys oldMods (currentModifiers);
  220224. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220225. if (oldMods != currentModifiers)
  220226. handleModifierKeysChange();
  220227. if (keyDownChange)
  220228. handleKeyUpOrDown (false);
  220229. }
  220230. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  220231. {
  220232. updateKeyModifiers (buttonPressEvent->state);
  220233. bool buttonMsg = false;
  220234. const int map = pointerMap [buttonPressEvent->button - Button1];
  220235. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220236. {
  220237. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220238. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220239. }
  220240. if (map == Keys::LeftButton)
  220241. {
  220242. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220243. buttonMsg = true;
  220244. }
  220245. else if (map == Keys::RightButton)
  220246. {
  220247. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220248. buttonMsg = true;
  220249. }
  220250. else if (map == Keys::MiddleButton)
  220251. {
  220252. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220253. buttonMsg = true;
  220254. }
  220255. if (buttonMsg)
  220256. {
  220257. toFront (true);
  220258. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220259. getEventTime (buttonPressEvent->time));
  220260. }
  220261. clearLastMousePos();
  220262. }
  220263. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  220264. {
  220265. updateKeyModifiers (buttonRelEvent->state);
  220266. const int map = pointerMap [buttonRelEvent->button - Button1];
  220267. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220268. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220269. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220270. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220271. getEventTime (buttonRelEvent->time));
  220272. clearLastMousePos();
  220273. }
  220274. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  220275. {
  220276. updateKeyModifiers (movedEvent->state);
  220277. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  220278. if (lastMousePos != mousePos)
  220279. {
  220280. lastMousePos = mousePos;
  220281. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220282. {
  220283. Window wRoot = 0, wParent = 0;
  220284. {
  220285. ScopedXLock xlock;
  220286. unsigned int numChildren;
  220287. Window* wChild = 0;
  220288. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220289. }
  220290. if (wParent != 0
  220291. && wParent != windowH
  220292. && wParent != wRoot)
  220293. {
  220294. parentWindow = wParent;
  220295. updateBounds();
  220296. }
  220297. else
  220298. {
  220299. parentWindow = 0;
  220300. }
  220301. }
  220302. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220303. }
  220304. }
  220305. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  220306. {
  220307. clearLastMousePos();
  220308. if (! currentModifiers.isAnyMouseButtonDown())
  220309. {
  220310. updateKeyModifiers (enterEvent->state);
  220311. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220312. }
  220313. }
  220314. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  220315. {
  220316. // Suppress the normal leave if we've got a pointer grab, or if
  220317. // it's a bogus one caused by clicking a mouse button when running
  220318. // in a Window manager
  220319. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220320. || leaveEvent->mode == NotifyUngrab)
  220321. {
  220322. updateKeyModifiers (leaveEvent->state);
  220323. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220324. }
  220325. }
  220326. void handleFocusInEvent()
  220327. {
  220328. isActiveApplication = true;
  220329. if (isFocused())
  220330. handleFocusGain();
  220331. }
  220332. void handleFocusOutEvent()
  220333. {
  220334. isActiveApplication = false;
  220335. if (! isFocused())
  220336. handleFocusLoss();
  220337. }
  220338. void handleExposeEvent (XExposeEvent* exposeEvent)
  220339. {
  220340. // Batch together all pending expose events
  220341. XEvent nextEvent;
  220342. ScopedXLock xlock;
  220343. if (exposeEvent->window != windowH)
  220344. {
  220345. Window child;
  220346. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220347. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220348. &child);
  220349. }
  220350. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220351. exposeEvent->width, exposeEvent->height));
  220352. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220353. {
  220354. XPeekEvent (display, (XEvent*) &nextEvent);
  220355. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220356. break;
  220357. XNextEvent (display, (XEvent*) &nextEvent);
  220358. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220359. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220360. nextExposeEvent->width, nextExposeEvent->height));
  220361. }
  220362. }
  220363. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220364. {
  220365. updateBounds();
  220366. updateBorderSize();
  220367. handleMovedOrResized();
  220368. // if the native title bar is dragged, need to tell any active menus, etc.
  220369. if ((styleFlags & windowHasTitleBar) != 0
  220370. && component->isCurrentlyBlockedByAnotherModalComponent())
  220371. {
  220372. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220373. if (currentModalComp != 0)
  220374. currentModalComp->inputAttemptWhenModal();
  220375. }
  220376. if (confEvent->window == windowH
  220377. && confEvent->above != 0
  220378. && isFrontWindow())
  220379. {
  220380. handleBroughtToFront();
  220381. }
  220382. }
  220383. void handleReparentNotifyEvent()
  220384. {
  220385. parentWindow = 0;
  220386. Window wRoot = 0;
  220387. Window* wChild = 0;
  220388. unsigned int numChildren;
  220389. {
  220390. ScopedXLock xlock;
  220391. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220392. }
  220393. if (parentWindow == windowH || parentWindow == wRoot)
  220394. parentWindow = 0;
  220395. handleGravityNotify();
  220396. }
  220397. void handleGravityNotify()
  220398. {
  220399. updateBounds();
  220400. updateBorderSize();
  220401. handleMovedOrResized();
  220402. }
  220403. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220404. {
  220405. if (mappingEvent->request != MappingPointer)
  220406. {
  220407. // Deal with modifier/keyboard mapping
  220408. ScopedXLock xlock;
  220409. XRefreshKeyboardMapping (mappingEvent);
  220410. updateModifierMappings();
  220411. }
  220412. }
  220413. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220414. {
  220415. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220416. {
  220417. const Atom atom = (Atom) clientMsg->data.l[0];
  220418. if (atom == Atoms::ProtocolList [Atoms::PING])
  220419. {
  220420. Window root = RootWindow (display, DefaultScreen (display));
  220421. clientMsg->window = root;
  220422. XSendEvent (display, root, False, NoEventMask, event);
  220423. XFlush (display);
  220424. }
  220425. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220426. {
  220427. XWindowAttributes atts;
  220428. ScopedXLock xlock;
  220429. if (clientMsg->window != 0
  220430. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220431. {
  220432. if (atts.map_state == IsViewable)
  220433. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220434. }
  220435. }
  220436. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220437. {
  220438. handleUserClosingWindow();
  220439. }
  220440. }
  220441. else if (clientMsg->message_type == Atoms::XdndEnter)
  220442. {
  220443. handleDragAndDropEnter (clientMsg);
  220444. }
  220445. else if (clientMsg->message_type == Atoms::XdndLeave)
  220446. {
  220447. resetDragAndDrop();
  220448. }
  220449. else if (clientMsg->message_type == Atoms::XdndPosition)
  220450. {
  220451. handleDragAndDropPosition (clientMsg);
  220452. }
  220453. else if (clientMsg->message_type == Atoms::XdndDrop)
  220454. {
  220455. handleDragAndDropDrop (clientMsg);
  220456. }
  220457. else if (clientMsg->message_type == Atoms::XdndStatus)
  220458. {
  220459. handleDragAndDropStatus (clientMsg);
  220460. }
  220461. else if (clientMsg->message_type == Atoms::XdndFinished)
  220462. {
  220463. resetDragAndDrop();
  220464. }
  220465. }
  220466. void showMouseCursor (Cursor cursor) throw()
  220467. {
  220468. ScopedXLock xlock;
  220469. XDefineCursor (display, windowH, cursor);
  220470. }
  220471. void setTaskBarIcon (const Image& image)
  220472. {
  220473. ScopedXLock xlock;
  220474. taskbarImage = image;
  220475. Screen* const screen = XDefaultScreenOfDisplay (display);
  220476. const int screenNumber = XScreenNumberOfScreen (screen);
  220477. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220478. screenAtom << screenNumber;
  220479. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220480. XGrabServer (display);
  220481. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220482. if (managerWin != None)
  220483. XSelectInput (display, managerWin, StructureNotifyMask);
  220484. XUngrabServer (display);
  220485. XFlush (display);
  220486. if (managerWin != None)
  220487. {
  220488. XEvent ev;
  220489. zerostruct (ev);
  220490. ev.xclient.type = ClientMessage;
  220491. ev.xclient.window = managerWin;
  220492. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220493. ev.xclient.format = 32;
  220494. ev.xclient.data.l[0] = CurrentTime;
  220495. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220496. ev.xclient.data.l[2] = windowH;
  220497. ev.xclient.data.l[3] = 0;
  220498. ev.xclient.data.l[4] = 0;
  220499. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220500. XSync (display, False);
  220501. }
  220502. // For older KDE's ...
  220503. long atomData = 1;
  220504. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220505. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220506. // For more recent KDE's...
  220507. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220508. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220509. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220510. XSizeHints* hints = XAllocSizeHints();
  220511. hints->flags = PMinSize;
  220512. hints->min_width = 22;
  220513. hints->min_height = 22;
  220514. XSetWMNormalHints (display, windowH, hints);
  220515. XFree (hints);
  220516. }
  220517. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220518. bool dontRepaint;
  220519. static ModifierKeys currentModifiers;
  220520. static bool isActiveApplication;
  220521. private:
  220522. class LinuxRepaintManager : public Timer
  220523. {
  220524. public:
  220525. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220526. : peer (peer_),
  220527. lastTimeImageUsed (0)
  220528. {
  220529. #if JUCE_USE_XSHM
  220530. shmCompletedDrawing = true;
  220531. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220532. if (useARGBImagesForRendering)
  220533. {
  220534. ScopedXLock xlock;
  220535. XShmSegmentInfo segmentinfo;
  220536. XImage* const testImage
  220537. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220538. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220539. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220540. XDestroyImage (testImage);
  220541. }
  220542. #endif
  220543. }
  220544. void timerCallback()
  220545. {
  220546. #if JUCE_USE_XSHM
  220547. if (! shmCompletedDrawing)
  220548. return;
  220549. #endif
  220550. if (! regionsNeedingRepaint.isEmpty())
  220551. {
  220552. stopTimer();
  220553. performAnyPendingRepaintsNow();
  220554. }
  220555. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220556. {
  220557. stopTimer();
  220558. image = Image::null;
  220559. }
  220560. }
  220561. void repaint (const Rectangle<int>& area)
  220562. {
  220563. if (! isTimerRunning())
  220564. startTimer (repaintTimerPeriod);
  220565. regionsNeedingRepaint.add (area);
  220566. }
  220567. void performAnyPendingRepaintsNow()
  220568. {
  220569. #if JUCE_USE_XSHM
  220570. if (! shmCompletedDrawing)
  220571. {
  220572. startTimer (repaintTimerPeriod);
  220573. return;
  220574. }
  220575. #endif
  220576. peer->clearMaskedRegion();
  220577. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220578. regionsNeedingRepaint.clear();
  220579. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220580. if (! totalArea.isEmpty())
  220581. {
  220582. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220583. || image.getHeight() < totalArea.getHeight())
  220584. {
  220585. #if JUCE_USE_XSHM
  220586. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220587. : Image::RGB,
  220588. #else
  220589. image = Image (new XBitmapImage (Image::RGB,
  220590. #endif
  220591. (totalArea.getWidth() + 31) & ~31,
  220592. (totalArea.getHeight() + 31) & ~31,
  220593. false, peer->depth, peer->visual));
  220594. }
  220595. startTimer (repaintTimerPeriod);
  220596. RectangleList adjustedList (originalRepaintRegion);
  220597. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220598. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220599. if (peer->depth == 32)
  220600. {
  220601. RectangleList::Iterator i (originalRepaintRegion);
  220602. while (i.next())
  220603. image.clear (*i.getRectangle() - totalArea.getPosition());
  220604. }
  220605. peer->handlePaint (context);
  220606. if (! peer->maskedRegion.isEmpty())
  220607. originalRepaintRegion.subtract (peer->maskedRegion);
  220608. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220609. {
  220610. #if JUCE_USE_XSHM
  220611. shmCompletedDrawing = false;
  220612. #endif
  220613. const Rectangle<int>& r = *i.getRectangle();
  220614. static_cast<XBitmapImage*> (image.getSharedImage())
  220615. ->blitToWindow (peer->windowH,
  220616. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220617. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220618. }
  220619. }
  220620. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220621. startTimer (repaintTimerPeriod);
  220622. }
  220623. #if JUCE_USE_XSHM
  220624. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220625. #endif
  220626. private:
  220627. enum { repaintTimerPeriod = 1000 / 100 };
  220628. LinuxComponentPeer* const peer;
  220629. Image image;
  220630. uint32 lastTimeImageUsed;
  220631. RectangleList regionsNeedingRepaint;
  220632. #if JUCE_USE_XSHM
  220633. bool useARGBImagesForRendering, shmCompletedDrawing;
  220634. #endif
  220635. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220636. };
  220637. ScopedPointer <LinuxRepaintManager> repainter;
  220638. friend class LinuxRepaintManager;
  220639. Window windowH, parentWindow;
  220640. int wx, wy, ww, wh;
  220641. Image taskbarImage;
  220642. bool fullScreen, mapped;
  220643. Visual* visual;
  220644. int depth;
  220645. BorderSize<int> windowBorder;
  220646. struct MotifWmHints
  220647. {
  220648. unsigned long flags;
  220649. unsigned long functions;
  220650. unsigned long decorations;
  220651. long input_mode;
  220652. unsigned long status;
  220653. };
  220654. static void updateKeyStates (const int keycode, const bool press) throw()
  220655. {
  220656. const int keybyte = keycode >> 3;
  220657. const int keybit = (1 << (keycode & 7));
  220658. if (press)
  220659. Keys::keyStates [keybyte] |= keybit;
  220660. else
  220661. Keys::keyStates [keybyte] &= ~keybit;
  220662. }
  220663. static void updateKeyModifiers (const int status) throw()
  220664. {
  220665. int keyMods = 0;
  220666. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220667. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220668. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220669. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220670. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220671. Keys::capsLock = ((status & LockMask) != 0);
  220672. }
  220673. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220674. {
  220675. int modifier = 0;
  220676. bool isModifier = true;
  220677. switch (sym)
  220678. {
  220679. case XK_Shift_L:
  220680. case XK_Shift_R:
  220681. modifier = ModifierKeys::shiftModifier;
  220682. break;
  220683. case XK_Control_L:
  220684. case XK_Control_R:
  220685. modifier = ModifierKeys::ctrlModifier;
  220686. break;
  220687. case XK_Alt_L:
  220688. case XK_Alt_R:
  220689. modifier = ModifierKeys::altModifier;
  220690. break;
  220691. case XK_Num_Lock:
  220692. if (press)
  220693. Keys::numLock = ! Keys::numLock;
  220694. break;
  220695. case XK_Caps_Lock:
  220696. if (press)
  220697. Keys::capsLock = ! Keys::capsLock;
  220698. break;
  220699. case XK_Scroll_Lock:
  220700. break;
  220701. default:
  220702. isModifier = false;
  220703. break;
  220704. }
  220705. if (modifier != 0)
  220706. {
  220707. if (press)
  220708. currentModifiers = currentModifiers.withFlags (modifier);
  220709. else
  220710. currentModifiers = currentModifiers.withoutFlags (modifier);
  220711. }
  220712. return isModifier;
  220713. }
  220714. // Alt and Num lock are not defined by standard X
  220715. // modifier constants: check what they're mapped to
  220716. static void updateModifierMappings() throw()
  220717. {
  220718. ScopedXLock xlock;
  220719. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220720. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220721. Keys::AltMask = 0;
  220722. Keys::NumLockMask = 0;
  220723. XModifierKeymap* mapping = XGetModifierMapping (display);
  220724. if (mapping)
  220725. {
  220726. for (int i = 0; i < 8; i++)
  220727. {
  220728. if (mapping->modifiermap [i << 1] == altLeftCode)
  220729. Keys::AltMask = 1 << i;
  220730. else if (mapping->modifiermap [i << 1] == numLockCode)
  220731. Keys::NumLockMask = 1 << i;
  220732. }
  220733. XFreeModifiermap (mapping);
  220734. }
  220735. }
  220736. void removeWindowDecorations (Window wndH)
  220737. {
  220738. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220739. if (hints != None)
  220740. {
  220741. MotifWmHints motifHints;
  220742. zerostruct (motifHints);
  220743. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220744. motifHints.decorations = 0;
  220745. ScopedXLock xlock;
  220746. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220747. (unsigned char*) &motifHints, 4);
  220748. }
  220749. hints = XInternAtom (display, "_WIN_HINTS", True);
  220750. if (hints != None)
  220751. {
  220752. long gnomeHints = 0;
  220753. ScopedXLock xlock;
  220754. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220755. (unsigned char*) &gnomeHints, 1);
  220756. }
  220757. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220758. if (hints != None)
  220759. {
  220760. long kwmHints = 2; /*KDE_tinyDecoration*/
  220761. ScopedXLock xlock;
  220762. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220763. (unsigned char*) &kwmHints, 1);
  220764. }
  220765. }
  220766. void addWindowButtons (Window wndH)
  220767. {
  220768. ScopedXLock xlock;
  220769. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220770. if (hints != None)
  220771. {
  220772. MotifWmHints motifHints;
  220773. zerostruct (motifHints);
  220774. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220775. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220776. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220777. if ((styleFlags & windowHasCloseButton) != 0)
  220778. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220779. if ((styleFlags & windowHasMinimiseButton) != 0)
  220780. {
  220781. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220782. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220783. }
  220784. if ((styleFlags & windowHasMaximiseButton) != 0)
  220785. {
  220786. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220787. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220788. }
  220789. if ((styleFlags & windowIsResizable) != 0)
  220790. {
  220791. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220792. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220793. }
  220794. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220795. }
  220796. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220797. if (hints != None)
  220798. {
  220799. int netHints [6];
  220800. int num = 0;
  220801. if ((styleFlags & windowIsResizable) != 0)
  220802. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220803. if ((styleFlags & windowHasMaximiseButton) != 0)
  220804. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220805. if ((styleFlags & windowHasMinimiseButton) != 0)
  220806. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220807. if ((styleFlags & windowHasCloseButton) != 0)
  220808. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220809. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220810. }
  220811. }
  220812. void setWindowType()
  220813. {
  220814. int netHints [2];
  220815. int numHints = 0;
  220816. if ((styleFlags & windowIsTemporary) != 0
  220817. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220818. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220819. else
  220820. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220821. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220822. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220823. (unsigned char*) &netHints, numHints);
  220824. numHints = 0;
  220825. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220826. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220827. if (component->isAlwaysOnTop())
  220828. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220829. if (numHints > 0)
  220830. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220831. (unsigned char*) &netHints, numHints);
  220832. }
  220833. void createWindow()
  220834. {
  220835. ScopedXLock xlock;
  220836. Atoms::initialiseAtoms();
  220837. resetDragAndDrop();
  220838. // Get defaults for various properties
  220839. const int screen = DefaultScreen (display);
  220840. Window root = RootWindow (display, screen);
  220841. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220842. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220843. if (visual == 0)
  220844. {
  220845. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220846. Process::terminate();
  220847. }
  220848. // Create and install a colormap suitable fr our visual
  220849. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220850. XInstallColormap (display, colormap);
  220851. // Set up the window attributes
  220852. XSetWindowAttributes swa;
  220853. swa.border_pixel = 0;
  220854. swa.background_pixmap = None;
  220855. swa.colormap = colormap;
  220856. swa.event_mask = getAllEventsMask();
  220857. windowH = XCreateWindow (display, root,
  220858. 0, 0, 1, 1,
  220859. 0, depth, InputOutput, visual,
  220860. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220861. &swa);
  220862. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220863. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220864. GrabModeAsync, GrabModeAsync, None, None);
  220865. // Set the window context to identify the window handle object
  220866. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220867. {
  220868. // Failed
  220869. jassertfalse;
  220870. Logger::outputDebugString ("Failed to create context information for window.\n");
  220871. XDestroyWindow (display, windowH);
  220872. windowH = 0;
  220873. return;
  220874. }
  220875. // Set window manager hints
  220876. XWMHints* wmHints = XAllocWMHints();
  220877. wmHints->flags = InputHint | StateHint;
  220878. wmHints->input = True; // Locally active input model
  220879. wmHints->initial_state = NormalState;
  220880. XSetWMHints (display, windowH, wmHints);
  220881. XFree (wmHints);
  220882. // Set the window type
  220883. setWindowType();
  220884. // Define decoration
  220885. if ((styleFlags & windowHasTitleBar) == 0)
  220886. removeWindowDecorations (windowH);
  220887. else
  220888. addWindowButtons (windowH);
  220889. setTitle (getComponent()->getName());
  220890. // Associate the PID, allowing to be shut down when something goes wrong
  220891. unsigned long pid = getpid();
  220892. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220893. (unsigned char*) &pid, 1);
  220894. // Set window manager protocols
  220895. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220896. (unsigned char*) Atoms::ProtocolList, 2);
  220897. // Set drag and drop flags
  220898. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220899. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220900. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220901. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220902. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220903. (const unsigned char*) "", 0);
  220904. unsigned long dndVersion = Atoms::DndVersion;
  220905. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220906. (const unsigned char*) &dndVersion, 1);
  220907. // Initialise the pointer and keyboard mapping
  220908. // This is not the same as the logical pointer mapping the X server uses:
  220909. // we don't mess with this.
  220910. static bool mappingInitialised = false;
  220911. if (! mappingInitialised)
  220912. {
  220913. mappingInitialised = true;
  220914. const int numButtons = XGetPointerMapping (display, 0, 0);
  220915. if (numButtons == 2)
  220916. {
  220917. pointerMap[0] = Keys::LeftButton;
  220918. pointerMap[1] = Keys::RightButton;
  220919. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220920. }
  220921. else if (numButtons >= 3)
  220922. {
  220923. pointerMap[0] = Keys::LeftButton;
  220924. pointerMap[1] = Keys::MiddleButton;
  220925. pointerMap[2] = Keys::RightButton;
  220926. if (numButtons >= 5)
  220927. {
  220928. pointerMap[3] = Keys::WheelUp;
  220929. pointerMap[4] = Keys::WheelDown;
  220930. }
  220931. }
  220932. updateModifierMappings();
  220933. }
  220934. }
  220935. void destroyWindow()
  220936. {
  220937. ScopedXLock xlock;
  220938. XPointer handlePointer;
  220939. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220940. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220941. XDestroyWindow (display, windowH);
  220942. // Wait for it to complete and then remove any events for this
  220943. // window from the event queue.
  220944. XSync (display, false);
  220945. XEvent event;
  220946. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220947. {}
  220948. }
  220949. static int getAllEventsMask() throw()
  220950. {
  220951. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220952. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220953. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220954. }
  220955. static int64 getEventTime (::Time t)
  220956. {
  220957. static int64 eventTimeOffset = 0x12345678;
  220958. const int64 thisMessageTime = t;
  220959. if (eventTimeOffset == 0x12345678)
  220960. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220961. return eventTimeOffset + thisMessageTime;
  220962. }
  220963. void updateBorderSize()
  220964. {
  220965. if ((styleFlags & windowHasTitleBar) == 0)
  220966. {
  220967. windowBorder = BorderSize<int> (0);
  220968. }
  220969. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220970. {
  220971. ScopedXLock xlock;
  220972. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220973. if (hints != None)
  220974. {
  220975. unsigned char* data = 0;
  220976. unsigned long nitems, bytesLeft;
  220977. Atom actualType;
  220978. int actualFormat;
  220979. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220980. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220981. &data) == Success)
  220982. {
  220983. const unsigned long* const sizes = (const unsigned long*) data;
  220984. if (actualFormat == 32)
  220985. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220986. (int) sizes[3], (int) sizes[1]);
  220987. XFree (data);
  220988. }
  220989. }
  220990. }
  220991. }
  220992. void updateBounds()
  220993. {
  220994. jassert (windowH != 0);
  220995. if (windowH != 0)
  220996. {
  220997. Window root, child;
  220998. unsigned int bw, depth;
  220999. ScopedXLock xlock;
  221000. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221001. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221002. &bw, &depth))
  221003. {
  221004. wx = wy = ww = wh = 0;
  221005. }
  221006. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221007. {
  221008. wx = wy = 0;
  221009. }
  221010. }
  221011. }
  221012. void resetDragAndDrop()
  221013. {
  221014. dragAndDropFiles.clear();
  221015. lastDropPos = Point<int> (-1, -1);
  221016. dragAndDropCurrentMimeType = 0;
  221017. dragAndDropSourceWindow = 0;
  221018. srcMimeTypeAtomList.clear();
  221019. }
  221020. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221021. {
  221022. msg.type = ClientMessage;
  221023. msg.display = display;
  221024. msg.window = dragAndDropSourceWindow;
  221025. msg.format = 32;
  221026. msg.data.l[0] = windowH;
  221027. ScopedXLock xlock;
  221028. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221029. }
  221030. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221031. {
  221032. XClientMessageEvent msg;
  221033. zerostruct (msg);
  221034. msg.message_type = Atoms::XdndStatus;
  221035. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221036. msg.data.l[4] = dropAction;
  221037. sendDragAndDropMessage (msg);
  221038. }
  221039. void sendDragAndDropLeave()
  221040. {
  221041. XClientMessageEvent msg;
  221042. zerostruct (msg);
  221043. msg.message_type = Atoms::XdndLeave;
  221044. sendDragAndDropMessage (msg);
  221045. }
  221046. void sendDragAndDropFinish()
  221047. {
  221048. XClientMessageEvent msg;
  221049. zerostruct (msg);
  221050. msg.message_type = Atoms::XdndFinished;
  221051. sendDragAndDropMessage (msg);
  221052. }
  221053. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221054. {
  221055. if ((clientMsg->data.l[1] & 1) == 0)
  221056. {
  221057. sendDragAndDropLeave();
  221058. if (dragAndDropFiles.size() > 0)
  221059. handleFileDragExit (dragAndDropFiles);
  221060. dragAndDropFiles.clear();
  221061. }
  221062. }
  221063. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221064. {
  221065. if (dragAndDropSourceWindow == 0)
  221066. return;
  221067. dragAndDropSourceWindow = clientMsg->data.l[0];
  221068. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221069. (int) clientMsg->data.l[2] & 0xffff);
  221070. dropPos -= getScreenPosition();
  221071. if (lastDropPos != dropPos)
  221072. {
  221073. lastDropPos = dropPos;
  221074. dragAndDropTimestamp = clientMsg->data.l[3];
  221075. Atom targetAction = Atoms::XdndActionCopy;
  221076. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221077. {
  221078. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221079. {
  221080. targetAction = Atoms::allowedActions[i];
  221081. break;
  221082. }
  221083. }
  221084. sendDragAndDropStatus (true, targetAction);
  221085. if (dragAndDropFiles.size() == 0)
  221086. updateDraggedFileList (clientMsg);
  221087. if (dragAndDropFiles.size() > 0)
  221088. handleFileDragMove (dragAndDropFiles, dropPos);
  221089. }
  221090. }
  221091. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221092. {
  221093. if (dragAndDropFiles.size() == 0)
  221094. updateDraggedFileList (clientMsg);
  221095. const StringArray files (dragAndDropFiles);
  221096. const Point<int> lastPos (lastDropPos);
  221097. sendDragAndDropFinish();
  221098. resetDragAndDrop();
  221099. if (files.size() > 0)
  221100. handleFileDragDrop (files, lastPos);
  221101. }
  221102. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221103. {
  221104. dragAndDropFiles.clear();
  221105. srcMimeTypeAtomList.clear();
  221106. dragAndDropCurrentMimeType = 0;
  221107. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221108. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221109. {
  221110. dragAndDropSourceWindow = 0;
  221111. return;
  221112. }
  221113. dragAndDropSourceWindow = clientMsg->data.l[0];
  221114. if ((clientMsg->data.l[1] & 1) != 0)
  221115. {
  221116. Atom actual;
  221117. int format;
  221118. unsigned long count = 0, remaining = 0;
  221119. unsigned char* data = 0;
  221120. ScopedXLock xlock;
  221121. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221122. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221123. &count, &remaining, &data);
  221124. if (data != 0)
  221125. {
  221126. if (actual == XA_ATOM && format == 32 && count != 0)
  221127. {
  221128. const unsigned long* const types = (const unsigned long*) data;
  221129. for (unsigned int i = 0; i < count; ++i)
  221130. if (types[i] != None)
  221131. srcMimeTypeAtomList.add (types[i]);
  221132. }
  221133. XFree (data);
  221134. }
  221135. }
  221136. if (srcMimeTypeAtomList.size() == 0)
  221137. {
  221138. for (int i = 2; i < 5; ++i)
  221139. if (clientMsg->data.l[i] != None)
  221140. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221141. if (srcMimeTypeAtomList.size() == 0)
  221142. {
  221143. dragAndDropSourceWindow = 0;
  221144. return;
  221145. }
  221146. }
  221147. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221148. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221149. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221150. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221151. handleDragAndDropPosition (clientMsg);
  221152. }
  221153. void handleDragAndDropSelection (const XEvent* const evt)
  221154. {
  221155. dragAndDropFiles.clear();
  221156. if (evt->xselection.property != 0)
  221157. {
  221158. StringArray lines;
  221159. {
  221160. MemoryBlock dropData;
  221161. for (;;)
  221162. {
  221163. Atom actual;
  221164. uint8* data = 0;
  221165. unsigned long count = 0, remaining = 0;
  221166. int format = 0;
  221167. ScopedXLock xlock;
  221168. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221169. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221170. &format, &count, &remaining, &data) == Success)
  221171. {
  221172. dropData.append (data, count * format / 8);
  221173. XFree (data);
  221174. if (remaining == 0)
  221175. break;
  221176. }
  221177. else
  221178. {
  221179. XFree (data);
  221180. break;
  221181. }
  221182. }
  221183. lines.addLines (dropData.toString());
  221184. }
  221185. for (int i = 0; i < lines.size(); ++i)
  221186. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221187. dragAndDropFiles.trim();
  221188. dragAndDropFiles.removeEmptyStrings();
  221189. }
  221190. }
  221191. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221192. {
  221193. dragAndDropFiles.clear();
  221194. if (dragAndDropSourceWindow != None
  221195. && dragAndDropCurrentMimeType != 0)
  221196. {
  221197. dragAndDropTimestamp = clientMsg->data.l[2];
  221198. ScopedXLock xlock;
  221199. XConvertSelection (display,
  221200. Atoms::XdndSelection,
  221201. dragAndDropCurrentMimeType,
  221202. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221203. windowH,
  221204. dragAndDropTimestamp);
  221205. }
  221206. }
  221207. StringArray dragAndDropFiles;
  221208. int dragAndDropTimestamp;
  221209. Point<int> lastDropPos;
  221210. Atom dragAndDropCurrentMimeType;
  221211. Window dragAndDropSourceWindow;
  221212. Array <Atom> srcMimeTypeAtomList;
  221213. static int pointerMap[5];
  221214. static Point<int> lastMousePos;
  221215. static void clearLastMousePos() throw()
  221216. {
  221217. lastMousePos = Point<int> (0x100000, 0x100000);
  221218. }
  221219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  221220. };
  221221. ModifierKeys LinuxComponentPeer::currentModifiers;
  221222. bool LinuxComponentPeer::isActiveApplication = false;
  221223. int LinuxComponentPeer::pointerMap[5];
  221224. Point<int> LinuxComponentPeer::lastMousePos;
  221225. bool Process::isForegroundProcess()
  221226. {
  221227. return LinuxComponentPeer::isActiveApplication;
  221228. }
  221229. void ModifierKeys::updateCurrentModifiers() throw()
  221230. {
  221231. currentModifiers = LinuxComponentPeer::currentModifiers;
  221232. }
  221233. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221234. {
  221235. Window root, child;
  221236. int x, y, winx, winy;
  221237. unsigned int mask;
  221238. int mouseMods = 0;
  221239. ScopedXLock xlock;
  221240. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221241. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221242. {
  221243. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221244. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221245. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221246. }
  221247. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221248. return LinuxComponentPeer::currentModifiers;
  221249. }
  221250. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221251. {
  221252. if (enableOrDisable)
  221253. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221254. }
  221255. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221256. {
  221257. return new LinuxComponentPeer (this, styleFlags);
  221258. }
  221259. // (this callback is hooked up in the messaging code)
  221260. void juce_windowMessageReceive (XEvent* event)
  221261. {
  221262. if (event->xany.window != None)
  221263. {
  221264. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221265. if (ComponentPeer::isValidPeer (peer))
  221266. peer->handleWindowMessage (event);
  221267. }
  221268. else
  221269. {
  221270. switch (event->xany.type)
  221271. {
  221272. case KeymapNotify:
  221273. {
  221274. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221275. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221276. break;
  221277. }
  221278. default:
  221279. break;
  221280. }
  221281. }
  221282. }
  221283. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221284. {
  221285. if (display == 0)
  221286. return;
  221287. #if JUCE_USE_XINERAMA
  221288. int major_opcode, first_event, first_error;
  221289. ScopedXLock xlock;
  221290. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221291. {
  221292. typedef Bool (*tXineramaIsActive) (Display*);
  221293. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221294. static tXineramaIsActive xXineramaIsActive = 0;
  221295. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221296. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221297. {
  221298. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221299. if (h == 0)
  221300. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221301. if (h != 0)
  221302. {
  221303. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221304. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221305. }
  221306. }
  221307. if (xXineramaIsActive != 0
  221308. && xXineramaQueryScreens != 0
  221309. && xXineramaIsActive (display))
  221310. {
  221311. int numMonitors = 0;
  221312. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221313. if (screens != 0)
  221314. {
  221315. for (int i = numMonitors; --i >= 0;)
  221316. {
  221317. int index = screens[i].screen_number;
  221318. if (index >= 0)
  221319. {
  221320. while (monitorCoords.size() < index)
  221321. monitorCoords.add (Rectangle<int>());
  221322. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221323. screens[i].y_org,
  221324. screens[i].width,
  221325. screens[i].height));
  221326. }
  221327. }
  221328. XFree (screens);
  221329. }
  221330. }
  221331. }
  221332. if (monitorCoords.size() == 0)
  221333. #endif
  221334. {
  221335. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221336. if (hints != None)
  221337. {
  221338. const int numMonitors = ScreenCount (display);
  221339. for (int i = 0; i < numMonitors; ++i)
  221340. {
  221341. Window root = RootWindow (display, i);
  221342. unsigned long nitems, bytesLeft;
  221343. Atom actualType;
  221344. int actualFormat;
  221345. unsigned char* data = 0;
  221346. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221347. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221348. &data) == Success)
  221349. {
  221350. const long* const position = (const long*) data;
  221351. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221352. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221353. position[2], position[3]));
  221354. XFree (data);
  221355. }
  221356. }
  221357. }
  221358. if (monitorCoords.size() == 0)
  221359. {
  221360. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221361. DisplayHeight (display, DefaultScreen (display))));
  221362. }
  221363. }
  221364. }
  221365. void Desktop::createMouseInputSources()
  221366. {
  221367. mouseSources.add (new MouseInputSource (0, true));
  221368. }
  221369. bool Desktop::canUseSemiTransparentWindows() throw()
  221370. {
  221371. int matchedDepth = 0;
  221372. const int desiredDepth = 32;
  221373. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221374. && (matchedDepth == desiredDepth);
  221375. }
  221376. const Point<int> MouseInputSource::getCurrentMousePosition()
  221377. {
  221378. Window root, child;
  221379. int x, y, winx, winy;
  221380. unsigned int mask;
  221381. ScopedXLock xlock;
  221382. if (XQueryPointer (display,
  221383. RootWindow (display, DefaultScreen (display)),
  221384. &root, &child,
  221385. &x, &y, &winx, &winy, &mask) == False)
  221386. {
  221387. // Pointer not on the default screen
  221388. x = y = -1;
  221389. }
  221390. return Point<int> (x, y);
  221391. }
  221392. void Desktop::setMousePosition (const Point<int>& newPosition)
  221393. {
  221394. ScopedXLock xlock;
  221395. Window root = RootWindow (display, DefaultScreen (display));
  221396. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221397. }
  221398. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221399. {
  221400. return upright;
  221401. }
  221402. static bool screenSaverAllowed = true;
  221403. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221404. {
  221405. if (screenSaverAllowed != isEnabled)
  221406. {
  221407. screenSaverAllowed = isEnabled;
  221408. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221409. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221410. if (xScreenSaverSuspend == 0)
  221411. {
  221412. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221413. if (h != 0)
  221414. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221415. }
  221416. ScopedXLock xlock;
  221417. if (xScreenSaverSuspend != 0)
  221418. xScreenSaverSuspend (display, ! isEnabled);
  221419. }
  221420. }
  221421. bool Desktop::isScreenSaverEnabled()
  221422. {
  221423. return screenSaverAllowed;
  221424. }
  221425. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221426. {
  221427. ScopedXLock xlock;
  221428. const unsigned int imageW = image.getWidth();
  221429. const unsigned int imageH = image.getHeight();
  221430. #if JUCE_USE_XCURSOR
  221431. {
  221432. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221433. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221434. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221435. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221436. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221437. static tXcursorImageCreate xXcursorImageCreate = 0;
  221438. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221439. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221440. static bool hasBeenLoaded = false;
  221441. if (! hasBeenLoaded)
  221442. {
  221443. hasBeenLoaded = true;
  221444. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221445. if (h != 0)
  221446. {
  221447. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221448. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221449. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221450. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221451. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221452. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221453. || ! xXcursorSupportsARGB (display))
  221454. xXcursorSupportsARGB = 0;
  221455. }
  221456. }
  221457. if (xXcursorSupportsARGB != 0)
  221458. {
  221459. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221460. if (xcImage != 0)
  221461. {
  221462. xcImage->xhot = hotspotX;
  221463. xcImage->yhot = hotspotY;
  221464. XcursorPixel* dest = xcImage->pixels;
  221465. for (int y = 0; y < (int) imageH; ++y)
  221466. for (int x = 0; x < (int) imageW; ++x)
  221467. *dest++ = image.getPixelAt (x, y).getARGB();
  221468. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221469. xXcursorImageDestroy (xcImage);
  221470. if (result != 0)
  221471. return result;
  221472. }
  221473. }
  221474. }
  221475. #endif
  221476. Window root = RootWindow (display, DefaultScreen (display));
  221477. unsigned int cursorW, cursorH;
  221478. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221479. return 0;
  221480. Image im (Image::ARGB, cursorW, cursorH, true);
  221481. {
  221482. Graphics g (im);
  221483. if (imageW > cursorW || imageH > cursorH)
  221484. {
  221485. hotspotX = (hotspotX * cursorW) / imageW;
  221486. hotspotY = (hotspotY * cursorH) / imageH;
  221487. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221488. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221489. false);
  221490. }
  221491. else
  221492. {
  221493. g.drawImageAt (image, 0, 0);
  221494. }
  221495. }
  221496. const int stride = (cursorW + 7) >> 3;
  221497. HeapBlock <char> maskPlane, sourcePlane;
  221498. maskPlane.calloc (stride * cursorH);
  221499. sourcePlane.calloc (stride * cursorH);
  221500. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221501. for (int y = cursorH; --y >= 0;)
  221502. {
  221503. for (int x = cursorW; --x >= 0;)
  221504. {
  221505. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221506. const int offset = y * stride + (x >> 3);
  221507. const Colour c (im.getPixelAt (x, y));
  221508. if (c.getAlpha() >= 128)
  221509. maskPlane[offset] |= mask;
  221510. if (c.getBrightness() >= 0.5f)
  221511. sourcePlane[offset] |= mask;
  221512. }
  221513. }
  221514. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221515. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221516. XColor white, black;
  221517. black.red = black.green = black.blue = 0;
  221518. white.red = white.green = white.blue = 0xffff;
  221519. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221520. XFreePixmap (display, sourcePixmap);
  221521. XFreePixmap (display, maskPixmap);
  221522. return result;
  221523. }
  221524. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221525. {
  221526. ScopedXLock xlock;
  221527. if (cursorHandle != 0)
  221528. XFreeCursor (display, (Cursor) cursorHandle);
  221529. }
  221530. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221531. {
  221532. unsigned int shape;
  221533. switch (type)
  221534. {
  221535. case NormalCursor: return None; // Use parent cursor
  221536. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221537. case WaitCursor: shape = XC_watch; break;
  221538. case IBeamCursor: shape = XC_xterm; break;
  221539. case PointingHandCursor: shape = XC_hand2; break;
  221540. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221541. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221542. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221543. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221544. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221545. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221546. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221547. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221548. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221549. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221550. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221551. case CrosshairCursor: shape = XC_crosshair; break;
  221552. case DraggingHandCursor:
  221553. {
  221554. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221555. 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,
  221556. 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 };
  221557. const int dragHandDataSize = 99;
  221558. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221559. }
  221560. case CopyingCursor:
  221561. {
  221562. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221563. 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,
  221564. 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,
  221565. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221566. const int copyCursorSize = 119;
  221567. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221568. }
  221569. default:
  221570. jassertfalse;
  221571. return None;
  221572. }
  221573. ScopedXLock xlock;
  221574. return (void*) XCreateFontCursor (display, shape);
  221575. }
  221576. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221577. {
  221578. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221579. if (lp != 0)
  221580. lp->showMouseCursor ((Cursor) getHandle());
  221581. }
  221582. void MouseCursor::showInAllWindows() const
  221583. {
  221584. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221585. showInWindow (ComponentPeer::getPeer (i));
  221586. }
  221587. const Image juce_createIconForFile (const File& file)
  221588. {
  221589. return Image::null;
  221590. }
  221591. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221592. {
  221593. return createSoftwareImage (format, width, height, clearImage);
  221594. }
  221595. #if JUCE_OPENGL
  221596. class WindowedGLContext : public OpenGLContext
  221597. {
  221598. public:
  221599. WindowedGLContext (Component* const component,
  221600. const OpenGLPixelFormat& pixelFormat_,
  221601. GLXContext sharedContext)
  221602. : renderContext (0),
  221603. embeddedWindow (0),
  221604. pixelFormat (pixelFormat_),
  221605. swapInterval (0)
  221606. {
  221607. jassert (component != 0);
  221608. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221609. if (peer == 0)
  221610. return;
  221611. ScopedXLock xlock;
  221612. XSync (display, False);
  221613. GLint attribs [64];
  221614. int n = 0;
  221615. attribs[n++] = GLX_RGBA;
  221616. attribs[n++] = GLX_DOUBLEBUFFER;
  221617. attribs[n++] = GLX_RED_SIZE;
  221618. attribs[n++] = pixelFormat.redBits;
  221619. attribs[n++] = GLX_GREEN_SIZE;
  221620. attribs[n++] = pixelFormat.greenBits;
  221621. attribs[n++] = GLX_BLUE_SIZE;
  221622. attribs[n++] = pixelFormat.blueBits;
  221623. attribs[n++] = GLX_ALPHA_SIZE;
  221624. attribs[n++] = pixelFormat.alphaBits;
  221625. attribs[n++] = GLX_DEPTH_SIZE;
  221626. attribs[n++] = pixelFormat.depthBufferBits;
  221627. attribs[n++] = GLX_STENCIL_SIZE;
  221628. attribs[n++] = pixelFormat.stencilBufferBits;
  221629. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221630. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221631. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221632. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221633. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221634. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221635. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221636. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221637. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221638. attribs[n++] = None;
  221639. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221640. if (bestVisual == 0)
  221641. return;
  221642. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221643. Window windowH = (Window) peer->getNativeHandle();
  221644. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221645. XSetWindowAttributes swa;
  221646. swa.colormap = colourMap;
  221647. swa.border_pixel = 0;
  221648. swa.event_mask = ExposureMask | StructureNotifyMask;
  221649. embeddedWindow = XCreateWindow (display, windowH,
  221650. 0, 0, 1, 1, 0,
  221651. bestVisual->depth,
  221652. InputOutput,
  221653. bestVisual->visual,
  221654. CWBorderPixel | CWColormap | CWEventMask,
  221655. &swa);
  221656. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221657. XMapWindow (display, embeddedWindow);
  221658. XFreeColormap (display, colourMap);
  221659. XFree (bestVisual);
  221660. XSync (display, False);
  221661. }
  221662. ~WindowedGLContext()
  221663. {
  221664. ScopedXLock xlock;
  221665. deleteContext();
  221666. XUnmapWindow (display, embeddedWindow);
  221667. XDestroyWindow (display, embeddedWindow);
  221668. }
  221669. void deleteContext()
  221670. {
  221671. makeInactive();
  221672. if (renderContext != 0)
  221673. {
  221674. ScopedXLock xlock;
  221675. glXDestroyContext (display, renderContext);
  221676. renderContext = 0;
  221677. }
  221678. }
  221679. bool makeActive() const throw()
  221680. {
  221681. jassert (renderContext != 0);
  221682. ScopedXLock xlock;
  221683. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221684. && XSync (display, False);
  221685. }
  221686. bool makeInactive() const throw()
  221687. {
  221688. ScopedXLock xlock;
  221689. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221690. }
  221691. bool isActive() const throw()
  221692. {
  221693. ScopedXLock xlock;
  221694. return glXGetCurrentContext() == renderContext;
  221695. }
  221696. const OpenGLPixelFormat getPixelFormat() const
  221697. {
  221698. return pixelFormat;
  221699. }
  221700. void* getRawContext() const throw()
  221701. {
  221702. return renderContext;
  221703. }
  221704. void updateWindowPosition (int x, int y, int w, int h, int)
  221705. {
  221706. ScopedXLock xlock;
  221707. XMoveResizeWindow (display, embeddedWindow,
  221708. x, y, jmax (1, w), jmax (1, h));
  221709. }
  221710. void swapBuffers()
  221711. {
  221712. ScopedXLock xlock;
  221713. glXSwapBuffers (display, embeddedWindow);
  221714. }
  221715. bool setSwapInterval (const int numFramesPerSwap)
  221716. {
  221717. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221718. if (GLXSwapIntervalSGI != 0)
  221719. {
  221720. swapInterval = numFramesPerSwap;
  221721. GLXSwapIntervalSGI (numFramesPerSwap);
  221722. return true;
  221723. }
  221724. return false;
  221725. }
  221726. int getSwapInterval() const
  221727. {
  221728. return swapInterval;
  221729. }
  221730. void repaint()
  221731. {
  221732. }
  221733. GLXContext renderContext;
  221734. private:
  221735. Window embeddedWindow;
  221736. OpenGLPixelFormat pixelFormat;
  221737. int swapInterval;
  221738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221739. };
  221740. OpenGLContext* OpenGLComponent::createContext()
  221741. {
  221742. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221743. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221744. return (c->renderContext != 0) ? c.release() : 0;
  221745. }
  221746. void juce_glViewport (const int w, const int h)
  221747. {
  221748. glViewport (0, 0, w, h);
  221749. }
  221750. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221751. OwnedArray <OpenGLPixelFormat>& results)
  221752. {
  221753. results.add (new OpenGLPixelFormat()); // xxx
  221754. }
  221755. #endif
  221756. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221757. {
  221758. jassertfalse; // not implemented!
  221759. return false;
  221760. }
  221761. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221762. {
  221763. jassertfalse; // not implemented!
  221764. return false;
  221765. }
  221766. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221767. {
  221768. if (! isOnDesktop ())
  221769. addToDesktop (0);
  221770. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221771. if (wp != 0)
  221772. {
  221773. wp->setTaskBarIcon (newImage);
  221774. setVisible (true);
  221775. toFront (false);
  221776. repaint();
  221777. }
  221778. }
  221779. void SystemTrayIconComponent::paint (Graphics& g)
  221780. {
  221781. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221782. if (wp != 0)
  221783. {
  221784. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221785. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221786. false);
  221787. }
  221788. }
  221789. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221790. {
  221791. // xxx not yet implemented!
  221792. }
  221793. void PlatformUtilities::beep()
  221794. {
  221795. std::cout << "\a" << std::flush;
  221796. }
  221797. bool AlertWindow::showNativeDialogBox (const String& title,
  221798. const String& bodyText,
  221799. bool isOkCancel)
  221800. {
  221801. // use a non-native one for the time being..
  221802. if (isOkCancel)
  221803. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221804. else
  221805. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221806. return true;
  221807. }
  221808. const int KeyPress::spaceKey = XK_space & 0xff;
  221809. const int KeyPress::returnKey = XK_Return & 0xff;
  221810. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221811. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221812. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221813. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221814. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221815. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221816. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221817. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221818. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221819. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221820. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221821. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221822. const int KeyPress::tabKey = XK_Tab & 0xff;
  221823. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221824. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221825. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221826. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221827. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221828. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221829. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221830. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221831. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221832. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221833. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221834. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221835. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221836. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221837. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221838. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221839. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221840. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221841. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221842. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221843. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221844. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221845. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221846. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221847. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221848. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221849. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221850. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221851. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221852. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221853. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221854. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221855. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221856. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221857. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221858. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221859. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221860. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221861. #endif
  221862. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221863. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221864. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221865. // compiled on its own).
  221866. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221867. namespace
  221868. {
  221869. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221870. {
  221871. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221872. snd_pcm_hw_params_t* hwParams;
  221873. snd_pcm_hw_params_alloca (&hwParams);
  221874. for (int i = 0; ratesToTry[i] != 0; ++i)
  221875. {
  221876. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221877. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221878. {
  221879. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221880. }
  221881. }
  221882. }
  221883. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221884. {
  221885. snd_pcm_hw_params_t *params;
  221886. snd_pcm_hw_params_alloca (&params);
  221887. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221888. {
  221889. snd_pcm_hw_params_get_channels_min (params, minChans);
  221890. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221891. }
  221892. }
  221893. void getDeviceProperties (const String& deviceID,
  221894. unsigned int& minChansOut,
  221895. unsigned int& maxChansOut,
  221896. unsigned int& minChansIn,
  221897. unsigned int& maxChansIn,
  221898. Array <int>& rates)
  221899. {
  221900. if (deviceID.isEmpty())
  221901. return;
  221902. snd_ctl_t* handle;
  221903. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221904. {
  221905. snd_pcm_info_t* info;
  221906. snd_pcm_info_alloca (&info);
  221907. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221908. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221909. snd_pcm_info_set_subdevice (info, 0);
  221910. if (snd_ctl_pcm_info (handle, info) >= 0)
  221911. {
  221912. snd_pcm_t* pcmHandle;
  221913. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221914. {
  221915. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221916. getDeviceSampleRates (pcmHandle, rates);
  221917. snd_pcm_close (pcmHandle);
  221918. }
  221919. }
  221920. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221921. if (snd_ctl_pcm_info (handle, info) >= 0)
  221922. {
  221923. snd_pcm_t* pcmHandle;
  221924. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221925. {
  221926. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221927. if (rates.size() == 0)
  221928. getDeviceSampleRates (pcmHandle, rates);
  221929. snd_pcm_close (pcmHandle);
  221930. }
  221931. }
  221932. snd_ctl_close (handle);
  221933. }
  221934. }
  221935. }
  221936. class ALSADevice
  221937. {
  221938. public:
  221939. ALSADevice (const String& deviceID, bool forInput)
  221940. : handle (0),
  221941. bitDepth (16),
  221942. numChannelsRunning (0),
  221943. latency (0),
  221944. isInput (forInput),
  221945. isInterleaved (true)
  221946. {
  221947. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221948. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221949. SND_PCM_ASYNC));
  221950. }
  221951. ~ALSADevice()
  221952. {
  221953. if (handle != 0)
  221954. snd_pcm_close (handle);
  221955. }
  221956. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221957. {
  221958. if (handle == 0)
  221959. return false;
  221960. snd_pcm_hw_params_t* hwParams;
  221961. snd_pcm_hw_params_alloca (&hwParams);
  221962. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221963. return false;
  221964. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221965. isInterleaved = false;
  221966. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221967. isInterleaved = true;
  221968. else
  221969. {
  221970. jassertfalse;
  221971. return false;
  221972. }
  221973. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221974. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221975. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221976. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221977. SND_PCM_FORMAT_S32_BE, 32,
  221978. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221979. SND_PCM_FORMAT_S24_3BE, 24,
  221980. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221981. SND_PCM_FORMAT_S16_BE, 16 };
  221982. bitDepth = 0;
  221983. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221984. {
  221985. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221986. {
  221987. bitDepth = formatsToTry [i + 1] & 255;
  221988. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221989. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221990. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221991. break;
  221992. }
  221993. }
  221994. if (bitDepth == 0)
  221995. {
  221996. error = "device doesn't support a compatible PCM format";
  221997. DBG ("ALSA error: " + error + "\n");
  221998. return false;
  221999. }
  222000. int dir = 0;
  222001. unsigned int periods = 4;
  222002. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222003. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222004. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222005. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222006. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222007. || failed (snd_pcm_hw_params (handle, hwParams)))
  222008. {
  222009. return false;
  222010. }
  222011. snd_pcm_uframes_t frames = 0;
  222012. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222013. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222014. latency = 0;
  222015. else
  222016. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222017. snd_pcm_sw_params_t* swParams;
  222018. snd_pcm_sw_params_alloca (&swParams);
  222019. snd_pcm_uframes_t boundary;
  222020. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222021. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222022. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222023. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222024. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222025. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222026. || failed (snd_pcm_sw_params (handle, swParams)))
  222027. {
  222028. return false;
  222029. }
  222030. #if 0
  222031. // enable this to dump the config of the devices that get opened
  222032. snd_output_t* out;
  222033. snd_output_stdio_attach (&out, stderr, 0);
  222034. snd_pcm_hw_params_dump (hwParams, out);
  222035. snd_pcm_sw_params_dump (swParams, out);
  222036. #endif
  222037. numChannelsRunning = numChannels;
  222038. return true;
  222039. }
  222040. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222041. {
  222042. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222043. float** const data = outputChannelBuffer.getArrayOfChannels();
  222044. snd_pcm_sframes_t numDone = 0;
  222045. if (isInterleaved)
  222046. {
  222047. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222048. for (int i = 0; i < numChannelsRunning; ++i)
  222049. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222050. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222051. }
  222052. else
  222053. {
  222054. for (int i = 0; i < numChannelsRunning; ++i)
  222055. converter->convertSamples (data[i], data[i], numSamples);
  222056. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222057. }
  222058. if (failed (numDone))
  222059. {
  222060. if (numDone == -EPIPE)
  222061. {
  222062. if (failed (snd_pcm_prepare (handle)))
  222063. return false;
  222064. }
  222065. else if (numDone != -ESTRPIPE)
  222066. return false;
  222067. }
  222068. return true;
  222069. }
  222070. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222071. {
  222072. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222073. float** const data = inputChannelBuffer.getArrayOfChannels();
  222074. if (isInterleaved)
  222075. {
  222076. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222077. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222078. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222079. if (failed (num))
  222080. {
  222081. if (num == -EPIPE)
  222082. {
  222083. if (failed (snd_pcm_prepare (handle)))
  222084. return false;
  222085. }
  222086. else if (num != -ESTRPIPE)
  222087. return false;
  222088. }
  222089. for (int i = 0; i < numChannelsRunning; ++i)
  222090. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222091. }
  222092. else
  222093. {
  222094. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222095. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222096. return false;
  222097. for (int i = 0; i < numChannelsRunning; ++i)
  222098. converter->convertSamples (data[i], data[i], numSamples);
  222099. }
  222100. return true;
  222101. }
  222102. snd_pcm_t* handle;
  222103. String error;
  222104. int bitDepth, numChannelsRunning, latency;
  222105. private:
  222106. const bool isInput;
  222107. bool isInterleaved;
  222108. MemoryBlock scratch;
  222109. ScopedPointer<AudioData::Converter> converter;
  222110. template <class SampleType>
  222111. struct ConverterHelper
  222112. {
  222113. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222114. {
  222115. if (forInput)
  222116. {
  222117. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222118. if (isLittleEndian)
  222119. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222120. else
  222121. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222122. }
  222123. else
  222124. {
  222125. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222126. if (isLittleEndian)
  222127. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222128. else
  222129. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222130. }
  222131. }
  222132. };
  222133. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222134. {
  222135. switch (bitDepth)
  222136. {
  222137. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222138. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222139. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222140. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222141. default: jassertfalse; break; // unsupported format!
  222142. }
  222143. return 0;
  222144. }
  222145. bool failed (const int errorNum)
  222146. {
  222147. if (errorNum >= 0)
  222148. return false;
  222149. error = snd_strerror (errorNum);
  222150. DBG ("ALSA error: " + error + "\n");
  222151. return true;
  222152. }
  222153. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  222154. };
  222155. class ALSAThread : public Thread
  222156. {
  222157. public:
  222158. ALSAThread (const String& inputId_,
  222159. const String& outputId_)
  222160. : Thread ("Juce ALSA"),
  222161. sampleRate (0),
  222162. bufferSize (0),
  222163. outputLatency (0),
  222164. inputLatency (0),
  222165. callback (0),
  222166. inputId (inputId_),
  222167. outputId (outputId_),
  222168. numCallbacks (0),
  222169. inputChannelBuffer (1, 1),
  222170. outputChannelBuffer (1, 1)
  222171. {
  222172. initialiseRatesAndChannels();
  222173. }
  222174. ~ALSAThread()
  222175. {
  222176. close();
  222177. }
  222178. void open (BigInteger inputChannels,
  222179. BigInteger outputChannels,
  222180. const double sampleRate_,
  222181. const int bufferSize_)
  222182. {
  222183. close();
  222184. error = String::empty;
  222185. sampleRate = sampleRate_;
  222186. bufferSize = bufferSize_;
  222187. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222188. inputChannelBuffer.clear();
  222189. inputChannelDataForCallback.clear();
  222190. currentInputChans.clear();
  222191. if (inputChannels.getHighestBit() >= 0)
  222192. {
  222193. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222194. {
  222195. if (inputChannels[i])
  222196. {
  222197. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222198. currentInputChans.setBit (i);
  222199. }
  222200. }
  222201. }
  222202. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222203. outputChannelBuffer.clear();
  222204. outputChannelDataForCallback.clear();
  222205. currentOutputChans.clear();
  222206. if (outputChannels.getHighestBit() >= 0)
  222207. {
  222208. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222209. {
  222210. if (outputChannels[i])
  222211. {
  222212. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222213. currentOutputChans.setBit (i);
  222214. }
  222215. }
  222216. }
  222217. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222218. {
  222219. outputDevice = new ALSADevice (outputId, false);
  222220. if (outputDevice->error.isNotEmpty())
  222221. {
  222222. error = outputDevice->error;
  222223. outputDevice = 0;
  222224. return;
  222225. }
  222226. currentOutputChans.setRange (0, minChansOut, true);
  222227. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222228. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222229. bufferSize))
  222230. {
  222231. error = outputDevice->error;
  222232. outputDevice = 0;
  222233. return;
  222234. }
  222235. outputLatency = outputDevice->latency;
  222236. }
  222237. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222238. {
  222239. inputDevice = new ALSADevice (inputId, true);
  222240. if (inputDevice->error.isNotEmpty())
  222241. {
  222242. error = inputDevice->error;
  222243. inputDevice = 0;
  222244. return;
  222245. }
  222246. currentInputChans.setRange (0, minChansIn, true);
  222247. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222248. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222249. bufferSize))
  222250. {
  222251. error = inputDevice->error;
  222252. inputDevice = 0;
  222253. return;
  222254. }
  222255. inputLatency = inputDevice->latency;
  222256. }
  222257. if (outputDevice == 0 && inputDevice == 0)
  222258. {
  222259. error = "no channels";
  222260. return;
  222261. }
  222262. if (outputDevice != 0 && inputDevice != 0)
  222263. {
  222264. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222265. }
  222266. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222267. return;
  222268. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222269. return;
  222270. startThread (9);
  222271. int count = 1000;
  222272. while (numCallbacks == 0)
  222273. {
  222274. sleep (5);
  222275. if (--count < 0 || ! isThreadRunning())
  222276. {
  222277. error = "device didn't start";
  222278. break;
  222279. }
  222280. }
  222281. }
  222282. void close()
  222283. {
  222284. stopThread (6000);
  222285. inputDevice = 0;
  222286. outputDevice = 0;
  222287. inputChannelBuffer.setSize (1, 1);
  222288. outputChannelBuffer.setSize (1, 1);
  222289. numCallbacks = 0;
  222290. }
  222291. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222292. {
  222293. const ScopedLock sl (callbackLock);
  222294. callback = newCallback;
  222295. }
  222296. void run()
  222297. {
  222298. while (! threadShouldExit())
  222299. {
  222300. if (inputDevice != 0)
  222301. {
  222302. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222303. {
  222304. DBG ("ALSA: read failure");
  222305. break;
  222306. }
  222307. }
  222308. if (threadShouldExit())
  222309. break;
  222310. {
  222311. const ScopedLock sl (callbackLock);
  222312. ++numCallbacks;
  222313. if (callback != 0)
  222314. {
  222315. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222316. inputChannelDataForCallback.size(),
  222317. outputChannelDataForCallback.getRawDataPointer(),
  222318. outputChannelDataForCallback.size(),
  222319. bufferSize);
  222320. }
  222321. else
  222322. {
  222323. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222324. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222325. }
  222326. }
  222327. if (outputDevice != 0)
  222328. {
  222329. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222330. if (threadShouldExit())
  222331. break;
  222332. failed (snd_pcm_avail_update (outputDevice->handle));
  222333. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222334. {
  222335. DBG ("ALSA: write failure");
  222336. break;
  222337. }
  222338. }
  222339. }
  222340. }
  222341. int getBitDepth() const throw()
  222342. {
  222343. if (outputDevice != 0)
  222344. return outputDevice->bitDepth;
  222345. if (inputDevice != 0)
  222346. return inputDevice->bitDepth;
  222347. return 16;
  222348. }
  222349. String error;
  222350. double sampleRate;
  222351. int bufferSize, outputLatency, inputLatency;
  222352. BigInteger currentInputChans, currentOutputChans;
  222353. Array <int> sampleRates;
  222354. StringArray channelNamesOut, channelNamesIn;
  222355. AudioIODeviceCallback* callback;
  222356. private:
  222357. const String inputId, outputId;
  222358. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222359. int numCallbacks;
  222360. CriticalSection callbackLock;
  222361. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222362. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222363. unsigned int minChansOut, maxChansOut;
  222364. unsigned int minChansIn, maxChansIn;
  222365. bool failed (const int errorNum)
  222366. {
  222367. if (errorNum >= 0)
  222368. return false;
  222369. error = snd_strerror (errorNum);
  222370. DBG ("ALSA error: " + error + "\n");
  222371. return true;
  222372. }
  222373. void initialiseRatesAndChannels()
  222374. {
  222375. sampleRates.clear();
  222376. channelNamesOut.clear();
  222377. channelNamesIn.clear();
  222378. minChansOut = 0;
  222379. maxChansOut = 0;
  222380. minChansIn = 0;
  222381. maxChansIn = 0;
  222382. unsigned int dummy = 0;
  222383. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222384. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222385. unsigned int i;
  222386. for (i = 0; i < maxChansOut; ++i)
  222387. channelNamesOut.add ("channel " + String ((int) i + 1));
  222388. for (i = 0; i < maxChansIn; ++i)
  222389. channelNamesIn.add ("channel " + String ((int) i + 1));
  222390. }
  222391. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222392. };
  222393. class ALSAAudioIODevice : public AudioIODevice
  222394. {
  222395. public:
  222396. ALSAAudioIODevice (const String& deviceName,
  222397. const String& inputId_,
  222398. const String& outputId_)
  222399. : AudioIODevice (deviceName, "ALSA"),
  222400. inputId (inputId_),
  222401. outputId (outputId_),
  222402. isOpen_ (false),
  222403. isStarted (false),
  222404. internal (inputId_, outputId_)
  222405. {
  222406. }
  222407. ~ALSAAudioIODevice()
  222408. {
  222409. }
  222410. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222411. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222412. int getNumSampleRates() { return internal.sampleRates.size(); }
  222413. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222414. int getDefaultBufferSize() { return 512; }
  222415. int getNumBufferSizesAvailable() { return 50; }
  222416. int getBufferSizeSamples (int index)
  222417. {
  222418. int n = 16;
  222419. for (int i = 0; i < index; ++i)
  222420. n += n < 64 ? 16
  222421. : (n < 512 ? 32
  222422. : (n < 1024 ? 64
  222423. : (n < 2048 ? 128 : 256)));
  222424. return n;
  222425. }
  222426. const String open (const BigInteger& inputChannels,
  222427. const BigInteger& outputChannels,
  222428. double sampleRate,
  222429. int bufferSizeSamples)
  222430. {
  222431. close();
  222432. if (bufferSizeSamples <= 0)
  222433. bufferSizeSamples = getDefaultBufferSize();
  222434. if (sampleRate <= 0)
  222435. {
  222436. for (int i = 0; i < getNumSampleRates(); ++i)
  222437. {
  222438. if (getSampleRate (i) >= 44100)
  222439. {
  222440. sampleRate = getSampleRate (i);
  222441. break;
  222442. }
  222443. }
  222444. }
  222445. internal.open (inputChannels, outputChannels,
  222446. sampleRate, bufferSizeSamples);
  222447. isOpen_ = internal.error.isEmpty();
  222448. return internal.error;
  222449. }
  222450. void close()
  222451. {
  222452. stop();
  222453. internal.close();
  222454. isOpen_ = false;
  222455. }
  222456. bool isOpen() { return isOpen_; }
  222457. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222458. const String getLastError() { return internal.error; }
  222459. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222460. double getCurrentSampleRate() { return internal.sampleRate; }
  222461. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222462. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222463. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222464. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222465. int getInputLatencyInSamples() { return internal.inputLatency; }
  222466. void start (AudioIODeviceCallback* callback)
  222467. {
  222468. if (! isOpen_)
  222469. callback = 0;
  222470. if (callback != 0)
  222471. callback->audioDeviceAboutToStart (this);
  222472. internal.setCallback (callback);
  222473. isStarted = (callback != 0);
  222474. }
  222475. void stop()
  222476. {
  222477. AudioIODeviceCallback* const oldCallback = internal.callback;
  222478. start (0);
  222479. if (oldCallback != 0)
  222480. oldCallback->audioDeviceStopped();
  222481. }
  222482. String inputId, outputId;
  222483. private:
  222484. bool isOpen_, isStarted;
  222485. ALSAThread internal;
  222486. };
  222487. class ALSAAudioIODeviceType : public AudioIODeviceType
  222488. {
  222489. public:
  222490. ALSAAudioIODeviceType()
  222491. : AudioIODeviceType ("ALSA"),
  222492. hasScanned (false)
  222493. {
  222494. }
  222495. ~ALSAAudioIODeviceType()
  222496. {
  222497. }
  222498. void scanForDevices()
  222499. {
  222500. if (hasScanned)
  222501. return;
  222502. hasScanned = true;
  222503. inputNames.clear();
  222504. inputIds.clear();
  222505. outputNames.clear();
  222506. outputIds.clear();
  222507. /* void** hints = 0;
  222508. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222509. {
  222510. for (void** hint = hints; *hint != 0; ++hint)
  222511. {
  222512. const String name (getHint (*hint, "NAME"));
  222513. if (name.isNotEmpty())
  222514. {
  222515. const String ioid (getHint (*hint, "IOID"));
  222516. String desc (getHint (*hint, "DESC"));
  222517. if (desc.isEmpty())
  222518. desc = name;
  222519. desc = desc.replaceCharacters ("\n\r", " ");
  222520. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222521. if (ioid.isEmpty() || ioid == "Input")
  222522. {
  222523. inputNames.add (desc);
  222524. inputIds.add (name);
  222525. }
  222526. if (ioid.isEmpty() || ioid == "Output")
  222527. {
  222528. outputNames.add (desc);
  222529. outputIds.add (name);
  222530. }
  222531. }
  222532. }
  222533. snd_device_name_free_hint (hints);
  222534. }
  222535. */
  222536. snd_ctl_t* handle = 0;
  222537. snd_ctl_card_info_t* info = 0;
  222538. snd_ctl_card_info_alloca (&info);
  222539. int cardNum = -1;
  222540. while (outputIds.size() + inputIds.size() <= 32)
  222541. {
  222542. snd_card_next (&cardNum);
  222543. if (cardNum < 0)
  222544. break;
  222545. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222546. {
  222547. if (snd_ctl_card_info (handle, info) >= 0)
  222548. {
  222549. String cardId (snd_ctl_card_info_get_id (info));
  222550. if (cardId.removeCharacters ("0123456789").isEmpty())
  222551. cardId = String (cardNum);
  222552. int device = -1;
  222553. for (;;)
  222554. {
  222555. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222556. break;
  222557. String id, name;
  222558. id << "hw:" << cardId << ',' << device;
  222559. bool isInput, isOutput;
  222560. if (testDevice (id, isInput, isOutput))
  222561. {
  222562. name << snd_ctl_card_info_get_name (info);
  222563. if (name.isEmpty())
  222564. name = id;
  222565. if (isInput)
  222566. {
  222567. inputNames.add (name);
  222568. inputIds.add (id);
  222569. }
  222570. if (isOutput)
  222571. {
  222572. outputNames.add (name);
  222573. outputIds.add (id);
  222574. }
  222575. }
  222576. }
  222577. }
  222578. snd_ctl_close (handle);
  222579. }
  222580. }
  222581. inputNames.appendNumbersToDuplicates (false, true);
  222582. outputNames.appendNumbersToDuplicates (false, true);
  222583. }
  222584. const StringArray getDeviceNames (bool wantInputNames) const
  222585. {
  222586. jassert (hasScanned); // need to call scanForDevices() before doing this
  222587. return wantInputNames ? inputNames : outputNames;
  222588. }
  222589. int getDefaultDeviceIndex (bool forInput) const
  222590. {
  222591. jassert (hasScanned); // need to call scanForDevices() before doing this
  222592. return 0;
  222593. }
  222594. bool hasSeparateInputsAndOutputs() const { return true; }
  222595. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222596. {
  222597. jassert (hasScanned); // need to call scanForDevices() before doing this
  222598. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222599. if (d == 0)
  222600. return -1;
  222601. return asInput ? inputIds.indexOf (d->inputId)
  222602. : outputIds.indexOf (d->outputId);
  222603. }
  222604. AudioIODevice* createDevice (const String& outputDeviceName,
  222605. const String& inputDeviceName)
  222606. {
  222607. jassert (hasScanned); // need to call scanForDevices() before doing this
  222608. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222609. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222610. String deviceName (outputIndex >= 0 ? outputDeviceName
  222611. : inputDeviceName);
  222612. if (inputIndex >= 0 || outputIndex >= 0)
  222613. return new ALSAAudioIODevice (deviceName,
  222614. inputIds [inputIndex],
  222615. outputIds [outputIndex]);
  222616. return 0;
  222617. }
  222618. private:
  222619. StringArray inputNames, outputNames, inputIds, outputIds;
  222620. bool hasScanned;
  222621. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222622. {
  222623. unsigned int minChansOut = 0, maxChansOut = 0;
  222624. unsigned int minChansIn = 0, maxChansIn = 0;
  222625. Array <int> rates;
  222626. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222627. DBG ("ALSA device: " + id
  222628. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222629. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222630. + " rates=" + String (rates.size()));
  222631. isInput = maxChansIn > 0;
  222632. isOutput = maxChansOut > 0;
  222633. return (isInput || isOutput) && rates.size() > 0;
  222634. }
  222635. /*static const String getHint (void* hint, const char* type)
  222636. {
  222637. char* const n = snd_device_name_get_hint (hint, type);
  222638. const String s ((const char*) n);
  222639. free (n);
  222640. return s;
  222641. }*/
  222642. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222643. };
  222644. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()
  222645. {
  222646. return new ALSAAudioIODeviceType();
  222647. }
  222648. #endif
  222649. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222650. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222651. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222652. // compiled on its own).
  222653. #ifdef JUCE_INCLUDED_FILE
  222654. #if JUCE_JACK
  222655. static void* juce_libjack_handle = 0;
  222656. void* juce_load_jack_function (const char* const name)
  222657. {
  222658. if (juce_libjack_handle == 0)
  222659. return 0;
  222660. return dlsym (juce_libjack_handle, name);
  222661. }
  222662. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222663. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222664. return_type fn_name argument_types { \
  222665. static fn_name##_ptr_t fn = 0; \
  222666. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222667. if (fn) return (*fn)arguments; \
  222668. else return 0; \
  222669. }
  222670. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222671. typedef void (*fn_name##_ptr_t)argument_types; \
  222672. void fn_name argument_types { \
  222673. static fn_name##_ptr_t fn = 0; \
  222674. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222675. if (fn) (*fn)arguments; \
  222676. }
  222677. 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));
  222678. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222679. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222680. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222681. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222682. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222683. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222684. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222685. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222686. 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));
  222687. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222688. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222689. 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));
  222690. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222691. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222692. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222693. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222694. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222695. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222696. #if JUCE_DEBUG
  222697. #define JACK_LOGGING_ENABLED 1
  222698. #endif
  222699. #if JACK_LOGGING_ENABLED
  222700. namespace
  222701. {
  222702. void jack_Log (const String& s)
  222703. {
  222704. std::cerr << s << std::endl;
  222705. }
  222706. void dumpJackErrorMessage (const jack_status_t status)
  222707. {
  222708. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222709. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222710. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222711. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222712. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222713. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222714. }
  222715. }
  222716. #else
  222717. #define dumpJackErrorMessage(a) {}
  222718. #define jack_Log(...) {}
  222719. #endif
  222720. #ifndef JUCE_JACK_CLIENT_NAME
  222721. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222722. #endif
  222723. class JackAudioIODevice : public AudioIODevice
  222724. {
  222725. public:
  222726. JackAudioIODevice (const String& deviceName,
  222727. const String& inputId_,
  222728. const String& outputId_)
  222729. : AudioIODevice (deviceName, "JACK"),
  222730. inputId (inputId_),
  222731. outputId (outputId_),
  222732. isOpen_ (false),
  222733. callback (0),
  222734. totalNumberOfInputChannels (0),
  222735. totalNumberOfOutputChannels (0)
  222736. {
  222737. jassert (deviceName.isNotEmpty());
  222738. jack_status_t status;
  222739. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222740. if (client == 0)
  222741. {
  222742. dumpJackErrorMessage (status);
  222743. }
  222744. else
  222745. {
  222746. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222747. // open input ports
  222748. const StringArray inputChannels (getInputChannelNames());
  222749. for (int i = 0; i < inputChannels.size(); i++)
  222750. {
  222751. String inputName;
  222752. inputName << "in_" << ++totalNumberOfInputChannels;
  222753. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222754. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222755. }
  222756. // open output ports
  222757. const StringArray outputChannels (getOutputChannelNames());
  222758. for (int i = 0; i < outputChannels.size (); i++)
  222759. {
  222760. String outputName;
  222761. outputName << "out_" << ++totalNumberOfOutputChannels;
  222762. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222763. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222764. }
  222765. inChans.calloc (totalNumberOfInputChannels + 2);
  222766. outChans.calloc (totalNumberOfOutputChannels + 2);
  222767. }
  222768. }
  222769. ~JackAudioIODevice()
  222770. {
  222771. close();
  222772. if (client != 0)
  222773. {
  222774. JUCE_NAMESPACE::jack_client_close (client);
  222775. client = 0;
  222776. }
  222777. }
  222778. const StringArray getChannelNames (bool forInput) const
  222779. {
  222780. StringArray names;
  222781. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222782. forInput ? JackPortIsInput : JackPortIsOutput);
  222783. if (ports != 0)
  222784. {
  222785. int j = 0;
  222786. while (ports[j] != 0)
  222787. {
  222788. const String portName (ports [j++]);
  222789. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222790. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222791. }
  222792. free (ports);
  222793. }
  222794. return names;
  222795. }
  222796. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222797. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222798. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222799. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222800. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222801. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222802. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222803. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222804. double sampleRate, int bufferSizeSamples)
  222805. {
  222806. if (client == 0)
  222807. {
  222808. lastError = "No JACK client running";
  222809. return lastError;
  222810. }
  222811. lastError = String::empty;
  222812. close();
  222813. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222814. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222815. JUCE_NAMESPACE::jack_activate (client);
  222816. isOpen_ = true;
  222817. if (! inputChannels.isZero())
  222818. {
  222819. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222820. if (ports != 0)
  222821. {
  222822. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222823. for (int i = 0; i < numInputChannels; ++i)
  222824. {
  222825. const String portName (ports[i]);
  222826. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222827. {
  222828. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222829. if (error != 0)
  222830. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222831. }
  222832. }
  222833. free (ports);
  222834. }
  222835. }
  222836. if (! outputChannels.isZero())
  222837. {
  222838. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222839. if (ports != 0)
  222840. {
  222841. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222842. for (int i = 0; i < numOutputChannels; ++i)
  222843. {
  222844. const String portName (ports[i]);
  222845. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222846. {
  222847. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222848. if (error != 0)
  222849. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222850. }
  222851. }
  222852. free (ports);
  222853. }
  222854. }
  222855. return lastError;
  222856. }
  222857. void close()
  222858. {
  222859. stop();
  222860. if (client != 0)
  222861. {
  222862. JUCE_NAMESPACE::jack_deactivate (client);
  222863. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222864. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222865. }
  222866. isOpen_ = false;
  222867. }
  222868. void start (AudioIODeviceCallback* newCallback)
  222869. {
  222870. if (isOpen_ && newCallback != callback)
  222871. {
  222872. if (newCallback != 0)
  222873. newCallback->audioDeviceAboutToStart (this);
  222874. AudioIODeviceCallback* const oldCallback = callback;
  222875. {
  222876. const ScopedLock sl (callbackLock);
  222877. callback = newCallback;
  222878. }
  222879. if (oldCallback != 0)
  222880. oldCallback->audioDeviceStopped();
  222881. }
  222882. }
  222883. void stop()
  222884. {
  222885. start (0);
  222886. }
  222887. bool isOpen() { return isOpen_; }
  222888. bool isPlaying() { return callback != 0; }
  222889. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222890. double getCurrentSampleRate() { return getSampleRate (0); }
  222891. int getCurrentBitDepth() { return 32; }
  222892. const String getLastError() { return lastError; }
  222893. const BigInteger getActiveOutputChannels() const
  222894. {
  222895. BigInteger outputBits;
  222896. for (int i = 0; i < outputPorts.size(); i++)
  222897. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222898. outputBits.setBit (i);
  222899. return outputBits;
  222900. }
  222901. const BigInteger getActiveInputChannels() const
  222902. {
  222903. BigInteger inputBits;
  222904. for (int i = 0; i < inputPorts.size(); i++)
  222905. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222906. inputBits.setBit (i);
  222907. return inputBits;
  222908. }
  222909. int getOutputLatencyInSamples()
  222910. {
  222911. int latency = 0;
  222912. for (int i = 0; i < outputPorts.size(); i++)
  222913. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222914. return latency;
  222915. }
  222916. int getInputLatencyInSamples()
  222917. {
  222918. int latency = 0;
  222919. for (int i = 0; i < inputPorts.size(); i++)
  222920. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222921. return latency;
  222922. }
  222923. String inputId, outputId;
  222924. private:
  222925. void process (const int numSamples)
  222926. {
  222927. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222928. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222929. {
  222930. jack_default_audio_sample_t* in
  222931. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222932. if (in != 0)
  222933. inChans [numActiveInChans++] = (float*) in;
  222934. }
  222935. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222936. {
  222937. jack_default_audio_sample_t* out
  222938. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222939. if (out != 0)
  222940. outChans [numActiveOutChans++] = (float*) out;
  222941. }
  222942. const ScopedLock sl (callbackLock);
  222943. if (callback != 0)
  222944. {
  222945. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222946. outChans, numActiveOutChans, numSamples);
  222947. }
  222948. else
  222949. {
  222950. for (i = 0; i < numActiveOutChans; ++i)
  222951. zeromem (outChans[i], sizeof (float) * numSamples);
  222952. }
  222953. }
  222954. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222955. {
  222956. if (callbackArgument != 0)
  222957. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222958. return 0;
  222959. }
  222960. static void threadInitCallback (void* callbackArgument)
  222961. {
  222962. jack_Log ("JackAudioIODevice::initialise");
  222963. }
  222964. static void shutdownCallback (void* callbackArgument)
  222965. {
  222966. jack_Log ("JackAudioIODevice::shutdown");
  222967. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222968. if (device != 0)
  222969. {
  222970. device->client = 0;
  222971. device->close();
  222972. }
  222973. }
  222974. static void errorCallback (const char* msg)
  222975. {
  222976. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222977. }
  222978. bool isOpen_;
  222979. jack_client_t* client;
  222980. String lastError;
  222981. AudioIODeviceCallback* callback;
  222982. CriticalSection callbackLock;
  222983. HeapBlock <float*> inChans, outChans;
  222984. int totalNumberOfInputChannels;
  222985. int totalNumberOfOutputChannels;
  222986. Array<void*> inputPorts, outputPorts;
  222987. };
  222988. class JackAudioIODeviceType : public AudioIODeviceType
  222989. {
  222990. public:
  222991. JackAudioIODeviceType()
  222992. : AudioIODeviceType ("JACK"),
  222993. hasScanned (false)
  222994. {
  222995. }
  222996. ~JackAudioIODeviceType()
  222997. {
  222998. }
  222999. void scanForDevices()
  223000. {
  223001. hasScanned = true;
  223002. inputNames.clear();
  223003. inputIds.clear();
  223004. outputNames.clear();
  223005. outputIds.clear();
  223006. if (juce_libjack_handle == 0)
  223007. {
  223008. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223009. if (juce_libjack_handle == 0)
  223010. return;
  223011. }
  223012. // open a dummy client
  223013. jack_status_t status;
  223014. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223015. if (client == 0)
  223016. {
  223017. dumpJackErrorMessage (status);
  223018. }
  223019. else
  223020. {
  223021. // scan for output devices
  223022. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223023. if (ports != 0)
  223024. {
  223025. int j = 0;
  223026. while (ports[j] != 0)
  223027. {
  223028. String clientName (ports[j]);
  223029. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223030. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223031. && ! inputNames.contains (clientName))
  223032. {
  223033. inputNames.add (clientName);
  223034. inputIds.add (ports [j]);
  223035. }
  223036. ++j;
  223037. }
  223038. free (ports);
  223039. }
  223040. // scan for input devices
  223041. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223042. if (ports != 0)
  223043. {
  223044. int j = 0;
  223045. while (ports[j] != 0)
  223046. {
  223047. String clientName (ports[j]);
  223048. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223049. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223050. && ! outputNames.contains (clientName))
  223051. {
  223052. outputNames.add (clientName);
  223053. outputIds.add (ports [j]);
  223054. }
  223055. ++j;
  223056. }
  223057. free (ports);
  223058. }
  223059. JUCE_NAMESPACE::jack_client_close (client);
  223060. }
  223061. }
  223062. const StringArray getDeviceNames (bool wantInputNames) const
  223063. {
  223064. jassert (hasScanned); // need to call scanForDevices() before doing this
  223065. return wantInputNames ? inputNames : outputNames;
  223066. }
  223067. int getDefaultDeviceIndex (bool forInput) const
  223068. {
  223069. jassert (hasScanned); // need to call scanForDevices() before doing this
  223070. return 0;
  223071. }
  223072. bool hasSeparateInputsAndOutputs() const { return true; }
  223073. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223074. {
  223075. jassert (hasScanned); // need to call scanForDevices() before doing this
  223076. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223077. if (d == 0)
  223078. return -1;
  223079. return asInput ? inputIds.indexOf (d->inputId)
  223080. : outputIds.indexOf (d->outputId);
  223081. }
  223082. AudioIODevice* createDevice (const String& outputDeviceName,
  223083. const String& inputDeviceName)
  223084. {
  223085. jassert (hasScanned); // need to call scanForDevices() before doing this
  223086. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223087. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223088. if (inputIndex >= 0 || outputIndex >= 0)
  223089. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223090. : inputDeviceName,
  223091. inputIds [inputIndex],
  223092. outputIds [outputIndex]);
  223093. return 0;
  223094. }
  223095. private:
  223096. StringArray inputNames, outputNames, inputIds, outputIds;
  223097. bool hasScanned;
  223098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  223099. };
  223100. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()
  223101. {
  223102. return new JackAudioIODeviceType();
  223103. }
  223104. #endif
  223105. #endif
  223106. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223107. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223108. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223109. // compiled on its own).
  223110. #if JUCE_INCLUDED_FILE
  223111. #if JUCE_ALSA
  223112. namespace
  223113. {
  223114. snd_seq_t* iterateMidiDevices (const bool forInput,
  223115. StringArray& deviceNamesFound,
  223116. const int deviceIndexToOpen)
  223117. {
  223118. snd_seq_t* returnedHandle = 0;
  223119. snd_seq_t* seqHandle;
  223120. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223121. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223122. {
  223123. snd_seq_system_info_t* systemInfo;
  223124. snd_seq_client_info_t* clientInfo;
  223125. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223126. {
  223127. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223128. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223129. {
  223130. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223131. while (--numClients >= 0 && returnedHandle == 0)
  223132. {
  223133. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223134. {
  223135. snd_seq_port_info_t* portInfo;
  223136. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223137. {
  223138. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223139. const int client = snd_seq_client_info_get_client (clientInfo);
  223140. snd_seq_port_info_set_client (portInfo, client);
  223141. snd_seq_port_info_set_port (portInfo, -1);
  223142. while (--numPorts >= 0)
  223143. {
  223144. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223145. && (snd_seq_port_info_get_capability (portInfo)
  223146. & (forInput ? SND_SEQ_PORT_CAP_READ
  223147. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223148. {
  223149. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223150. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223151. {
  223152. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223153. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223154. if (sourcePort != -1)
  223155. {
  223156. snd_seq_set_client_name (seqHandle,
  223157. forInput ? "Juce Midi Input"
  223158. : "Juce Midi Output");
  223159. const int portId
  223160. = snd_seq_create_simple_port (seqHandle,
  223161. forInput ? "Juce Midi In Port"
  223162. : "Juce Midi Out Port",
  223163. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223164. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223165. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223166. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223167. returnedHandle = seqHandle;
  223168. }
  223169. }
  223170. }
  223171. }
  223172. snd_seq_port_info_free (portInfo);
  223173. }
  223174. }
  223175. }
  223176. snd_seq_client_info_free (clientInfo);
  223177. }
  223178. snd_seq_system_info_free (systemInfo);
  223179. }
  223180. if (returnedHandle == 0)
  223181. snd_seq_close (seqHandle);
  223182. }
  223183. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223184. return returnedHandle;
  223185. }
  223186. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223187. {
  223188. snd_seq_t* seqHandle = 0;
  223189. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223190. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223191. {
  223192. snd_seq_set_client_name (seqHandle,
  223193. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223194. const int portId
  223195. = snd_seq_create_simple_port (seqHandle,
  223196. forInput ? "in"
  223197. : "out",
  223198. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223199. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223200. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223201. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223202. if (portId < 0)
  223203. {
  223204. snd_seq_close (seqHandle);
  223205. seqHandle = 0;
  223206. }
  223207. }
  223208. return seqHandle;
  223209. }
  223210. }
  223211. class MidiOutputDevice
  223212. {
  223213. public:
  223214. MidiOutputDevice (MidiOutput* const midiOutput_,
  223215. snd_seq_t* const seqHandle_)
  223216. :
  223217. midiOutput (midiOutput_),
  223218. seqHandle (seqHandle_),
  223219. maxEventSize (16 * 1024)
  223220. {
  223221. jassert (seqHandle != 0 && midiOutput != 0);
  223222. snd_midi_event_new (maxEventSize, &midiParser);
  223223. }
  223224. ~MidiOutputDevice()
  223225. {
  223226. snd_midi_event_free (midiParser);
  223227. snd_seq_close (seqHandle);
  223228. }
  223229. void sendMessageNow (const MidiMessage& message)
  223230. {
  223231. if (message.getRawDataSize() > maxEventSize)
  223232. {
  223233. maxEventSize = message.getRawDataSize();
  223234. snd_midi_event_free (midiParser);
  223235. snd_midi_event_new (maxEventSize, &midiParser);
  223236. }
  223237. snd_seq_event_t event;
  223238. snd_seq_ev_clear (&event);
  223239. snd_midi_event_encode (midiParser,
  223240. message.getRawData(),
  223241. message.getRawDataSize(),
  223242. &event);
  223243. snd_midi_event_reset_encode (midiParser);
  223244. snd_seq_ev_set_source (&event, 0);
  223245. snd_seq_ev_set_subs (&event);
  223246. snd_seq_ev_set_direct (&event);
  223247. snd_seq_event_output (seqHandle, &event);
  223248. snd_seq_drain_output (seqHandle);
  223249. }
  223250. private:
  223251. MidiOutput* const midiOutput;
  223252. snd_seq_t* const seqHandle;
  223253. snd_midi_event_t* midiParser;
  223254. int maxEventSize;
  223255. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  223256. };
  223257. const StringArray MidiOutput::getDevices()
  223258. {
  223259. StringArray devices;
  223260. iterateMidiDevices (false, devices, -1);
  223261. return devices;
  223262. }
  223263. int MidiOutput::getDefaultDeviceIndex()
  223264. {
  223265. return 0;
  223266. }
  223267. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223268. {
  223269. MidiOutput* newDevice = 0;
  223270. StringArray devices;
  223271. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223272. if (handle != 0)
  223273. {
  223274. newDevice = new MidiOutput();
  223275. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223276. }
  223277. return newDevice;
  223278. }
  223279. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223280. {
  223281. MidiOutput* newDevice = 0;
  223282. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223283. if (handle != 0)
  223284. {
  223285. newDevice = new MidiOutput();
  223286. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223287. }
  223288. return newDevice;
  223289. }
  223290. MidiOutput::~MidiOutput()
  223291. {
  223292. delete static_cast <MidiOutputDevice*> (internal);
  223293. }
  223294. void MidiOutput::reset()
  223295. {
  223296. }
  223297. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223298. {
  223299. return false;
  223300. }
  223301. void MidiOutput::setVolume (float leftVol, float rightVol)
  223302. {
  223303. }
  223304. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223305. {
  223306. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223307. }
  223308. class MidiInputThread : public Thread
  223309. {
  223310. public:
  223311. MidiInputThread (MidiInput* const midiInput_,
  223312. snd_seq_t* const seqHandle_,
  223313. MidiInputCallback* const callback_)
  223314. : Thread ("Juce MIDI Input"),
  223315. midiInput (midiInput_),
  223316. seqHandle (seqHandle_),
  223317. callback (callback_)
  223318. {
  223319. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223320. }
  223321. ~MidiInputThread()
  223322. {
  223323. snd_seq_close (seqHandle);
  223324. }
  223325. void run()
  223326. {
  223327. const int maxEventSize = 16 * 1024;
  223328. snd_midi_event_t* midiParser;
  223329. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223330. {
  223331. HeapBlock <uint8> buffer (maxEventSize);
  223332. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223333. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223334. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223335. while (! threadShouldExit())
  223336. {
  223337. if (poll (pfd, numPfds, 500) > 0)
  223338. {
  223339. snd_seq_event_t* inputEvent = 0;
  223340. snd_seq_nonblock (seqHandle, 1);
  223341. do
  223342. {
  223343. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223344. {
  223345. // xxx what about SYSEXes that are too big for the buffer?
  223346. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223347. snd_midi_event_reset_decode (midiParser);
  223348. if (numBytes > 0)
  223349. {
  223350. const MidiMessage message ((const uint8*) buffer,
  223351. numBytes,
  223352. Time::getMillisecondCounter() * 0.001);
  223353. callback->handleIncomingMidiMessage (midiInput, message);
  223354. }
  223355. snd_seq_free_event (inputEvent);
  223356. }
  223357. }
  223358. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223359. snd_seq_free_event (inputEvent);
  223360. }
  223361. }
  223362. snd_midi_event_free (midiParser);
  223363. }
  223364. };
  223365. private:
  223366. MidiInput* const midiInput;
  223367. snd_seq_t* const seqHandle;
  223368. MidiInputCallback* const callback;
  223369. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223370. };
  223371. MidiInput::MidiInput (const String& name_)
  223372. : name (name_),
  223373. internal (0)
  223374. {
  223375. }
  223376. MidiInput::~MidiInput()
  223377. {
  223378. stop();
  223379. delete static_cast <MidiInputThread*> (internal);
  223380. }
  223381. void MidiInput::start()
  223382. {
  223383. static_cast <MidiInputThread*> (internal)->startThread();
  223384. }
  223385. void MidiInput::stop()
  223386. {
  223387. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223388. }
  223389. int MidiInput::getDefaultDeviceIndex()
  223390. {
  223391. return 0;
  223392. }
  223393. const StringArray MidiInput::getDevices()
  223394. {
  223395. StringArray devices;
  223396. iterateMidiDevices (true, devices, -1);
  223397. return devices;
  223398. }
  223399. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223400. {
  223401. MidiInput* newDevice = 0;
  223402. StringArray devices;
  223403. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223404. if (handle != 0)
  223405. {
  223406. newDevice = new MidiInput (devices [deviceIndex]);
  223407. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223408. }
  223409. return newDevice;
  223410. }
  223411. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223412. {
  223413. MidiInput* newDevice = 0;
  223414. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223415. if (handle != 0)
  223416. {
  223417. newDevice = new MidiInput (deviceName);
  223418. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223419. }
  223420. return newDevice;
  223421. }
  223422. #else
  223423. // (These are just stub functions if ALSA is unavailable...)
  223424. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223425. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223426. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223427. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223428. MidiOutput::~MidiOutput() {}
  223429. void MidiOutput::reset() {}
  223430. bool MidiOutput::getVolume (float&, float&) { return false; }
  223431. void MidiOutput::setVolume (float, float) {}
  223432. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223433. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223434. MidiInput::~MidiInput() {}
  223435. void MidiInput::start() {}
  223436. void MidiInput::stop() {}
  223437. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223438. const StringArray MidiInput::getDevices() { return StringArray(); }
  223439. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223440. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223441. #endif
  223442. #endif
  223443. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223444. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223445. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223446. // compiled on its own).
  223447. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223448. AudioCDReader::AudioCDReader()
  223449. : AudioFormatReader (0, "CD Audio")
  223450. {
  223451. }
  223452. const StringArray AudioCDReader::getAvailableCDNames()
  223453. {
  223454. StringArray names;
  223455. return names;
  223456. }
  223457. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223458. {
  223459. return 0;
  223460. }
  223461. AudioCDReader::~AudioCDReader()
  223462. {
  223463. }
  223464. void AudioCDReader::refreshTrackLengths()
  223465. {
  223466. }
  223467. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223468. int64 startSampleInFile, int numSamples)
  223469. {
  223470. return false;
  223471. }
  223472. bool AudioCDReader::isCDStillPresent() const
  223473. {
  223474. return false;
  223475. }
  223476. bool AudioCDReader::isTrackAudio (int trackNum) const
  223477. {
  223478. return false;
  223479. }
  223480. void AudioCDReader::enableIndexScanning (bool b)
  223481. {
  223482. }
  223483. int AudioCDReader::getLastIndex() const
  223484. {
  223485. return 0;
  223486. }
  223487. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223488. {
  223489. return Array<int>();
  223490. }
  223491. #endif
  223492. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223493. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223494. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223495. // compiled on its own).
  223496. #if JUCE_INCLUDED_FILE
  223497. void FileChooser::showPlatformDialog (Array<File>& results,
  223498. const String& title,
  223499. const File& file,
  223500. const String& filters,
  223501. bool isDirectory,
  223502. bool selectsFiles,
  223503. bool isSave,
  223504. bool warnAboutOverwritingExistingFiles,
  223505. bool selectMultipleFiles,
  223506. FilePreviewComponent* previewComponent)
  223507. {
  223508. const String separator (":");
  223509. String command ("zenity --file-selection");
  223510. if (title.isNotEmpty())
  223511. command << " --title=\"" << title << "\"";
  223512. if (file != File::nonexistent)
  223513. command << " --filename=\"" << file.getFullPathName () << "\"";
  223514. if (isDirectory)
  223515. command << " --directory";
  223516. if (isSave)
  223517. command << " --save";
  223518. if (selectMultipleFiles)
  223519. command << " --multiple --separator=\"" << separator << "\"";
  223520. command << " 2>&1";
  223521. MemoryOutputStream result;
  223522. int status = -1;
  223523. FILE* stream = popen (command.toUTF8(), "r");
  223524. if (stream != 0)
  223525. {
  223526. for (;;)
  223527. {
  223528. char buffer [1024];
  223529. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223530. if (bytesRead <= 0)
  223531. break;
  223532. result.write (buffer, bytesRead);
  223533. }
  223534. status = pclose (stream);
  223535. }
  223536. if (status == 0)
  223537. {
  223538. StringArray tokens;
  223539. if (selectMultipleFiles)
  223540. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223541. else
  223542. tokens.add (result.toUTF8());
  223543. for (int i = 0; i < tokens.size(); i++)
  223544. results.add (File (tokens[i]));
  223545. return;
  223546. }
  223547. //xxx ain't got one!
  223548. jassertfalse;
  223549. }
  223550. #endif
  223551. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223552. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223553. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223554. // compiled on its own).
  223555. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223556. /*
  223557. Sorry.. This class isn't implemented on Linux!
  223558. */
  223559. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223560. : browser (0),
  223561. blankPageShown (false),
  223562. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223563. {
  223564. setOpaque (true);
  223565. }
  223566. WebBrowserComponent::~WebBrowserComponent()
  223567. {
  223568. }
  223569. void WebBrowserComponent::goToURL (const String& url,
  223570. const StringArray* headers,
  223571. const MemoryBlock* postData)
  223572. {
  223573. lastURL = url;
  223574. lastHeaders.clear();
  223575. if (headers != 0)
  223576. lastHeaders = *headers;
  223577. lastPostData.setSize (0);
  223578. if (postData != 0)
  223579. lastPostData = *postData;
  223580. blankPageShown = false;
  223581. }
  223582. void WebBrowserComponent::stop()
  223583. {
  223584. }
  223585. void WebBrowserComponent::goBack()
  223586. {
  223587. lastURL = String::empty;
  223588. blankPageShown = false;
  223589. }
  223590. void WebBrowserComponent::goForward()
  223591. {
  223592. lastURL = String::empty;
  223593. }
  223594. void WebBrowserComponent::refresh()
  223595. {
  223596. }
  223597. void WebBrowserComponent::paint (Graphics& g)
  223598. {
  223599. g.fillAll (Colours::white);
  223600. }
  223601. void WebBrowserComponent::checkWindowAssociation()
  223602. {
  223603. }
  223604. void WebBrowserComponent::reloadLastURL()
  223605. {
  223606. if (lastURL.isNotEmpty())
  223607. {
  223608. goToURL (lastURL, &lastHeaders, &lastPostData);
  223609. lastURL = String::empty;
  223610. }
  223611. }
  223612. void WebBrowserComponent::parentHierarchyChanged()
  223613. {
  223614. checkWindowAssociation();
  223615. }
  223616. void WebBrowserComponent::resized()
  223617. {
  223618. }
  223619. void WebBrowserComponent::visibilityChanged()
  223620. {
  223621. checkWindowAssociation();
  223622. }
  223623. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223624. {
  223625. return true;
  223626. }
  223627. #endif
  223628. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223629. #endif
  223630. END_JUCE_NAMESPACE
  223631. #endif
  223632. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223633. #elif JUCE_MAC || JUCE_IOS
  223634. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223635. /*
  223636. This file wraps together all the mac-specific code, so that
  223637. we can include all the native headers just once, and compile all our
  223638. platform-specific stuff in one big lump, keeping it out of the way of
  223639. the rest of the codebase.
  223640. */
  223641. #if JUCE_MAC || JUCE_IOS
  223642. #undef JUCE_BUILD_NATIVE
  223643. #define JUCE_BUILD_NATIVE 1
  223644. BEGIN_JUCE_NAMESPACE
  223645. #undef Point
  223646. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223647. namespace
  223648. {
  223649. template <class RectType>
  223650. const Rectangle<int> convertToRectInt (const RectType& r)
  223651. {
  223652. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223653. }
  223654. template <class RectType>
  223655. const Rectangle<float> convertToRectFloat (const RectType& r)
  223656. {
  223657. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223658. }
  223659. template <class RectType>
  223660. CGRect convertToCGRect (const RectType& r)
  223661. {
  223662. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223663. }
  223664. }
  223665. class MessageQueue
  223666. {
  223667. public:
  223668. MessageQueue()
  223669. {
  223670. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223671. runLoop = CFRunLoopGetMain();
  223672. #else
  223673. runLoop = CFRunLoopGetCurrent();
  223674. #endif
  223675. CFRunLoopSourceContext sourceContext;
  223676. zerostruct (sourceContext);
  223677. sourceContext.info = this;
  223678. sourceContext.perform = runLoopSourceCallback;
  223679. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223680. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223681. }
  223682. ~MessageQueue()
  223683. {
  223684. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223685. CFRunLoopSourceInvalidate (runLoopSource);
  223686. CFRelease (runLoopSource);
  223687. }
  223688. void post (Message* const message)
  223689. {
  223690. messages.add (message);
  223691. CFRunLoopSourceSignal (runLoopSource);
  223692. CFRunLoopWakeUp (runLoop);
  223693. }
  223694. private:
  223695. ReferenceCountedArray <Message, CriticalSection> messages;
  223696. CriticalSection lock;
  223697. CFRunLoopRef runLoop;
  223698. CFRunLoopSourceRef runLoopSource;
  223699. bool deliverNextMessage()
  223700. {
  223701. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223702. if (nextMessage == 0)
  223703. return false;
  223704. const ScopedAutoReleasePool pool;
  223705. MessageManager::getInstance()->deliverMessage (nextMessage);
  223706. return true;
  223707. }
  223708. void runLoopCallback()
  223709. {
  223710. for (int i = 4; --i >= 0;)
  223711. if (! deliverNextMessage())
  223712. return;
  223713. CFRunLoopSourceSignal (runLoopSource);
  223714. CFRunLoopWakeUp (runLoop);
  223715. }
  223716. static void runLoopSourceCallback (void* info)
  223717. {
  223718. static_cast <MessageQueue*> (info)->runLoopCallback();
  223719. }
  223720. };
  223721. #endif
  223722. #define JUCE_INCLUDED_FILE 1
  223723. // Now include the actual code files..
  223724. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223725. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223726. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223727. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223728. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223729. actually calling into a similarly named class in the other module's address space.
  223730. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223731. have unique names, and should avoid this problem.
  223732. If you're using the amalgamated version, you can just set this macro to something unique before
  223733. you include juce_amalgamated.cpp.
  223734. */
  223735. #ifndef JUCE_ObjCExtraSuffix
  223736. #define JUCE_ObjCExtraSuffix 3
  223737. #endif
  223738. #ifndef DOXYGEN
  223739. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223740. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223741. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223742. #endif
  223743. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223744. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223745. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223746. // compiled on its own).
  223747. #if JUCE_INCLUDED_FILE
  223748. namespace
  223749. {
  223750. const String nsStringToJuce (NSString* s)
  223751. {
  223752. return String::fromUTF8 ([s UTF8String]);
  223753. }
  223754. NSString* juceStringToNS (const String& s)
  223755. {
  223756. return [NSString stringWithUTF8String: s.toUTF8()];
  223757. }
  223758. const String convertUTF16ToString (const UniChar* utf16)
  223759. {
  223760. String s;
  223761. while (*utf16 != 0)
  223762. s += (juce_wchar) *utf16++;
  223763. return s;
  223764. }
  223765. }
  223766. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223767. {
  223768. String result;
  223769. if (cfString != 0)
  223770. {
  223771. CFRange range = { 0, CFStringGetLength (cfString) };
  223772. HeapBlock <UniChar> u (range.length + 1);
  223773. CFStringGetCharacters (cfString, range, u);
  223774. u[range.length] = 0;
  223775. result = convertUTF16ToString (u);
  223776. }
  223777. return result;
  223778. }
  223779. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223780. {
  223781. const int len = s.length();
  223782. HeapBlock <UniChar> temp (len + 2);
  223783. for (int i = 0; i <= len; ++i)
  223784. temp[i] = s[i];
  223785. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223786. }
  223787. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223788. {
  223789. #if JUCE_IOS
  223790. const ScopedAutoReleasePool pool;
  223791. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223792. #else
  223793. UnicodeMapping map;
  223794. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223795. kUnicodeNoSubset,
  223796. kTextEncodingDefaultFormat);
  223797. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223798. kUnicodeCanonicalCompVariant,
  223799. kTextEncodingDefaultFormat);
  223800. map.mappingVersion = kUnicodeUseLatestMapping;
  223801. UnicodeToTextInfo conversionInfo = 0;
  223802. String result;
  223803. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223804. {
  223805. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223806. HeapBlock <char> tempOut;
  223807. tempOut.calloc (bytesNeeded + 4);
  223808. ByteCount bytesRead = 0;
  223809. ByteCount outputBufferSize = 0;
  223810. if (ConvertFromUnicodeToText (conversionInfo,
  223811. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223812. kUnicodeDefaultDirectionMask,
  223813. 0, 0, 0, 0,
  223814. bytesNeeded, &bytesRead,
  223815. &outputBufferSize, tempOut) == noErr)
  223816. {
  223817. result = String (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223818. }
  223819. DisposeUnicodeToTextInfo (&conversionInfo);
  223820. }
  223821. return result;
  223822. #endif
  223823. }
  223824. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223825. void SystemClipboard::copyTextToClipboard (const String& text)
  223826. {
  223827. #if JUCE_IOS
  223828. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223829. forPasteboardType: @"public.text"];
  223830. #else
  223831. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223832. owner: nil];
  223833. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223834. forType: NSStringPboardType];
  223835. #endif
  223836. }
  223837. const String SystemClipboard::getTextFromClipboard()
  223838. {
  223839. #if JUCE_IOS
  223840. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223841. #else
  223842. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223843. #endif
  223844. return text == 0 ? String::empty
  223845. : nsStringToJuce (text);
  223846. }
  223847. #endif
  223848. #endif
  223849. /*** End of inlined file: juce_mac_Strings.mm ***/
  223850. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223851. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223852. // compiled on its own).
  223853. #if JUCE_INCLUDED_FILE
  223854. namespace SystemStatsHelpers
  223855. {
  223856. static int64 highResTimerFrequency = 0;
  223857. static double highResTimerToMillisecRatio = 0;
  223858. #if JUCE_INTEL
  223859. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223860. {
  223861. uint32 la = a, lb = b, lc = c, ld = d;
  223862. asm ("mov %%ebx, %%esi \n\t"
  223863. "cpuid \n\t"
  223864. "xchg %%esi, %%ebx"
  223865. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223866. #if JUCE_64BIT
  223867. , "b" (lb), "c" (lc), "d" (ld)
  223868. #endif
  223869. );
  223870. a = la; b = lb; c = lc; d = ld;
  223871. }
  223872. #endif
  223873. }
  223874. void SystemStats::initialiseStats()
  223875. {
  223876. using namespace SystemStatsHelpers;
  223877. static bool initialised = false;
  223878. if (! initialised)
  223879. {
  223880. initialised = true;
  223881. #if JUCE_MAC
  223882. [NSApplication sharedApplication];
  223883. #endif
  223884. #if JUCE_INTEL
  223885. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223886. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223887. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223888. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223889. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223890. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223891. #else
  223892. cpuFlags.hasMMX = false;
  223893. cpuFlags.hasSSE = false;
  223894. cpuFlags.hasSSE2 = false;
  223895. cpuFlags.has3DNow = false;
  223896. #endif
  223897. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223898. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223899. #else
  223900. cpuFlags.numCpus = (int) MPProcessors();
  223901. #endif
  223902. mach_timebase_info_data_t timebase;
  223903. (void) mach_timebase_info (&timebase);
  223904. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223905. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223906. String s (SystemStats::getJUCEVersion());
  223907. rlimit lim;
  223908. getrlimit (RLIMIT_NOFILE, &lim);
  223909. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223910. setrlimit (RLIMIT_NOFILE, &lim);
  223911. }
  223912. }
  223913. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223914. {
  223915. return MacOSX;
  223916. }
  223917. const String SystemStats::getOperatingSystemName()
  223918. {
  223919. return "Mac OS X";
  223920. }
  223921. #if ! JUCE_IOS
  223922. int PlatformUtilities::getOSXMinorVersionNumber()
  223923. {
  223924. SInt32 versionMinor = 0;
  223925. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223926. (void) err;
  223927. jassert (err == noErr);
  223928. return (int) versionMinor;
  223929. }
  223930. #endif
  223931. bool SystemStats::isOperatingSystem64Bit()
  223932. {
  223933. #if JUCE_IOS
  223934. return false;
  223935. #elif JUCE_64BIT
  223936. return true;
  223937. #else
  223938. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223939. #endif
  223940. }
  223941. int SystemStats::getMemorySizeInMegabytes()
  223942. {
  223943. uint64 mem = 0;
  223944. size_t memSize = sizeof (mem);
  223945. int mib[] = { CTL_HW, HW_MEMSIZE };
  223946. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223947. return (int) (mem / (1024 * 1024));
  223948. }
  223949. const String SystemStats::getCpuVendor()
  223950. {
  223951. #if JUCE_INTEL
  223952. uint32 dummy = 0;
  223953. uint32 vendor[4];
  223954. zerostruct (vendor);
  223955. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223956. return String (reinterpret_cast <const char*> (vendor), 12);
  223957. #else
  223958. return String::empty;
  223959. #endif
  223960. }
  223961. int SystemStats::getCpuSpeedInMegaherz()
  223962. {
  223963. uint64 speedHz = 0;
  223964. size_t speedSize = sizeof (speedHz);
  223965. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223966. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223967. #if JUCE_BIG_ENDIAN
  223968. if (speedSize == 4)
  223969. speedHz >>= 32;
  223970. #endif
  223971. return (int) (speedHz / 1000000);
  223972. }
  223973. const String SystemStats::getLogonName()
  223974. {
  223975. return nsStringToJuce (NSUserName());
  223976. }
  223977. const String SystemStats::getFullUserName()
  223978. {
  223979. return nsStringToJuce (NSFullUserName());
  223980. }
  223981. uint32 juce_millisecondsSinceStartup() throw()
  223982. {
  223983. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223984. }
  223985. double Time::getMillisecondCounterHiRes() throw()
  223986. {
  223987. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223988. }
  223989. int64 Time::getHighResolutionTicks() throw()
  223990. {
  223991. return (int64) mach_absolute_time();
  223992. }
  223993. int64 Time::getHighResolutionTicksPerSecond() throw()
  223994. {
  223995. return SystemStatsHelpers::highResTimerFrequency;
  223996. }
  223997. bool Time::setSystemTimeToThisTime() const
  223998. {
  223999. jassertfalse;
  224000. return false;
  224001. }
  224002. int SystemStats::getPageSize()
  224003. {
  224004. return (int) NSPageSize();
  224005. }
  224006. void PlatformUtilities::fpuReset()
  224007. {
  224008. }
  224009. #endif
  224010. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224011. /*** Start of inlined file: juce_mac_Network.mm ***/
  224012. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224013. // compiled on its own).
  224014. #if JUCE_INCLUDED_FILE
  224015. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  224016. {
  224017. ifaddrs* addrs = 0;
  224018. if (getifaddrs (&addrs) == 0)
  224019. {
  224020. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224021. {
  224022. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224023. if (sto->ss_family == AF_LINK)
  224024. {
  224025. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224026. #ifndef IFT_ETHER
  224027. #define IFT_ETHER 6
  224028. #endif
  224029. if (sadd->sdl_type == IFT_ETHER)
  224030. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224031. }
  224032. }
  224033. freeifaddrs (addrs);
  224034. }
  224035. }
  224036. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224037. const String& emailSubject,
  224038. const String& bodyText,
  224039. const StringArray& filesToAttach)
  224040. {
  224041. #if JUCE_IOS
  224042. //xxx probably need to use MFMailComposeViewController
  224043. jassertfalse;
  224044. return false;
  224045. #else
  224046. const ScopedAutoReleasePool pool;
  224047. String script;
  224048. script << "tell application \"Mail\"\r\n"
  224049. "set newMessage to make new outgoing message with properties {subject:\""
  224050. << emailSubject.replace ("\"", "\\\"")
  224051. << "\", content:\""
  224052. << bodyText.replace ("\"", "\\\"")
  224053. << "\" & return & return}\r\n"
  224054. "tell newMessage\r\n"
  224055. "set visible to true\r\n"
  224056. "set sender to \"sdfsdfsdfewf\"\r\n"
  224057. "make new to recipient at end of to recipients with properties {address:\""
  224058. << targetEmailAddress
  224059. << "\"}\r\n";
  224060. for (int i = 0; i < filesToAttach.size(); ++i)
  224061. {
  224062. script << "tell content\r\n"
  224063. "make new attachment with properties {file name:\""
  224064. << filesToAttach[i].replace ("\"", "\\\"")
  224065. << "\"} at after the last paragraph\r\n"
  224066. "end tell\r\n";
  224067. }
  224068. script << "end tell\r\n"
  224069. "end tell\r\n";
  224070. NSAppleScript* s = [[NSAppleScript alloc]
  224071. initWithSource: juceStringToNS (script)];
  224072. NSDictionary* error = 0;
  224073. const bool ok = [s executeAndReturnError: &error] != nil;
  224074. [s release];
  224075. return ok;
  224076. #endif
  224077. }
  224078. END_JUCE_NAMESPACE
  224079. using namespace JUCE_NAMESPACE;
  224080. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224081. @interface JuceURLConnection : NSObject
  224082. {
  224083. @public
  224084. NSURLRequest* request;
  224085. NSURLConnection* connection;
  224086. NSMutableData* data;
  224087. Thread* runLoopThread;
  224088. bool initialised, hasFailed, hasFinished;
  224089. int position;
  224090. int64 contentLength;
  224091. NSDictionary* headers;
  224092. NSLock* dataLock;
  224093. }
  224094. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224095. - (void) dealloc;
  224096. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224097. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224098. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224099. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224100. - (BOOL) isOpen;
  224101. - (int) read: (char*) dest numBytes: (int) num;
  224102. - (int) readPosition;
  224103. - (void) stop;
  224104. - (void) createConnection;
  224105. @end
  224106. class JuceURLConnectionMessageThread : public Thread
  224107. {
  224108. public:
  224109. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224110. : Thread ("http connection"),
  224111. owner (owner_)
  224112. {
  224113. }
  224114. ~JuceURLConnectionMessageThread()
  224115. {
  224116. stopThread (10000);
  224117. }
  224118. void run()
  224119. {
  224120. [owner createConnection];
  224121. while (! threadShouldExit())
  224122. {
  224123. const ScopedAutoReleasePool pool;
  224124. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224125. }
  224126. }
  224127. private:
  224128. JuceURLConnection* owner;
  224129. };
  224130. @implementation JuceURLConnection
  224131. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224132. withCallback: (URL::OpenStreamProgressCallback*) callback
  224133. withContext: (void*) context;
  224134. {
  224135. [super init];
  224136. request = req;
  224137. [request retain];
  224138. data = [[NSMutableData data] retain];
  224139. dataLock = [[NSLock alloc] init];
  224140. connection = 0;
  224141. initialised = false;
  224142. hasFailed = false;
  224143. hasFinished = false;
  224144. contentLength = -1;
  224145. headers = 0;
  224146. runLoopThread = new JuceURLConnectionMessageThread (self);
  224147. runLoopThread->startThread();
  224148. while (runLoopThread->isThreadRunning() && ! initialised)
  224149. {
  224150. if (callback != 0)
  224151. callback (context, -1, (int) [[request HTTPBody] length]);
  224152. Thread::sleep (1);
  224153. }
  224154. return self;
  224155. }
  224156. - (void) dealloc
  224157. {
  224158. [self stop];
  224159. deleteAndZero (runLoopThread);
  224160. [connection release];
  224161. [data release];
  224162. [dataLock release];
  224163. [request release];
  224164. [headers release];
  224165. [super dealloc];
  224166. }
  224167. - (void) createConnection
  224168. {
  224169. NSUInteger oldRetainCount = [self retainCount];
  224170. connection = [[NSURLConnection alloc] initWithRequest: request
  224171. delegate: self];
  224172. if (oldRetainCount == [self retainCount])
  224173. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224174. if (connection == nil)
  224175. runLoopThread->signalThreadShouldExit();
  224176. }
  224177. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224178. {
  224179. (void) conn;
  224180. [dataLock lock];
  224181. [data setLength: 0];
  224182. [dataLock unlock];
  224183. initialised = true;
  224184. contentLength = [response expectedContentLength];
  224185. [headers release];
  224186. headers = 0;
  224187. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224188. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224189. }
  224190. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224191. {
  224192. (void) conn;
  224193. DBG (nsStringToJuce ([error description]));
  224194. hasFailed = true;
  224195. initialised = true;
  224196. if (runLoopThread != 0)
  224197. runLoopThread->signalThreadShouldExit();
  224198. }
  224199. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224200. {
  224201. (void) conn;
  224202. [dataLock lock];
  224203. [data appendData: newData];
  224204. [dataLock unlock];
  224205. initialised = true;
  224206. }
  224207. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224208. {
  224209. (void) conn;
  224210. hasFinished = true;
  224211. initialised = true;
  224212. if (runLoopThread != 0)
  224213. runLoopThread->signalThreadShouldExit();
  224214. }
  224215. - (BOOL) isOpen
  224216. {
  224217. return connection != 0 && ! hasFailed;
  224218. }
  224219. - (int) readPosition
  224220. {
  224221. return position;
  224222. }
  224223. - (int) read: (char*) dest numBytes: (int) numNeeded
  224224. {
  224225. int numDone = 0;
  224226. while (numNeeded > 0)
  224227. {
  224228. int available = jmin (numNeeded, (int) [data length]);
  224229. if (available > 0)
  224230. {
  224231. [dataLock lock];
  224232. [data getBytes: dest length: available];
  224233. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224234. [dataLock unlock];
  224235. numDone += available;
  224236. numNeeded -= available;
  224237. dest += available;
  224238. }
  224239. else
  224240. {
  224241. if (hasFailed || hasFinished)
  224242. break;
  224243. Thread::sleep (1);
  224244. }
  224245. }
  224246. position += numDone;
  224247. return numDone;
  224248. }
  224249. - (void) stop
  224250. {
  224251. [connection cancel];
  224252. if (runLoopThread != 0)
  224253. runLoopThread->stopThread (10000);
  224254. }
  224255. @end
  224256. BEGIN_JUCE_NAMESPACE
  224257. class WebInputStream : public InputStream
  224258. {
  224259. public:
  224260. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  224261. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224262. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  224263. : connection (nil),
  224264. address (address_), headers (headers_), postData (postData_), position (0),
  224265. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  224266. {
  224267. JUCE_AUTORELEASEPOOL
  224268. connection = createConnection (progressCallback, progressCallbackContext);
  224269. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  224270. {
  224271. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  224272. NSString* key;
  224273. while ((key = [enumerator nextObject]) != nil)
  224274. responseHeaders->set (nsStringToJuce (key),
  224275. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  224276. }
  224277. }
  224278. ~WebInputStream()
  224279. {
  224280. close();
  224281. }
  224282. bool isError() const { return connection == nil; }
  224283. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  224284. bool isExhausted() { return finished; }
  224285. int64 getPosition() { return position; }
  224286. int read (void* buffer, int bytesToRead)
  224287. {
  224288. if (finished || isError())
  224289. {
  224290. return 0;
  224291. }
  224292. else
  224293. {
  224294. JUCE_AUTORELEASEPOOL
  224295. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  224296. position += bytesRead;
  224297. if (bytesRead == 0)
  224298. finished = true;
  224299. return bytesRead;
  224300. }
  224301. }
  224302. bool setPosition (int64 wantedPos)
  224303. {
  224304. if (wantedPos != position)
  224305. {
  224306. finished = false;
  224307. if (wantedPos < position)
  224308. {
  224309. close();
  224310. position = 0;
  224311. connection = createConnection (0, 0);
  224312. }
  224313. skipNextBytes (wantedPos - position);
  224314. }
  224315. return true;
  224316. }
  224317. private:
  224318. JuceURLConnection* connection;
  224319. String address, headers;
  224320. MemoryBlock postData;
  224321. int64 position;
  224322. bool finished;
  224323. const bool isPost;
  224324. const int timeOutMs;
  224325. void close()
  224326. {
  224327. [connection stop];
  224328. [connection release];
  224329. connection = nil;
  224330. }
  224331. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224332. void* progressCallbackContext)
  224333. {
  224334. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224335. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224336. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224337. if (req == nil)
  224338. return 0;
  224339. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224340. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224341. StringArray headerLines;
  224342. headerLines.addLines (headers);
  224343. headerLines.removeEmptyStrings (true);
  224344. for (int i = 0; i < headerLines.size(); ++i)
  224345. {
  224346. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224347. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224348. if (key.isNotEmpty() && value.isNotEmpty())
  224349. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224350. }
  224351. if (isPost && postData.getSize() > 0)
  224352. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224353. length: postData.getSize()]];
  224354. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224355. withCallback: progressCallback
  224356. withContext: progressCallbackContext];
  224357. if ([s isOpen])
  224358. return s;
  224359. [s release];
  224360. return 0;
  224361. }
  224362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224363. };
  224364. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224365. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224366. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224367. {
  224368. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224369. progressCallback, progressCallbackContext,
  224370. headers, timeOutMs, responseHeaders));
  224371. return wi->isError() ? 0 : wi.release();
  224372. }
  224373. #endif
  224374. /*** End of inlined file: juce_mac_Network.mm ***/
  224375. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224376. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224377. // compiled on its own).
  224378. #if JUCE_INCLUDED_FILE
  224379. struct NamedPipeInternal
  224380. {
  224381. String pipeInName, pipeOutName;
  224382. int pipeIn, pipeOut;
  224383. bool volatile createdPipe, blocked, stopReadOperation;
  224384. static void signalHandler (int) {}
  224385. };
  224386. void NamedPipe::cancelPendingReads()
  224387. {
  224388. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224389. {
  224390. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224391. intern->stopReadOperation = true;
  224392. char buffer [1] = { 0 };
  224393. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224394. (void) bytesWritten;
  224395. int timeout = 2000;
  224396. while (intern->blocked && --timeout >= 0)
  224397. Thread::sleep (2);
  224398. intern->stopReadOperation = false;
  224399. }
  224400. }
  224401. void NamedPipe::close()
  224402. {
  224403. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224404. if (intern != 0)
  224405. {
  224406. internal = 0;
  224407. if (intern->pipeIn != -1)
  224408. ::close (intern->pipeIn);
  224409. if (intern->pipeOut != -1)
  224410. ::close (intern->pipeOut);
  224411. if (intern->createdPipe)
  224412. {
  224413. unlink (intern->pipeInName.toUTF8());
  224414. unlink (intern->pipeOutName.toUTF8());
  224415. }
  224416. delete intern;
  224417. }
  224418. }
  224419. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224420. {
  224421. close();
  224422. NamedPipeInternal* const intern = new NamedPipeInternal();
  224423. internal = intern;
  224424. intern->createdPipe = createPipe;
  224425. intern->blocked = false;
  224426. intern->stopReadOperation = false;
  224427. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224428. siginterrupt (SIGPIPE, 1);
  224429. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224430. intern->pipeInName = pipePath + "_in";
  224431. intern->pipeOutName = pipePath + "_out";
  224432. intern->pipeIn = -1;
  224433. intern->pipeOut = -1;
  224434. if (createPipe)
  224435. {
  224436. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224437. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224438. {
  224439. delete intern;
  224440. internal = 0;
  224441. return false;
  224442. }
  224443. }
  224444. return true;
  224445. }
  224446. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224447. {
  224448. int bytesRead = -1;
  224449. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224450. if (intern != 0)
  224451. {
  224452. intern->blocked = true;
  224453. if (intern->pipeIn == -1)
  224454. {
  224455. if (intern->createdPipe)
  224456. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224457. else
  224458. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224459. if (intern->pipeIn == -1)
  224460. {
  224461. intern->blocked = false;
  224462. return -1;
  224463. }
  224464. }
  224465. bytesRead = 0;
  224466. char* p = static_cast<char*> (destBuffer);
  224467. while (bytesRead < maxBytesToRead)
  224468. {
  224469. const int bytesThisTime = maxBytesToRead - bytesRead;
  224470. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224471. if (numRead <= 0 || intern->stopReadOperation)
  224472. {
  224473. bytesRead = -1;
  224474. break;
  224475. }
  224476. bytesRead += numRead;
  224477. p += bytesRead;
  224478. }
  224479. intern->blocked = false;
  224480. }
  224481. return bytesRead;
  224482. }
  224483. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224484. {
  224485. int bytesWritten = -1;
  224486. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224487. if (intern != 0)
  224488. {
  224489. if (intern->pipeOut == -1)
  224490. {
  224491. if (intern->createdPipe)
  224492. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224493. else
  224494. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224495. if (intern->pipeOut == -1)
  224496. {
  224497. return -1;
  224498. }
  224499. }
  224500. const char* p = static_cast<const char*> (sourceBuffer);
  224501. bytesWritten = 0;
  224502. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224503. while (bytesWritten < numBytesToWrite
  224504. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224505. {
  224506. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224507. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224508. if (numWritten <= 0)
  224509. {
  224510. bytesWritten = -1;
  224511. break;
  224512. }
  224513. bytesWritten += numWritten;
  224514. p += bytesWritten;
  224515. }
  224516. }
  224517. return bytesWritten;
  224518. }
  224519. #endif
  224520. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224521. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224522. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224523. // compiled on its own).
  224524. #if JUCE_INCLUDED_FILE
  224525. /*
  224526. Note that a lot of methods that you'd expect to find in this file actually
  224527. live in juce_posix_SharedCode.h!
  224528. */
  224529. bool Process::isForegroundProcess()
  224530. {
  224531. #if JUCE_MAC
  224532. return [NSApp isActive];
  224533. #else
  224534. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224535. #endif
  224536. }
  224537. void Process::raisePrivilege()
  224538. {
  224539. jassertfalse;
  224540. }
  224541. void Process::lowerPrivilege()
  224542. {
  224543. jassertfalse;
  224544. }
  224545. void Process::terminate()
  224546. {
  224547. exit (0);
  224548. }
  224549. void Process::setPriority (ProcessPriority)
  224550. {
  224551. // xxx
  224552. }
  224553. #endif
  224554. /*** End of inlined file: juce_mac_Threads.mm ***/
  224555. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224556. /*
  224557. This file contains posix routines that are common to both the Linux and Mac builds.
  224558. It gets included directly in the cpp files for these platforms.
  224559. */
  224560. CriticalSection::CriticalSection() throw()
  224561. {
  224562. pthread_mutexattr_t atts;
  224563. pthread_mutexattr_init (&atts);
  224564. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224565. #if ! JUCE_ANDROID
  224566. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224567. #endif
  224568. pthread_mutex_init (&internal, &atts);
  224569. }
  224570. CriticalSection::~CriticalSection() throw()
  224571. {
  224572. pthread_mutex_destroy (&internal);
  224573. }
  224574. void CriticalSection::enter() const throw()
  224575. {
  224576. pthread_mutex_lock (&internal);
  224577. }
  224578. bool CriticalSection::tryEnter() const throw()
  224579. {
  224580. return pthread_mutex_trylock (&internal) == 0;
  224581. }
  224582. void CriticalSection::exit() const throw()
  224583. {
  224584. pthread_mutex_unlock (&internal);
  224585. }
  224586. class WaitableEventImpl
  224587. {
  224588. public:
  224589. WaitableEventImpl (const bool manualReset_)
  224590. : triggered (false),
  224591. manualReset (manualReset_)
  224592. {
  224593. pthread_cond_init (&condition, 0);
  224594. pthread_mutexattr_t atts;
  224595. pthread_mutexattr_init (&atts);
  224596. #if ! JUCE_ANDROID
  224597. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224598. #endif
  224599. pthread_mutex_init (&mutex, &atts);
  224600. }
  224601. ~WaitableEventImpl()
  224602. {
  224603. pthread_cond_destroy (&condition);
  224604. pthread_mutex_destroy (&mutex);
  224605. }
  224606. bool wait (const int timeOutMillisecs) throw()
  224607. {
  224608. pthread_mutex_lock (&mutex);
  224609. if (! triggered)
  224610. {
  224611. if (timeOutMillisecs < 0)
  224612. {
  224613. do
  224614. {
  224615. pthread_cond_wait (&condition, &mutex);
  224616. }
  224617. while (! triggered);
  224618. }
  224619. else
  224620. {
  224621. struct timeval now;
  224622. gettimeofday (&now, 0);
  224623. struct timespec time;
  224624. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224625. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224626. if (time.tv_nsec >= 1000000000)
  224627. {
  224628. time.tv_nsec -= 1000000000;
  224629. time.tv_sec++;
  224630. }
  224631. do
  224632. {
  224633. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224634. {
  224635. pthread_mutex_unlock (&mutex);
  224636. return false;
  224637. }
  224638. }
  224639. while (! triggered);
  224640. }
  224641. }
  224642. if (! manualReset)
  224643. triggered = false;
  224644. pthread_mutex_unlock (&mutex);
  224645. return true;
  224646. }
  224647. void signal() throw()
  224648. {
  224649. pthread_mutex_lock (&mutex);
  224650. triggered = true;
  224651. pthread_cond_broadcast (&condition);
  224652. pthread_mutex_unlock (&mutex);
  224653. }
  224654. void reset() throw()
  224655. {
  224656. pthread_mutex_lock (&mutex);
  224657. triggered = false;
  224658. pthread_mutex_unlock (&mutex);
  224659. }
  224660. private:
  224661. pthread_cond_t condition;
  224662. pthread_mutex_t mutex;
  224663. bool triggered;
  224664. const bool manualReset;
  224665. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224666. };
  224667. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224668. : internal (new WaitableEventImpl (manualReset))
  224669. {
  224670. }
  224671. WaitableEvent::~WaitableEvent() throw()
  224672. {
  224673. delete static_cast <WaitableEventImpl*> (internal);
  224674. }
  224675. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224676. {
  224677. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224678. }
  224679. void WaitableEvent::signal() const throw()
  224680. {
  224681. static_cast <WaitableEventImpl*> (internal)->signal();
  224682. }
  224683. void WaitableEvent::reset() const throw()
  224684. {
  224685. static_cast <WaitableEventImpl*> (internal)->reset();
  224686. }
  224687. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224688. {
  224689. struct timespec time;
  224690. time.tv_sec = millisecs / 1000;
  224691. time.tv_nsec = (millisecs % 1000) * 1000000;
  224692. nanosleep (&time, 0);
  224693. }
  224694. const juce_wchar File::separator = '/';
  224695. const String File::separatorString ("/");
  224696. const File File::getCurrentWorkingDirectory()
  224697. {
  224698. HeapBlock<char> heapBuffer;
  224699. char localBuffer [1024];
  224700. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224701. int bufferSize = 4096;
  224702. while (cwd == 0 && errno == ERANGE)
  224703. {
  224704. heapBuffer.malloc (bufferSize);
  224705. cwd = getcwd (heapBuffer, bufferSize - 1);
  224706. bufferSize += 1024;
  224707. }
  224708. return File (String::fromUTF8 (cwd));
  224709. }
  224710. bool File::setAsCurrentWorkingDirectory() const
  224711. {
  224712. return chdir (getFullPathName().toUTF8()) == 0;
  224713. }
  224714. namespace
  224715. {
  224716. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224717. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224718. #else
  224719. typedef struct stat juce_statStruct;
  224720. #endif
  224721. bool juce_stat (const String& fileName, juce_statStruct& info)
  224722. {
  224723. return fileName.isNotEmpty()
  224724. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224725. && (stat64 (fileName.toUTF8(), &info) == 0);
  224726. #else
  224727. && (stat (fileName.toUTF8(), &info) == 0);
  224728. #endif
  224729. }
  224730. // if this file doesn't exist, find a parent of it that does..
  224731. bool juce_doStatFS (File f, struct statfs& result)
  224732. {
  224733. for (int i = 5; --i >= 0;)
  224734. {
  224735. if (f.exists())
  224736. break;
  224737. f = f.getParentDirectory();
  224738. }
  224739. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224740. }
  224741. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224742. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224743. {
  224744. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224745. {
  224746. juce_statStruct info;
  224747. const bool statOk = juce_stat (path, info);
  224748. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224749. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224750. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224751. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224752. }
  224753. if (isReadOnly != 0)
  224754. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224755. }
  224756. }
  224757. bool File::isDirectory() const
  224758. {
  224759. juce_statStruct info;
  224760. return fullPath.isEmpty()
  224761. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224762. }
  224763. bool File::exists() const
  224764. {
  224765. juce_statStruct info;
  224766. return fullPath.isNotEmpty()
  224767. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224768. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224769. #else
  224770. && (lstat (fullPath.toUTF8(), &info) == 0);
  224771. #endif
  224772. }
  224773. bool File::existsAsFile() const
  224774. {
  224775. return exists() && ! isDirectory();
  224776. }
  224777. int64 File::getSize() const
  224778. {
  224779. juce_statStruct info;
  224780. return juce_stat (fullPath, info) ? info.st_size : 0;
  224781. }
  224782. bool File::hasWriteAccess() const
  224783. {
  224784. if (exists())
  224785. return access (fullPath.toUTF8(), W_OK) == 0;
  224786. if ((! isDirectory()) && fullPath.containsChar (separator))
  224787. return getParentDirectory().hasWriteAccess();
  224788. return false;
  224789. }
  224790. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224791. {
  224792. juce_statStruct info;
  224793. if (! juce_stat (fullPath, info))
  224794. return false;
  224795. info.st_mode &= 0777; // Just permissions
  224796. if (shouldBeReadOnly)
  224797. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224798. else
  224799. // Give everybody write permission?
  224800. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224801. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224802. }
  224803. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224804. {
  224805. modificationTime = 0;
  224806. accessTime = 0;
  224807. creationTime = 0;
  224808. juce_statStruct info;
  224809. if (juce_stat (fullPath, info))
  224810. {
  224811. modificationTime = (int64) info.st_mtime * 1000;
  224812. accessTime = (int64) info.st_atime * 1000;
  224813. creationTime = (int64) info.st_ctime * 1000;
  224814. }
  224815. }
  224816. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224817. {
  224818. juce_statStruct info;
  224819. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224820. {
  224821. struct utimbuf times;
  224822. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224823. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224824. return utime (fullPath.toUTF8(), &times) == 0;
  224825. }
  224826. return false;
  224827. }
  224828. bool File::deleteFile() const
  224829. {
  224830. if (! exists())
  224831. return true;
  224832. if (isDirectory())
  224833. return rmdir (fullPath.toUTF8()) == 0;
  224834. return remove (fullPath.toUTF8()) == 0;
  224835. }
  224836. bool File::moveInternal (const File& dest) const
  224837. {
  224838. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224839. return true;
  224840. if (hasWriteAccess() && copyInternal (dest))
  224841. {
  224842. if (deleteFile())
  224843. return true;
  224844. dest.deleteFile();
  224845. }
  224846. return false;
  224847. }
  224848. void File::createDirectoryInternal (const String& fileName) const
  224849. {
  224850. mkdir (fileName.toUTF8(), 0777);
  224851. }
  224852. int64 juce_fileSetPosition (void* handle, int64 pos)
  224853. {
  224854. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224855. return pos;
  224856. return -1;
  224857. }
  224858. void FileInputStream::openHandle()
  224859. {
  224860. totalSize = file.getSize();
  224861. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224862. if (f != -1)
  224863. fileHandle = (void*) f;
  224864. }
  224865. void FileInputStream::closeHandle()
  224866. {
  224867. if (fileHandle != 0)
  224868. {
  224869. close ((int) (pointer_sized_int) fileHandle);
  224870. fileHandle = 0;
  224871. }
  224872. }
  224873. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224874. {
  224875. if (fileHandle != 0)
  224876. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224877. return 0;
  224878. }
  224879. void FileOutputStream::openHandle()
  224880. {
  224881. if (file.exists())
  224882. {
  224883. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224884. if (f != -1)
  224885. {
  224886. currentPosition = lseek (f, 0, SEEK_END);
  224887. if (currentPosition >= 0)
  224888. fileHandle = (void*) f;
  224889. else
  224890. close (f);
  224891. }
  224892. }
  224893. else
  224894. {
  224895. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224896. if (f != -1)
  224897. fileHandle = (void*) f;
  224898. }
  224899. }
  224900. void FileOutputStream::closeHandle()
  224901. {
  224902. if (fileHandle != 0)
  224903. {
  224904. close ((int) (pointer_sized_int) fileHandle);
  224905. fileHandle = 0;
  224906. }
  224907. }
  224908. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224909. {
  224910. if (fileHandle != 0)
  224911. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224912. return 0;
  224913. }
  224914. void FileOutputStream::flushInternal()
  224915. {
  224916. if (fileHandle != 0)
  224917. fsync ((int) (pointer_sized_int) fileHandle);
  224918. }
  224919. const File juce_getExecutableFile()
  224920. {
  224921. #if JUCE_ANDROID
  224922. return File (android.appFile);
  224923. #else
  224924. Dl_info exeInfo;
  224925. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224926. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224927. #endif
  224928. }
  224929. int64 File::getBytesFreeOnVolume() const
  224930. {
  224931. struct statfs buf;
  224932. if (juce_doStatFS (*this, buf))
  224933. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224934. return 0;
  224935. }
  224936. int64 File::getVolumeTotalSize() const
  224937. {
  224938. struct statfs buf;
  224939. if (juce_doStatFS (*this, buf))
  224940. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224941. return 0;
  224942. }
  224943. const String File::getVolumeLabel() const
  224944. {
  224945. #if JUCE_MAC
  224946. struct VolAttrBuf
  224947. {
  224948. u_int32_t length;
  224949. attrreference_t mountPointRef;
  224950. char mountPointSpace [MAXPATHLEN];
  224951. } attrBuf;
  224952. struct attrlist attrList;
  224953. zerostruct (attrList);
  224954. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224955. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224956. File f (*this);
  224957. for (;;)
  224958. {
  224959. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224960. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224961. (int) attrBuf.mountPointRef.attr_length);
  224962. const File parent (f.getParentDirectory());
  224963. if (f == parent)
  224964. break;
  224965. f = parent;
  224966. }
  224967. #endif
  224968. return String::empty;
  224969. }
  224970. int File::getVolumeSerialNumber() const
  224971. {
  224972. int result = 0;
  224973. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  224974. char info [512];
  224975. #ifndef HDIO_GET_IDENTITY
  224976. #define HDIO_GET_IDENTITY 0x030d
  224977. #endif
  224978. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  224979. {
  224980. DBG (String (info + 20, 20));
  224981. result = String (info + 20, 20).trim().getIntValue();
  224982. }
  224983. close (fd);*/
  224984. return result;
  224985. }
  224986. void juce_runSystemCommand (const String& command)
  224987. {
  224988. int result = system (command.toUTF8());
  224989. (void) result;
  224990. }
  224991. const String juce_getOutputFromCommand (const String& command)
  224992. {
  224993. // slight bodge here, as we just pipe the output into a temp file and read it...
  224994. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224995. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224996. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224997. String result (tempFile.loadFileAsString());
  224998. tempFile.deleteFile();
  224999. return result;
  225000. }
  225001. class InterProcessLock::Pimpl
  225002. {
  225003. public:
  225004. Pimpl (const String& name, const int timeOutMillisecs)
  225005. : handle (0), refCount (1)
  225006. {
  225007. #if JUCE_MAC
  225008. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225009. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225010. #else
  225011. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225012. #endif
  225013. temp.create();
  225014. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225015. if (handle != 0)
  225016. {
  225017. struct flock fl;
  225018. zerostruct (fl);
  225019. fl.l_whence = SEEK_SET;
  225020. fl.l_type = F_WRLCK;
  225021. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225022. for (;;)
  225023. {
  225024. const int result = fcntl (handle, F_SETLK, &fl);
  225025. if (result >= 0)
  225026. return;
  225027. if (errno != EINTR)
  225028. {
  225029. if (timeOutMillisecs == 0
  225030. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225031. break;
  225032. Thread::sleep (10);
  225033. }
  225034. }
  225035. }
  225036. closeFile();
  225037. }
  225038. ~Pimpl()
  225039. {
  225040. closeFile();
  225041. }
  225042. void closeFile()
  225043. {
  225044. if (handle != 0)
  225045. {
  225046. struct flock fl;
  225047. zerostruct (fl);
  225048. fl.l_whence = SEEK_SET;
  225049. fl.l_type = F_UNLCK;
  225050. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225051. {}
  225052. close (handle);
  225053. handle = 0;
  225054. }
  225055. }
  225056. int handle, refCount;
  225057. };
  225058. InterProcessLock::InterProcessLock (const String& name_)
  225059. : name (name_)
  225060. {
  225061. }
  225062. InterProcessLock::~InterProcessLock()
  225063. {
  225064. }
  225065. bool InterProcessLock::enter (const int timeOutMillisecs)
  225066. {
  225067. const ScopedLock sl (lock);
  225068. if (pimpl == 0)
  225069. {
  225070. pimpl = new Pimpl (name, timeOutMillisecs);
  225071. if (pimpl->handle == 0)
  225072. pimpl = 0;
  225073. }
  225074. else
  225075. {
  225076. pimpl->refCount++;
  225077. }
  225078. return pimpl != 0;
  225079. }
  225080. void InterProcessLock::exit()
  225081. {
  225082. const ScopedLock sl (lock);
  225083. // Trying to release the lock too many times!
  225084. jassert (pimpl != 0);
  225085. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225086. pimpl = 0;
  225087. }
  225088. void JUCE_API juce_threadEntryPoint (void*);
  225089. void* threadEntryProc (void* userData)
  225090. {
  225091. JUCE_AUTORELEASEPOOL
  225092. #if JUCE_ANDROID
  225093. const AndroidThreadScope androidEnv;
  225094. #endif
  225095. juce_threadEntryPoint (userData);
  225096. return 0;
  225097. }
  225098. void Thread::launchThread()
  225099. {
  225100. threadHandle_ = 0;
  225101. pthread_t handle = 0;
  225102. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  225103. {
  225104. pthread_detach (handle);
  225105. threadHandle_ = (void*) handle;
  225106. threadId_ = (ThreadID) threadHandle_;
  225107. }
  225108. }
  225109. void Thread::closeThreadHandle()
  225110. {
  225111. threadId_ = 0;
  225112. threadHandle_ = 0;
  225113. }
  225114. void Thread::killThread()
  225115. {
  225116. if (threadHandle_ != 0)
  225117. {
  225118. #if JUCE_ANDROID
  225119. jassertfalse; // pthread_cancel not available!
  225120. #else
  225121. pthread_cancel ((pthread_t) threadHandle_);
  225122. #endif
  225123. }
  225124. }
  225125. void Thread::setCurrentThreadName (const String& name)
  225126. {
  225127. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225128. pthread_setname_np (name.toUTF8());
  225129. #elif JUCE_LINUX
  225130. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  225131. #endif
  225132. }
  225133. bool Thread::setThreadPriority (void* handle, int priority)
  225134. {
  225135. struct sched_param param;
  225136. int policy;
  225137. priority = jlimit (0, 10, priority);
  225138. if (handle == 0)
  225139. handle = (void*) pthread_self();
  225140. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225141. return false;
  225142. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225143. const int minPriority = sched_get_priority_min (policy);
  225144. const int maxPriority = sched_get_priority_max (policy);
  225145. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225146. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225147. }
  225148. Thread::ThreadID Thread::getCurrentThreadId()
  225149. {
  225150. return (ThreadID) pthread_self();
  225151. }
  225152. void Thread::yield()
  225153. {
  225154. sched_yield();
  225155. }
  225156. /* Remove this macro if you're having problems compiling the cpu affinity
  225157. calls (the API for these has changed about quite a bit in various Linux
  225158. versions, and a lot of distros seem to ship with obsolete versions)
  225159. */
  225160. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225161. #define SUPPORT_AFFINITIES 1
  225162. #endif
  225163. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225164. {
  225165. #if SUPPORT_AFFINITIES
  225166. cpu_set_t affinity;
  225167. CPU_ZERO (&affinity);
  225168. for (int i = 0; i < 32; ++i)
  225169. if ((affinityMask & (1 << i)) != 0)
  225170. CPU_SET (i, &affinity);
  225171. /*
  225172. N.B. If this line causes a compile error, then you've probably not got the latest
  225173. version of glibc installed.
  225174. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225175. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225176. */
  225177. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225178. sched_yield();
  225179. #else
  225180. /* affinities aren't supported because either the appropriate header files weren't found,
  225181. or the SUPPORT_AFFINITIES macro was turned off
  225182. */
  225183. jassertfalse;
  225184. (void) affinityMask;
  225185. #endif
  225186. }
  225187. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225188. /*** Start of inlined file: juce_mac_Files.mm ***/
  225189. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225190. // compiled on its own).
  225191. #if JUCE_INCLUDED_FILE
  225192. /*
  225193. Note that a lot of methods that you'd expect to find in this file actually
  225194. live in juce_posix_SharedCode.h!
  225195. */
  225196. bool File::copyInternal (const File& dest) const
  225197. {
  225198. const ScopedAutoReleasePool pool;
  225199. NSFileManager* fm = [NSFileManager defaultManager];
  225200. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225201. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225202. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225203. toPath: juceStringToNS (dest.getFullPathName())
  225204. error: nil];
  225205. #else
  225206. && [fm copyPath: juceStringToNS (fullPath)
  225207. toPath: juceStringToNS (dest.getFullPathName())
  225208. handler: nil];
  225209. #endif
  225210. }
  225211. void File::findFileSystemRoots (Array<File>& destArray)
  225212. {
  225213. destArray.add (File ("/"));
  225214. }
  225215. namespace FileHelpers
  225216. {
  225217. bool isFileOnDriveType (const File& f, const char* const* types)
  225218. {
  225219. struct statfs buf;
  225220. if (juce_doStatFS (f, buf))
  225221. {
  225222. const String type (buf.f_fstypename);
  225223. while (*types != 0)
  225224. if (type.equalsIgnoreCase (*types++))
  225225. return true;
  225226. }
  225227. return false;
  225228. }
  225229. bool isHiddenFile (const String& path)
  225230. {
  225231. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225232. const ScopedAutoReleasePool pool;
  225233. NSNumber* hidden = nil;
  225234. NSError* err = nil;
  225235. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225236. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225237. && [hidden boolValue];
  225238. #else
  225239. #if JUCE_IOS
  225240. return File (path).getFileName().startsWithChar ('.');
  225241. #else
  225242. FSRef ref;
  225243. LSItemInfoRecord info;
  225244. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8().getAddress(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225245. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225246. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225247. #endif
  225248. #endif
  225249. }
  225250. #if JUCE_IOS
  225251. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225252. {
  225253. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225254. objectAtIndex: 0]);
  225255. }
  225256. #endif
  225257. bool launchExecutable (const String& pathAndArguments)
  225258. {
  225259. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225260. const int cpid = fork();
  225261. if (cpid == 0)
  225262. {
  225263. // Child process
  225264. if (execve (argv[0], (char**) argv, 0) < 0)
  225265. exit (0);
  225266. }
  225267. else
  225268. {
  225269. if (cpid < 0)
  225270. return false;
  225271. }
  225272. return true;
  225273. }
  225274. }
  225275. bool File::isOnCDRomDrive() const
  225276. {
  225277. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225278. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  225279. }
  225280. bool File::isOnHardDisk() const
  225281. {
  225282. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225283. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  225284. }
  225285. bool File::isOnRemovableDrive() const
  225286. {
  225287. #if JUCE_IOS
  225288. return false; // xxx is this possible?
  225289. #else
  225290. const ScopedAutoReleasePool pool;
  225291. BOOL removable = false;
  225292. [[NSWorkspace sharedWorkspace]
  225293. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225294. isRemovable: &removable
  225295. isWritable: nil
  225296. isUnmountable: nil
  225297. description: nil
  225298. type: nil];
  225299. return removable;
  225300. #endif
  225301. }
  225302. bool File::isHidden() const
  225303. {
  225304. return FileHelpers::isHiddenFile (getFullPathName());
  225305. }
  225306. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225307. const File File::getSpecialLocation (const SpecialLocationType type)
  225308. {
  225309. const ScopedAutoReleasePool pool;
  225310. String resultPath;
  225311. switch (type)
  225312. {
  225313. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225314. #if JUCE_IOS
  225315. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  225316. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  225317. case tempDirectory:
  225318. {
  225319. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  225320. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225321. tmp.createDirectory();
  225322. return tmp.getFullPathName();
  225323. }
  225324. #else
  225325. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225326. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225327. case tempDirectory:
  225328. {
  225329. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225330. tmp.createDirectory();
  225331. return tmp.getFullPathName();
  225332. }
  225333. #endif
  225334. case userMusicDirectory: resultPath = "~/Music"; break;
  225335. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225336. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225337. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225338. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225339. case invokedExecutableFile:
  225340. if (juce_Argv0 != 0)
  225341. return File (String::fromUTF8 (juce_Argv0));
  225342. // deliberate fall-through...
  225343. case currentExecutableFile:
  225344. return juce_getExecutableFile();
  225345. case currentApplicationFile:
  225346. {
  225347. const File exe (juce_getExecutableFile());
  225348. const File parent (exe.getParentDirectory());
  225349. #if JUCE_IOS
  225350. return parent;
  225351. #else
  225352. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225353. ? parent.getParentDirectory().getParentDirectory()
  225354. : exe;
  225355. #endif
  225356. }
  225357. case hostApplicationPath:
  225358. {
  225359. unsigned int size = 8192;
  225360. HeapBlock<char> buffer;
  225361. buffer.calloc (size + 8);
  225362. _NSGetExecutablePath (buffer.getData(), &size);
  225363. return String::fromUTF8 (buffer, size);
  225364. }
  225365. default:
  225366. jassertfalse; // unknown type?
  225367. break;
  225368. }
  225369. if (resultPath.isNotEmpty())
  225370. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225371. return File::nonexistent;
  225372. }
  225373. const String File::getVersion() const
  225374. {
  225375. const ScopedAutoReleasePool pool;
  225376. String result;
  225377. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225378. if (bundle != 0)
  225379. {
  225380. NSDictionary* info = [bundle infoDictionary];
  225381. if (info != 0)
  225382. {
  225383. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225384. if (name != nil)
  225385. result = nsStringToJuce (name);
  225386. }
  225387. }
  225388. return result;
  225389. }
  225390. const File File::getLinkedTarget() const
  225391. {
  225392. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225393. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225394. #else
  225395. // (the cast here avoids a deprecation warning)
  225396. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225397. #endif
  225398. if (dest != nil)
  225399. return File (nsStringToJuce (dest));
  225400. return *this;
  225401. }
  225402. bool File::moveToTrash() const
  225403. {
  225404. if (! exists())
  225405. return true;
  225406. #if JUCE_IOS
  225407. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225408. #else
  225409. const ScopedAutoReleasePool pool;
  225410. NSString* p = juceStringToNS (getFullPathName());
  225411. return [[NSWorkspace sharedWorkspace]
  225412. performFileOperation: NSWorkspaceRecycleOperation
  225413. source: [p stringByDeletingLastPathComponent]
  225414. destination: @""
  225415. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225416. tag: nil ];
  225417. #endif
  225418. }
  225419. class DirectoryIterator::NativeIterator::Pimpl
  225420. {
  225421. public:
  225422. Pimpl (const File& directory, const String& wildCard_)
  225423. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225424. wildCard (wildCard_),
  225425. enumerator (0)
  225426. {
  225427. const ScopedAutoReleasePool pool;
  225428. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225429. wildcardUTF8 = wildCard.toUTF8();
  225430. }
  225431. ~Pimpl()
  225432. {
  225433. [enumerator release];
  225434. }
  225435. bool next (String& filenameFound,
  225436. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225437. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225438. {
  225439. const ScopedAutoReleasePool pool;
  225440. for (;;)
  225441. {
  225442. NSString* file;
  225443. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225444. return false;
  225445. [enumerator skipDescendents];
  225446. filenameFound = nsStringToJuce (file);
  225447. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225448. continue;
  225449. const String path (parentDir + filenameFound);
  225450. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  225451. if (isHidden != 0)
  225452. *isHidden = FileHelpers::isHiddenFile (path);
  225453. return true;
  225454. }
  225455. }
  225456. private:
  225457. String parentDir, wildCard;
  225458. const char* wildcardUTF8;
  225459. NSDirectoryEnumerator* enumerator;
  225460. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225461. };
  225462. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225463. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225464. {
  225465. }
  225466. DirectoryIterator::NativeIterator::~NativeIterator()
  225467. {
  225468. }
  225469. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225470. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225471. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225472. {
  225473. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225474. }
  225475. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225476. {
  225477. #if JUCE_IOS
  225478. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225479. #else
  225480. const ScopedAutoReleasePool pool;
  225481. if (parameters.isEmpty())
  225482. {
  225483. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225484. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225485. }
  225486. bool ok = false;
  225487. if (PlatformUtilities::isBundle (fileName))
  225488. {
  225489. NSMutableArray* urls = [NSMutableArray array];
  225490. StringArray docs;
  225491. docs.addTokens (parameters, true);
  225492. for (int i = 0; i < docs.size(); ++i)
  225493. [urls addObject: juceStringToNS (docs[i])];
  225494. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225495. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225496. options: 0
  225497. additionalEventParamDescriptor: nil
  225498. launchIdentifiers: nil];
  225499. }
  225500. else if (File (fileName).exists())
  225501. {
  225502. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225503. }
  225504. return ok;
  225505. #endif
  225506. }
  225507. void File::revealToUser() const
  225508. {
  225509. #if ! JUCE_IOS
  225510. if (exists())
  225511. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225512. else if (getParentDirectory().exists())
  225513. getParentDirectory().revealToUser();
  225514. #endif
  225515. }
  225516. #if ! JUCE_IOS
  225517. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225518. {
  225519. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  225520. }
  225521. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225522. {
  225523. char path [2048];
  225524. zerostruct (path);
  225525. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225526. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225527. return String::empty;
  225528. }
  225529. #endif
  225530. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225531. {
  225532. const ScopedAutoReleasePool pool;
  225533. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225534. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225535. #else
  225536. // (the cast here avoids a deprecation warning)
  225537. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225538. #endif
  225539. return [fileDict fileHFSTypeCode];
  225540. }
  225541. bool PlatformUtilities::isBundle (const String& filename)
  225542. {
  225543. #if JUCE_IOS
  225544. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225545. #else
  225546. const ScopedAutoReleasePool pool;
  225547. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225548. #endif
  225549. }
  225550. #endif
  225551. /*** End of inlined file: juce_mac_Files.mm ***/
  225552. #if JUCE_IOS
  225553. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  225554. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225555. // compiled on its own).
  225556. #if JUCE_INCLUDED_FILE
  225557. END_JUCE_NAMESPACE
  225558. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225559. {
  225560. }
  225561. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225562. - (void) applicationWillTerminate: (UIApplication*) application;
  225563. @end
  225564. @implementation JuceAppStartupDelegate
  225565. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225566. {
  225567. initialiseJuce_GUI();
  225568. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225569. exit (0);
  225570. }
  225571. - (void) applicationWillTerminate: (UIApplication*) application
  225572. {
  225573. JUCEApplication::appWillTerminateByForce();
  225574. }
  225575. @end
  225576. BEGIN_JUCE_NAMESPACE
  225577. int juce_iOSMain (int argc, const char* argv[])
  225578. {
  225579. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225580. }
  225581. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225582. {
  225583. pool = [[NSAutoreleasePool alloc] init];
  225584. }
  225585. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225586. {
  225587. [((NSAutoreleasePool*) pool) release];
  225588. }
  225589. void PlatformUtilities::beep()
  225590. {
  225591. //xxx
  225592. //AudioServicesPlaySystemSound ();
  225593. }
  225594. void PlatformUtilities::addItemToDock (const File& file)
  225595. {
  225596. }
  225597. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225598. END_JUCE_NAMESPACE
  225599. @interface JuceAlertBoxDelegate : NSObject
  225600. {
  225601. @public
  225602. bool clickedOk;
  225603. }
  225604. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225605. @end
  225606. @implementation JuceAlertBoxDelegate
  225607. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225608. {
  225609. clickedOk = (buttonIndex == 0);
  225610. alertView.hidden = true;
  225611. }
  225612. @end
  225613. BEGIN_JUCE_NAMESPACE
  225614. // (This function is used directly by other bits of code)
  225615. bool juce_iPhoneShowModalAlert (const String& title,
  225616. const String& bodyText,
  225617. NSString* okButtonText,
  225618. NSString* cancelButtonText)
  225619. {
  225620. const ScopedAutoReleasePool pool;
  225621. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225622. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225623. message: juceStringToNS (bodyText)
  225624. delegate: callback
  225625. cancelButtonTitle: okButtonText
  225626. otherButtonTitles: cancelButtonText, nil];
  225627. [alert retain];
  225628. [alert show];
  225629. while (! alert.hidden && alert.superview != nil)
  225630. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225631. const bool result = callback->clickedOk;
  225632. [alert release];
  225633. [callback release];
  225634. return result;
  225635. }
  225636. bool AlertWindow::showNativeDialogBox (const String& title,
  225637. const String& bodyText,
  225638. bool isOkCancel)
  225639. {
  225640. return juce_iPhoneShowModalAlert (title, bodyText,
  225641. @"OK",
  225642. isOkCancel ? @"Cancel" : nil);
  225643. }
  225644. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225645. {
  225646. jassertfalse; // no such thing on the iphone!
  225647. return false;
  225648. }
  225649. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225650. {
  225651. jassertfalse; // no such thing on the iphone!
  225652. return false;
  225653. }
  225654. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225655. {
  225656. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225657. }
  225658. bool Desktop::isScreenSaverEnabled()
  225659. {
  225660. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225661. }
  225662. #endif
  225663. #endif
  225664. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225665. #else
  225666. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225667. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225668. // compiled on its own).
  225669. #if JUCE_INCLUDED_FILE
  225670. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225671. {
  225672. pool = [[NSAutoreleasePool alloc] init];
  225673. }
  225674. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225675. {
  225676. [((NSAutoreleasePool*) pool) release];
  225677. }
  225678. void PlatformUtilities::beep()
  225679. {
  225680. NSBeep();
  225681. }
  225682. void PlatformUtilities::addItemToDock (const File& file)
  225683. {
  225684. // check that it's not already there...
  225685. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225686. .containsIgnoreCase (file.getFullPathName()))
  225687. {
  225688. 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>"
  225689. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225690. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225691. }
  225692. }
  225693. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225694. bool AlertWindow::showNativeDialogBox (const String& title,
  225695. const String& bodyText,
  225696. bool isOkCancel)
  225697. {
  225698. const ScopedAutoReleasePool pool;
  225699. return NSRunAlertPanel (juceStringToNS (title),
  225700. juceStringToNS (bodyText),
  225701. @"Ok",
  225702. isOkCancel ? @"Cancel" : nil,
  225703. nil) == NSAlertDefaultReturn;
  225704. }
  225705. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225706. {
  225707. if (files.size() == 0)
  225708. return false;
  225709. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225710. if (draggingSource == 0)
  225711. {
  225712. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225713. return false;
  225714. }
  225715. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225716. if (sourceComp == 0)
  225717. {
  225718. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225719. return false;
  225720. }
  225721. const ScopedAutoReleasePool pool;
  225722. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225723. if (view == 0)
  225724. return false;
  225725. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225726. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225727. owner: nil];
  225728. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225729. for (int i = 0; i < files.size(); ++i)
  225730. [filesArray addObject: juceStringToNS (files[i])];
  225731. [pboard setPropertyList: filesArray
  225732. forType: NSFilenamesPboardType];
  225733. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225734. fromView: nil];
  225735. dragPosition.x -= 16;
  225736. dragPosition.y -= 16;
  225737. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225738. at: dragPosition
  225739. offset: NSMakeSize (0, 0)
  225740. event: [[view window] currentEvent]
  225741. pasteboard: pboard
  225742. source: view
  225743. slideBack: YES];
  225744. return true;
  225745. }
  225746. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225747. {
  225748. jassertfalse; // not implemented!
  225749. return false;
  225750. }
  225751. bool Desktop::canUseSemiTransparentWindows() throw()
  225752. {
  225753. return true;
  225754. }
  225755. const Point<int> MouseInputSource::getCurrentMousePosition()
  225756. {
  225757. const ScopedAutoReleasePool pool;
  225758. const NSPoint p ([NSEvent mouseLocation]);
  225759. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225760. }
  225761. void Desktop::setMousePosition (const Point<int>& newPosition)
  225762. {
  225763. // this rubbish needs to be done around the warp call, to avoid causing a
  225764. // bizarre glitch..
  225765. CGAssociateMouseAndMouseCursorPosition (false);
  225766. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225767. CGAssociateMouseAndMouseCursorPosition (true);
  225768. }
  225769. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225770. {
  225771. return upright;
  225772. }
  225773. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225774. class ScreenSaverDefeater : public Timer,
  225775. public DeletedAtShutdown
  225776. {
  225777. public:
  225778. ScreenSaverDefeater()
  225779. {
  225780. startTimer (10000);
  225781. timerCallback();
  225782. }
  225783. ~ScreenSaverDefeater() {}
  225784. void timerCallback()
  225785. {
  225786. if (Process::isForegroundProcess())
  225787. UpdateSystemActivity (UsrActivity);
  225788. }
  225789. };
  225790. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225791. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225792. {
  225793. if (isEnabled)
  225794. deleteAndZero (screenSaverDefeater);
  225795. else if (screenSaverDefeater == 0)
  225796. screenSaverDefeater = new ScreenSaverDefeater();
  225797. }
  225798. bool Desktop::isScreenSaverEnabled()
  225799. {
  225800. return screenSaverDefeater == 0;
  225801. }
  225802. #else
  225803. static IOPMAssertionID screenSaverDisablerID = 0;
  225804. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225805. {
  225806. if (isEnabled)
  225807. {
  225808. if (screenSaverDisablerID != 0)
  225809. {
  225810. IOPMAssertionRelease (screenSaverDisablerID);
  225811. screenSaverDisablerID = 0;
  225812. }
  225813. }
  225814. else
  225815. {
  225816. if (screenSaverDisablerID == 0)
  225817. {
  225818. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225819. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225820. CFSTR ("Juce"), &screenSaverDisablerID);
  225821. #else
  225822. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225823. &screenSaverDisablerID);
  225824. #endif
  225825. }
  225826. }
  225827. }
  225828. bool Desktop::isScreenSaverEnabled()
  225829. {
  225830. return screenSaverDisablerID == 0;
  225831. }
  225832. #endif
  225833. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225834. {
  225835. const ScopedAutoReleasePool pool;
  225836. monitorCoords.clear();
  225837. NSArray* screens = [NSScreen screens];
  225838. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225839. for (unsigned int i = 0; i < [screens count]; ++i)
  225840. {
  225841. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225842. NSRect r = clipToWorkArea ? [s visibleFrame]
  225843. : [s frame];
  225844. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225845. monitorCoords.add (convertToRectInt (r));
  225846. }
  225847. jassert (monitorCoords.size() > 0);
  225848. }
  225849. #endif
  225850. #endif
  225851. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225852. #endif
  225853. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225854. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225855. // compiled on its own).
  225856. #if JUCE_INCLUDED_FILE
  225857. void Logger::outputDebugString (const String& text)
  225858. {
  225859. std::cerr << text << std::endl;
  225860. }
  225861. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225862. {
  225863. static char testResult = 0;
  225864. if (testResult == 0)
  225865. {
  225866. struct kinfo_proc info;
  225867. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225868. size_t sz = sizeof (info);
  225869. sysctl (m, 4, &info, &sz, 0, 0);
  225870. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225871. }
  225872. return testResult > 0;
  225873. }
  225874. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225875. {
  225876. return juce_isRunningUnderDebugger();
  225877. }
  225878. #endif
  225879. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225880. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225881. #if JUCE_IOS
  225882. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225883. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225884. // compiled on its own).
  225885. #if JUCE_INCLUDED_FILE
  225886. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225887. #define SUPPORT_10_4_FONTS 1
  225888. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225889. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225890. #define SUPPORT_ONLY_10_4_FONTS 1
  225891. #endif
  225892. END_JUCE_NAMESPACE
  225893. @interface NSFont (PrivateHack)
  225894. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225895. @end
  225896. BEGIN_JUCE_NAMESPACE
  225897. #endif
  225898. class MacTypeface : public Typeface
  225899. {
  225900. public:
  225901. MacTypeface (const Font& font)
  225902. : Typeface (font.getTypefaceName())
  225903. {
  225904. const ScopedAutoReleasePool pool;
  225905. renderingTransform = CGAffineTransformIdentity;
  225906. bool needsItalicTransform = false;
  225907. #if JUCE_IOS
  225908. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225909. if (font.isItalic() || font.isBold())
  225910. {
  225911. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225912. for (NSString* i in familyFonts)
  225913. {
  225914. const String fn (nsStringToJuce (i));
  225915. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225916. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225917. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225918. || afterDash.containsIgnoreCase ("italic")
  225919. || fn.endsWithIgnoreCase ("oblique")
  225920. || fn.endsWithIgnoreCase ("italic");
  225921. if (probablyBold == font.isBold()
  225922. && probablyItalic == font.isItalic())
  225923. {
  225924. fontName = i;
  225925. needsItalicTransform = false;
  225926. break;
  225927. }
  225928. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225929. {
  225930. fontName = i;
  225931. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225932. }
  225933. }
  225934. if (needsItalicTransform)
  225935. renderingTransform.c = 0.15f;
  225936. }
  225937. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225938. const int ascender = abs (CGFontGetAscent (fontRef));
  225939. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225940. ascent = ascender / totalHeight;
  225941. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225942. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225943. #else
  225944. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225945. if (font.isItalic())
  225946. {
  225947. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225948. toHaveTrait: NSItalicFontMask];
  225949. if (newFont == nsFont)
  225950. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225951. nsFont = newFont;
  225952. }
  225953. if (font.isBold())
  225954. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225955. [nsFont retain];
  225956. ascent = std::abs ((float) [nsFont ascender]);
  225957. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225958. ascent /= totalSize;
  225959. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225960. if (needsItalicTransform)
  225961. {
  225962. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225963. renderingTransform.c = 0.15f;
  225964. }
  225965. #if SUPPORT_ONLY_10_4_FONTS
  225966. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225967. if (atsFont == 0)
  225968. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225969. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225970. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225971. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225972. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225973. #else
  225974. #if SUPPORT_10_4_FONTS
  225975. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225976. {
  225977. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225978. if (atsFont == 0)
  225979. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225980. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225981. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225982. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225983. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225984. }
  225985. else
  225986. #endif
  225987. {
  225988. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225989. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225990. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225991. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225992. }
  225993. #endif
  225994. #endif
  225995. }
  225996. ~MacTypeface()
  225997. {
  225998. #if ! JUCE_IOS
  225999. [nsFont release];
  226000. #endif
  226001. if (fontRef != 0)
  226002. CGFontRelease (fontRef);
  226003. }
  226004. float getAscent() const
  226005. {
  226006. return ascent;
  226007. }
  226008. float getDescent() const
  226009. {
  226010. return 1.0f - ascent;
  226011. }
  226012. float getStringWidth (const String& text)
  226013. {
  226014. if (fontRef == 0 || text.isEmpty())
  226015. return 0;
  226016. const int length = text.length();
  226017. HeapBlock <CGGlyph> glyphs;
  226018. createGlyphsForString (text.getCharPointer(), length, glyphs);
  226019. float x = 0;
  226020. #if SUPPORT_ONLY_10_4_FONTS
  226021. HeapBlock <NSSize> advances (length);
  226022. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226023. for (int i = 0; i < length; ++i)
  226024. x += advances[i].width;
  226025. #else
  226026. #if SUPPORT_10_4_FONTS
  226027. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226028. {
  226029. HeapBlock <NSSize> advances (length);
  226030. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226031. for (int i = 0; i < length; ++i)
  226032. x += advances[i].width;
  226033. }
  226034. else
  226035. #endif
  226036. {
  226037. HeapBlock <int> advances (length);
  226038. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226039. for (int i = 0; i < length; ++i)
  226040. x += advances[i];
  226041. }
  226042. #endif
  226043. return x * unitsToHeightScaleFactor;
  226044. }
  226045. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226046. {
  226047. xOffsets.add (0);
  226048. if (fontRef == 0 || text.isEmpty())
  226049. return;
  226050. const int length = text.length();
  226051. HeapBlock <CGGlyph> glyphs;
  226052. createGlyphsForString (text.getCharPointer(), length, glyphs);
  226053. #if SUPPORT_ONLY_10_4_FONTS
  226054. HeapBlock <NSSize> advances (length);
  226055. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226056. int x = 0;
  226057. for (int i = 0; i < length; ++i)
  226058. {
  226059. x += advances[i].width;
  226060. xOffsets.add (x * unitsToHeightScaleFactor);
  226061. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226062. }
  226063. #else
  226064. #if SUPPORT_10_4_FONTS
  226065. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226066. {
  226067. HeapBlock <NSSize> advances (length);
  226068. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226069. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226070. float x = 0;
  226071. for (int i = 0; i < length; ++i)
  226072. {
  226073. x += advances[i].width;
  226074. xOffsets.add (x * unitsToHeightScaleFactor);
  226075. resultGlyphs.add (nsGlyphs[i]);
  226076. }
  226077. }
  226078. else
  226079. #endif
  226080. {
  226081. HeapBlock <int> advances (length);
  226082. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226083. {
  226084. int x = 0;
  226085. for (int i = 0; i < length; ++i)
  226086. {
  226087. x += advances [i];
  226088. xOffsets.add (x * unitsToHeightScaleFactor);
  226089. resultGlyphs.add (glyphs[i]);
  226090. }
  226091. }
  226092. }
  226093. #endif
  226094. }
  226095. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226096. {
  226097. #if JUCE_IOS
  226098. return false;
  226099. #else
  226100. if (nsFont == 0)
  226101. return false;
  226102. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226103. jassert (path.isEmpty());
  226104. const ScopedAutoReleasePool pool;
  226105. NSBezierPath* bez = [NSBezierPath bezierPath];
  226106. [bez moveToPoint: NSMakePoint (0, 0)];
  226107. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226108. inFont: nsFont];
  226109. for (int i = 0; i < [bez elementCount]; ++i)
  226110. {
  226111. NSPoint p[3];
  226112. switch ([bez elementAtIndex: i associatedPoints: p])
  226113. {
  226114. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  226115. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  226116. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  226117. (float) p[1].x, (float) -p[1].y,
  226118. (float) p[2].x, (float) -p[2].y); break;
  226119. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  226120. default: jassertfalse; break;
  226121. }
  226122. }
  226123. path.applyTransform (pathTransform);
  226124. return true;
  226125. #endif
  226126. }
  226127. CGFontRef fontRef;
  226128. float fontHeightToCGSizeFactor;
  226129. CGAffineTransform renderingTransform;
  226130. private:
  226131. float ascent, unitsToHeightScaleFactor;
  226132. #if JUCE_IOS
  226133. #else
  226134. NSFont* nsFont;
  226135. AffineTransform pathTransform;
  226136. #endif
  226137. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  226138. {
  226139. #if SUPPORT_10_4_FONTS
  226140. #if ! SUPPORT_ONLY_10_4_FONTS
  226141. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226142. #endif
  226143. {
  226144. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226145. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226146. for (int i = 0; i < length; ++i)
  226147. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  226148. return;
  226149. }
  226150. #endif
  226151. #if ! SUPPORT_ONLY_10_4_FONTS
  226152. if (charToGlyphMapper == 0)
  226153. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226154. glyphs.malloc (length);
  226155. for (int i = 0; i < length; ++i)
  226156. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  226157. #endif
  226158. }
  226159. #if ! SUPPORT_ONLY_10_4_FONTS
  226160. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226161. class CharToGlyphMapper
  226162. {
  226163. public:
  226164. CharToGlyphMapper (CGFontRef fontRef)
  226165. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226166. idRangeOffset (0), glyphIndexes (0)
  226167. {
  226168. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226169. if (cmapTable != 0)
  226170. {
  226171. const int numSubtables = getValue16 (cmapTable, 2);
  226172. for (int i = 0; i < numSubtables; ++i)
  226173. {
  226174. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226175. {
  226176. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226177. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226178. {
  226179. const int length = getValue16 (cmapTable, offset + 2);
  226180. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226181. segCount = segCountX2 / 2;
  226182. const int endCodeOffset = offset + 14;
  226183. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226184. const int idDeltaOffset = startCodeOffset + segCountX2;
  226185. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226186. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226187. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226188. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226189. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226190. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226191. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226192. }
  226193. break;
  226194. }
  226195. }
  226196. CFRelease (cmapTable);
  226197. }
  226198. }
  226199. ~CharToGlyphMapper()
  226200. {
  226201. if (endCode != 0)
  226202. {
  226203. CFRelease (endCode);
  226204. CFRelease (startCode);
  226205. CFRelease (idDelta);
  226206. CFRelease (idRangeOffset);
  226207. CFRelease (glyphIndexes);
  226208. }
  226209. }
  226210. int getGlyphForCharacter (const juce_wchar c) const
  226211. {
  226212. for (int i = 0; i < segCount; ++i)
  226213. {
  226214. if (getValue16 (endCode, i * 2) >= c)
  226215. {
  226216. const int start = getValue16 (startCode, i * 2);
  226217. if (start > c)
  226218. break;
  226219. const int delta = getValue16 (idDelta, i * 2);
  226220. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226221. if (rangeOffset == 0)
  226222. return delta + c;
  226223. else
  226224. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226225. }
  226226. }
  226227. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226228. return jmax (-1, (int) c - 29);
  226229. }
  226230. private:
  226231. int segCount;
  226232. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226233. static uint16 getValue16 (CFDataRef data, const int index)
  226234. {
  226235. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226236. }
  226237. static uint32 getValue32 (CFDataRef data, const int index)
  226238. {
  226239. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226240. }
  226241. };
  226242. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226243. #endif
  226244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  226245. };
  226246. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226247. {
  226248. return new MacTypeface (font);
  226249. }
  226250. const StringArray Font::findAllTypefaceNames()
  226251. {
  226252. StringArray names;
  226253. const ScopedAutoReleasePool pool;
  226254. #if JUCE_IOS
  226255. NSArray* fonts = [UIFont familyNames];
  226256. #else
  226257. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226258. #endif
  226259. for (unsigned int i = 0; i < [fonts count]; ++i)
  226260. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226261. names.sort (true);
  226262. return names;
  226263. }
  226264. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226265. {
  226266. #if JUCE_IOS
  226267. defaultSans = "Helvetica";
  226268. defaultSerif = "Times New Roman";
  226269. defaultFixed = "Courier New";
  226270. #else
  226271. defaultSans = "Lucida Grande";
  226272. defaultSerif = "Times New Roman";
  226273. defaultFixed = "Monaco";
  226274. #endif
  226275. defaultFallback = "Arial Unicode MS";
  226276. }
  226277. #endif
  226278. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226279. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226280. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226281. // compiled on its own).
  226282. #if JUCE_INCLUDED_FILE
  226283. class CoreGraphicsImage : public Image::SharedImage
  226284. {
  226285. public:
  226286. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226287. : Image::SharedImage (format_, width_, height_)
  226288. {
  226289. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226290. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226291. imageData.allocate (lineStride * jmax (1, height), clearImage);
  226292. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226293. : CGColorSpaceCreateDeviceRGB();
  226294. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226295. colourSpace, getCGImageFlags (format_));
  226296. CGColorSpaceRelease (colourSpace);
  226297. }
  226298. ~CoreGraphicsImage()
  226299. {
  226300. CGContextRelease (context);
  226301. }
  226302. Image::ImageType getType() const { return Image::NativeImage; }
  226303. LowLevelGraphicsContext* createLowLevelContext();
  226304. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  226305. {
  226306. bitmap.data = imageData + x * pixelStride + y * lineStride;
  226307. bitmap.pixelFormat = format;
  226308. bitmap.lineStride = lineStride;
  226309. bitmap.pixelStride = pixelStride;
  226310. }
  226311. SharedImage* clone()
  226312. {
  226313. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226314. memcpy (im->imageData, imageData, lineStride * height);
  226315. return im;
  226316. }
  226317. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  226318. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  226319. {
  226320. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226321. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226322. {
  226323. return CGBitmapContextCreateImage (nativeImage->context);
  226324. }
  226325. else
  226326. {
  226327. const Image::BitmapData srcData (juceImage, Image::BitmapData::readOnly);
  226328. CGDataProviderRef provider;
  226329. if (mustOutliveSource)
  226330. {
  226331. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  226332. provider = CGDataProviderCreateWithCFData (data);
  226333. CFRelease (data);
  226334. }
  226335. else
  226336. {
  226337. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226338. }
  226339. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226340. 8, srcData.pixelStride * 8, srcData.lineStride,
  226341. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226342. 0, true, kCGRenderingIntentDefault);
  226343. CGDataProviderRelease (provider);
  226344. return imageRef;
  226345. }
  226346. }
  226347. #if JUCE_MAC
  226348. static NSImage* createNSImage (const Image& image)
  226349. {
  226350. const ScopedAutoReleasePool pool;
  226351. NSImage* im = [[NSImage alloc] init];
  226352. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226353. [im lockFocus];
  226354. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226355. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  226356. CGColorSpaceRelease (colourSpace);
  226357. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226358. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226359. CGImageRelease (imageRef);
  226360. [im unlockFocus];
  226361. return im;
  226362. }
  226363. #endif
  226364. CGContextRef context;
  226365. HeapBlock<uint8> imageData;
  226366. int pixelStride, lineStride;
  226367. private:
  226368. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226369. {
  226370. #if JUCE_BIG_ENDIAN
  226371. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226372. #else
  226373. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226374. #endif
  226375. }
  226376. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  226377. };
  226378. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226379. {
  226380. #if USE_COREGRAPHICS_RENDERING
  226381. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226382. #else
  226383. return createSoftwareImage (format, width, height, clearImage);
  226384. #endif
  226385. }
  226386. class CoreGraphicsContext : public LowLevelGraphicsContext
  226387. {
  226388. public:
  226389. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226390. : context (context_),
  226391. flipHeight (flipHeight_),
  226392. lastClipRectIsValid (false),
  226393. state (new SavedState()),
  226394. numGradientLookupEntries (0)
  226395. {
  226396. CGContextRetain (context);
  226397. CGContextSaveGState(context);
  226398. CGContextSetShouldSmoothFonts (context, true);
  226399. CGContextSetShouldAntialias (context, true);
  226400. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226401. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226402. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226403. gradientCallbacks.version = 0;
  226404. gradientCallbacks.evaluate = gradientCallback;
  226405. gradientCallbacks.releaseInfo = 0;
  226406. setFont (Font());
  226407. }
  226408. ~CoreGraphicsContext()
  226409. {
  226410. CGContextRestoreGState (context);
  226411. CGContextRelease (context);
  226412. CGColorSpaceRelease (rgbColourSpace);
  226413. CGColorSpaceRelease (greyColourSpace);
  226414. }
  226415. bool isVectorDevice() const { return false; }
  226416. void setOrigin (int x, int y)
  226417. {
  226418. CGContextTranslateCTM (context, x, -y);
  226419. if (lastClipRectIsValid)
  226420. lastClipRect.translate (-x, -y);
  226421. }
  226422. void addTransform (const AffineTransform& transform)
  226423. {
  226424. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226425. .translated (0, flipHeight)
  226426. .followedBy (transform)
  226427. .translated (0, -flipHeight)
  226428. .scaled (1.0f, -1.0f));
  226429. lastClipRectIsValid = false;
  226430. }
  226431. float getScaleFactor()
  226432. {
  226433. CGAffineTransform t = CGContextGetCTM (context);
  226434. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226435. }
  226436. bool clipToRectangle (const Rectangle<int>& r)
  226437. {
  226438. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226439. if (lastClipRectIsValid)
  226440. {
  226441. // This is actually incorrect, because the actual clip region may be complex, and
  226442. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226443. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226444. // when calculating the resultant clip bounds, and makes the same mistake!
  226445. lastClipRect = lastClipRect.getIntersection (r);
  226446. return ! lastClipRect.isEmpty();
  226447. }
  226448. return ! isClipEmpty();
  226449. }
  226450. bool clipToRectangleList (const RectangleList& clipRegion)
  226451. {
  226452. if (clipRegion.isEmpty())
  226453. {
  226454. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226455. lastClipRectIsValid = true;
  226456. lastClipRect = Rectangle<int>();
  226457. return false;
  226458. }
  226459. else
  226460. {
  226461. const int numRects = clipRegion.getNumRectangles();
  226462. HeapBlock <CGRect> rects (numRects);
  226463. for (int i = 0; i < numRects; ++i)
  226464. {
  226465. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226466. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226467. }
  226468. CGContextClipToRects (context, rects, numRects);
  226469. lastClipRectIsValid = false;
  226470. return ! isClipEmpty();
  226471. }
  226472. }
  226473. void excludeClipRectangle (const Rectangle<int>& r)
  226474. {
  226475. RectangleList remaining (getClipBounds());
  226476. remaining.subtract (r);
  226477. clipToRectangleList (remaining);
  226478. lastClipRectIsValid = false;
  226479. }
  226480. void clipToPath (const Path& path, const AffineTransform& transform)
  226481. {
  226482. createPath (path, transform);
  226483. CGContextClip (context);
  226484. lastClipRectIsValid = false;
  226485. }
  226486. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226487. {
  226488. if (! transform.isSingularity())
  226489. {
  226490. Image singleChannelImage (sourceImage);
  226491. if (sourceImage.getFormat() != Image::SingleChannel)
  226492. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226493. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  226494. flip();
  226495. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226496. applyTransform (t);
  226497. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226498. CGContextClipToMask (context, r, image);
  226499. applyTransform (t.inverted());
  226500. flip();
  226501. CGImageRelease (image);
  226502. lastClipRectIsValid = false;
  226503. }
  226504. }
  226505. bool clipRegionIntersects (const Rectangle<int>& r)
  226506. {
  226507. return getClipBounds().intersects (r);
  226508. }
  226509. const Rectangle<int> getClipBounds() const
  226510. {
  226511. if (! lastClipRectIsValid)
  226512. {
  226513. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226514. lastClipRectIsValid = true;
  226515. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226516. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226517. roundToInt (bounds.size.width),
  226518. roundToInt (bounds.size.height));
  226519. }
  226520. return lastClipRect;
  226521. }
  226522. bool isClipEmpty() const
  226523. {
  226524. return getClipBounds().isEmpty();
  226525. }
  226526. void saveState()
  226527. {
  226528. CGContextSaveGState (context);
  226529. stateStack.add (new SavedState (*state));
  226530. }
  226531. void restoreState()
  226532. {
  226533. CGContextRestoreGState (context);
  226534. SavedState* const top = stateStack.getLast();
  226535. if (top != 0)
  226536. {
  226537. state = top;
  226538. stateStack.removeLast (1, false);
  226539. lastClipRectIsValid = false;
  226540. }
  226541. else
  226542. {
  226543. jassertfalse; // trying to pop with an empty stack!
  226544. }
  226545. }
  226546. void beginTransparencyLayer (float opacity)
  226547. {
  226548. saveState();
  226549. CGContextSetAlpha (context, opacity);
  226550. CGContextBeginTransparencyLayer (context, 0);
  226551. }
  226552. void endTransparencyLayer()
  226553. {
  226554. CGContextEndTransparencyLayer (context);
  226555. restoreState();
  226556. }
  226557. void setFill (const FillType& fillType)
  226558. {
  226559. state->fillType = fillType;
  226560. if (fillType.isColour())
  226561. {
  226562. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226563. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226564. CGContextSetAlpha (context, 1.0f);
  226565. }
  226566. }
  226567. void setOpacity (float newOpacity)
  226568. {
  226569. state->fillType.setOpacity (newOpacity);
  226570. setFill (state->fillType);
  226571. }
  226572. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226573. {
  226574. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226575. ? kCGInterpolationLow
  226576. : kCGInterpolationHigh);
  226577. }
  226578. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226579. {
  226580. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226581. }
  226582. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226583. {
  226584. if (replaceExistingContents)
  226585. {
  226586. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226587. CGContextClearRect (context, cgRect);
  226588. #else
  226589. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226590. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226591. CGContextClearRect (context, cgRect);
  226592. else
  226593. #endif
  226594. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226595. #endif
  226596. fillCGRect (cgRect, false);
  226597. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226598. }
  226599. else
  226600. {
  226601. if (state->fillType.isColour())
  226602. {
  226603. CGContextFillRect (context, cgRect);
  226604. }
  226605. else if (state->fillType.isGradient())
  226606. {
  226607. CGContextSaveGState (context);
  226608. CGContextClipToRect (context, cgRect);
  226609. drawGradient();
  226610. CGContextRestoreGState (context);
  226611. }
  226612. else
  226613. {
  226614. CGContextSaveGState (context);
  226615. CGContextClipToRect (context, cgRect);
  226616. drawImage (state->fillType.image, state->fillType.transform, true);
  226617. CGContextRestoreGState (context);
  226618. }
  226619. }
  226620. }
  226621. void fillPath (const Path& path, const AffineTransform& transform)
  226622. {
  226623. CGContextSaveGState (context);
  226624. if (state->fillType.isColour())
  226625. {
  226626. flip();
  226627. applyTransform (transform);
  226628. createPath (path);
  226629. if (path.isUsingNonZeroWinding())
  226630. CGContextFillPath (context);
  226631. else
  226632. CGContextEOFillPath (context);
  226633. }
  226634. else
  226635. {
  226636. createPath (path, transform);
  226637. if (path.isUsingNonZeroWinding())
  226638. CGContextClip (context);
  226639. else
  226640. CGContextEOClip (context);
  226641. if (state->fillType.isGradient())
  226642. drawGradient();
  226643. else
  226644. drawImage (state->fillType.image, state->fillType.transform, true);
  226645. }
  226646. CGContextRestoreGState (context);
  226647. }
  226648. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226649. {
  226650. const int iw = sourceImage.getWidth();
  226651. const int ih = sourceImage.getHeight();
  226652. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226653. CGContextSaveGState (context);
  226654. CGContextSetAlpha (context, state->fillType.getOpacity());
  226655. flip();
  226656. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226657. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226658. if (fillEntireClipAsTiles)
  226659. {
  226660. #if JUCE_IOS
  226661. CGContextDrawTiledImage (context, imageRect, image);
  226662. #else
  226663. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226664. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226665. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226666. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226667. CGContextDrawTiledImage (context, imageRect, image);
  226668. else
  226669. #endif
  226670. {
  226671. // Fallback to manually doing a tiled fill on 10.4
  226672. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226673. int x = 0, y = 0;
  226674. while (x > clip.origin.x) x -= iw;
  226675. while (y > clip.origin.y) y -= ih;
  226676. const int right = (int) (clip.origin.x + clip.size.width);
  226677. const int bottom = (int) (clip.origin.y + clip.size.height);
  226678. while (y < bottom)
  226679. {
  226680. for (int x2 = x; x2 < right; x2 += iw)
  226681. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226682. y += ih;
  226683. }
  226684. }
  226685. #endif
  226686. }
  226687. else
  226688. {
  226689. CGContextDrawImage (context, imageRect, image);
  226690. }
  226691. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226692. CGContextRestoreGState (context);
  226693. }
  226694. void drawLine (const Line<float>& line)
  226695. {
  226696. if (state->fillType.isColour())
  226697. {
  226698. CGContextSetLineCap (context, kCGLineCapSquare);
  226699. CGContextSetLineWidth (context, 1.0f);
  226700. CGContextSetRGBStrokeColor (context,
  226701. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226702. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226703. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226704. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226705. CGContextStrokeLineSegments (context, cgLine, 1);
  226706. }
  226707. else
  226708. {
  226709. Path p;
  226710. p.addLineSegment (line, 1.0f);
  226711. fillPath (p, AffineTransform::identity);
  226712. }
  226713. }
  226714. void drawVerticalLine (const int x, float top, float bottom)
  226715. {
  226716. if (state->fillType.isColour())
  226717. {
  226718. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226719. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226720. #else
  226721. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226722. // the x co-ord slightly to trick it..
  226723. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226724. #endif
  226725. }
  226726. else
  226727. {
  226728. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226729. }
  226730. }
  226731. void drawHorizontalLine (const int y, float left, float right)
  226732. {
  226733. if (state->fillType.isColour())
  226734. {
  226735. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226736. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226737. #else
  226738. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226739. // the x co-ord slightly to trick it..
  226740. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226741. #endif
  226742. }
  226743. else
  226744. {
  226745. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226746. }
  226747. }
  226748. void setFont (const Font& newFont)
  226749. {
  226750. if (state->font != newFont)
  226751. {
  226752. state->fontRef = 0;
  226753. state->font = newFont;
  226754. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226755. if (mf != 0)
  226756. {
  226757. state->fontRef = mf->fontRef;
  226758. CGContextSetFont (context, state->fontRef);
  226759. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226760. state->fontTransform = mf->renderingTransform;
  226761. state->fontTransform.a *= state->font.getHorizontalScale();
  226762. CGContextSetTextMatrix (context, state->fontTransform);
  226763. }
  226764. }
  226765. }
  226766. const Font getFont()
  226767. {
  226768. return state->font;
  226769. }
  226770. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226771. {
  226772. if (state->fontRef != 0 && state->fillType.isColour())
  226773. {
  226774. if (transform.isOnlyTranslation())
  226775. {
  226776. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226777. CGGlyph g = glyphNumber;
  226778. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226779. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226780. }
  226781. else
  226782. {
  226783. CGContextSaveGState (context);
  226784. flip();
  226785. applyTransform (transform);
  226786. CGAffineTransform t = state->fontTransform;
  226787. t.d = -t.d;
  226788. CGContextSetTextMatrix (context, t);
  226789. CGGlyph g = glyphNumber;
  226790. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226791. CGContextRestoreGState (context);
  226792. }
  226793. }
  226794. else
  226795. {
  226796. Path p;
  226797. Font& f = state->font;
  226798. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226799. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226800. .followedBy (transform));
  226801. }
  226802. }
  226803. private:
  226804. CGContextRef context;
  226805. const CGFloat flipHeight;
  226806. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226807. CGFunctionCallbacks gradientCallbacks;
  226808. mutable Rectangle<int> lastClipRect;
  226809. mutable bool lastClipRectIsValid;
  226810. struct SavedState
  226811. {
  226812. SavedState()
  226813. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226814. {
  226815. }
  226816. SavedState (const SavedState& other)
  226817. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226818. fontTransform (other.fontTransform)
  226819. {
  226820. }
  226821. FillType fillType;
  226822. Font font;
  226823. CGFontRef fontRef;
  226824. CGAffineTransform fontTransform;
  226825. };
  226826. ScopedPointer <SavedState> state;
  226827. OwnedArray <SavedState> stateStack;
  226828. HeapBlock <PixelARGB> gradientLookupTable;
  226829. int numGradientLookupEntries;
  226830. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226831. {
  226832. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226833. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226834. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226835. colour.unpremultiply();
  226836. outData[0] = colour.getRed() / 255.0f;
  226837. outData[1] = colour.getGreen() / 255.0f;
  226838. outData[2] = colour.getBlue() / 255.0f;
  226839. outData[3] = colour.getAlpha() / 255.0f;
  226840. }
  226841. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226842. {
  226843. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226844. CGShadingRef result = 0;
  226845. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226846. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226847. if (gradient.isRadial)
  226848. {
  226849. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226850. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226851. function, true, true);
  226852. }
  226853. else
  226854. {
  226855. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226856. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226857. function, true, true);
  226858. }
  226859. CGFunctionRelease (function);
  226860. return result;
  226861. }
  226862. void drawGradient()
  226863. {
  226864. flip();
  226865. applyTransform (state->fillType.transform);
  226866. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226867. // you draw a gradient with high quality interp enabled).
  226868. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226869. CGContextSetAlpha (context, state->fillType.getOpacity());
  226870. CGContextDrawShading (context, shading);
  226871. CGShadingRelease (shading);
  226872. }
  226873. void createPath (const Path& path) const
  226874. {
  226875. CGContextBeginPath (context);
  226876. Path::Iterator i (path);
  226877. while (i.next())
  226878. {
  226879. switch (i.elementType)
  226880. {
  226881. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226882. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226883. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226884. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226885. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226886. default: jassertfalse; break;
  226887. }
  226888. }
  226889. }
  226890. void createPath (const Path& path, const AffineTransform& transform) const
  226891. {
  226892. CGContextBeginPath (context);
  226893. Path::Iterator i (path);
  226894. while (i.next())
  226895. {
  226896. switch (i.elementType)
  226897. {
  226898. case Path::Iterator::startNewSubPath:
  226899. transform.transformPoint (i.x1, i.y1);
  226900. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226901. break;
  226902. case Path::Iterator::lineTo:
  226903. transform.transformPoint (i.x1, i.y1);
  226904. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226905. break;
  226906. case Path::Iterator::quadraticTo:
  226907. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226908. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226909. break;
  226910. case Path::Iterator::cubicTo:
  226911. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226912. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226913. break;
  226914. case Path::Iterator::closePath:
  226915. CGContextClosePath (context); break;
  226916. default:
  226917. jassertfalse;
  226918. break;
  226919. }
  226920. }
  226921. }
  226922. void flip() const
  226923. {
  226924. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226925. }
  226926. void applyTransform (const AffineTransform& transform) const
  226927. {
  226928. CGAffineTransform t;
  226929. t.a = transform.mat00;
  226930. t.b = transform.mat10;
  226931. t.c = transform.mat01;
  226932. t.d = transform.mat11;
  226933. t.tx = transform.mat02;
  226934. t.ty = transform.mat12;
  226935. CGContextConcatCTM (context, t);
  226936. }
  226937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226938. };
  226939. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226940. {
  226941. return new CoreGraphicsContext (context, height);
  226942. }
  226943. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226944. const Image juce_loadWithCoreImage (InputStream& input)
  226945. {
  226946. MemoryBlock data;
  226947. input.readIntoMemoryBlock (data, -1);
  226948. #if JUCE_IOS
  226949. JUCE_AUTORELEASEPOOL
  226950. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226951. length: data.getSize()
  226952. freeWhenDone: NO]];
  226953. if (image != nil)
  226954. {
  226955. CGImageRef loadedImage = image.CGImage;
  226956. #else
  226957. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226958. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226959. CGDataProviderRelease (provider);
  226960. if (imageSource != 0)
  226961. {
  226962. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226963. CFRelease (imageSource);
  226964. #endif
  226965. if (loadedImage != 0)
  226966. {
  226967. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226968. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226969. && alphaInfo != kCGImageAlphaNoneSkipLast
  226970. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226971. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226972. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226973. hasAlphaChan, Image::NativeImage);
  226974. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226975. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226976. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226977. CGContextFlush (cgImage->context);
  226978. #if ! JUCE_IOS
  226979. CFRelease (loadedImage);
  226980. #endif
  226981. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226982. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226983. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226984. return image;
  226985. }
  226986. }
  226987. return Image::null;
  226988. }
  226989. #endif
  226990. #endif
  226991. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226992. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  226993. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226994. // compiled on its own).
  226995. #if JUCE_INCLUDED_FILE
  226996. class UIViewComponentPeer;
  226997. END_JUCE_NAMESPACE
  226998. #define JuceUIView MakeObjCClassName(JuceUIView)
  226999. @interface JuceUIView : UIView <UITextViewDelegate>
  227000. {
  227001. @public
  227002. UIViewComponentPeer* owner;
  227003. UITextView* hiddenTextView;
  227004. }
  227005. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227006. - (void) dealloc;
  227007. - (void) drawRect: (CGRect) r;
  227008. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227009. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227010. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227011. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227012. - (BOOL) becomeFirstResponder;
  227013. - (BOOL) resignFirstResponder;
  227014. - (BOOL) canBecomeFirstResponder;
  227015. - (void) asyncRepaint: (id) rect;
  227016. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227017. @end
  227018. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227019. @interface JuceUIViewController : UIViewController
  227020. {
  227021. }
  227022. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227023. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227024. @end
  227025. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227026. @interface JuceUIWindow : UIWindow
  227027. {
  227028. @private
  227029. UIViewComponentPeer* owner;
  227030. bool isZooming;
  227031. }
  227032. - (void) setOwner: (UIViewComponentPeer*) owner;
  227033. - (void) becomeKeyWindow;
  227034. @end
  227035. BEGIN_JUCE_NAMESPACE
  227036. class UIViewComponentPeer : public ComponentPeer,
  227037. public FocusChangeListener
  227038. {
  227039. public:
  227040. UIViewComponentPeer (Component* const component,
  227041. const int windowStyleFlags,
  227042. UIView* viewToAttachTo);
  227043. ~UIViewComponentPeer();
  227044. void* getNativeHandle() const;
  227045. void setVisible (bool shouldBeVisible);
  227046. void setTitle (const String& title);
  227047. void setPosition (int x, int y);
  227048. void setSize (int w, int h);
  227049. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227050. const Rectangle<int> getBounds() const;
  227051. const Rectangle<int> getBounds (const bool global) const;
  227052. const Point<int> getScreenPosition() const;
  227053. const Point<int> localToGlobal (const Point<int>& relativePosition);
  227054. const Point<int> globalToLocal (const Point<int>& screenPosition);
  227055. void setAlpha (float newAlpha);
  227056. void setMinimised (bool shouldBeMinimised);
  227057. bool isMinimised() const;
  227058. void setFullScreen (bool shouldBeFullScreen);
  227059. bool isFullScreen() const;
  227060. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227061. const BorderSize<int> getFrameSize() const;
  227062. bool setAlwaysOnTop (bool alwaysOnTop);
  227063. void toFront (bool makeActiveWindow);
  227064. void toBehind (ComponentPeer* other);
  227065. void setIcon (const Image& newIcon);
  227066. virtual void drawRect (CGRect r);
  227067. virtual bool canBecomeKeyWindow();
  227068. virtual bool windowShouldClose();
  227069. virtual void redirectMovedOrResized();
  227070. virtual CGRect constrainRect (CGRect r);
  227071. virtual void viewFocusGain();
  227072. virtual void viewFocusLoss();
  227073. bool isFocused() const;
  227074. void grabFocus();
  227075. void textInputRequired (const Point<int>& position);
  227076. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227077. void updateHiddenTextContent (TextInputTarget* target);
  227078. void globalFocusChanged (Component*);
  227079. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227080. virtual void displayRotated();
  227081. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227082. void repaint (const Rectangle<int>& area);
  227083. void performAnyPendingRepaintsNow();
  227084. UIWindow* window;
  227085. JuceUIView* view;
  227086. JuceUIViewController* controller;
  227087. bool isSharedWindow, fullScreen, insideDrawRect;
  227088. static ModifierKeys currentModifiers;
  227089. static int64 getMouseTime (UIEvent* e)
  227090. {
  227091. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227092. + (int64) ([e timestamp] * 1000.0);
  227093. }
  227094. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227095. {
  227096. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227097. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227098. {
  227099. case UIInterfaceOrientationPortrait:
  227100. return r;
  227101. case UIInterfaceOrientationPortraitUpsideDown:
  227102. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227103. r.getWidth(), r.getHeight());
  227104. case UIInterfaceOrientationLandscapeLeft:
  227105. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227106. r.getHeight(), r.getWidth());
  227107. case UIInterfaceOrientationLandscapeRight:
  227108. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227109. r.getHeight(), r.getWidth());
  227110. default: jassertfalse; // unknown orientation!
  227111. }
  227112. return r;
  227113. }
  227114. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227115. {
  227116. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227117. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227118. {
  227119. case UIInterfaceOrientationPortrait:
  227120. return r;
  227121. case UIInterfaceOrientationPortraitUpsideDown:
  227122. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227123. r.getWidth(), r.getHeight());
  227124. case UIInterfaceOrientationLandscapeLeft:
  227125. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227126. r.getHeight(), r.getWidth());
  227127. case UIInterfaceOrientationLandscapeRight:
  227128. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227129. r.getHeight(), r.getWidth());
  227130. default: jassertfalse; // unknown orientation!
  227131. }
  227132. return r;
  227133. }
  227134. Array <UITouch*> currentTouches;
  227135. private:
  227136. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  227137. };
  227138. END_JUCE_NAMESPACE
  227139. @implementation JuceUIViewController
  227140. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227141. {
  227142. JuceUIView* juceView = (JuceUIView*) [self view];
  227143. jassert (juceView != 0 && juceView->owner != 0);
  227144. return juceView->owner->shouldRotate (interfaceOrientation);
  227145. }
  227146. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227147. {
  227148. JuceUIView* juceView = (JuceUIView*) [self view];
  227149. jassert (juceView != 0 && juceView->owner != 0);
  227150. juceView->owner->displayRotated();
  227151. }
  227152. @end
  227153. @implementation JuceUIView
  227154. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227155. withFrame: (CGRect) frame
  227156. {
  227157. [super initWithFrame: frame];
  227158. owner = owner_;
  227159. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227160. [self addSubview: hiddenTextView];
  227161. hiddenTextView.delegate = self;
  227162. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227163. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227164. return self;
  227165. }
  227166. - (void) dealloc
  227167. {
  227168. [hiddenTextView removeFromSuperview];
  227169. [hiddenTextView release];
  227170. [super dealloc];
  227171. }
  227172. - (void) drawRect: (CGRect) r
  227173. {
  227174. if (owner != 0)
  227175. owner->drawRect (r);
  227176. }
  227177. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227178. {
  227179. return false;
  227180. }
  227181. ModifierKeys UIViewComponentPeer::currentModifiers;
  227182. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227183. {
  227184. return UIViewComponentPeer::currentModifiers;
  227185. }
  227186. void ModifierKeys::updateCurrentModifiers() throw()
  227187. {
  227188. currentModifiers = UIViewComponentPeer::currentModifiers;
  227189. }
  227190. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227191. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227192. {
  227193. if (owner != 0)
  227194. owner->handleTouches (event, true, false, false);
  227195. }
  227196. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227197. {
  227198. if (owner != 0)
  227199. owner->handleTouches (event, false, false, false);
  227200. }
  227201. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227202. {
  227203. if (owner != 0)
  227204. owner->handleTouches (event, false, true, false);
  227205. }
  227206. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227207. {
  227208. if (owner != 0)
  227209. owner->handleTouches (event, false, true, true);
  227210. [self touchesEnded: touches withEvent: event];
  227211. }
  227212. - (BOOL) becomeFirstResponder
  227213. {
  227214. if (owner != 0)
  227215. owner->viewFocusGain();
  227216. return true;
  227217. }
  227218. - (BOOL) resignFirstResponder
  227219. {
  227220. if (owner != 0)
  227221. owner->viewFocusLoss();
  227222. return true;
  227223. }
  227224. - (BOOL) canBecomeFirstResponder
  227225. {
  227226. return owner != 0 && owner->canBecomeKeyWindow();
  227227. }
  227228. - (void) asyncRepaint: (id) rect
  227229. {
  227230. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227231. [self setNeedsDisplayInRect: *r];
  227232. }
  227233. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227234. {
  227235. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227236. nsStringToJuce (text));
  227237. }
  227238. @end
  227239. @implementation JuceUIWindow
  227240. - (void) setOwner: (UIViewComponentPeer*) owner_
  227241. {
  227242. owner = owner_;
  227243. isZooming = false;
  227244. }
  227245. - (void) becomeKeyWindow
  227246. {
  227247. [super becomeKeyWindow];
  227248. if (owner != 0)
  227249. owner->grabFocus();
  227250. }
  227251. @end
  227252. BEGIN_JUCE_NAMESPACE
  227253. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227254. const int windowStyleFlags,
  227255. UIView* viewToAttachTo)
  227256. : ComponentPeer (component, windowStyleFlags),
  227257. window (0),
  227258. view (0), controller (0),
  227259. isSharedWindow (viewToAttachTo != 0),
  227260. fullScreen (false),
  227261. insideDrawRect (false)
  227262. {
  227263. CGRect r = convertToCGRect (component->getLocalBounds());
  227264. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227265. if (isSharedWindow)
  227266. {
  227267. window = [viewToAttachTo window];
  227268. [viewToAttachTo addSubview: view];
  227269. setVisible (component->isVisible());
  227270. }
  227271. else
  227272. {
  227273. controller = [[JuceUIViewController alloc] init];
  227274. controller.view = view;
  227275. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227276. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227277. window = [[JuceUIWindow alloc] init];
  227278. window.frame = r;
  227279. window.opaque = component->isOpaque();
  227280. view.opaque = component->isOpaque();
  227281. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227282. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227283. [((JuceUIWindow*) window) setOwner: this];
  227284. if (component->isAlwaysOnTop())
  227285. window.windowLevel = UIWindowLevelAlert;
  227286. [window addSubview: view];
  227287. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227288. view.hidden = ! component->isVisible();
  227289. window.hidden = ! component->isVisible();
  227290. view.multipleTouchEnabled = YES;
  227291. }
  227292. setTitle (component->getName());
  227293. Desktop::getInstance().addFocusChangeListener (this);
  227294. }
  227295. UIViewComponentPeer::~UIViewComponentPeer()
  227296. {
  227297. Desktop::getInstance().removeFocusChangeListener (this);
  227298. view->owner = 0;
  227299. [view removeFromSuperview];
  227300. [view release];
  227301. [controller release];
  227302. if (! isSharedWindow)
  227303. {
  227304. [((JuceUIWindow*) window) setOwner: 0];
  227305. [window release];
  227306. }
  227307. }
  227308. void* UIViewComponentPeer::getNativeHandle() const
  227309. {
  227310. return view;
  227311. }
  227312. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227313. {
  227314. view.hidden = ! shouldBeVisible;
  227315. if (! isSharedWindow)
  227316. window.hidden = ! shouldBeVisible;
  227317. }
  227318. void UIViewComponentPeer::setTitle (const String& title)
  227319. {
  227320. // xxx is this possible?
  227321. }
  227322. void UIViewComponentPeer::setPosition (int x, int y)
  227323. {
  227324. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227325. }
  227326. void UIViewComponentPeer::setSize (int w, int h)
  227327. {
  227328. setBounds (component->getX(), component->getY(), w, h, false);
  227329. }
  227330. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227331. {
  227332. fullScreen = isNowFullScreen;
  227333. w = jmax (0, w);
  227334. h = jmax (0, h);
  227335. if (isSharedWindow)
  227336. {
  227337. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227338. if ([view frame].size.width != r.size.width
  227339. || [view frame].size.height != r.size.height)
  227340. [view setNeedsDisplay];
  227341. view.frame = r;
  227342. }
  227343. else
  227344. {
  227345. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227346. window.frame = convertToCGRect (bounds);
  227347. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227348. handleMovedOrResized();
  227349. }
  227350. }
  227351. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227352. {
  227353. CGRect r = [view frame];
  227354. if (global && [view window] != 0)
  227355. {
  227356. r = [view convertRect: r toView: nil];
  227357. CGRect wr = [[view window] frame];
  227358. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227359. r.origin.x = windowBounds.getX();
  227360. r.origin.y = windowBounds.getY();
  227361. }
  227362. return convertToRectInt (r);
  227363. }
  227364. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227365. {
  227366. return getBounds (! isSharedWindow);
  227367. }
  227368. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227369. {
  227370. return getBounds (true).getPosition();
  227371. }
  227372. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227373. {
  227374. return relativePosition + getScreenPosition();
  227375. }
  227376. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227377. {
  227378. return screenPosition - getScreenPosition();
  227379. }
  227380. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227381. {
  227382. if (constrainer != 0)
  227383. {
  227384. CGRect current = [window frame];
  227385. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227386. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227387. Rectangle<int> pos (convertToRectInt (r));
  227388. Rectangle<int> original (convertToRectInt (current));
  227389. constrainer->checkBounds (pos, original,
  227390. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227391. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227392. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227393. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227394. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227395. r.origin.x = pos.getX();
  227396. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227397. r.size.width = pos.getWidth();
  227398. r.size.height = pos.getHeight();
  227399. }
  227400. return r;
  227401. }
  227402. void UIViewComponentPeer::setAlpha (float newAlpha)
  227403. {
  227404. [[view window] setAlpha: (CGFloat) newAlpha];
  227405. }
  227406. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227407. {
  227408. }
  227409. bool UIViewComponentPeer::isMinimised() const
  227410. {
  227411. return false;
  227412. }
  227413. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227414. {
  227415. if (! isSharedWindow)
  227416. {
  227417. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227418. : lastNonFullscreenBounds);
  227419. if ((! shouldBeFullScreen) && r.isEmpty())
  227420. r = getBounds();
  227421. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227422. if (! r.isEmpty())
  227423. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227424. component->repaint();
  227425. }
  227426. }
  227427. bool UIViewComponentPeer::isFullScreen() const
  227428. {
  227429. return fullScreen;
  227430. }
  227431. namespace
  227432. {
  227433. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227434. {
  227435. switch (interfaceOrientation)
  227436. {
  227437. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227438. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227439. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227440. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227441. default: jassertfalse; // unknown orientation!
  227442. }
  227443. return Desktop::upright;
  227444. }
  227445. }
  227446. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227447. {
  227448. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227449. }
  227450. void UIViewComponentPeer::displayRotated()
  227451. {
  227452. const Rectangle<int> oldArea (component->getBounds());
  227453. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227454. Desktop::getInstance().refreshMonitorSizes();
  227455. if (fullScreen)
  227456. {
  227457. fullScreen = false;
  227458. setFullScreen (true);
  227459. }
  227460. else
  227461. {
  227462. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227463. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227464. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227465. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227466. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227467. setBounds ((int) (l * newDesktop.getWidth()),
  227468. (int) (t * newDesktop.getHeight()),
  227469. (int) ((r - l) * newDesktop.getWidth()),
  227470. (int) ((b - t) * newDesktop.getHeight()),
  227471. false);
  227472. }
  227473. }
  227474. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227475. {
  227476. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227477. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227478. return false;
  227479. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227480. withEvent: nil];
  227481. if (trueIfInAChildWindow)
  227482. return v != nil;
  227483. return v == view;
  227484. }
  227485. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  227486. {
  227487. return BorderSize<int>();
  227488. }
  227489. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227490. {
  227491. if (! isSharedWindow)
  227492. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227493. return true;
  227494. }
  227495. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227496. {
  227497. if (isSharedWindow)
  227498. [[view superview] bringSubviewToFront: view];
  227499. if (window != 0 && component->isVisible())
  227500. [window makeKeyAndVisible];
  227501. }
  227502. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227503. {
  227504. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227505. jassert (otherPeer != 0); // wrong type of window?
  227506. if (otherPeer != 0)
  227507. {
  227508. if (isSharedWindow)
  227509. {
  227510. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227511. }
  227512. else
  227513. {
  227514. jassertfalse; // don't know how to do this
  227515. }
  227516. }
  227517. }
  227518. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227519. {
  227520. // to do..
  227521. }
  227522. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227523. {
  227524. NSArray* touches = [[event touchesForView: view] allObjects];
  227525. for (unsigned int i = 0; i < [touches count]; ++i)
  227526. {
  227527. UITouch* touch = [touches objectAtIndex: i];
  227528. CGPoint p = [touch locationInView: view];
  227529. const Point<int> pos ((int) p.x, (int) p.y);
  227530. juce_lastMousePos = pos + getScreenPosition();
  227531. const int64 time = getMouseTime (event);
  227532. int touchIndex = currentTouches.indexOf (touch);
  227533. if (touchIndex < 0)
  227534. {
  227535. touchIndex = currentTouches.size();
  227536. currentTouches.add (touch);
  227537. }
  227538. if (isDown)
  227539. {
  227540. currentModifiers = currentModifiers.withoutMouseButtons();
  227541. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227542. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227543. }
  227544. else if (isUp)
  227545. {
  227546. currentModifiers = currentModifiers.withoutMouseButtons();
  227547. currentTouches.remove (touchIndex);
  227548. }
  227549. if (isCancel)
  227550. currentTouches.clear();
  227551. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227552. }
  227553. }
  227554. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227555. void UIViewComponentPeer::viewFocusGain()
  227556. {
  227557. if (currentlyFocusedPeer != this)
  227558. {
  227559. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227560. currentlyFocusedPeer->handleFocusLoss();
  227561. currentlyFocusedPeer = this;
  227562. handleFocusGain();
  227563. }
  227564. }
  227565. void UIViewComponentPeer::viewFocusLoss()
  227566. {
  227567. if (currentlyFocusedPeer == this)
  227568. {
  227569. currentlyFocusedPeer = 0;
  227570. handleFocusLoss();
  227571. }
  227572. }
  227573. void juce_HandleProcessFocusChange()
  227574. {
  227575. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227576. {
  227577. if (Process::isForegroundProcess())
  227578. {
  227579. currentlyFocusedPeer->handleFocusGain();
  227580. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227581. }
  227582. else
  227583. {
  227584. currentlyFocusedPeer->handleFocusLoss();
  227585. // turn kiosk mode off if we lose focus..
  227586. Desktop::getInstance().setKioskModeComponent (0);
  227587. }
  227588. }
  227589. }
  227590. bool UIViewComponentPeer::isFocused() const
  227591. {
  227592. return isSharedWindow ? this == currentlyFocusedPeer
  227593. : (window != 0 && [window isKeyWindow]);
  227594. }
  227595. void UIViewComponentPeer::grabFocus()
  227596. {
  227597. if (window != 0)
  227598. {
  227599. [window makeKeyWindow];
  227600. viewFocusGain();
  227601. }
  227602. }
  227603. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227604. {
  227605. }
  227606. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227607. {
  227608. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227609. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227610. }
  227611. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227612. {
  227613. TextInputTarget* const target = findCurrentTextInputTarget();
  227614. if (target != 0)
  227615. {
  227616. const Range<int> currentSelection (target->getHighlightedRegion());
  227617. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227618. if (currentSelection.isEmpty())
  227619. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227620. target->insertTextAtCaret (text);
  227621. updateHiddenTextContent (target);
  227622. }
  227623. return NO;
  227624. }
  227625. void UIViewComponentPeer::globalFocusChanged (Component*)
  227626. {
  227627. TextInputTarget* const target = findCurrentTextInputTarget();
  227628. if (target != 0)
  227629. {
  227630. Component* comp = dynamic_cast<Component*> (target);
  227631. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227632. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227633. updateHiddenTextContent (target);
  227634. [view->hiddenTextView becomeFirstResponder];
  227635. }
  227636. else
  227637. {
  227638. [view->hiddenTextView resignFirstResponder];
  227639. }
  227640. }
  227641. void UIViewComponentPeer::drawRect (CGRect r)
  227642. {
  227643. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227644. return;
  227645. CGContextRef cg = UIGraphicsGetCurrentContext();
  227646. if (! component->isOpaque())
  227647. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227648. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227649. CoreGraphicsContext g (cg, view.bounds.size.height);
  227650. insideDrawRect = true;
  227651. handlePaint (g);
  227652. insideDrawRect = false;
  227653. }
  227654. bool UIViewComponentPeer::canBecomeKeyWindow()
  227655. {
  227656. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227657. }
  227658. bool UIViewComponentPeer::windowShouldClose()
  227659. {
  227660. if (! isValidPeer (this))
  227661. return YES;
  227662. handleUserClosingWindow();
  227663. return NO;
  227664. }
  227665. void UIViewComponentPeer::redirectMovedOrResized()
  227666. {
  227667. handleMovedOrResized();
  227668. }
  227669. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227670. {
  227671. }
  227672. class AsyncRepaintMessage : public CallbackMessage
  227673. {
  227674. public:
  227675. UIViewComponentPeer* const peer;
  227676. const Rectangle<int> rect;
  227677. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227678. : peer (peer_), rect (rect_)
  227679. {
  227680. }
  227681. void messageCallback()
  227682. {
  227683. if (ComponentPeer::isValidPeer (peer))
  227684. peer->repaint (rect);
  227685. }
  227686. };
  227687. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227688. {
  227689. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227690. {
  227691. (new AsyncRepaintMessage (this, area))->post();
  227692. }
  227693. else
  227694. {
  227695. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227696. }
  227697. }
  227698. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227699. {
  227700. }
  227701. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227702. {
  227703. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227704. }
  227705. const Image juce_createIconForFile (const File& file)
  227706. {
  227707. return Image::null;
  227708. }
  227709. void Desktop::createMouseInputSources()
  227710. {
  227711. for (int i = 0; i < 10; ++i)
  227712. mouseSources.add (new MouseInputSource (i, false));
  227713. }
  227714. bool Desktop::canUseSemiTransparentWindows() throw()
  227715. {
  227716. return true;
  227717. }
  227718. const Point<int> MouseInputSource::getCurrentMousePosition()
  227719. {
  227720. return juce_lastMousePos;
  227721. }
  227722. void Desktop::setMousePosition (const Point<int>&)
  227723. {
  227724. }
  227725. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227726. {
  227727. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227728. }
  227729. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227730. {
  227731. const ScopedAutoReleasePool pool;
  227732. monitorCoords.clear();
  227733. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227734. : [[UIScreen mainScreen] bounds];
  227735. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227736. }
  227737. const int KeyPress::spaceKey = ' ';
  227738. const int KeyPress::returnKey = 0x0d;
  227739. const int KeyPress::escapeKey = 0x1b;
  227740. const int KeyPress::backspaceKey = 0x7f;
  227741. const int KeyPress::leftKey = 0x1000;
  227742. const int KeyPress::rightKey = 0x1001;
  227743. const int KeyPress::upKey = 0x1002;
  227744. const int KeyPress::downKey = 0x1003;
  227745. const int KeyPress::pageUpKey = 0x1004;
  227746. const int KeyPress::pageDownKey = 0x1005;
  227747. const int KeyPress::endKey = 0x1006;
  227748. const int KeyPress::homeKey = 0x1007;
  227749. const int KeyPress::deleteKey = 0x1008;
  227750. const int KeyPress::insertKey = -1;
  227751. const int KeyPress::tabKey = 9;
  227752. const int KeyPress::F1Key = 0x2001;
  227753. const int KeyPress::F2Key = 0x2002;
  227754. const int KeyPress::F3Key = 0x2003;
  227755. const int KeyPress::F4Key = 0x2004;
  227756. const int KeyPress::F5Key = 0x2005;
  227757. const int KeyPress::F6Key = 0x2006;
  227758. const int KeyPress::F7Key = 0x2007;
  227759. const int KeyPress::F8Key = 0x2008;
  227760. const int KeyPress::F9Key = 0x2009;
  227761. const int KeyPress::F10Key = 0x200a;
  227762. const int KeyPress::F11Key = 0x200b;
  227763. const int KeyPress::F12Key = 0x200c;
  227764. const int KeyPress::F13Key = 0x200d;
  227765. const int KeyPress::F14Key = 0x200e;
  227766. const int KeyPress::F15Key = 0x200f;
  227767. const int KeyPress::F16Key = 0x2010;
  227768. const int KeyPress::numberPad0 = 0x30020;
  227769. const int KeyPress::numberPad1 = 0x30021;
  227770. const int KeyPress::numberPad2 = 0x30022;
  227771. const int KeyPress::numberPad3 = 0x30023;
  227772. const int KeyPress::numberPad4 = 0x30024;
  227773. const int KeyPress::numberPad5 = 0x30025;
  227774. const int KeyPress::numberPad6 = 0x30026;
  227775. const int KeyPress::numberPad7 = 0x30027;
  227776. const int KeyPress::numberPad8 = 0x30028;
  227777. const int KeyPress::numberPad9 = 0x30029;
  227778. const int KeyPress::numberPadAdd = 0x3002a;
  227779. const int KeyPress::numberPadSubtract = 0x3002b;
  227780. const int KeyPress::numberPadMultiply = 0x3002c;
  227781. const int KeyPress::numberPadDivide = 0x3002d;
  227782. const int KeyPress::numberPadSeparator = 0x3002e;
  227783. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227784. const int KeyPress::numberPadEquals = 0x30030;
  227785. const int KeyPress::numberPadDelete = 0x30031;
  227786. const int KeyPress::playKey = 0x30000;
  227787. const int KeyPress::stopKey = 0x30001;
  227788. const int KeyPress::fastForwardKey = 0x30002;
  227789. const int KeyPress::rewindKey = 0x30003;
  227790. #endif
  227791. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227792. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227793. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227794. // compiled on its own).
  227795. #if JUCE_INCLUDED_FILE
  227796. struct CallbackMessagePayload
  227797. {
  227798. MessageCallbackFunction* function;
  227799. void* parameter;
  227800. void* volatile result;
  227801. bool volatile hasBeenExecuted;
  227802. };
  227803. END_JUCE_NAMESPACE
  227804. @interface JuceCustomMessageHandler : NSObject
  227805. {
  227806. }
  227807. - (void) performCallback: (id) info;
  227808. @end
  227809. @implementation JuceCustomMessageHandler
  227810. - (void) performCallback: (id) info
  227811. {
  227812. if ([info isKindOfClass: [NSData class]])
  227813. {
  227814. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227815. if (pl != 0)
  227816. {
  227817. pl->result = (*pl->function) (pl->parameter);
  227818. pl->hasBeenExecuted = true;
  227819. }
  227820. }
  227821. else
  227822. {
  227823. jassertfalse; // should never get here!
  227824. }
  227825. }
  227826. @end
  227827. BEGIN_JUCE_NAMESPACE
  227828. void MessageManager::runDispatchLoop()
  227829. {
  227830. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227831. runDispatchLoopUntil (-1);
  227832. }
  227833. void MessageManager::stopDispatchLoop()
  227834. {
  227835. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227836. exit (0); // iPhone apps get no mercy..
  227837. }
  227838. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227839. {
  227840. const ScopedAutoReleasePool pool;
  227841. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227842. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227843. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227844. while (! quitMessagePosted)
  227845. {
  227846. const ScopedAutoReleasePool pool;
  227847. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227848. beforeDate: endDate];
  227849. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227850. break;
  227851. }
  227852. return ! quitMessagePosted;
  227853. }
  227854. struct MessageDispatchSystem
  227855. {
  227856. MessageDispatchSystem()
  227857. : juceCustomMessageHandler (0)
  227858. {
  227859. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227860. }
  227861. ~MessageDispatchSystem()
  227862. {
  227863. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227864. [juceCustomMessageHandler release];
  227865. }
  227866. JuceCustomMessageHandler* juceCustomMessageHandler;
  227867. MessageQueue messageQueue;
  227868. };
  227869. static MessageDispatchSystem* dispatcher = 0;
  227870. void MessageManager::doPlatformSpecificInitialisation()
  227871. {
  227872. if (dispatcher == 0)
  227873. dispatcher = new MessageDispatchSystem();
  227874. }
  227875. void MessageManager::doPlatformSpecificShutdown()
  227876. {
  227877. deleteAndZero (dispatcher);
  227878. }
  227879. bool juce_postMessageToSystemQueue (Message* message)
  227880. {
  227881. if (dispatcher != 0)
  227882. dispatcher->messageQueue.post (message);
  227883. return true;
  227884. }
  227885. void MessageManager::broadcastMessage (const String& value)
  227886. {
  227887. }
  227888. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227889. {
  227890. if (isThisTheMessageThread())
  227891. {
  227892. return (*callback) (data);
  227893. }
  227894. else
  227895. {
  227896. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227897. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227898. // deadlock because the message manager is blocked from running, so can never
  227899. // call your function..
  227900. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227901. const ScopedAutoReleasePool pool;
  227902. CallbackMessagePayload cmp;
  227903. cmp.function = callback;
  227904. cmp.parameter = data;
  227905. cmp.result = 0;
  227906. cmp.hasBeenExecuted = false;
  227907. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227908. withObject: [NSData dataWithBytesNoCopy: &cmp
  227909. length: sizeof (cmp)
  227910. freeWhenDone: NO]
  227911. waitUntilDone: YES];
  227912. return cmp.result;
  227913. }
  227914. }
  227915. #endif
  227916. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227917. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227918. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227919. // compiled on its own).
  227920. #if JUCE_INCLUDED_FILE
  227921. #if JUCE_MAC
  227922. END_JUCE_NAMESPACE
  227923. using namespace JUCE_NAMESPACE;
  227924. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227925. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227926. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227927. #else
  227928. @interface JuceFileChooserDelegate : NSObject
  227929. #endif
  227930. {
  227931. StringArray* filters;
  227932. }
  227933. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227934. - (void) dealloc;
  227935. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227936. @end
  227937. @implementation JuceFileChooserDelegate
  227938. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227939. {
  227940. [super init];
  227941. filters = filters_;
  227942. return self;
  227943. }
  227944. - (void) dealloc
  227945. {
  227946. delete filters;
  227947. [super dealloc];
  227948. }
  227949. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227950. {
  227951. (void) sender;
  227952. const File f (nsStringToJuce (filename));
  227953. for (int i = filters->size(); --i >= 0;)
  227954. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227955. return true;
  227956. return f.isDirectory();
  227957. }
  227958. @end
  227959. BEGIN_JUCE_NAMESPACE
  227960. void FileChooser::showPlatformDialog (Array<File>& results,
  227961. const String& title,
  227962. const File& currentFileOrDirectory,
  227963. const String& filter,
  227964. bool selectsDirectory,
  227965. bool selectsFiles,
  227966. bool isSaveDialogue,
  227967. bool /*warnAboutOverwritingExistingFiles*/,
  227968. bool selectMultipleFiles,
  227969. FilePreviewComponent* /*extraInfoComponent*/)
  227970. {
  227971. const ScopedAutoReleasePool pool;
  227972. StringArray* filters = new StringArray();
  227973. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227974. filters->trim();
  227975. filters->removeEmptyStrings();
  227976. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227977. [delegate autorelease];
  227978. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227979. : [NSOpenPanel openPanel];
  227980. [panel setTitle: juceStringToNS (title)];
  227981. if (! isSaveDialogue)
  227982. {
  227983. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227984. [openPanel setCanChooseDirectories: selectsDirectory];
  227985. [openPanel setCanChooseFiles: selectsFiles];
  227986. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227987. }
  227988. [panel setDelegate: delegate];
  227989. if (isSaveDialogue || selectsDirectory)
  227990. [panel setCanCreateDirectories: YES];
  227991. String directory, filename;
  227992. if (currentFileOrDirectory.isDirectory())
  227993. {
  227994. directory = currentFileOrDirectory.getFullPathName();
  227995. }
  227996. else
  227997. {
  227998. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227999. filename = currentFileOrDirectory.getFileName();
  228000. }
  228001. if ([panel runModalForDirectory: juceStringToNS (directory)
  228002. file: juceStringToNS (filename)]
  228003. == NSOKButton)
  228004. {
  228005. if (isSaveDialogue)
  228006. {
  228007. results.add (File (nsStringToJuce ([panel filename])));
  228008. }
  228009. else
  228010. {
  228011. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228012. NSArray* urls = [openPanel filenames];
  228013. for (unsigned int i = 0; i < [urls count]; ++i)
  228014. {
  228015. NSString* f = [urls objectAtIndex: i];
  228016. results.add (File (nsStringToJuce (f)));
  228017. }
  228018. }
  228019. }
  228020. [panel setDelegate: nil];
  228021. }
  228022. #else
  228023. void FileChooser::showPlatformDialog (Array<File>& results,
  228024. const String& title,
  228025. const File& currentFileOrDirectory,
  228026. const String& filter,
  228027. bool selectsDirectory,
  228028. bool selectsFiles,
  228029. bool isSaveDialogue,
  228030. bool warnAboutOverwritingExistingFiles,
  228031. bool selectMultipleFiles,
  228032. FilePreviewComponent* extraInfoComponent)
  228033. {
  228034. const ScopedAutoReleasePool pool;
  228035. jassertfalse; //xxx to do
  228036. }
  228037. #endif
  228038. #endif
  228039. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228040. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228041. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228042. // compiled on its own).
  228043. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228044. #if JUCE_MAC
  228045. END_JUCE_NAMESPACE
  228046. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228047. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228048. {
  228049. CriticalSection* contextLock;
  228050. bool needsUpdate;
  228051. }
  228052. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228053. - (bool) makeActive;
  228054. - (void) makeInactive;
  228055. - (void) reshape;
  228056. - (void) rightMouseDown: (NSEvent*) ev;
  228057. - (void) rightMouseUp: (NSEvent*) ev;
  228058. @end
  228059. @implementation ThreadSafeNSOpenGLView
  228060. - (id) initWithFrame: (NSRect) frameRect
  228061. pixelFormat: (NSOpenGLPixelFormat*) format
  228062. {
  228063. contextLock = new CriticalSection();
  228064. self = [super initWithFrame: frameRect pixelFormat: format];
  228065. if (self != nil)
  228066. [[NSNotificationCenter defaultCenter] addObserver: self
  228067. selector: @selector (_surfaceNeedsUpdate:)
  228068. name: NSViewGlobalFrameDidChangeNotification
  228069. object: self];
  228070. return self;
  228071. }
  228072. - (void) dealloc
  228073. {
  228074. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228075. delete contextLock;
  228076. [super dealloc];
  228077. }
  228078. - (bool) makeActive
  228079. {
  228080. const ScopedLock sl (*contextLock);
  228081. if ([self openGLContext] == 0)
  228082. return false;
  228083. [[self openGLContext] makeCurrentContext];
  228084. if (needsUpdate)
  228085. {
  228086. [super update];
  228087. needsUpdate = false;
  228088. }
  228089. return true;
  228090. }
  228091. - (void) makeInactive
  228092. {
  228093. const ScopedLock sl (*contextLock);
  228094. [NSOpenGLContext clearCurrentContext];
  228095. }
  228096. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228097. {
  228098. (void) notification;
  228099. const ScopedLock sl (*contextLock);
  228100. needsUpdate = true;
  228101. }
  228102. - (void) update
  228103. {
  228104. const ScopedLock sl (*contextLock);
  228105. needsUpdate = true;
  228106. }
  228107. - (void) reshape
  228108. {
  228109. const ScopedLock sl (*contextLock);
  228110. needsUpdate = true;
  228111. }
  228112. - (void) rightMouseDown: (NSEvent*) ev
  228113. {
  228114. [[self superview] rightMouseDown: ev];
  228115. }
  228116. - (void) rightMouseUp: (NSEvent*) ev
  228117. {
  228118. [[self superview] rightMouseUp: ev];
  228119. }
  228120. @end
  228121. BEGIN_JUCE_NAMESPACE
  228122. class WindowedGLContext : public OpenGLContext
  228123. {
  228124. public:
  228125. WindowedGLContext (Component& component,
  228126. const OpenGLPixelFormat& pixelFormat_,
  228127. NSOpenGLContext* sharedContext)
  228128. : renderContext (0),
  228129. pixelFormat (pixelFormat_)
  228130. {
  228131. NSOpenGLPixelFormatAttribute attribs [64];
  228132. int n = 0;
  228133. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228134. attribs[n++] = NSOpenGLPFAAccelerated;
  228135. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228136. attribs[n++] = NSOpenGLPFAColorSize;
  228137. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228138. pixelFormat.greenBits,
  228139. pixelFormat.blueBits);
  228140. attribs[n++] = NSOpenGLPFAAlphaSize;
  228141. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228142. attribs[n++] = NSOpenGLPFADepthSize;
  228143. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228144. attribs[n++] = NSOpenGLPFAStencilSize;
  228145. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228146. attribs[n++] = NSOpenGLPFAAccumSize;
  228147. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228148. pixelFormat.accumulationBufferGreenBits,
  228149. pixelFormat.accumulationBufferBlueBits,
  228150. pixelFormat.accumulationBufferAlphaBits);
  228151. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228152. attribs[n++] = NSOpenGLPFASampleBuffers;
  228153. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228154. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228155. attribs[n++] = NSOpenGLPFANoRecovery;
  228156. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228157. NSOpenGLPixelFormat* format
  228158. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228159. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228160. pixelFormat: format];
  228161. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228162. shareContext: sharedContext] autorelease];
  228163. const GLint swapInterval = 1;
  228164. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228165. [view setOpenGLContext: renderContext];
  228166. [format release];
  228167. viewHolder = new NSViewComponentInternal (view, component);
  228168. }
  228169. ~WindowedGLContext()
  228170. {
  228171. deleteContext();
  228172. viewHolder = 0;
  228173. }
  228174. void deleteContext()
  228175. {
  228176. makeInactive();
  228177. [renderContext clearDrawable];
  228178. [renderContext setView: nil];
  228179. [view setOpenGLContext: nil];
  228180. renderContext = nil;
  228181. }
  228182. bool makeActive() const throw()
  228183. {
  228184. jassert (renderContext != 0);
  228185. if ([renderContext view] != view)
  228186. [renderContext setView: view];
  228187. [view makeActive];
  228188. return isActive();
  228189. }
  228190. bool makeInactive() const throw()
  228191. {
  228192. [view makeInactive];
  228193. return true;
  228194. }
  228195. bool isActive() const throw()
  228196. {
  228197. return [NSOpenGLContext currentContext] == renderContext;
  228198. }
  228199. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228200. void* getRawContext() const throw() { return renderContext; }
  228201. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  228202. {
  228203. }
  228204. void swapBuffers()
  228205. {
  228206. [renderContext flushBuffer];
  228207. }
  228208. bool setSwapInterval (const int numFramesPerSwap)
  228209. {
  228210. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228211. forParameter: NSOpenGLCPSwapInterval];
  228212. return true;
  228213. }
  228214. int getSwapInterval() const
  228215. {
  228216. GLint numFrames = 0;
  228217. [renderContext getValues: &numFrames
  228218. forParameter: NSOpenGLCPSwapInterval];
  228219. return numFrames;
  228220. }
  228221. void repaint()
  228222. {
  228223. // we need to invalidate the juce view that holds this gl view, to make it
  228224. // cause a repaint callback
  228225. NSView* v = (NSView*) viewHolder->view;
  228226. NSRect r = [v frame];
  228227. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228228. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228229. // repaint message, thus never causing our paint() callback, and never repainting
  228230. // the comp. So invalidating just a little bit around the edge helps..
  228231. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228232. }
  228233. void* getNativeWindowHandle() const { return viewHolder->view; }
  228234. NSOpenGLContext* renderContext;
  228235. ThreadSafeNSOpenGLView* view;
  228236. private:
  228237. OpenGLPixelFormat pixelFormat;
  228238. ScopedPointer <NSViewComponentInternal> viewHolder;
  228239. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  228240. };
  228241. OpenGLContext* OpenGLComponent::createContext()
  228242. {
  228243. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  228244. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228245. return (c->renderContext != 0) ? c.release() : 0;
  228246. }
  228247. void* OpenGLComponent::getNativeWindowHandle() const
  228248. {
  228249. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228250. : 0;
  228251. }
  228252. void juce_glViewport (const int w, const int h)
  228253. {
  228254. glViewport (0, 0, w, h);
  228255. }
  228256. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228257. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228258. {
  228259. /* GLint attribs [64];
  228260. int n = 0;
  228261. attribs[n++] = AGL_RGBA;
  228262. attribs[n++] = AGL_DOUBLEBUFFER;
  228263. attribs[n++] = AGL_ACCELERATED;
  228264. attribs[n++] = AGL_NO_RECOVERY;
  228265. attribs[n++] = AGL_NONE;
  228266. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228267. while (p != 0)
  228268. {
  228269. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228270. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228271. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228272. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228273. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228274. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228275. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228276. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228277. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228278. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228279. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228280. results.add (pf);
  228281. p = aglNextPixelFormat (p);
  228282. }*/
  228283. //jassertfalse // can't see how you do this in cocoa!
  228284. }
  228285. #else
  228286. END_JUCE_NAMESPACE
  228287. @interface JuceGLView : UIView
  228288. {
  228289. }
  228290. + (Class) layerClass;
  228291. @end
  228292. @implementation JuceGLView
  228293. + (Class) layerClass
  228294. {
  228295. return [CAEAGLLayer class];
  228296. }
  228297. @end
  228298. BEGIN_JUCE_NAMESPACE
  228299. class GLESContext : public OpenGLContext
  228300. {
  228301. public:
  228302. GLESContext (UIViewComponentPeer* peer,
  228303. Component* const component_,
  228304. const OpenGLPixelFormat& pixelFormat_,
  228305. const GLESContext* const sharedContext,
  228306. NSUInteger apiType)
  228307. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228308. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228309. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228310. {
  228311. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228312. view.opaque = YES;
  228313. view.hidden = NO;
  228314. view.backgroundColor = [UIColor blackColor];
  228315. view.userInteractionEnabled = NO;
  228316. glLayer = (CAEAGLLayer*) [view layer];
  228317. [peer->view addSubview: view];
  228318. if (sharedContext != 0)
  228319. context = [[EAGLContext alloc] initWithAPI: apiType
  228320. sharegroup: [sharedContext->context sharegroup]];
  228321. else
  228322. context = [[EAGLContext alloc] initWithAPI: apiType];
  228323. createGLBuffers();
  228324. }
  228325. ~GLESContext()
  228326. {
  228327. deleteContext();
  228328. [view removeFromSuperview];
  228329. [view release];
  228330. freeGLBuffers();
  228331. }
  228332. void deleteContext()
  228333. {
  228334. makeInactive();
  228335. [context release];
  228336. context = nil;
  228337. }
  228338. bool makeActive() const throw()
  228339. {
  228340. jassert (context != 0);
  228341. [EAGLContext setCurrentContext: context];
  228342. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228343. return true;
  228344. }
  228345. void swapBuffers()
  228346. {
  228347. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228348. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228349. }
  228350. bool makeInactive() const throw()
  228351. {
  228352. return [EAGLContext setCurrentContext: nil];
  228353. }
  228354. bool isActive() const throw()
  228355. {
  228356. return [EAGLContext currentContext] == context;
  228357. }
  228358. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228359. void* getRawContext() const throw() { return glLayer; }
  228360. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228361. {
  228362. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228363. if (lastWidth != w || lastHeight != h)
  228364. {
  228365. lastWidth = w;
  228366. lastHeight = h;
  228367. freeGLBuffers();
  228368. createGLBuffers();
  228369. }
  228370. }
  228371. bool setSwapInterval (const int numFramesPerSwap)
  228372. {
  228373. numFrames = numFramesPerSwap;
  228374. return true;
  228375. }
  228376. int getSwapInterval() const
  228377. {
  228378. return numFrames;
  228379. }
  228380. void repaint()
  228381. {
  228382. }
  228383. void createGLBuffers()
  228384. {
  228385. makeActive();
  228386. glGenFramebuffersOES (1, &frameBufferHandle);
  228387. glGenRenderbuffersOES (1, &colorBufferHandle);
  228388. glGenRenderbuffersOES (1, &depthBufferHandle);
  228389. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228390. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228391. GLint width, height;
  228392. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228393. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228394. if (useDepthBuffer)
  228395. {
  228396. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228397. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228398. }
  228399. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228400. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228401. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228402. if (useDepthBuffer)
  228403. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228404. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228405. }
  228406. void freeGLBuffers()
  228407. {
  228408. if (frameBufferHandle != 0)
  228409. {
  228410. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228411. frameBufferHandle = 0;
  228412. }
  228413. if (colorBufferHandle != 0)
  228414. {
  228415. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228416. colorBufferHandle = 0;
  228417. }
  228418. if (depthBufferHandle != 0)
  228419. {
  228420. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228421. depthBufferHandle = 0;
  228422. }
  228423. }
  228424. private:
  228425. WeakReference<Component> component;
  228426. OpenGLPixelFormat pixelFormat;
  228427. JuceGLView* view;
  228428. CAEAGLLayer* glLayer;
  228429. EAGLContext* context;
  228430. bool useDepthBuffer;
  228431. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228432. int numFrames;
  228433. int lastWidth, lastHeight;
  228434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228435. };
  228436. OpenGLContext* OpenGLComponent::createContext()
  228437. {
  228438. ScopedAutoReleasePool pool;
  228439. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228440. if (peer != 0)
  228441. return new GLESContext (peer, this, preferredPixelFormat,
  228442. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228443. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228444. return 0;
  228445. }
  228446. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228447. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228448. {
  228449. }
  228450. void juce_glViewport (const int w, const int h)
  228451. {
  228452. glViewport (0, 0, w, h);
  228453. }
  228454. #endif
  228455. #endif
  228456. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228457. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228458. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228459. // compiled on its own).
  228460. #if JUCE_INCLUDED_FILE
  228461. #if JUCE_MAC
  228462. namespace MouseCursorHelpers
  228463. {
  228464. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228465. {
  228466. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228467. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228468. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228469. [im release];
  228470. return c;
  228471. }
  228472. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228473. {
  228474. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228475. BufferedInputStream buf (fileStream, 4096);
  228476. PNGImageFormat pngFormat;
  228477. Image im (pngFormat.decodeImage (buf));
  228478. if (im.isValid())
  228479. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228480. jassertfalse;
  228481. return 0;
  228482. }
  228483. }
  228484. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228485. {
  228486. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228487. }
  228488. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228489. {
  228490. const ScopedAutoReleasePool pool;
  228491. NSCursor* c = 0;
  228492. switch (type)
  228493. {
  228494. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228495. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228496. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228497. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228498. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228499. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228500. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228501. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228502. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228503. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228504. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228505. case UpDownResizeCursor:
  228506. case TopEdgeResizeCursor:
  228507. case BottomEdgeResizeCursor:
  228508. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228509. case TopLeftCornerResizeCursor:
  228510. case BottomRightCornerResizeCursor:
  228511. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228512. case TopRightCornerResizeCursor:
  228513. case BottomLeftCornerResizeCursor:
  228514. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228515. case UpDownLeftRightResizeCursor:
  228516. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228517. default:
  228518. jassertfalse;
  228519. break;
  228520. }
  228521. [c retain];
  228522. return c;
  228523. }
  228524. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228525. {
  228526. [((NSCursor*) cursorHandle) release];
  228527. }
  228528. void MouseCursor::showInAllWindows() const
  228529. {
  228530. showInWindow (0);
  228531. }
  228532. void MouseCursor::showInWindow (ComponentPeer*) const
  228533. {
  228534. NSCursor* c = (NSCursor*) getHandle();
  228535. if (c == 0)
  228536. c = [NSCursor arrowCursor];
  228537. [c set];
  228538. }
  228539. #else
  228540. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228541. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228542. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228543. void MouseCursor::showInAllWindows() const {}
  228544. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228545. #endif
  228546. #endif
  228547. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228548. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228549. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228550. // compiled on its own).
  228551. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228552. #if JUCE_MAC
  228553. END_JUCE_NAMESPACE
  228554. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228555. @interface DownloadClickDetector : NSObject
  228556. {
  228557. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228558. }
  228559. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228560. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228561. request: (NSURLRequest*) request
  228562. frame: (WebFrame*) frame
  228563. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228564. @end
  228565. @implementation DownloadClickDetector
  228566. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228567. {
  228568. [super init];
  228569. ownerComponent = ownerComponent_;
  228570. return self;
  228571. }
  228572. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228573. request: (NSURLRequest*) request
  228574. frame: (WebFrame*) frame
  228575. decisionListener: (id <WebPolicyDecisionListener>) listener
  228576. {
  228577. (void) sender;
  228578. (void) request;
  228579. (void) frame;
  228580. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228581. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228582. [listener use];
  228583. else
  228584. [listener ignore];
  228585. }
  228586. @end
  228587. BEGIN_JUCE_NAMESPACE
  228588. class WebBrowserComponentInternal : public NSViewComponent
  228589. {
  228590. public:
  228591. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228592. {
  228593. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228594. frameName: @""
  228595. groupName: @""];
  228596. setView (webView);
  228597. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228598. [webView setPolicyDelegate: clickListener];
  228599. }
  228600. ~WebBrowserComponentInternal()
  228601. {
  228602. [webView setPolicyDelegate: nil];
  228603. [clickListener release];
  228604. setView (0);
  228605. }
  228606. void goToURL (const String& url,
  228607. const StringArray* headers,
  228608. const MemoryBlock* postData)
  228609. {
  228610. NSMutableURLRequest* r
  228611. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228612. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228613. timeoutInterval: 30.0];
  228614. if (postData != 0 && postData->getSize() > 0)
  228615. {
  228616. [r setHTTPMethod: @"POST"];
  228617. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228618. length: postData->getSize()]];
  228619. }
  228620. if (headers != 0)
  228621. {
  228622. for (int i = 0; i < headers->size(); ++i)
  228623. {
  228624. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228625. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228626. [r setValue: juceStringToNS (headerValue)
  228627. forHTTPHeaderField: juceStringToNS (headerName)];
  228628. }
  228629. }
  228630. stop();
  228631. [[webView mainFrame] loadRequest: r];
  228632. }
  228633. void goBack()
  228634. {
  228635. [webView goBack];
  228636. }
  228637. void goForward()
  228638. {
  228639. [webView goForward];
  228640. }
  228641. void stop()
  228642. {
  228643. [webView stopLoading: nil];
  228644. }
  228645. void refresh()
  228646. {
  228647. [webView reload: nil];
  228648. }
  228649. void mouseMove (const MouseEvent&)
  228650. {
  228651. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228652. // them work is to push them via this non-public method..
  228653. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228654. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228655. }
  228656. private:
  228657. WebView* webView;
  228658. DownloadClickDetector* clickListener;
  228659. };
  228660. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228661. : browser (0),
  228662. blankPageShown (false),
  228663. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228664. {
  228665. setOpaque (true);
  228666. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228667. }
  228668. WebBrowserComponent::~WebBrowserComponent()
  228669. {
  228670. deleteAndZero (browser);
  228671. }
  228672. void WebBrowserComponent::goToURL (const String& url,
  228673. const StringArray* headers,
  228674. const MemoryBlock* postData)
  228675. {
  228676. lastURL = url;
  228677. lastHeaders.clear();
  228678. if (headers != 0)
  228679. lastHeaders = *headers;
  228680. lastPostData.setSize (0);
  228681. if (postData != 0)
  228682. lastPostData = *postData;
  228683. blankPageShown = false;
  228684. browser->goToURL (url, headers, postData);
  228685. }
  228686. void WebBrowserComponent::stop()
  228687. {
  228688. browser->stop();
  228689. }
  228690. void WebBrowserComponent::goBack()
  228691. {
  228692. lastURL = String::empty;
  228693. blankPageShown = false;
  228694. browser->goBack();
  228695. }
  228696. void WebBrowserComponent::goForward()
  228697. {
  228698. lastURL = String::empty;
  228699. browser->goForward();
  228700. }
  228701. void WebBrowserComponent::refresh()
  228702. {
  228703. browser->refresh();
  228704. }
  228705. void WebBrowserComponent::paint (Graphics&)
  228706. {
  228707. }
  228708. void WebBrowserComponent::checkWindowAssociation()
  228709. {
  228710. if (isShowing())
  228711. {
  228712. if (blankPageShown)
  228713. goBack();
  228714. }
  228715. else
  228716. {
  228717. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228718. {
  228719. // when the component becomes invisible, some stuff like flash
  228720. // carries on playing audio, so we need to force it onto a blank
  228721. // page to avoid this, (and send it back when it's made visible again).
  228722. blankPageShown = true;
  228723. browser->goToURL ("about:blank", 0, 0);
  228724. }
  228725. }
  228726. }
  228727. void WebBrowserComponent::reloadLastURL()
  228728. {
  228729. if (lastURL.isNotEmpty())
  228730. {
  228731. goToURL (lastURL, &lastHeaders, &lastPostData);
  228732. lastURL = String::empty;
  228733. }
  228734. }
  228735. void WebBrowserComponent::parentHierarchyChanged()
  228736. {
  228737. checkWindowAssociation();
  228738. }
  228739. void WebBrowserComponent::resized()
  228740. {
  228741. browser->setSize (getWidth(), getHeight());
  228742. }
  228743. void WebBrowserComponent::visibilityChanged()
  228744. {
  228745. checkWindowAssociation();
  228746. }
  228747. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228748. {
  228749. return true;
  228750. }
  228751. #else
  228752. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228753. {
  228754. }
  228755. WebBrowserComponent::~WebBrowserComponent()
  228756. {
  228757. }
  228758. void WebBrowserComponent::goToURL (const String& url,
  228759. const StringArray* headers,
  228760. const MemoryBlock* postData)
  228761. {
  228762. }
  228763. void WebBrowserComponent::stop()
  228764. {
  228765. }
  228766. void WebBrowserComponent::goBack()
  228767. {
  228768. }
  228769. void WebBrowserComponent::goForward()
  228770. {
  228771. }
  228772. void WebBrowserComponent::refresh()
  228773. {
  228774. }
  228775. void WebBrowserComponent::paint (Graphics& g)
  228776. {
  228777. }
  228778. void WebBrowserComponent::checkWindowAssociation()
  228779. {
  228780. }
  228781. void WebBrowserComponent::reloadLastURL()
  228782. {
  228783. }
  228784. void WebBrowserComponent::parentHierarchyChanged()
  228785. {
  228786. }
  228787. void WebBrowserComponent::resized()
  228788. {
  228789. }
  228790. void WebBrowserComponent::visibilityChanged()
  228791. {
  228792. }
  228793. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228794. {
  228795. return true;
  228796. }
  228797. #endif
  228798. #endif
  228799. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228800. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228801. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228802. // compiled on its own).
  228803. #if JUCE_INCLUDED_FILE
  228804. class IPhoneAudioIODevice : public AudioIODevice
  228805. {
  228806. public:
  228807. IPhoneAudioIODevice (const String& deviceName)
  228808. : AudioIODevice (deviceName, "Audio"),
  228809. actualBufferSize (0),
  228810. isRunning (false),
  228811. audioUnit (0),
  228812. callback (0),
  228813. floatData (1, 2)
  228814. {
  228815. numInputChannels = 2;
  228816. numOutputChannels = 2;
  228817. preferredBufferSize = 0;
  228818. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228819. updateDeviceInfo();
  228820. }
  228821. ~IPhoneAudioIODevice()
  228822. {
  228823. close();
  228824. }
  228825. const StringArray getOutputChannelNames()
  228826. {
  228827. StringArray s;
  228828. s.add ("Left");
  228829. s.add ("Right");
  228830. return s;
  228831. }
  228832. const StringArray getInputChannelNames()
  228833. {
  228834. StringArray s;
  228835. if (audioInputIsAvailable)
  228836. {
  228837. s.add ("Left");
  228838. s.add ("Right");
  228839. }
  228840. return s;
  228841. }
  228842. int getNumSampleRates()
  228843. {
  228844. return 1;
  228845. }
  228846. double getSampleRate (int index)
  228847. {
  228848. return sampleRate;
  228849. }
  228850. int getNumBufferSizesAvailable()
  228851. {
  228852. return 1;
  228853. }
  228854. int getBufferSizeSamples (int index)
  228855. {
  228856. return getDefaultBufferSize();
  228857. }
  228858. int getDefaultBufferSize()
  228859. {
  228860. return 1024;
  228861. }
  228862. const String open (const BigInteger& inputChannels,
  228863. const BigInteger& outputChannels,
  228864. double sampleRate,
  228865. int bufferSize)
  228866. {
  228867. close();
  228868. lastError = String::empty;
  228869. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228870. // xxx set up channel mapping
  228871. activeOutputChans = outputChannels;
  228872. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228873. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228874. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228875. activeInputChans = inputChannels;
  228876. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228877. numInputChannels = activeInputChans.countNumberOfSetBits();
  228878. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228879. AudioSessionSetActive (true);
  228880. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228881. : kAudioSessionCategory_MediaPlayback;
  228882. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228883. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228884. fixAudioRouteIfSetToReceiver();
  228885. updateDeviceInfo();
  228886. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228887. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228888. actualBufferSize = preferredBufferSize;
  228889. prepareFloatBuffers();
  228890. isRunning = true;
  228891. propertyChanged (0, 0, 0); // creates and starts the AU
  228892. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228893. return lastError;
  228894. }
  228895. void close()
  228896. {
  228897. if (isRunning)
  228898. {
  228899. isRunning = false;
  228900. AudioSessionSetActive (false);
  228901. if (audioUnit != 0)
  228902. {
  228903. AudioComponentInstanceDispose (audioUnit);
  228904. audioUnit = 0;
  228905. }
  228906. }
  228907. }
  228908. bool isOpen()
  228909. {
  228910. return isRunning;
  228911. }
  228912. int getCurrentBufferSizeSamples()
  228913. {
  228914. return actualBufferSize;
  228915. }
  228916. double getCurrentSampleRate()
  228917. {
  228918. return sampleRate;
  228919. }
  228920. int getCurrentBitDepth()
  228921. {
  228922. return 16;
  228923. }
  228924. const BigInteger getActiveOutputChannels() const
  228925. {
  228926. return activeOutputChans;
  228927. }
  228928. const BigInteger getActiveInputChannels() const
  228929. {
  228930. return activeInputChans;
  228931. }
  228932. int getOutputLatencyInSamples()
  228933. {
  228934. return 0; //xxx
  228935. }
  228936. int getInputLatencyInSamples()
  228937. {
  228938. return 0; //xxx
  228939. }
  228940. void start (AudioIODeviceCallback* callback_)
  228941. {
  228942. if (isRunning && callback != callback_)
  228943. {
  228944. if (callback_ != 0)
  228945. callback_->audioDeviceAboutToStart (this);
  228946. const ScopedLock sl (callbackLock);
  228947. callback = callback_;
  228948. }
  228949. }
  228950. void stop()
  228951. {
  228952. if (isRunning)
  228953. {
  228954. AudioIODeviceCallback* lastCallback;
  228955. {
  228956. const ScopedLock sl (callbackLock);
  228957. lastCallback = callback;
  228958. callback = 0;
  228959. }
  228960. if (lastCallback != 0)
  228961. lastCallback->audioDeviceStopped();
  228962. }
  228963. }
  228964. bool isPlaying()
  228965. {
  228966. return isRunning && callback != 0;
  228967. }
  228968. const String getLastError()
  228969. {
  228970. return lastError;
  228971. }
  228972. private:
  228973. CriticalSection callbackLock;
  228974. Float64 sampleRate;
  228975. int numInputChannels, numOutputChannels;
  228976. int preferredBufferSize;
  228977. int actualBufferSize;
  228978. bool isRunning;
  228979. String lastError;
  228980. AudioStreamBasicDescription format;
  228981. AudioUnit audioUnit;
  228982. UInt32 audioInputIsAvailable;
  228983. AudioIODeviceCallback* callback;
  228984. BigInteger activeOutputChans, activeInputChans;
  228985. AudioSampleBuffer floatData;
  228986. float* inputChannels[3];
  228987. float* outputChannels[3];
  228988. bool monoInputChannelNumber, monoOutputChannelNumber;
  228989. void prepareFloatBuffers()
  228990. {
  228991. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228992. zerostruct (inputChannels);
  228993. zerostruct (outputChannels);
  228994. for (int i = 0; i < numInputChannels; ++i)
  228995. inputChannels[i] = floatData.getSampleData (i);
  228996. for (int i = 0; i < numOutputChannels; ++i)
  228997. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228998. }
  228999. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229000. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229001. {
  229002. OSStatus err = noErr;
  229003. if (audioInputIsAvailable)
  229004. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229005. const ScopedLock sl (callbackLock);
  229006. if (callback != 0)
  229007. {
  229008. if (audioInputIsAvailable && numInputChannels > 0)
  229009. {
  229010. short* shortData = (short*) ioData->mBuffers[0].mData;
  229011. if (numInputChannels >= 2)
  229012. {
  229013. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229014. {
  229015. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229016. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229017. }
  229018. }
  229019. else
  229020. {
  229021. if (monoInputChannelNumber > 0)
  229022. ++shortData;
  229023. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229024. {
  229025. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229026. ++shortData;
  229027. }
  229028. }
  229029. }
  229030. else
  229031. {
  229032. for (int i = numInputChannels; --i >= 0;)
  229033. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229034. }
  229035. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229036. outputChannels, numOutputChannels,
  229037. (int) inNumberFrames);
  229038. short* shortData = (short*) ioData->mBuffers[0].mData;
  229039. int n = 0;
  229040. if (numOutputChannels >= 2)
  229041. {
  229042. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229043. {
  229044. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229045. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229046. }
  229047. }
  229048. else if (numOutputChannels == 1)
  229049. {
  229050. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229051. {
  229052. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229053. shortData [n++] = s;
  229054. shortData [n++] = s;
  229055. }
  229056. }
  229057. else
  229058. {
  229059. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229060. }
  229061. }
  229062. else
  229063. {
  229064. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229065. }
  229066. return err;
  229067. }
  229068. void updateDeviceInfo()
  229069. {
  229070. UInt32 size = sizeof (sampleRate);
  229071. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229072. size = sizeof (audioInputIsAvailable);
  229073. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229074. }
  229075. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229076. {
  229077. if (! isRunning)
  229078. return;
  229079. if (inPropertyValue != 0)
  229080. {
  229081. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229082. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229083. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229084. SInt32 routeChangeReason;
  229085. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229086. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229087. fixAudioRouteIfSetToReceiver();
  229088. }
  229089. updateDeviceInfo();
  229090. createAudioUnit();
  229091. AudioSessionSetActive (true);
  229092. if (audioUnit != 0)
  229093. {
  229094. UInt32 formatSize = sizeof (format);
  229095. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229096. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229097. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229098. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229099. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229100. AudioOutputUnitStart (audioUnit);
  229101. }
  229102. }
  229103. void interruptionListener (UInt32 inInterruption)
  229104. {
  229105. /*if (inInterruption == kAudioSessionBeginInterruption)
  229106. {
  229107. isRunning = false;
  229108. AudioOutputUnitStop (audioUnit);
  229109. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229110. "This could have been interrupted by another application or by unplugging a headset",
  229111. @"Resume",
  229112. @"Cancel"))
  229113. {
  229114. isRunning = true;
  229115. propertyChanged (0, 0, 0);
  229116. }
  229117. }*/
  229118. if (inInterruption == kAudioSessionEndInterruption)
  229119. {
  229120. isRunning = true;
  229121. AudioSessionSetActive (true);
  229122. AudioOutputUnitStart (audioUnit);
  229123. }
  229124. }
  229125. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229126. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229127. {
  229128. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229129. }
  229130. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229131. {
  229132. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229133. }
  229134. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229135. {
  229136. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229137. }
  229138. void resetFormat (const int numChannels)
  229139. {
  229140. memset (&format, 0, sizeof (format));
  229141. format.mFormatID = kAudioFormatLinearPCM;
  229142. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229143. format.mBitsPerChannel = 8 * sizeof (short);
  229144. format.mChannelsPerFrame = 2;
  229145. format.mFramesPerPacket = 1;
  229146. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229147. }
  229148. bool createAudioUnit()
  229149. {
  229150. if (audioUnit != 0)
  229151. {
  229152. AudioComponentInstanceDispose (audioUnit);
  229153. audioUnit = 0;
  229154. }
  229155. resetFormat (2);
  229156. AudioComponentDescription desc;
  229157. desc.componentType = kAudioUnitType_Output;
  229158. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229159. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229160. desc.componentFlags = 0;
  229161. desc.componentFlagsMask = 0;
  229162. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229163. AudioComponentInstanceNew (comp, &audioUnit);
  229164. if (audioUnit == 0)
  229165. return false;
  229166. const UInt32 one = 1;
  229167. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229168. AudioChannelLayout layout;
  229169. layout.mChannelBitmap = 0;
  229170. layout.mNumberChannelDescriptions = 0;
  229171. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229172. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229173. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229174. AURenderCallbackStruct inputProc;
  229175. inputProc.inputProc = processStatic;
  229176. inputProc.inputProcRefCon = this;
  229177. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229178. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229179. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229180. AudioUnitInitialize (audioUnit);
  229181. return true;
  229182. }
  229183. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229184. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229185. static void fixAudioRouteIfSetToReceiver()
  229186. {
  229187. CFStringRef audioRoute = 0;
  229188. UInt32 propertySize = sizeof (audioRoute);
  229189. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229190. {
  229191. NSString* route = (NSString*) audioRoute;
  229192. //DBG ("audio route: " + nsStringToJuce (route));
  229193. if ([route hasPrefix: @"Receiver"])
  229194. {
  229195. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229196. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229197. }
  229198. CFRelease (audioRoute);
  229199. }
  229200. }
  229201. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  229202. };
  229203. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229204. {
  229205. public:
  229206. IPhoneAudioIODeviceType()
  229207. : AudioIODeviceType ("iPhone Audio")
  229208. {
  229209. }
  229210. void scanForDevices()
  229211. {
  229212. }
  229213. const StringArray getDeviceNames (bool wantInputNames) const
  229214. {
  229215. StringArray s;
  229216. s.add ("iPhone Audio");
  229217. return s;
  229218. }
  229219. int getDefaultDeviceIndex (bool forInput) const
  229220. {
  229221. return 0;
  229222. }
  229223. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229224. {
  229225. return device != 0 ? 0 : -1;
  229226. }
  229227. bool hasSeparateInputsAndOutputs() const { return false; }
  229228. AudioIODevice* createDevice (const String& outputDeviceName,
  229229. const String& inputDeviceName)
  229230. {
  229231. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229232. {
  229233. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229234. : inputDeviceName);
  229235. }
  229236. return 0;
  229237. }
  229238. private:
  229239. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  229240. };
  229241. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()
  229242. {
  229243. return new IPhoneAudioIODeviceType();
  229244. }
  229245. #endif
  229246. /*** End of inlined file: juce_ios_Audio.cpp ***/
  229247. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229248. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229249. // compiled on its own).
  229250. #if JUCE_INCLUDED_FILE
  229251. #if JUCE_MAC
  229252. namespace CoreMidiHelpers
  229253. {
  229254. bool logError (const OSStatus err, const int lineNum)
  229255. {
  229256. if (err == noErr)
  229257. return true;
  229258. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229259. jassertfalse;
  229260. return false;
  229261. }
  229262. #undef CHECK_ERROR
  229263. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229264. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229265. {
  229266. String result;
  229267. CFStringRef str = 0;
  229268. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229269. if (str != 0)
  229270. {
  229271. result = PlatformUtilities::cfStringToJuceString (str);
  229272. CFRelease (str);
  229273. str = 0;
  229274. }
  229275. MIDIEntityRef entity = 0;
  229276. MIDIEndpointGetEntity (endpoint, &entity);
  229277. if (entity == 0)
  229278. return result; // probably virtual
  229279. if (result.isEmpty())
  229280. {
  229281. // endpoint name has zero length - try the entity
  229282. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229283. if (str != 0)
  229284. {
  229285. result += PlatformUtilities::cfStringToJuceString (str);
  229286. CFRelease (str);
  229287. str = 0;
  229288. }
  229289. }
  229290. // now consider the device's name
  229291. MIDIDeviceRef device = 0;
  229292. MIDIEntityGetDevice (entity, &device);
  229293. if (device == 0)
  229294. return result;
  229295. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229296. if (str != 0)
  229297. {
  229298. const String s (PlatformUtilities::cfStringToJuceString (str));
  229299. CFRelease (str);
  229300. // if an external device has only one entity, throw away
  229301. // the endpoint name and just use the device name
  229302. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229303. {
  229304. result = s;
  229305. }
  229306. else if (! result.startsWithIgnoreCase (s))
  229307. {
  229308. // prepend the device name to the entity name
  229309. result = (s + " " + result).trimEnd();
  229310. }
  229311. }
  229312. return result;
  229313. }
  229314. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229315. {
  229316. String result;
  229317. // Does the endpoint have connections?
  229318. CFDataRef connections = 0;
  229319. int numConnections = 0;
  229320. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229321. if (connections != 0)
  229322. {
  229323. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229324. if (numConnections > 0)
  229325. {
  229326. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229327. for (int i = 0; i < numConnections; ++i, ++pid)
  229328. {
  229329. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229330. MIDIObjectRef connObject;
  229331. MIDIObjectType connObjectType;
  229332. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229333. if (err == noErr)
  229334. {
  229335. String s;
  229336. if (connObjectType == kMIDIObjectType_ExternalSource
  229337. || connObjectType == kMIDIObjectType_ExternalDestination)
  229338. {
  229339. // Connected to an external device's endpoint (10.3 and later).
  229340. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229341. }
  229342. else
  229343. {
  229344. // Connected to an external device (10.2) (or something else, catch-all)
  229345. CFStringRef str = 0;
  229346. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229347. if (str != 0)
  229348. {
  229349. s = PlatformUtilities::cfStringToJuceString (str);
  229350. CFRelease (str);
  229351. }
  229352. }
  229353. if (s.isNotEmpty())
  229354. {
  229355. if (result.isNotEmpty())
  229356. result += ", ";
  229357. result += s;
  229358. }
  229359. }
  229360. }
  229361. }
  229362. CFRelease (connections);
  229363. }
  229364. if (result.isNotEmpty())
  229365. return result;
  229366. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229367. return getEndpointName (endpoint, false);
  229368. }
  229369. MIDIClientRef getGlobalMidiClient()
  229370. {
  229371. static MIDIClientRef globalMidiClient = 0;
  229372. if (globalMidiClient == 0)
  229373. {
  229374. String name ("JUCE");
  229375. if (JUCEApplication::getInstance() != 0)
  229376. name = JUCEApplication::getInstance()->getApplicationName();
  229377. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229378. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229379. CFRelease (appName);
  229380. }
  229381. return globalMidiClient;
  229382. }
  229383. class MidiPortAndEndpoint
  229384. {
  229385. public:
  229386. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229387. : port (port_), endPoint (endPoint_)
  229388. {
  229389. }
  229390. ~MidiPortAndEndpoint()
  229391. {
  229392. if (port != 0)
  229393. MIDIPortDispose (port);
  229394. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229395. MIDIEndpointDispose (endPoint);
  229396. }
  229397. void send (const MIDIPacketList* const packets)
  229398. {
  229399. if (port != 0)
  229400. MIDISend (port, endPoint, packets);
  229401. else
  229402. MIDIReceived (endPoint, packets);
  229403. }
  229404. MIDIPortRef port;
  229405. MIDIEndpointRef endPoint;
  229406. };
  229407. class MidiPortAndCallback;
  229408. CriticalSection callbackLock;
  229409. Array<MidiPortAndCallback*> activeCallbacks;
  229410. class MidiPortAndCallback
  229411. {
  229412. public:
  229413. MidiPortAndCallback (MidiInputCallback& callback_)
  229414. : input (0), active (false), callback (callback_), concatenator (2048)
  229415. {
  229416. }
  229417. ~MidiPortAndCallback()
  229418. {
  229419. active = false;
  229420. {
  229421. const ScopedLock sl (callbackLock);
  229422. activeCallbacks.removeValue (this);
  229423. }
  229424. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229425. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229426. }
  229427. void handlePackets (const MIDIPacketList* const pktlist)
  229428. {
  229429. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229430. const ScopedLock sl (callbackLock);
  229431. if (activeCallbacks.contains (this) && active)
  229432. {
  229433. const MIDIPacket* packet = &pktlist->packet[0];
  229434. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229435. {
  229436. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229437. input, callback);
  229438. packet = MIDIPacketNext (packet);
  229439. }
  229440. }
  229441. }
  229442. MidiInput* input;
  229443. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229444. volatile bool active;
  229445. private:
  229446. MidiInputCallback& callback;
  229447. MidiDataConcatenator concatenator;
  229448. };
  229449. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229450. {
  229451. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229452. }
  229453. }
  229454. const StringArray MidiOutput::getDevices()
  229455. {
  229456. StringArray s;
  229457. const ItemCount num = MIDIGetNumberOfDestinations();
  229458. for (ItemCount i = 0; i < num; ++i)
  229459. {
  229460. MIDIEndpointRef dest = MIDIGetDestination (i);
  229461. if (dest != 0)
  229462. {
  229463. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229464. if (name.isEmpty())
  229465. name = "<error>";
  229466. s.add (name);
  229467. }
  229468. else
  229469. {
  229470. s.add ("<error>");
  229471. }
  229472. }
  229473. return s;
  229474. }
  229475. int MidiOutput::getDefaultDeviceIndex()
  229476. {
  229477. return 0;
  229478. }
  229479. MidiOutput* MidiOutput::openDevice (int index)
  229480. {
  229481. MidiOutput* mo = 0;
  229482. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229483. {
  229484. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229485. CFStringRef pname;
  229486. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229487. {
  229488. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229489. MIDIPortRef port;
  229490. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229491. {
  229492. mo = new MidiOutput();
  229493. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229494. }
  229495. CFRelease (pname);
  229496. }
  229497. }
  229498. return mo;
  229499. }
  229500. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229501. {
  229502. MidiOutput* mo = 0;
  229503. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229504. MIDIEndpointRef endPoint;
  229505. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229506. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229507. {
  229508. mo = new MidiOutput();
  229509. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229510. }
  229511. CFRelease (name);
  229512. return mo;
  229513. }
  229514. MidiOutput::~MidiOutput()
  229515. {
  229516. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229517. }
  229518. void MidiOutput::reset()
  229519. {
  229520. }
  229521. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229522. {
  229523. return false;
  229524. }
  229525. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229526. {
  229527. }
  229528. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229529. {
  229530. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229531. if (message.isSysEx())
  229532. {
  229533. const int maxPacketSize = 256;
  229534. int pos = 0, bytesLeft = message.getRawDataSize();
  229535. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229536. HeapBlock <MIDIPacketList> packets;
  229537. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229538. packets->numPackets = numPackets;
  229539. MIDIPacket* p = packets->packet;
  229540. for (int i = 0; i < numPackets; ++i)
  229541. {
  229542. p->timeStamp = AudioGetCurrentHostTime();
  229543. p->length = jmin (maxPacketSize, bytesLeft);
  229544. memcpy (p->data, message.getRawData() + pos, p->length);
  229545. pos += p->length;
  229546. bytesLeft -= p->length;
  229547. p = MIDIPacketNext (p);
  229548. }
  229549. mpe->send (packets);
  229550. }
  229551. else
  229552. {
  229553. MIDIPacketList packets;
  229554. packets.numPackets = 1;
  229555. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229556. packets.packet[0].length = message.getRawDataSize();
  229557. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229558. mpe->send (&packets);
  229559. }
  229560. }
  229561. const StringArray MidiInput::getDevices()
  229562. {
  229563. StringArray s;
  229564. const ItemCount num = MIDIGetNumberOfSources();
  229565. for (ItemCount i = 0; i < num; ++i)
  229566. {
  229567. MIDIEndpointRef source = MIDIGetSource (i);
  229568. if (source != 0)
  229569. {
  229570. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229571. if (name.isEmpty())
  229572. name = "<error>";
  229573. s.add (name);
  229574. }
  229575. else
  229576. {
  229577. s.add ("<error>");
  229578. }
  229579. }
  229580. return s;
  229581. }
  229582. int MidiInput::getDefaultDeviceIndex()
  229583. {
  229584. return 0;
  229585. }
  229586. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229587. {
  229588. jassert (callback != 0);
  229589. using namespace CoreMidiHelpers;
  229590. MidiInput* newInput = 0;
  229591. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229592. {
  229593. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229594. if (endPoint != 0)
  229595. {
  229596. CFStringRef name;
  229597. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229598. {
  229599. MIDIClientRef client = getGlobalMidiClient();
  229600. if (client != 0)
  229601. {
  229602. MIDIPortRef port;
  229603. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229604. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229605. {
  229606. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229607. {
  229608. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229609. newInput = new MidiInput (getDevices() [index]);
  229610. mpc->input = newInput;
  229611. newInput->internal = mpc;
  229612. const ScopedLock sl (callbackLock);
  229613. activeCallbacks.add (mpc.release());
  229614. }
  229615. else
  229616. {
  229617. CHECK_ERROR (MIDIPortDispose (port));
  229618. }
  229619. }
  229620. }
  229621. }
  229622. CFRelease (name);
  229623. }
  229624. }
  229625. return newInput;
  229626. }
  229627. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229628. {
  229629. jassert (callback != 0);
  229630. using namespace CoreMidiHelpers;
  229631. MidiInput* mi = 0;
  229632. MIDIClientRef client = getGlobalMidiClient();
  229633. if (client != 0)
  229634. {
  229635. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229636. mpc->active = false;
  229637. MIDIEndpointRef endPoint;
  229638. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229639. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229640. {
  229641. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229642. mi = new MidiInput (deviceName);
  229643. mpc->input = mi;
  229644. mi->internal = mpc;
  229645. const ScopedLock sl (callbackLock);
  229646. activeCallbacks.add (mpc.release());
  229647. }
  229648. CFRelease (name);
  229649. }
  229650. return mi;
  229651. }
  229652. MidiInput::MidiInput (const String& name_)
  229653. : name (name_)
  229654. {
  229655. }
  229656. MidiInput::~MidiInput()
  229657. {
  229658. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229659. }
  229660. void MidiInput::start()
  229661. {
  229662. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229663. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229664. }
  229665. void MidiInput::stop()
  229666. {
  229667. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229668. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229669. }
  229670. #undef CHECK_ERROR
  229671. #else // Stubs for iOS...
  229672. MidiOutput::~MidiOutput() {}
  229673. void MidiOutput::reset() {}
  229674. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229675. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229676. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229677. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229678. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229679. const StringArray MidiInput::getDevices() { return StringArray(); }
  229680. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229681. #endif
  229682. #endif
  229683. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229684. #else
  229685. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229686. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229687. // compiled on its own).
  229688. #if JUCE_INCLUDED_FILE
  229689. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229690. #define SUPPORT_10_4_FONTS 1
  229691. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229692. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229693. #define SUPPORT_ONLY_10_4_FONTS 1
  229694. #endif
  229695. END_JUCE_NAMESPACE
  229696. @interface NSFont (PrivateHack)
  229697. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229698. @end
  229699. BEGIN_JUCE_NAMESPACE
  229700. #endif
  229701. class MacTypeface : public Typeface
  229702. {
  229703. public:
  229704. MacTypeface (const Font& font)
  229705. : Typeface (font.getTypefaceName())
  229706. {
  229707. const ScopedAutoReleasePool pool;
  229708. renderingTransform = CGAffineTransformIdentity;
  229709. bool needsItalicTransform = false;
  229710. #if JUCE_IOS
  229711. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229712. if (font.isItalic() || font.isBold())
  229713. {
  229714. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229715. for (NSString* i in familyFonts)
  229716. {
  229717. const String fn (nsStringToJuce (i));
  229718. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229719. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229720. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229721. || afterDash.containsIgnoreCase ("italic")
  229722. || fn.endsWithIgnoreCase ("oblique")
  229723. || fn.endsWithIgnoreCase ("italic");
  229724. if (probablyBold == font.isBold()
  229725. && probablyItalic == font.isItalic())
  229726. {
  229727. fontName = i;
  229728. needsItalicTransform = false;
  229729. break;
  229730. }
  229731. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229732. {
  229733. fontName = i;
  229734. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229735. }
  229736. }
  229737. if (needsItalicTransform)
  229738. renderingTransform.c = 0.15f;
  229739. }
  229740. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229741. const int ascender = abs (CGFontGetAscent (fontRef));
  229742. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229743. ascent = ascender / totalHeight;
  229744. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229745. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229746. #else
  229747. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229748. if (font.isItalic())
  229749. {
  229750. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229751. toHaveTrait: NSItalicFontMask];
  229752. if (newFont == nsFont)
  229753. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229754. nsFont = newFont;
  229755. }
  229756. if (font.isBold())
  229757. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229758. [nsFont retain];
  229759. ascent = std::abs ((float) [nsFont ascender]);
  229760. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229761. ascent /= totalSize;
  229762. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229763. if (needsItalicTransform)
  229764. {
  229765. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229766. renderingTransform.c = 0.15f;
  229767. }
  229768. #if SUPPORT_ONLY_10_4_FONTS
  229769. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229770. if (atsFont == 0)
  229771. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229772. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229773. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229774. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229775. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229776. #else
  229777. #if SUPPORT_10_4_FONTS
  229778. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229779. {
  229780. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229781. if (atsFont == 0)
  229782. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229783. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229784. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229785. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229786. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229787. }
  229788. else
  229789. #endif
  229790. {
  229791. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229792. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229793. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229794. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229795. }
  229796. #endif
  229797. #endif
  229798. }
  229799. ~MacTypeface()
  229800. {
  229801. #if ! JUCE_IOS
  229802. [nsFont release];
  229803. #endif
  229804. if (fontRef != 0)
  229805. CGFontRelease (fontRef);
  229806. }
  229807. float getAscent() const
  229808. {
  229809. return ascent;
  229810. }
  229811. float getDescent() const
  229812. {
  229813. return 1.0f - ascent;
  229814. }
  229815. float getStringWidth (const String& text)
  229816. {
  229817. if (fontRef == 0 || text.isEmpty())
  229818. return 0;
  229819. const int length = text.length();
  229820. HeapBlock <CGGlyph> glyphs;
  229821. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229822. float x = 0;
  229823. #if SUPPORT_ONLY_10_4_FONTS
  229824. HeapBlock <NSSize> advances (length);
  229825. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229826. for (int i = 0; i < length; ++i)
  229827. x += advances[i].width;
  229828. #else
  229829. #if SUPPORT_10_4_FONTS
  229830. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229831. {
  229832. HeapBlock <NSSize> advances (length);
  229833. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229834. for (int i = 0; i < length; ++i)
  229835. x += advances[i].width;
  229836. }
  229837. else
  229838. #endif
  229839. {
  229840. HeapBlock <int> advances (length);
  229841. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229842. for (int i = 0; i < length; ++i)
  229843. x += advances[i];
  229844. }
  229845. #endif
  229846. return x * unitsToHeightScaleFactor;
  229847. }
  229848. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229849. {
  229850. xOffsets.add (0);
  229851. if (fontRef == 0 || text.isEmpty())
  229852. return;
  229853. const int length = text.length();
  229854. HeapBlock <CGGlyph> glyphs;
  229855. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229856. #if SUPPORT_ONLY_10_4_FONTS
  229857. HeapBlock <NSSize> advances (length);
  229858. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229859. int x = 0;
  229860. for (int i = 0; i < length; ++i)
  229861. {
  229862. x += advances[i].width;
  229863. xOffsets.add (x * unitsToHeightScaleFactor);
  229864. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229865. }
  229866. #else
  229867. #if SUPPORT_10_4_FONTS
  229868. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229869. {
  229870. HeapBlock <NSSize> advances (length);
  229871. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229872. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229873. float x = 0;
  229874. for (int i = 0; i < length; ++i)
  229875. {
  229876. x += advances[i].width;
  229877. xOffsets.add (x * unitsToHeightScaleFactor);
  229878. resultGlyphs.add (nsGlyphs[i]);
  229879. }
  229880. }
  229881. else
  229882. #endif
  229883. {
  229884. HeapBlock <int> advances (length);
  229885. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229886. {
  229887. int x = 0;
  229888. for (int i = 0; i < length; ++i)
  229889. {
  229890. x += advances [i];
  229891. xOffsets.add (x * unitsToHeightScaleFactor);
  229892. resultGlyphs.add (glyphs[i]);
  229893. }
  229894. }
  229895. }
  229896. #endif
  229897. }
  229898. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229899. {
  229900. #if JUCE_IOS
  229901. return false;
  229902. #else
  229903. if (nsFont == 0)
  229904. return false;
  229905. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229906. jassert (path.isEmpty());
  229907. const ScopedAutoReleasePool pool;
  229908. NSBezierPath* bez = [NSBezierPath bezierPath];
  229909. [bez moveToPoint: NSMakePoint (0, 0)];
  229910. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229911. inFont: nsFont];
  229912. for (int i = 0; i < [bez elementCount]; ++i)
  229913. {
  229914. NSPoint p[3];
  229915. switch ([bez elementAtIndex: i associatedPoints: p])
  229916. {
  229917. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229918. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229919. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229920. (float) p[1].x, (float) -p[1].y,
  229921. (float) p[2].x, (float) -p[2].y); break;
  229922. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229923. default: jassertfalse; break;
  229924. }
  229925. }
  229926. path.applyTransform (pathTransform);
  229927. return true;
  229928. #endif
  229929. }
  229930. CGFontRef fontRef;
  229931. float fontHeightToCGSizeFactor;
  229932. CGAffineTransform renderingTransform;
  229933. private:
  229934. float ascent, unitsToHeightScaleFactor;
  229935. #if JUCE_IOS
  229936. #else
  229937. NSFont* nsFont;
  229938. AffineTransform pathTransform;
  229939. #endif
  229940. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  229941. {
  229942. #if SUPPORT_10_4_FONTS
  229943. #if ! SUPPORT_ONLY_10_4_FONTS
  229944. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229945. #endif
  229946. {
  229947. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229948. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229949. for (int i = 0; i < length; ++i)
  229950. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  229951. return;
  229952. }
  229953. #endif
  229954. #if ! SUPPORT_ONLY_10_4_FONTS
  229955. if (charToGlyphMapper == 0)
  229956. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229957. glyphs.malloc (length);
  229958. for (int i = 0; i < length; ++i)
  229959. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  229960. #endif
  229961. }
  229962. #if ! SUPPORT_ONLY_10_4_FONTS
  229963. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229964. class CharToGlyphMapper
  229965. {
  229966. public:
  229967. CharToGlyphMapper (CGFontRef fontRef)
  229968. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229969. idRangeOffset (0), glyphIndexes (0)
  229970. {
  229971. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229972. if (cmapTable != 0)
  229973. {
  229974. const int numSubtables = getValue16 (cmapTable, 2);
  229975. for (int i = 0; i < numSubtables; ++i)
  229976. {
  229977. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229978. {
  229979. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229980. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229981. {
  229982. const int length = getValue16 (cmapTable, offset + 2);
  229983. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229984. segCount = segCountX2 / 2;
  229985. const int endCodeOffset = offset + 14;
  229986. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229987. const int idDeltaOffset = startCodeOffset + segCountX2;
  229988. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229989. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229990. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229991. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229992. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229993. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229994. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229995. }
  229996. break;
  229997. }
  229998. }
  229999. CFRelease (cmapTable);
  230000. }
  230001. }
  230002. ~CharToGlyphMapper()
  230003. {
  230004. if (endCode != 0)
  230005. {
  230006. CFRelease (endCode);
  230007. CFRelease (startCode);
  230008. CFRelease (idDelta);
  230009. CFRelease (idRangeOffset);
  230010. CFRelease (glyphIndexes);
  230011. }
  230012. }
  230013. int getGlyphForCharacter (const juce_wchar c) const
  230014. {
  230015. for (int i = 0; i < segCount; ++i)
  230016. {
  230017. if (getValue16 (endCode, i * 2) >= c)
  230018. {
  230019. const int start = getValue16 (startCode, i * 2);
  230020. if (start > c)
  230021. break;
  230022. const int delta = getValue16 (idDelta, i * 2);
  230023. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230024. if (rangeOffset == 0)
  230025. return delta + c;
  230026. else
  230027. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230028. }
  230029. }
  230030. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230031. return jmax (-1, (int) c - 29);
  230032. }
  230033. private:
  230034. int segCount;
  230035. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230036. static uint16 getValue16 (CFDataRef data, const int index)
  230037. {
  230038. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230039. }
  230040. static uint32 getValue32 (CFDataRef data, const int index)
  230041. {
  230042. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230043. }
  230044. };
  230045. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230046. #endif
  230047. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  230048. };
  230049. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230050. {
  230051. return new MacTypeface (font);
  230052. }
  230053. const StringArray Font::findAllTypefaceNames()
  230054. {
  230055. StringArray names;
  230056. const ScopedAutoReleasePool pool;
  230057. #if JUCE_IOS
  230058. NSArray* fonts = [UIFont familyNames];
  230059. #else
  230060. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230061. #endif
  230062. for (unsigned int i = 0; i < [fonts count]; ++i)
  230063. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230064. names.sort (true);
  230065. return names;
  230066. }
  230067. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  230068. {
  230069. #if JUCE_IOS
  230070. defaultSans = "Helvetica";
  230071. defaultSerif = "Times New Roman";
  230072. defaultFixed = "Courier New";
  230073. #else
  230074. defaultSans = "Lucida Grande";
  230075. defaultSerif = "Times New Roman";
  230076. defaultFixed = "Monaco";
  230077. #endif
  230078. defaultFallback = "Arial Unicode MS";
  230079. }
  230080. #endif
  230081. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230082. // (must go before juce_mac_CoreGraphicsContext.mm)
  230083. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230084. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230085. // compiled on its own).
  230086. #if JUCE_INCLUDED_FILE
  230087. class CoreGraphicsImage : public Image::SharedImage
  230088. {
  230089. public:
  230090. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230091. : Image::SharedImage (format_, width_, height_)
  230092. {
  230093. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230094. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230095. imageData.allocate (lineStride * jmax (1, height), clearImage);
  230096. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230097. : CGColorSpaceCreateDeviceRGB();
  230098. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230099. colourSpace, getCGImageFlags (format_));
  230100. CGColorSpaceRelease (colourSpace);
  230101. }
  230102. ~CoreGraphicsImage()
  230103. {
  230104. CGContextRelease (context);
  230105. }
  230106. Image::ImageType getType() const { return Image::NativeImage; }
  230107. LowLevelGraphicsContext* createLowLevelContext();
  230108. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  230109. {
  230110. bitmap.data = imageData + x * pixelStride + y * lineStride;
  230111. bitmap.pixelFormat = format;
  230112. bitmap.lineStride = lineStride;
  230113. bitmap.pixelStride = pixelStride;
  230114. }
  230115. SharedImage* clone()
  230116. {
  230117. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230118. memcpy (im->imageData, imageData, lineStride * height);
  230119. return im;
  230120. }
  230121. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  230122. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  230123. {
  230124. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230125. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230126. {
  230127. return CGBitmapContextCreateImage (nativeImage->context);
  230128. }
  230129. else
  230130. {
  230131. const Image::BitmapData srcData (juceImage, Image::BitmapData::readOnly);
  230132. CGDataProviderRef provider;
  230133. if (mustOutliveSource)
  230134. {
  230135. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  230136. provider = CGDataProviderCreateWithCFData (data);
  230137. CFRelease (data);
  230138. }
  230139. else
  230140. {
  230141. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230142. }
  230143. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230144. 8, srcData.pixelStride * 8, srcData.lineStride,
  230145. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230146. 0, true, kCGRenderingIntentDefault);
  230147. CGDataProviderRelease (provider);
  230148. return imageRef;
  230149. }
  230150. }
  230151. #if JUCE_MAC
  230152. static NSImage* createNSImage (const Image& image)
  230153. {
  230154. const ScopedAutoReleasePool pool;
  230155. NSImage* im = [[NSImage alloc] init];
  230156. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230157. [im lockFocus];
  230158. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230159. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  230160. CGColorSpaceRelease (colourSpace);
  230161. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230162. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230163. CGImageRelease (imageRef);
  230164. [im unlockFocus];
  230165. return im;
  230166. }
  230167. #endif
  230168. CGContextRef context;
  230169. HeapBlock<uint8> imageData;
  230170. int pixelStride, lineStride;
  230171. private:
  230172. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230173. {
  230174. #if JUCE_BIG_ENDIAN
  230175. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230176. #else
  230177. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230178. #endif
  230179. }
  230180. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  230181. };
  230182. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230183. {
  230184. #if USE_COREGRAPHICS_RENDERING
  230185. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230186. #else
  230187. return createSoftwareImage (format, width, height, clearImage);
  230188. #endif
  230189. }
  230190. class CoreGraphicsContext : public LowLevelGraphicsContext
  230191. {
  230192. public:
  230193. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230194. : context (context_),
  230195. flipHeight (flipHeight_),
  230196. lastClipRectIsValid (false),
  230197. state (new SavedState()),
  230198. numGradientLookupEntries (0)
  230199. {
  230200. CGContextRetain (context);
  230201. CGContextSaveGState(context);
  230202. CGContextSetShouldSmoothFonts (context, true);
  230203. CGContextSetShouldAntialias (context, true);
  230204. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230205. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230206. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230207. gradientCallbacks.version = 0;
  230208. gradientCallbacks.evaluate = gradientCallback;
  230209. gradientCallbacks.releaseInfo = 0;
  230210. setFont (Font());
  230211. }
  230212. ~CoreGraphicsContext()
  230213. {
  230214. CGContextRestoreGState (context);
  230215. CGContextRelease (context);
  230216. CGColorSpaceRelease (rgbColourSpace);
  230217. CGColorSpaceRelease (greyColourSpace);
  230218. }
  230219. bool isVectorDevice() const { return false; }
  230220. void setOrigin (int x, int y)
  230221. {
  230222. CGContextTranslateCTM (context, x, -y);
  230223. if (lastClipRectIsValid)
  230224. lastClipRect.translate (-x, -y);
  230225. }
  230226. void addTransform (const AffineTransform& transform)
  230227. {
  230228. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230229. .translated (0, flipHeight)
  230230. .followedBy (transform)
  230231. .translated (0, -flipHeight)
  230232. .scaled (1.0f, -1.0f));
  230233. lastClipRectIsValid = false;
  230234. }
  230235. float getScaleFactor()
  230236. {
  230237. CGAffineTransform t = CGContextGetCTM (context);
  230238. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  230239. }
  230240. bool clipToRectangle (const Rectangle<int>& r)
  230241. {
  230242. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230243. if (lastClipRectIsValid)
  230244. {
  230245. // This is actually incorrect, because the actual clip region may be complex, and
  230246. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230247. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230248. // when calculating the resultant clip bounds, and makes the same mistake!
  230249. lastClipRect = lastClipRect.getIntersection (r);
  230250. return ! lastClipRect.isEmpty();
  230251. }
  230252. return ! isClipEmpty();
  230253. }
  230254. bool clipToRectangleList (const RectangleList& clipRegion)
  230255. {
  230256. if (clipRegion.isEmpty())
  230257. {
  230258. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230259. lastClipRectIsValid = true;
  230260. lastClipRect = Rectangle<int>();
  230261. return false;
  230262. }
  230263. else
  230264. {
  230265. const int numRects = clipRegion.getNumRectangles();
  230266. HeapBlock <CGRect> rects (numRects);
  230267. for (int i = 0; i < numRects; ++i)
  230268. {
  230269. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230270. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230271. }
  230272. CGContextClipToRects (context, rects, numRects);
  230273. lastClipRectIsValid = false;
  230274. return ! isClipEmpty();
  230275. }
  230276. }
  230277. void excludeClipRectangle (const Rectangle<int>& r)
  230278. {
  230279. RectangleList remaining (getClipBounds());
  230280. remaining.subtract (r);
  230281. clipToRectangleList (remaining);
  230282. lastClipRectIsValid = false;
  230283. }
  230284. void clipToPath (const Path& path, const AffineTransform& transform)
  230285. {
  230286. createPath (path, transform);
  230287. CGContextClip (context);
  230288. lastClipRectIsValid = false;
  230289. }
  230290. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230291. {
  230292. if (! transform.isSingularity())
  230293. {
  230294. Image singleChannelImage (sourceImage);
  230295. if (sourceImage.getFormat() != Image::SingleChannel)
  230296. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230297. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  230298. flip();
  230299. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230300. applyTransform (t);
  230301. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230302. CGContextClipToMask (context, r, image);
  230303. applyTransform (t.inverted());
  230304. flip();
  230305. CGImageRelease (image);
  230306. lastClipRectIsValid = false;
  230307. }
  230308. }
  230309. bool clipRegionIntersects (const Rectangle<int>& r)
  230310. {
  230311. return getClipBounds().intersects (r);
  230312. }
  230313. const Rectangle<int> getClipBounds() const
  230314. {
  230315. if (! lastClipRectIsValid)
  230316. {
  230317. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230318. lastClipRectIsValid = true;
  230319. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230320. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230321. roundToInt (bounds.size.width),
  230322. roundToInt (bounds.size.height));
  230323. }
  230324. return lastClipRect;
  230325. }
  230326. bool isClipEmpty() const
  230327. {
  230328. return getClipBounds().isEmpty();
  230329. }
  230330. void saveState()
  230331. {
  230332. CGContextSaveGState (context);
  230333. stateStack.add (new SavedState (*state));
  230334. }
  230335. void restoreState()
  230336. {
  230337. CGContextRestoreGState (context);
  230338. SavedState* const top = stateStack.getLast();
  230339. if (top != 0)
  230340. {
  230341. state = top;
  230342. stateStack.removeLast (1, false);
  230343. lastClipRectIsValid = false;
  230344. }
  230345. else
  230346. {
  230347. jassertfalse; // trying to pop with an empty stack!
  230348. }
  230349. }
  230350. void beginTransparencyLayer (float opacity)
  230351. {
  230352. saveState();
  230353. CGContextSetAlpha (context, opacity);
  230354. CGContextBeginTransparencyLayer (context, 0);
  230355. }
  230356. void endTransparencyLayer()
  230357. {
  230358. CGContextEndTransparencyLayer (context);
  230359. restoreState();
  230360. }
  230361. void setFill (const FillType& fillType)
  230362. {
  230363. state->fillType = fillType;
  230364. if (fillType.isColour())
  230365. {
  230366. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230367. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230368. CGContextSetAlpha (context, 1.0f);
  230369. }
  230370. }
  230371. void setOpacity (float newOpacity)
  230372. {
  230373. state->fillType.setOpacity (newOpacity);
  230374. setFill (state->fillType);
  230375. }
  230376. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230377. {
  230378. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230379. ? kCGInterpolationLow
  230380. : kCGInterpolationHigh);
  230381. }
  230382. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230383. {
  230384. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230385. }
  230386. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230387. {
  230388. if (replaceExistingContents)
  230389. {
  230390. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230391. CGContextClearRect (context, cgRect);
  230392. #else
  230393. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230394. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230395. CGContextClearRect (context, cgRect);
  230396. else
  230397. #endif
  230398. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230399. #endif
  230400. fillCGRect (cgRect, false);
  230401. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230402. }
  230403. else
  230404. {
  230405. if (state->fillType.isColour())
  230406. {
  230407. CGContextFillRect (context, cgRect);
  230408. }
  230409. else if (state->fillType.isGradient())
  230410. {
  230411. CGContextSaveGState (context);
  230412. CGContextClipToRect (context, cgRect);
  230413. drawGradient();
  230414. CGContextRestoreGState (context);
  230415. }
  230416. else
  230417. {
  230418. CGContextSaveGState (context);
  230419. CGContextClipToRect (context, cgRect);
  230420. drawImage (state->fillType.image, state->fillType.transform, true);
  230421. CGContextRestoreGState (context);
  230422. }
  230423. }
  230424. }
  230425. void fillPath (const Path& path, const AffineTransform& transform)
  230426. {
  230427. CGContextSaveGState (context);
  230428. if (state->fillType.isColour())
  230429. {
  230430. flip();
  230431. applyTransform (transform);
  230432. createPath (path);
  230433. if (path.isUsingNonZeroWinding())
  230434. CGContextFillPath (context);
  230435. else
  230436. CGContextEOFillPath (context);
  230437. }
  230438. else
  230439. {
  230440. createPath (path, transform);
  230441. if (path.isUsingNonZeroWinding())
  230442. CGContextClip (context);
  230443. else
  230444. CGContextEOClip (context);
  230445. if (state->fillType.isGradient())
  230446. drawGradient();
  230447. else
  230448. drawImage (state->fillType.image, state->fillType.transform, true);
  230449. }
  230450. CGContextRestoreGState (context);
  230451. }
  230452. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230453. {
  230454. const int iw = sourceImage.getWidth();
  230455. const int ih = sourceImage.getHeight();
  230456. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  230457. CGContextSaveGState (context);
  230458. CGContextSetAlpha (context, state->fillType.getOpacity());
  230459. flip();
  230460. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230461. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230462. if (fillEntireClipAsTiles)
  230463. {
  230464. #if JUCE_IOS
  230465. CGContextDrawTiledImage (context, imageRect, image);
  230466. #else
  230467. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230468. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230469. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230470. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230471. CGContextDrawTiledImage (context, imageRect, image);
  230472. else
  230473. #endif
  230474. {
  230475. // Fallback to manually doing a tiled fill on 10.4
  230476. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230477. int x = 0, y = 0;
  230478. while (x > clip.origin.x) x -= iw;
  230479. while (y > clip.origin.y) y -= ih;
  230480. const int right = (int) (clip.origin.x + clip.size.width);
  230481. const int bottom = (int) (clip.origin.y + clip.size.height);
  230482. while (y < bottom)
  230483. {
  230484. for (int x2 = x; x2 < right; x2 += iw)
  230485. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230486. y += ih;
  230487. }
  230488. }
  230489. #endif
  230490. }
  230491. else
  230492. {
  230493. CGContextDrawImage (context, imageRect, image);
  230494. }
  230495. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230496. CGContextRestoreGState (context);
  230497. }
  230498. void drawLine (const Line<float>& line)
  230499. {
  230500. if (state->fillType.isColour())
  230501. {
  230502. CGContextSetLineCap (context, kCGLineCapSquare);
  230503. CGContextSetLineWidth (context, 1.0f);
  230504. CGContextSetRGBStrokeColor (context,
  230505. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230506. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230507. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230508. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230509. CGContextStrokeLineSegments (context, cgLine, 1);
  230510. }
  230511. else
  230512. {
  230513. Path p;
  230514. p.addLineSegment (line, 1.0f);
  230515. fillPath (p, AffineTransform::identity);
  230516. }
  230517. }
  230518. void drawVerticalLine (const int x, float top, float bottom)
  230519. {
  230520. if (state->fillType.isColour())
  230521. {
  230522. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230523. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230524. #else
  230525. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230526. // the x co-ord slightly to trick it..
  230527. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230528. #endif
  230529. }
  230530. else
  230531. {
  230532. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230533. }
  230534. }
  230535. void drawHorizontalLine (const int y, float left, float right)
  230536. {
  230537. if (state->fillType.isColour())
  230538. {
  230539. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230540. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230541. #else
  230542. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230543. // the x co-ord slightly to trick it..
  230544. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230545. #endif
  230546. }
  230547. else
  230548. {
  230549. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230550. }
  230551. }
  230552. void setFont (const Font& newFont)
  230553. {
  230554. if (state->font != newFont)
  230555. {
  230556. state->fontRef = 0;
  230557. state->font = newFont;
  230558. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230559. if (mf != 0)
  230560. {
  230561. state->fontRef = mf->fontRef;
  230562. CGContextSetFont (context, state->fontRef);
  230563. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230564. state->fontTransform = mf->renderingTransform;
  230565. state->fontTransform.a *= state->font.getHorizontalScale();
  230566. CGContextSetTextMatrix (context, state->fontTransform);
  230567. }
  230568. }
  230569. }
  230570. const Font getFont()
  230571. {
  230572. return state->font;
  230573. }
  230574. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230575. {
  230576. if (state->fontRef != 0 && state->fillType.isColour())
  230577. {
  230578. if (transform.isOnlyTranslation())
  230579. {
  230580. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230581. CGGlyph g = glyphNumber;
  230582. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230583. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230584. }
  230585. else
  230586. {
  230587. CGContextSaveGState (context);
  230588. flip();
  230589. applyTransform (transform);
  230590. CGAffineTransform t = state->fontTransform;
  230591. t.d = -t.d;
  230592. CGContextSetTextMatrix (context, t);
  230593. CGGlyph g = glyphNumber;
  230594. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230595. CGContextRestoreGState (context);
  230596. }
  230597. }
  230598. else
  230599. {
  230600. Path p;
  230601. Font& f = state->font;
  230602. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230603. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230604. .followedBy (transform));
  230605. }
  230606. }
  230607. private:
  230608. CGContextRef context;
  230609. const CGFloat flipHeight;
  230610. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230611. CGFunctionCallbacks gradientCallbacks;
  230612. mutable Rectangle<int> lastClipRect;
  230613. mutable bool lastClipRectIsValid;
  230614. struct SavedState
  230615. {
  230616. SavedState()
  230617. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230618. {
  230619. }
  230620. SavedState (const SavedState& other)
  230621. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230622. fontTransform (other.fontTransform)
  230623. {
  230624. }
  230625. FillType fillType;
  230626. Font font;
  230627. CGFontRef fontRef;
  230628. CGAffineTransform fontTransform;
  230629. };
  230630. ScopedPointer <SavedState> state;
  230631. OwnedArray <SavedState> stateStack;
  230632. HeapBlock <PixelARGB> gradientLookupTable;
  230633. int numGradientLookupEntries;
  230634. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230635. {
  230636. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230637. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230638. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230639. colour.unpremultiply();
  230640. outData[0] = colour.getRed() / 255.0f;
  230641. outData[1] = colour.getGreen() / 255.0f;
  230642. outData[2] = colour.getBlue() / 255.0f;
  230643. outData[3] = colour.getAlpha() / 255.0f;
  230644. }
  230645. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230646. {
  230647. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230648. CGShadingRef result = 0;
  230649. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230650. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230651. if (gradient.isRadial)
  230652. {
  230653. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230654. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230655. function, true, true);
  230656. }
  230657. else
  230658. {
  230659. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230660. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230661. function, true, true);
  230662. }
  230663. CGFunctionRelease (function);
  230664. return result;
  230665. }
  230666. void drawGradient()
  230667. {
  230668. flip();
  230669. applyTransform (state->fillType.transform);
  230670. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230671. // you draw a gradient with high quality interp enabled).
  230672. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230673. CGContextSetAlpha (context, state->fillType.getOpacity());
  230674. CGContextDrawShading (context, shading);
  230675. CGShadingRelease (shading);
  230676. }
  230677. void createPath (const Path& path) const
  230678. {
  230679. CGContextBeginPath (context);
  230680. Path::Iterator i (path);
  230681. while (i.next())
  230682. {
  230683. switch (i.elementType)
  230684. {
  230685. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230686. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230687. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230688. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230689. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230690. default: jassertfalse; break;
  230691. }
  230692. }
  230693. }
  230694. void createPath (const Path& path, const AffineTransform& transform) const
  230695. {
  230696. CGContextBeginPath (context);
  230697. Path::Iterator i (path);
  230698. while (i.next())
  230699. {
  230700. switch (i.elementType)
  230701. {
  230702. case Path::Iterator::startNewSubPath:
  230703. transform.transformPoint (i.x1, i.y1);
  230704. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230705. break;
  230706. case Path::Iterator::lineTo:
  230707. transform.transformPoint (i.x1, i.y1);
  230708. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230709. break;
  230710. case Path::Iterator::quadraticTo:
  230711. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230712. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230713. break;
  230714. case Path::Iterator::cubicTo:
  230715. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230716. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230717. break;
  230718. case Path::Iterator::closePath:
  230719. CGContextClosePath (context); break;
  230720. default:
  230721. jassertfalse;
  230722. break;
  230723. }
  230724. }
  230725. }
  230726. void flip() const
  230727. {
  230728. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230729. }
  230730. void applyTransform (const AffineTransform& transform) const
  230731. {
  230732. CGAffineTransform t;
  230733. t.a = transform.mat00;
  230734. t.b = transform.mat10;
  230735. t.c = transform.mat01;
  230736. t.d = transform.mat11;
  230737. t.tx = transform.mat02;
  230738. t.ty = transform.mat12;
  230739. CGContextConcatCTM (context, t);
  230740. }
  230741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230742. };
  230743. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230744. {
  230745. return new CoreGraphicsContext (context, height);
  230746. }
  230747. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230748. const Image juce_loadWithCoreImage (InputStream& input)
  230749. {
  230750. MemoryBlock data;
  230751. input.readIntoMemoryBlock (data, -1);
  230752. #if JUCE_IOS
  230753. JUCE_AUTORELEASEPOOL
  230754. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230755. length: data.getSize()
  230756. freeWhenDone: NO]];
  230757. if (image != nil)
  230758. {
  230759. CGImageRef loadedImage = image.CGImage;
  230760. #else
  230761. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230762. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230763. CGDataProviderRelease (provider);
  230764. if (imageSource != 0)
  230765. {
  230766. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230767. CFRelease (imageSource);
  230768. #endif
  230769. if (loadedImage != 0)
  230770. {
  230771. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230772. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230773. && alphaInfo != kCGImageAlphaNoneSkipLast
  230774. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230775. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230776. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230777. hasAlphaChan, Image::NativeImage);
  230778. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230779. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230780. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230781. CGContextFlush (cgImage->context);
  230782. #if ! JUCE_IOS
  230783. CFRelease (loadedImage);
  230784. #endif
  230785. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230786. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230787. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230788. return image;
  230789. }
  230790. }
  230791. return Image::null;
  230792. }
  230793. #endif
  230794. #endif
  230795. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230796. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230797. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230798. // compiled on its own).
  230799. #if JUCE_INCLUDED_FILE
  230800. class NSViewComponentPeer;
  230801. END_JUCE_NAMESPACE
  230802. @interface NSEvent (JuceDeviceDelta)
  230803. - (float) deviceDeltaX;
  230804. - (float) deviceDeltaY;
  230805. @end
  230806. #define JuceNSView MakeObjCClassName(JuceNSView)
  230807. @interface JuceNSView : NSView<NSTextInput>
  230808. {
  230809. @public
  230810. NSViewComponentPeer* owner;
  230811. NSNotificationCenter* notificationCenter;
  230812. String* stringBeingComposed;
  230813. bool textWasInserted;
  230814. }
  230815. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230816. - (void) dealloc;
  230817. - (BOOL) isOpaque;
  230818. - (void) drawRect: (NSRect) r;
  230819. - (void) mouseDown: (NSEvent*) ev;
  230820. - (void) asyncMouseDown: (NSEvent*) ev;
  230821. - (void) mouseUp: (NSEvent*) ev;
  230822. - (void) asyncMouseUp: (NSEvent*) ev;
  230823. - (void) mouseDragged: (NSEvent*) ev;
  230824. - (void) mouseMoved: (NSEvent*) ev;
  230825. - (void) mouseEntered: (NSEvent*) ev;
  230826. - (void) mouseExited: (NSEvent*) ev;
  230827. - (void) rightMouseDown: (NSEvent*) ev;
  230828. - (void) rightMouseDragged: (NSEvent*) ev;
  230829. - (void) rightMouseUp: (NSEvent*) ev;
  230830. - (void) otherMouseDown: (NSEvent*) ev;
  230831. - (void) otherMouseDragged: (NSEvent*) ev;
  230832. - (void) otherMouseUp: (NSEvent*) ev;
  230833. - (void) scrollWheel: (NSEvent*) ev;
  230834. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230835. - (void) frameChanged: (NSNotification*) n;
  230836. - (void) viewDidMoveToWindow;
  230837. - (void) keyDown: (NSEvent*) ev;
  230838. - (void) keyUp: (NSEvent*) ev;
  230839. // NSTextInput Methods
  230840. - (void) insertText: (id) aString;
  230841. - (void) doCommandBySelector: (SEL) aSelector;
  230842. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230843. - (void) unmarkText;
  230844. - (BOOL) hasMarkedText;
  230845. - (long) conversationIdentifier;
  230846. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230847. - (NSRange) markedRange;
  230848. - (NSRange) selectedRange;
  230849. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230850. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230851. - (NSArray*) validAttributesForMarkedText;
  230852. - (void) flagsChanged: (NSEvent*) ev;
  230853. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230854. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230855. #endif
  230856. - (BOOL) becomeFirstResponder;
  230857. - (BOOL) resignFirstResponder;
  230858. - (BOOL) acceptsFirstResponder;
  230859. - (void) asyncRepaint: (id) rect;
  230860. - (NSArray*) getSupportedDragTypes;
  230861. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230862. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230863. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230864. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230865. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230866. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230867. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230868. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230869. @end
  230870. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230871. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230872. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230873. #else
  230874. @interface JuceNSWindow : NSWindow
  230875. #endif
  230876. {
  230877. @private
  230878. NSViewComponentPeer* owner;
  230879. bool isZooming;
  230880. }
  230881. - (void) setOwner: (NSViewComponentPeer*) owner;
  230882. - (BOOL) canBecomeKeyWindow;
  230883. - (void) becomeKeyWindow;
  230884. - (BOOL) windowShouldClose: (id) window;
  230885. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230886. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230887. - (void) zoom: (id) sender;
  230888. @end
  230889. BEGIN_JUCE_NAMESPACE
  230890. class NSViewComponentPeer : public ComponentPeer
  230891. {
  230892. public:
  230893. NSViewComponentPeer (Component* const component,
  230894. const int windowStyleFlags,
  230895. NSView* viewToAttachTo);
  230896. ~NSViewComponentPeer();
  230897. void* getNativeHandle() const;
  230898. void setVisible (bool shouldBeVisible);
  230899. void setTitle (const String& title);
  230900. void setPosition (int x, int y);
  230901. void setSize (int w, int h);
  230902. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230903. const Rectangle<int> getBounds (const bool global) const;
  230904. const Rectangle<int> getBounds() const;
  230905. const Point<int> getScreenPosition() const;
  230906. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230907. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230908. void setAlpha (float newAlpha);
  230909. void setMinimised (bool shouldBeMinimised);
  230910. bool isMinimised() const;
  230911. void setFullScreen (bool shouldBeFullScreen);
  230912. bool isFullScreen() const;
  230913. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230914. const BorderSize<int> getFrameSize() const;
  230915. bool setAlwaysOnTop (bool alwaysOnTop);
  230916. void toFront (bool makeActiveWindow);
  230917. void toBehind (ComponentPeer* other);
  230918. void setIcon (const Image& newIcon);
  230919. const StringArray getAvailableRenderingEngines();
  230920. int getCurrentRenderingEngine() throw();
  230921. void setCurrentRenderingEngine (int index);
  230922. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230923. for example having more than one juce plugin loaded into a host, then when a
  230924. method is called, the actual code that runs might actually be in a different module
  230925. than the one you expect... So any calls to library functions or statics that are
  230926. made inside obj-c methods will probably end up getting executed in a different DLL's
  230927. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230928. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230929. virtual methods of an object that's known to live inside the right module's space.
  230930. */
  230931. virtual void redirectMouseDown (NSEvent* ev);
  230932. virtual void redirectMouseUp (NSEvent* ev);
  230933. virtual void redirectMouseDrag (NSEvent* ev);
  230934. virtual void redirectMouseMove (NSEvent* ev);
  230935. virtual void redirectMouseEnter (NSEvent* ev);
  230936. virtual void redirectMouseExit (NSEvent* ev);
  230937. virtual void redirectMouseWheel (NSEvent* ev);
  230938. void sendMouseEvent (NSEvent* ev);
  230939. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230940. virtual bool redirectKeyDown (NSEvent* ev);
  230941. virtual bool redirectKeyUp (NSEvent* ev);
  230942. virtual void redirectModKeyChange (NSEvent* ev);
  230943. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230944. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230945. #endif
  230946. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230947. virtual bool isOpaque();
  230948. virtual void drawRect (NSRect r);
  230949. virtual bool canBecomeKeyWindow();
  230950. virtual bool windowShouldClose();
  230951. virtual void redirectMovedOrResized();
  230952. virtual void viewMovedToWindow();
  230953. virtual NSRect constrainRect (NSRect r);
  230954. static void showArrowCursorIfNeeded();
  230955. static void updateModifiers (NSEvent* e);
  230956. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230957. static int getKeyCodeFromEvent (NSEvent* ev)
  230958. {
  230959. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230960. int keyCode = unmodified[0];
  230961. if (keyCode == 0x19) // (backwards-tab)
  230962. keyCode = '\t';
  230963. else if (keyCode == 0x03) // (enter)
  230964. keyCode = '\r';
  230965. else
  230966. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230967. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230968. {
  230969. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230970. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230971. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230972. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230973. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230974. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230975. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230976. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230977. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230978. if (keyCode == numPadConversions [i])
  230979. keyCode = numPadConversions [i + 1];
  230980. }
  230981. return keyCode;
  230982. }
  230983. static int64 getMouseTime (NSEvent* e)
  230984. {
  230985. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230986. + (int64) ([e timestamp] * 1000.0);
  230987. }
  230988. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230989. {
  230990. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230991. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230992. }
  230993. static int getModifierForButtonNumber (const NSInteger num)
  230994. {
  230995. return num == 0 ? ModifierKeys::leftButtonModifier
  230996. : (num == 1 ? ModifierKeys::rightButtonModifier
  230997. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230998. }
  230999. virtual void viewFocusGain();
  231000. virtual void viewFocusLoss();
  231001. bool isFocused() const;
  231002. void grabFocus();
  231003. void textInputRequired (const Point<int>& position);
  231004. void repaint (const Rectangle<int>& area);
  231005. void performAnyPendingRepaintsNow();
  231006. NSWindow* window;
  231007. JuceNSView* view;
  231008. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231009. static ModifierKeys currentModifiers;
  231010. static ComponentPeer* currentlyFocusedPeer;
  231011. static Array<int> keysCurrentlyDown;
  231012. private:
  231013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  231014. };
  231015. END_JUCE_NAMESPACE
  231016. @implementation JuceNSView
  231017. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231018. withFrame: (NSRect) frame
  231019. {
  231020. [super initWithFrame: frame];
  231021. owner = owner_;
  231022. stringBeingComposed = 0;
  231023. textWasInserted = false;
  231024. notificationCenter = [NSNotificationCenter defaultCenter];
  231025. [notificationCenter addObserver: self
  231026. selector: @selector (frameChanged:)
  231027. name: NSViewFrameDidChangeNotification
  231028. object: self];
  231029. if (! owner_->isSharedWindow)
  231030. {
  231031. [notificationCenter addObserver: self
  231032. selector: @selector (frameChanged:)
  231033. name: NSWindowDidMoveNotification
  231034. object: owner_->window];
  231035. }
  231036. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231037. return self;
  231038. }
  231039. - (void) dealloc
  231040. {
  231041. [notificationCenter removeObserver: self];
  231042. delete stringBeingComposed;
  231043. [super dealloc];
  231044. }
  231045. - (void) drawRect: (NSRect) r
  231046. {
  231047. if (owner != 0)
  231048. owner->drawRect (r);
  231049. }
  231050. - (BOOL) isOpaque
  231051. {
  231052. return owner == 0 || owner->isOpaque();
  231053. }
  231054. - (void) mouseDown: (NSEvent*) ev
  231055. {
  231056. if (JUCEApplication::isStandaloneApp())
  231057. [self asyncMouseDown: ev];
  231058. else
  231059. // In some host situations, the host will stop modal loops from working
  231060. // correctly if they're called from a mouse event, so we'll trigger
  231061. // the event asynchronously..
  231062. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231063. withObject: ev
  231064. waitUntilDone: NO];
  231065. }
  231066. - (void) asyncMouseDown: (NSEvent*) ev
  231067. {
  231068. if (owner != 0)
  231069. owner->redirectMouseDown (ev);
  231070. }
  231071. - (void) mouseUp: (NSEvent*) ev
  231072. {
  231073. if (! JUCEApplication::isStandaloneApp())
  231074. [self asyncMouseUp: ev];
  231075. else
  231076. // In some host situations, the host will stop modal loops from working
  231077. // correctly if they're called from a mouse event, so we'll trigger
  231078. // the event asynchronously..
  231079. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231080. withObject: ev
  231081. waitUntilDone: NO];
  231082. }
  231083. - (void) asyncMouseUp: (NSEvent*) ev
  231084. {
  231085. if (owner != 0)
  231086. owner->redirectMouseUp (ev);
  231087. }
  231088. - (void) mouseDragged: (NSEvent*) ev
  231089. {
  231090. if (owner != 0)
  231091. owner->redirectMouseDrag (ev);
  231092. }
  231093. - (void) mouseMoved: (NSEvent*) ev
  231094. {
  231095. if (owner != 0)
  231096. owner->redirectMouseMove (ev);
  231097. }
  231098. - (void) mouseEntered: (NSEvent*) ev
  231099. {
  231100. if (owner != 0)
  231101. owner->redirectMouseEnter (ev);
  231102. }
  231103. - (void) mouseExited: (NSEvent*) ev
  231104. {
  231105. if (owner != 0)
  231106. owner->redirectMouseExit (ev);
  231107. }
  231108. - (void) rightMouseDown: (NSEvent*) ev
  231109. {
  231110. [self mouseDown: ev];
  231111. }
  231112. - (void) rightMouseDragged: (NSEvent*) ev
  231113. {
  231114. [self mouseDragged: ev];
  231115. }
  231116. - (void) rightMouseUp: (NSEvent*) ev
  231117. {
  231118. [self mouseUp: ev];
  231119. }
  231120. - (void) otherMouseDown: (NSEvent*) ev
  231121. {
  231122. [self mouseDown: ev];
  231123. }
  231124. - (void) otherMouseDragged: (NSEvent*) ev
  231125. {
  231126. [self mouseDragged: ev];
  231127. }
  231128. - (void) otherMouseUp: (NSEvent*) ev
  231129. {
  231130. [self mouseUp: ev];
  231131. }
  231132. - (void) scrollWheel: (NSEvent*) ev
  231133. {
  231134. if (owner != 0)
  231135. owner->redirectMouseWheel (ev);
  231136. }
  231137. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231138. {
  231139. (void) ev;
  231140. return YES;
  231141. }
  231142. - (void) frameChanged: (NSNotification*) n
  231143. {
  231144. (void) n;
  231145. if (owner != 0)
  231146. owner->redirectMovedOrResized();
  231147. }
  231148. - (void) viewDidMoveToWindow
  231149. {
  231150. if (owner != 0)
  231151. owner->viewMovedToWindow();
  231152. }
  231153. - (void) asyncRepaint: (id) rect
  231154. {
  231155. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231156. [self setNeedsDisplayInRect: *r];
  231157. }
  231158. - (void) keyDown: (NSEvent*) ev
  231159. {
  231160. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231161. textWasInserted = false;
  231162. if (target != 0)
  231163. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231164. else
  231165. deleteAndZero (stringBeingComposed);
  231166. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231167. [super keyDown: ev];
  231168. }
  231169. - (void) keyUp: (NSEvent*) ev
  231170. {
  231171. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231172. [super keyUp: ev];
  231173. }
  231174. - (void) insertText: (id) aString
  231175. {
  231176. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231177. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231178. if ([newText length] > 0)
  231179. {
  231180. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231181. if (target != 0)
  231182. {
  231183. target->insertTextAtCaret (nsStringToJuce (newText));
  231184. textWasInserted = true;
  231185. }
  231186. }
  231187. deleteAndZero (stringBeingComposed);
  231188. }
  231189. - (void) doCommandBySelector: (SEL) aSelector
  231190. {
  231191. (void) aSelector;
  231192. }
  231193. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231194. {
  231195. (void) selectionRange;
  231196. if (stringBeingComposed == 0)
  231197. stringBeingComposed = new String();
  231198. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231199. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231200. if (target != 0)
  231201. {
  231202. const Range<int> currentHighlight (target->getHighlightedRegion());
  231203. target->insertTextAtCaret (*stringBeingComposed);
  231204. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231205. textWasInserted = true;
  231206. }
  231207. }
  231208. - (void) unmarkText
  231209. {
  231210. if (stringBeingComposed != 0)
  231211. {
  231212. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231213. if (target != 0)
  231214. {
  231215. target->insertTextAtCaret (*stringBeingComposed);
  231216. textWasInserted = true;
  231217. }
  231218. }
  231219. deleteAndZero (stringBeingComposed);
  231220. }
  231221. - (BOOL) hasMarkedText
  231222. {
  231223. return stringBeingComposed != 0;
  231224. }
  231225. - (long) conversationIdentifier
  231226. {
  231227. return (long) (pointer_sized_int) self;
  231228. }
  231229. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231230. {
  231231. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231232. if (target != 0)
  231233. {
  231234. const Range<int> r ((int) theRange.location,
  231235. (int) (theRange.location + theRange.length));
  231236. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231237. }
  231238. return nil;
  231239. }
  231240. - (NSRange) markedRange
  231241. {
  231242. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231243. : NSMakeRange (NSNotFound, 0);
  231244. }
  231245. - (NSRange) selectedRange
  231246. {
  231247. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231248. if (target != 0)
  231249. {
  231250. const Range<int> highlight (target->getHighlightedRegion());
  231251. if (! highlight.isEmpty())
  231252. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231253. }
  231254. return NSMakeRange (NSNotFound, 0);
  231255. }
  231256. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231257. {
  231258. (void) theRange;
  231259. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231260. if (comp == 0)
  231261. return NSMakeRect (0, 0, 0, 0);
  231262. const Rectangle<int> bounds (comp->getScreenBounds());
  231263. return NSMakeRect (bounds.getX(),
  231264. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231265. bounds.getWidth(),
  231266. bounds.getHeight());
  231267. }
  231268. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231269. {
  231270. (void) thePoint;
  231271. return NSNotFound;
  231272. }
  231273. - (NSArray*) validAttributesForMarkedText
  231274. {
  231275. return [NSArray array];
  231276. }
  231277. - (void) flagsChanged: (NSEvent*) ev
  231278. {
  231279. if (owner != 0)
  231280. owner->redirectModKeyChange (ev);
  231281. }
  231282. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231283. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231284. {
  231285. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231286. return true;
  231287. return [super performKeyEquivalent: ev];
  231288. }
  231289. #endif
  231290. - (BOOL) becomeFirstResponder
  231291. {
  231292. if (owner != 0)
  231293. owner->viewFocusGain();
  231294. return true;
  231295. }
  231296. - (BOOL) resignFirstResponder
  231297. {
  231298. if (owner != 0)
  231299. owner->viewFocusLoss();
  231300. return true;
  231301. }
  231302. - (BOOL) acceptsFirstResponder
  231303. {
  231304. return owner != 0 && owner->canBecomeKeyWindow();
  231305. }
  231306. - (NSArray*) getSupportedDragTypes
  231307. {
  231308. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, /* NSStringPboardType,*/ nil];
  231309. }
  231310. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231311. {
  231312. return owner != 0 && owner->sendDragCallback (type, sender);
  231313. }
  231314. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231315. {
  231316. if ([self sendDragCallback: 0 sender: sender])
  231317. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231318. else
  231319. return NSDragOperationNone;
  231320. }
  231321. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231322. {
  231323. if ([self sendDragCallback: 0 sender: sender])
  231324. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231325. else
  231326. return NSDragOperationNone;
  231327. }
  231328. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231329. {
  231330. [self sendDragCallback: 1 sender: sender];
  231331. }
  231332. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231333. {
  231334. [self sendDragCallback: 1 sender: sender];
  231335. }
  231336. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231337. {
  231338. (void) sender;
  231339. return YES;
  231340. }
  231341. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231342. {
  231343. return [self sendDragCallback: 2 sender: sender];
  231344. }
  231345. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231346. {
  231347. (void) sender;
  231348. }
  231349. @end
  231350. @implementation JuceNSWindow
  231351. - (void) setOwner: (NSViewComponentPeer*) owner_
  231352. {
  231353. owner = owner_;
  231354. isZooming = false;
  231355. }
  231356. - (BOOL) canBecomeKeyWindow
  231357. {
  231358. return owner != 0 && owner->canBecomeKeyWindow();
  231359. }
  231360. - (void) becomeKeyWindow
  231361. {
  231362. [super becomeKeyWindow];
  231363. if (owner != 0)
  231364. owner->grabFocus();
  231365. }
  231366. - (BOOL) windowShouldClose: (id) window
  231367. {
  231368. (void) window;
  231369. return owner == 0 || owner->windowShouldClose();
  231370. }
  231371. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231372. {
  231373. (void) screen;
  231374. if (owner != 0)
  231375. frameRect = owner->constrainRect (frameRect);
  231376. return frameRect;
  231377. }
  231378. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231379. {
  231380. (void) window;
  231381. if (isZooming)
  231382. return proposedFrameSize;
  231383. NSRect frameRect = [self frame];
  231384. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231385. frameRect.size = proposedFrameSize;
  231386. if (owner != 0)
  231387. frameRect = owner->constrainRect (frameRect);
  231388. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231389. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231390. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231391. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231392. return frameRect.size;
  231393. }
  231394. - (void) zoom: (id) sender
  231395. {
  231396. isZooming = true;
  231397. [super zoom: sender];
  231398. isZooming = false;
  231399. }
  231400. - (void) windowWillMove: (NSNotification*) notification
  231401. {
  231402. (void) notification;
  231403. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231404. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231405. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231406. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231407. }
  231408. @end
  231409. BEGIN_JUCE_NAMESPACE
  231410. ModifierKeys NSViewComponentPeer::currentModifiers;
  231411. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231412. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231413. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231414. {
  231415. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231416. return true;
  231417. if (keyCode >= 'A' && keyCode <= 'Z'
  231418. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231419. return true;
  231420. if (keyCode >= 'a' && keyCode <= 'z'
  231421. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231422. return true;
  231423. return false;
  231424. }
  231425. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231426. {
  231427. int m = 0;
  231428. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231429. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231430. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231431. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231432. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231433. }
  231434. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231435. {
  231436. updateModifiers (ev);
  231437. int keyCode = getKeyCodeFromEvent (ev);
  231438. if (keyCode != 0)
  231439. {
  231440. if (isKeyDown)
  231441. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231442. else
  231443. keysCurrentlyDown.removeValue (keyCode);
  231444. }
  231445. }
  231446. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231447. {
  231448. return NSViewComponentPeer::currentModifiers;
  231449. }
  231450. void ModifierKeys::updateCurrentModifiers() throw()
  231451. {
  231452. currentModifiers = NSViewComponentPeer::currentModifiers;
  231453. }
  231454. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231455. const int windowStyleFlags,
  231456. NSView* viewToAttachTo)
  231457. : ComponentPeer (component_, windowStyleFlags),
  231458. window (0),
  231459. view (0),
  231460. isSharedWindow (viewToAttachTo != 0),
  231461. fullScreen (false),
  231462. insideDrawRect (false),
  231463. #if USE_COREGRAPHICS_RENDERING
  231464. usingCoreGraphics (true),
  231465. #else
  231466. usingCoreGraphics (false),
  231467. #endif
  231468. recursiveToFrontCall (false)
  231469. {
  231470. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231471. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231472. [view setPostsFrameChangedNotifications: YES];
  231473. if (isSharedWindow)
  231474. {
  231475. window = [viewToAttachTo window];
  231476. [viewToAttachTo addSubview: view];
  231477. }
  231478. else
  231479. {
  231480. r.origin.x = (float) component->getX();
  231481. r.origin.y = (float) component->getY();
  231482. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231483. unsigned int style = 0;
  231484. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231485. style = NSBorderlessWindowMask;
  231486. else
  231487. style = NSTitledWindowMask;
  231488. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231489. style |= NSMiniaturizableWindowMask;
  231490. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231491. style |= NSClosableWindowMask;
  231492. if ((windowStyleFlags & windowIsResizable) != 0)
  231493. style |= NSResizableWindowMask;
  231494. window = [[JuceNSWindow alloc] initWithContentRect: r
  231495. styleMask: style
  231496. backing: NSBackingStoreBuffered
  231497. defer: YES];
  231498. [((JuceNSWindow*) window) setOwner: this];
  231499. [window orderOut: nil];
  231500. [window setDelegate: (JuceNSWindow*) window];
  231501. [window setOpaque: component->isOpaque()];
  231502. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231503. if (component->isAlwaysOnTop())
  231504. [window setLevel: NSFloatingWindowLevel];
  231505. [window setContentView: view];
  231506. [window setAutodisplay: YES];
  231507. [window setAcceptsMouseMovedEvents: YES];
  231508. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231509. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231510. [window setReleasedWhenClosed: YES];
  231511. [window retain];
  231512. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231513. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231514. }
  231515. const float alpha = component->getAlpha();
  231516. if (alpha < 1.0f)
  231517. setAlpha (alpha);
  231518. setTitle (component->getName());
  231519. }
  231520. NSViewComponentPeer::~NSViewComponentPeer()
  231521. {
  231522. view->owner = 0;
  231523. [view removeFromSuperview];
  231524. [view release];
  231525. if (! isSharedWindow)
  231526. {
  231527. [((JuceNSWindow*) window) setOwner: 0];
  231528. [window close];
  231529. [window release];
  231530. }
  231531. }
  231532. void* NSViewComponentPeer::getNativeHandle() const
  231533. {
  231534. return view;
  231535. }
  231536. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231537. {
  231538. if (isSharedWindow)
  231539. {
  231540. [view setHidden: ! shouldBeVisible];
  231541. }
  231542. else
  231543. {
  231544. if (shouldBeVisible)
  231545. {
  231546. [window orderFront: nil];
  231547. handleBroughtToFront();
  231548. }
  231549. else
  231550. {
  231551. [window orderOut: nil];
  231552. }
  231553. }
  231554. }
  231555. void NSViewComponentPeer::setTitle (const String& title)
  231556. {
  231557. const ScopedAutoReleasePool pool;
  231558. if (! isSharedWindow)
  231559. [window setTitle: juceStringToNS (title)];
  231560. }
  231561. void NSViewComponentPeer::setPosition (int x, int y)
  231562. {
  231563. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231564. }
  231565. void NSViewComponentPeer::setSize (int w, int h)
  231566. {
  231567. setBounds (component->getX(), component->getY(), w, h, false);
  231568. }
  231569. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231570. {
  231571. fullScreen = isNowFullScreen;
  231572. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231573. if (isSharedWindow)
  231574. {
  231575. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231576. if ([view frame].size.width != r.size.width
  231577. || [view frame].size.height != r.size.height)
  231578. [view setNeedsDisplay: true];
  231579. [view setFrame: r];
  231580. }
  231581. else
  231582. {
  231583. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231584. [window setFrame: [window frameRectForContentRect: r]
  231585. display: true];
  231586. }
  231587. }
  231588. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231589. {
  231590. NSRect r = [view frame];
  231591. if (global && [view window] != 0)
  231592. {
  231593. r = [view convertRect: r toView: nil];
  231594. NSRect wr = [[view window] frame];
  231595. r.origin.x += wr.origin.x;
  231596. r.origin.y += wr.origin.y;
  231597. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231598. }
  231599. else
  231600. {
  231601. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231602. }
  231603. return Rectangle<int> (convertToRectInt (r));
  231604. }
  231605. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231606. {
  231607. return getBounds (! isSharedWindow);
  231608. }
  231609. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231610. {
  231611. return getBounds (true).getPosition();
  231612. }
  231613. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231614. {
  231615. return relativePosition + getScreenPosition();
  231616. }
  231617. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231618. {
  231619. return screenPosition - getScreenPosition();
  231620. }
  231621. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231622. {
  231623. if (constrainer != 0)
  231624. {
  231625. NSRect current = [window frame];
  231626. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231627. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231628. Rectangle<int> pos (convertToRectInt (r));
  231629. Rectangle<int> original (convertToRectInt (current));
  231630. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231631. if ([window inLiveResize])
  231632. #else
  231633. if ([window respondsToSelector: @selector (inLiveResize)]
  231634. && [window performSelector: @selector (inLiveResize)])
  231635. #endif
  231636. {
  231637. constrainer->checkBounds (pos, original,
  231638. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231639. false, false, true, true);
  231640. }
  231641. else
  231642. {
  231643. constrainer->checkBounds (pos, original,
  231644. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231645. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231646. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231647. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231648. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231649. }
  231650. r.origin.x = pos.getX();
  231651. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231652. r.size.width = pos.getWidth();
  231653. r.size.height = pos.getHeight();
  231654. }
  231655. return r;
  231656. }
  231657. void NSViewComponentPeer::setAlpha (float newAlpha)
  231658. {
  231659. if (! isSharedWindow)
  231660. {
  231661. [window setAlphaValue: (CGFloat) newAlpha];
  231662. }
  231663. else
  231664. {
  231665. #if defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5
  231666. [view setAlphaValue: (CGFloat) newAlpha];
  231667. #else
  231668. if ([view respondsToSelector: @selector (setAlphaValue:)])
  231669. {
  231670. // PITA dynamic invocation for 10.4 builds..
  231671. NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [view methodSignatureForSelector: @selector (setAlphaValue:)]];
  231672. [inv setSelector: @selector (setAlphaValue:)];
  231673. [inv setTarget: view];
  231674. CGFloat cgNewAlpha = (CGFloat) newAlpha;
  231675. [inv setArgument: &cgNewAlpha atIndex: 2];
  231676. [inv invoke];
  231677. }
  231678. #endif
  231679. }
  231680. }
  231681. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231682. {
  231683. if (! isSharedWindow)
  231684. {
  231685. if (shouldBeMinimised)
  231686. [window miniaturize: nil];
  231687. else
  231688. [window deminiaturize: nil];
  231689. }
  231690. }
  231691. bool NSViewComponentPeer::isMinimised() const
  231692. {
  231693. return window != 0 && [window isMiniaturized];
  231694. }
  231695. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231696. {
  231697. if (! isSharedWindow)
  231698. {
  231699. Rectangle<int> r (lastNonFullscreenBounds);
  231700. setMinimised (false);
  231701. if (fullScreen != shouldBeFullScreen)
  231702. {
  231703. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231704. {
  231705. fullScreen = true;
  231706. [window performZoom: nil];
  231707. }
  231708. else
  231709. {
  231710. if (shouldBeFullScreen)
  231711. r = Desktop::getInstance().getMainMonitorArea();
  231712. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231713. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231714. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231715. }
  231716. }
  231717. }
  231718. }
  231719. bool NSViewComponentPeer::isFullScreen() const
  231720. {
  231721. return fullScreen;
  231722. }
  231723. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231724. {
  231725. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231726. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231727. return false;
  231728. NSPoint p;
  231729. p.x = (float) position.getX();
  231730. p.y = (float) position.getY();
  231731. NSView* v = [view hitTest: p];
  231732. if (trueIfInAChildWindow)
  231733. return v != nil;
  231734. return v == view;
  231735. }
  231736. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231737. {
  231738. BorderSize<int> b;
  231739. if (! isSharedWindow)
  231740. {
  231741. NSRect v = [view convertRect: [view frame] toView: nil];
  231742. NSRect w = [window frame];
  231743. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231744. b.setBottom ((int) v.origin.y);
  231745. b.setLeft ((int) v.origin.x);
  231746. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231747. }
  231748. return b;
  231749. }
  231750. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231751. {
  231752. if (! isSharedWindow)
  231753. {
  231754. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231755. : NSNormalWindowLevel];
  231756. }
  231757. return true;
  231758. }
  231759. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231760. {
  231761. if (isSharedWindow)
  231762. {
  231763. [[view superview] addSubview: view
  231764. positioned: NSWindowAbove
  231765. relativeTo: nil];
  231766. }
  231767. if (window != 0 && component->isVisible())
  231768. {
  231769. if (makeActiveWindow)
  231770. [window makeKeyAndOrderFront: nil];
  231771. else
  231772. [window orderFront: nil];
  231773. if (! recursiveToFrontCall)
  231774. {
  231775. recursiveToFrontCall = true;
  231776. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231777. handleBroughtToFront();
  231778. recursiveToFrontCall = false;
  231779. }
  231780. }
  231781. }
  231782. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231783. {
  231784. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231785. jassert (otherPeer != 0); // wrong type of window?
  231786. if (otherPeer != 0)
  231787. {
  231788. if (isSharedWindow)
  231789. {
  231790. [[view superview] addSubview: view
  231791. positioned: NSWindowBelow
  231792. relativeTo: otherPeer->view];
  231793. }
  231794. else
  231795. {
  231796. [window orderWindow: NSWindowBelow
  231797. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231798. : nil ];
  231799. }
  231800. }
  231801. }
  231802. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231803. {
  231804. // to do..
  231805. }
  231806. void NSViewComponentPeer::viewFocusGain()
  231807. {
  231808. if (currentlyFocusedPeer != this)
  231809. {
  231810. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231811. currentlyFocusedPeer->handleFocusLoss();
  231812. currentlyFocusedPeer = this;
  231813. handleFocusGain();
  231814. }
  231815. }
  231816. void NSViewComponentPeer::viewFocusLoss()
  231817. {
  231818. if (currentlyFocusedPeer == this)
  231819. {
  231820. currentlyFocusedPeer = 0;
  231821. handleFocusLoss();
  231822. }
  231823. }
  231824. void juce_HandleProcessFocusChange()
  231825. {
  231826. NSViewComponentPeer::keysCurrentlyDown.clear();
  231827. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231828. {
  231829. if (Process::isForegroundProcess())
  231830. {
  231831. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231832. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231833. }
  231834. else
  231835. {
  231836. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231837. // turn kiosk mode off if we lose focus..
  231838. Desktop::getInstance().setKioskModeComponent (0);
  231839. }
  231840. }
  231841. }
  231842. bool NSViewComponentPeer::isFocused() const
  231843. {
  231844. return isSharedWindow ? this == currentlyFocusedPeer
  231845. : (window != 0 && [window isKeyWindow]);
  231846. }
  231847. void NSViewComponentPeer::grabFocus()
  231848. {
  231849. if (window != 0)
  231850. {
  231851. [window makeKeyWindow];
  231852. [window makeFirstResponder: view];
  231853. viewFocusGain();
  231854. }
  231855. }
  231856. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231857. {
  231858. }
  231859. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231860. {
  231861. String unicode (nsStringToJuce ([ev characters]));
  231862. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231863. int keyCode = getKeyCodeFromEvent (ev);
  231864. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231865. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231866. if (unicode.isNotEmpty() || keyCode != 0)
  231867. {
  231868. if (isKeyDown)
  231869. {
  231870. bool used = false;
  231871. while (unicode.length() > 0)
  231872. {
  231873. juce_wchar textCharacter = unicode[0];
  231874. unicode = unicode.substring (1);
  231875. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231876. textCharacter = 0;
  231877. used = handleKeyUpOrDown (true) || used;
  231878. used = handleKeyPress (keyCode, textCharacter) || used;
  231879. }
  231880. return used;
  231881. }
  231882. else
  231883. {
  231884. if (handleKeyUpOrDown (false))
  231885. return true;
  231886. }
  231887. }
  231888. return false;
  231889. }
  231890. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231891. {
  231892. updateKeysDown (ev, true);
  231893. bool used = handleKeyEvent (ev, true);
  231894. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231895. {
  231896. // for command keys, the key-up event is thrown away, so simulate one..
  231897. updateKeysDown (ev, false);
  231898. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231899. }
  231900. // (If we're running modally, don't allow unused keystrokes to be passed
  231901. // along to other blocked views..)
  231902. if (Component::getCurrentlyModalComponent() != 0)
  231903. used = true;
  231904. return used;
  231905. }
  231906. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231907. {
  231908. updateKeysDown (ev, false);
  231909. return handleKeyEvent (ev, false)
  231910. || Component::getCurrentlyModalComponent() != 0;
  231911. }
  231912. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231913. {
  231914. keysCurrentlyDown.clear();
  231915. handleKeyUpOrDown (true);
  231916. updateModifiers (ev);
  231917. handleModifierKeysChange();
  231918. }
  231919. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231920. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231921. {
  231922. if ([ev type] == NSKeyDown)
  231923. return redirectKeyDown (ev);
  231924. else if ([ev type] == NSKeyUp)
  231925. return redirectKeyUp (ev);
  231926. return false;
  231927. }
  231928. #endif
  231929. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231930. {
  231931. updateModifiers (ev);
  231932. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231933. }
  231934. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231935. {
  231936. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231937. sendMouseEvent (ev);
  231938. }
  231939. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231940. {
  231941. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231942. sendMouseEvent (ev);
  231943. showArrowCursorIfNeeded();
  231944. }
  231945. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231946. {
  231947. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231948. sendMouseEvent (ev);
  231949. }
  231950. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231951. {
  231952. currentModifiers = currentModifiers.withoutMouseButtons();
  231953. sendMouseEvent (ev);
  231954. showArrowCursorIfNeeded();
  231955. }
  231956. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231957. {
  231958. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231959. currentModifiers = currentModifiers.withoutMouseButtons();
  231960. sendMouseEvent (ev);
  231961. }
  231962. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231963. {
  231964. currentModifiers = currentModifiers.withoutMouseButtons();
  231965. sendMouseEvent (ev);
  231966. }
  231967. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231968. {
  231969. updateModifiers (ev);
  231970. float x = 0, y = 0;
  231971. @try
  231972. {
  231973. x = [ev deviceDeltaX] * 0.5f;
  231974. y = [ev deviceDeltaY] * 0.5f;
  231975. }
  231976. @catch (...)
  231977. {}
  231978. if (x == 0 && y == 0)
  231979. {
  231980. x = [ev deltaX] * 10.0f;
  231981. y = [ev deltaY] * 10.0f;
  231982. }
  231983. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231984. }
  231985. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231986. {
  231987. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231988. if (mouse.getComponentUnderMouse() == 0
  231989. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231990. {
  231991. [[NSCursor arrowCursor] set];
  231992. }
  231993. }
  231994. BOOL NSViewComponentPeer::sendDragCallback (const int type, id <NSDraggingInfo> sender)
  231995. {
  231996. NSString* bestType
  231997. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231998. if (bestType == nil)
  231999. return false;
  232000. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232001. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232002. NSPasteboard* pasteBoard = [sender draggingPasteboard];
  232003. StringArray files;
  232004. NSString* iTunesPasteboardType = @"CorePasteboardFlavorType 0x6974756E"; // 'itun'
  232005. if (bestType == NSFilesPromisePboardType
  232006. && [[pasteBoard types] containsObject: iTunesPasteboardType])
  232007. {
  232008. id list = [pasteBoard propertyListForType: iTunesPasteboardType];
  232009. if ([list isKindOfClass: [NSDictionary class]])
  232010. {
  232011. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  232012. NSArray* tracks = [iTunesDictionary valueForKey: @"Tracks"];
  232013. NSEnumerator* enumerator = [tracks objectEnumerator];
  232014. NSDictionary* track;
  232015. while ((track = [enumerator nextObject]) != nil)
  232016. {
  232017. NSURL* url = [NSURL URLWithString: [track valueForKey: @"Location"]];
  232018. if ([url isFileURL])
  232019. files.add (nsStringToJuce ([url path]));
  232020. }
  232021. }
  232022. }
  232023. else
  232024. {
  232025. id list = [pasteBoard propertyListForType: NSFilenamesPboardType];
  232026. if ([list isKindOfClass: [NSArray class]])
  232027. {
  232028. NSArray* items = (NSArray*) [pasteBoard propertyListForType: NSFilenamesPboardType];
  232029. for (unsigned int i = 0; i < [items count]; ++i)
  232030. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232031. }
  232032. }
  232033. if (files.size() > 0)
  232034. {
  232035. switch (type)
  232036. {
  232037. case 0: handleFileDragMove (files, pos); break;
  232038. case 1: handleFileDragExit (files); break;
  232039. case 2: handleFileDragDrop (files, pos); break;
  232040. default: jassertfalse; break;
  232041. }
  232042. return true;
  232043. }
  232044. return false;
  232045. }
  232046. bool NSViewComponentPeer::isOpaque()
  232047. {
  232048. return component == 0 || component->isOpaque();
  232049. }
  232050. void NSViewComponentPeer::drawRect (NSRect r)
  232051. {
  232052. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232053. return;
  232054. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232055. if (! component->isOpaque())
  232056. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232057. #if USE_COREGRAPHICS_RENDERING
  232058. if (usingCoreGraphics)
  232059. {
  232060. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232061. insideDrawRect = true;
  232062. handlePaint (context);
  232063. insideDrawRect = false;
  232064. }
  232065. else
  232066. #endif
  232067. {
  232068. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232069. (int) (r.size.width + 0.5f),
  232070. (int) (r.size.height + 0.5f),
  232071. ! getComponent()->isOpaque());
  232072. const int xOffset = -roundToInt (r.origin.x);
  232073. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232074. const NSRect* rects = 0;
  232075. NSInteger numRects = 0;
  232076. [view getRectsBeingDrawn: &rects count: &numRects];
  232077. const Rectangle<int> clipBounds (temp.getBounds());
  232078. RectangleList clip;
  232079. for (int i = 0; i < numRects; ++i)
  232080. {
  232081. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232082. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232083. roundToInt (rects[i].size.width),
  232084. roundToInt (rects[i].size.height))));
  232085. }
  232086. if (! clip.isEmpty())
  232087. {
  232088. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232089. insideDrawRect = true;
  232090. handlePaint (context);
  232091. insideDrawRect = false;
  232092. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232093. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  232094. CGColorSpaceRelease (colourSpace);
  232095. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232096. CGImageRelease (image);
  232097. }
  232098. }
  232099. }
  232100. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232101. {
  232102. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232103. #if USE_COREGRAPHICS_RENDERING
  232104. s.add ("CoreGraphics Renderer");
  232105. #endif
  232106. return s;
  232107. }
  232108. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232109. {
  232110. return usingCoreGraphics ? 1 : 0;
  232111. }
  232112. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232113. {
  232114. #if USE_COREGRAPHICS_RENDERING
  232115. if (usingCoreGraphics != (index > 0))
  232116. {
  232117. usingCoreGraphics = index > 0;
  232118. [view setNeedsDisplay: true];
  232119. }
  232120. #endif
  232121. }
  232122. bool NSViewComponentPeer::canBecomeKeyWindow()
  232123. {
  232124. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232125. }
  232126. bool NSViewComponentPeer::windowShouldClose()
  232127. {
  232128. if (! isValidPeer (this))
  232129. return YES;
  232130. handleUserClosingWindow();
  232131. return NO;
  232132. }
  232133. void NSViewComponentPeer::redirectMovedOrResized()
  232134. {
  232135. handleMovedOrResized();
  232136. }
  232137. void NSViewComponentPeer::viewMovedToWindow()
  232138. {
  232139. if (isSharedWindow)
  232140. window = [view window];
  232141. }
  232142. void Desktop::createMouseInputSources()
  232143. {
  232144. mouseSources.add (new MouseInputSource (0, true));
  232145. }
  232146. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232147. {
  232148. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  232149. if (enableOrDisable)
  232150. {
  232151. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  232152. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  232153. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232154. }
  232155. else
  232156. {
  232157. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  232158. }
  232159. #else
  232160. if (enableOrDisable)
  232161. {
  232162. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232163. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232164. }
  232165. else
  232166. {
  232167. SetSystemUIMode (kUIModeNormal, 0);
  232168. }
  232169. #endif
  232170. }
  232171. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232172. {
  232173. if (insideDrawRect)
  232174. {
  232175. class AsyncRepaintMessage : public CallbackMessage
  232176. {
  232177. public:
  232178. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232179. : peer (peer_), rect (rect_)
  232180. {
  232181. }
  232182. void messageCallback()
  232183. {
  232184. if (ComponentPeer::isValidPeer (peer))
  232185. peer->repaint (rect);
  232186. }
  232187. private:
  232188. NSViewComponentPeer* const peer;
  232189. const Rectangle<int> rect;
  232190. };
  232191. (new AsyncRepaintMessage (this, area))->post();
  232192. }
  232193. else
  232194. {
  232195. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232196. (float) area.getWidth(), (float) area.getHeight())];
  232197. }
  232198. }
  232199. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232200. {
  232201. [view displayIfNeeded];
  232202. }
  232203. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232204. {
  232205. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232206. }
  232207. const Image juce_createIconForFile (const File& file)
  232208. {
  232209. const ScopedAutoReleasePool pool;
  232210. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232211. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232212. [NSGraphicsContext saveGraphicsState];
  232213. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232214. [image drawAtPoint: NSMakePoint (0, 0)
  232215. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232216. operation: NSCompositeSourceOver fraction: 1.0f];
  232217. [[NSGraphicsContext currentContext] flushGraphics];
  232218. [NSGraphicsContext restoreGraphicsState];
  232219. return Image (result);
  232220. }
  232221. const int KeyPress::spaceKey = ' ';
  232222. const int KeyPress::returnKey = 0x0d;
  232223. const int KeyPress::escapeKey = 0x1b;
  232224. const int KeyPress::backspaceKey = 0x7f;
  232225. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232226. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232227. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232228. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232229. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232230. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232231. const int KeyPress::endKey = NSEndFunctionKey;
  232232. const int KeyPress::homeKey = NSHomeFunctionKey;
  232233. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232234. const int KeyPress::insertKey = -1;
  232235. const int KeyPress::tabKey = 9;
  232236. const int KeyPress::F1Key = NSF1FunctionKey;
  232237. const int KeyPress::F2Key = NSF2FunctionKey;
  232238. const int KeyPress::F3Key = NSF3FunctionKey;
  232239. const int KeyPress::F4Key = NSF4FunctionKey;
  232240. const int KeyPress::F5Key = NSF5FunctionKey;
  232241. const int KeyPress::F6Key = NSF6FunctionKey;
  232242. const int KeyPress::F7Key = NSF7FunctionKey;
  232243. const int KeyPress::F8Key = NSF8FunctionKey;
  232244. const int KeyPress::F9Key = NSF9FunctionKey;
  232245. const int KeyPress::F10Key = NSF10FunctionKey;
  232246. const int KeyPress::F11Key = NSF1FunctionKey;
  232247. const int KeyPress::F12Key = NSF12FunctionKey;
  232248. const int KeyPress::F13Key = NSF13FunctionKey;
  232249. const int KeyPress::F14Key = NSF14FunctionKey;
  232250. const int KeyPress::F15Key = NSF15FunctionKey;
  232251. const int KeyPress::F16Key = NSF16FunctionKey;
  232252. const int KeyPress::numberPad0 = 0x30020;
  232253. const int KeyPress::numberPad1 = 0x30021;
  232254. const int KeyPress::numberPad2 = 0x30022;
  232255. const int KeyPress::numberPad3 = 0x30023;
  232256. const int KeyPress::numberPad4 = 0x30024;
  232257. const int KeyPress::numberPad5 = 0x30025;
  232258. const int KeyPress::numberPad6 = 0x30026;
  232259. const int KeyPress::numberPad7 = 0x30027;
  232260. const int KeyPress::numberPad8 = 0x30028;
  232261. const int KeyPress::numberPad9 = 0x30029;
  232262. const int KeyPress::numberPadAdd = 0x3002a;
  232263. const int KeyPress::numberPadSubtract = 0x3002b;
  232264. const int KeyPress::numberPadMultiply = 0x3002c;
  232265. const int KeyPress::numberPadDivide = 0x3002d;
  232266. const int KeyPress::numberPadSeparator = 0x3002e;
  232267. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232268. const int KeyPress::numberPadEquals = 0x30030;
  232269. const int KeyPress::numberPadDelete = 0x30031;
  232270. const int KeyPress::playKey = 0x30000;
  232271. const int KeyPress::stopKey = 0x30001;
  232272. const int KeyPress::fastForwardKey = 0x30002;
  232273. const int KeyPress::rewindKey = 0x30003;
  232274. #endif
  232275. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232276. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232277. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232278. // compiled on its own).
  232279. #if JUCE_INCLUDED_FILE
  232280. #if JUCE_MAC
  232281. namespace MouseCursorHelpers
  232282. {
  232283. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232284. {
  232285. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232286. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232287. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232288. [im release];
  232289. return c;
  232290. }
  232291. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232292. {
  232293. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232294. BufferedInputStream buf (fileStream, 4096);
  232295. PNGImageFormat pngFormat;
  232296. Image im (pngFormat.decodeImage (buf));
  232297. if (im.isValid())
  232298. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232299. jassertfalse;
  232300. return 0;
  232301. }
  232302. }
  232303. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232304. {
  232305. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232306. }
  232307. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232308. {
  232309. const ScopedAutoReleasePool pool;
  232310. NSCursor* c = 0;
  232311. switch (type)
  232312. {
  232313. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232314. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232315. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232316. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232317. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232318. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232319. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232320. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232321. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232322. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232323. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232324. case UpDownResizeCursor:
  232325. case TopEdgeResizeCursor:
  232326. case BottomEdgeResizeCursor:
  232327. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232328. case TopLeftCornerResizeCursor:
  232329. case BottomRightCornerResizeCursor:
  232330. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232331. case TopRightCornerResizeCursor:
  232332. case BottomLeftCornerResizeCursor:
  232333. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232334. case UpDownLeftRightResizeCursor:
  232335. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232336. default:
  232337. jassertfalse;
  232338. break;
  232339. }
  232340. [c retain];
  232341. return c;
  232342. }
  232343. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232344. {
  232345. [((NSCursor*) cursorHandle) release];
  232346. }
  232347. void MouseCursor::showInAllWindows() const
  232348. {
  232349. showInWindow (0);
  232350. }
  232351. void MouseCursor::showInWindow (ComponentPeer*) const
  232352. {
  232353. NSCursor* c = (NSCursor*) getHandle();
  232354. if (c == 0)
  232355. c = [NSCursor arrowCursor];
  232356. [c set];
  232357. }
  232358. #else
  232359. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232360. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232361. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232362. void MouseCursor::showInAllWindows() const {}
  232363. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232364. #endif
  232365. #endif
  232366. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232367. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232368. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232369. // compiled on its own).
  232370. #if JUCE_INCLUDED_FILE
  232371. class NSViewComponentInternal : public ComponentMovementWatcher
  232372. {
  232373. public:
  232374. NSViewComponentInternal (NSView* const view_, Component& owner_)
  232375. : ComponentMovementWatcher (&owner_),
  232376. owner (owner_),
  232377. currentPeer (0),
  232378. view (view_)
  232379. {
  232380. [view_ retain];
  232381. if (owner.isShowing())
  232382. componentPeerChanged();
  232383. }
  232384. ~NSViewComponentInternal()
  232385. {
  232386. [view removeFromSuperview];
  232387. [view release];
  232388. }
  232389. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232390. {
  232391. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232392. // The ComponentMovementWatcher version of this method avoids calling
  232393. // us when the top-level comp is resized, but for an NSView we need to know this
  232394. // because with inverted co-ords, we need to update the position even if the
  232395. // top-left pos hasn't changed
  232396. if (comp.isOnDesktop() && wasResized)
  232397. componentMovedOrResized (wasMoved, wasResized);
  232398. }
  232399. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232400. {
  232401. Component* const topComp = owner.getTopLevelComponent();
  232402. if (topComp->getPeer() != 0)
  232403. {
  232404. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  232405. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  232406. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232407. [view setFrame: r];
  232408. }
  232409. }
  232410. void componentPeerChanged()
  232411. {
  232412. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  232413. if (currentPeer != peer)
  232414. {
  232415. if ([view superview] != nil)
  232416. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232417. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232418. currentPeer = peer;
  232419. if (peer != 0)
  232420. {
  232421. [peer->view addSubview: view];
  232422. componentMovedOrResized (false, false);
  232423. }
  232424. }
  232425. [view setHidden: ! owner.isShowing()];
  232426. }
  232427. void componentVisibilityChanged()
  232428. {
  232429. componentPeerChanged();
  232430. }
  232431. const Rectangle<int> getViewBounds() const
  232432. {
  232433. NSRect r = [view frame];
  232434. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232435. }
  232436. private:
  232437. Component& owner;
  232438. NSViewComponentPeer* currentPeer;
  232439. public:
  232440. NSView* const view;
  232441. private:
  232442. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232443. };
  232444. NSViewComponent::NSViewComponent()
  232445. {
  232446. }
  232447. NSViewComponent::~NSViewComponent()
  232448. {
  232449. }
  232450. void NSViewComponent::setView (void* view)
  232451. {
  232452. if (view != getView())
  232453. {
  232454. if (view != 0)
  232455. info = new NSViewComponentInternal ((NSView*) view, *this);
  232456. else
  232457. info = 0;
  232458. }
  232459. }
  232460. void* NSViewComponent::getView() const
  232461. {
  232462. return info == 0 ? 0 : info->view;
  232463. }
  232464. void NSViewComponent::resizeToFitView()
  232465. {
  232466. if (info != 0)
  232467. setBounds (info->getViewBounds());
  232468. }
  232469. void NSViewComponent::paint (Graphics&)
  232470. {
  232471. }
  232472. #endif
  232473. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232474. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232475. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232476. // compiled on its own).
  232477. #if JUCE_INCLUDED_FILE
  232478. AppleRemoteDevice::AppleRemoteDevice()
  232479. : device (0),
  232480. queue (0),
  232481. remoteId (0)
  232482. {
  232483. }
  232484. AppleRemoteDevice::~AppleRemoteDevice()
  232485. {
  232486. stop();
  232487. }
  232488. namespace
  232489. {
  232490. io_object_t getAppleRemoteDevice()
  232491. {
  232492. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232493. io_iterator_t iter = 0;
  232494. io_object_t iod = 0;
  232495. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232496. && iter != 0)
  232497. {
  232498. iod = IOIteratorNext (iter);
  232499. }
  232500. IOObjectRelease (iter);
  232501. return iod;
  232502. }
  232503. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232504. {
  232505. jassert (*device == 0);
  232506. io_name_t classname;
  232507. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232508. {
  232509. IOCFPlugInInterface** cfPlugInInterface = 0;
  232510. SInt32 score = 0;
  232511. if (IOCreatePlugInInterfaceForService (iod,
  232512. kIOHIDDeviceUserClientTypeID,
  232513. kIOCFPlugInInterfaceID,
  232514. &cfPlugInInterface,
  232515. &score) == kIOReturnSuccess)
  232516. {
  232517. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232518. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232519. device);
  232520. (void) hr;
  232521. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232522. }
  232523. }
  232524. return *device != 0;
  232525. }
  232526. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232527. {
  232528. if (result == kIOReturnSuccess)
  232529. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232530. }
  232531. }
  232532. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232533. {
  232534. if (queue != 0)
  232535. return true;
  232536. stop();
  232537. bool result = false;
  232538. io_object_t iod = getAppleRemoteDevice();
  232539. if (iod != 0)
  232540. {
  232541. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232542. result = true;
  232543. else
  232544. stop();
  232545. IOObjectRelease (iod);
  232546. }
  232547. return result;
  232548. }
  232549. void AppleRemoteDevice::stop()
  232550. {
  232551. if (queue != 0)
  232552. {
  232553. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232554. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232555. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232556. queue = 0;
  232557. }
  232558. if (device != 0)
  232559. {
  232560. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232561. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232562. device = 0;
  232563. }
  232564. }
  232565. bool AppleRemoteDevice::isActive() const
  232566. {
  232567. return queue != 0;
  232568. }
  232569. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232570. {
  232571. Array <int> cookies;
  232572. CFArrayRef elements;
  232573. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232574. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232575. return false;
  232576. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232577. {
  232578. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232579. // get the cookie
  232580. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232581. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232582. continue;
  232583. long number;
  232584. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232585. continue;
  232586. cookies.add ((int) number);
  232587. }
  232588. CFRelease (elements);
  232589. if ((*(IOHIDDeviceInterface**) device)
  232590. ->open ((IOHIDDeviceInterface**) device,
  232591. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232592. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232593. {
  232594. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232595. if (queue != 0)
  232596. {
  232597. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232598. for (int i = 0; i < cookies.size(); ++i)
  232599. {
  232600. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232601. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232602. }
  232603. CFRunLoopSourceRef eventSource;
  232604. if ((*(IOHIDQueueInterface**) queue)
  232605. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232606. {
  232607. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232608. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232609. {
  232610. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232611. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232612. return true;
  232613. }
  232614. }
  232615. }
  232616. }
  232617. return false;
  232618. }
  232619. void AppleRemoteDevice::handleCallbackInternal()
  232620. {
  232621. int totalValues = 0;
  232622. AbsoluteTime nullTime = { 0, 0 };
  232623. char cookies [12];
  232624. int numCookies = 0;
  232625. while (numCookies < numElementsInArray (cookies))
  232626. {
  232627. IOHIDEventStruct e;
  232628. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232629. break;
  232630. if ((int) e.elementCookie == 19)
  232631. {
  232632. remoteId = e.value;
  232633. buttonPressed (switched, false);
  232634. }
  232635. else
  232636. {
  232637. totalValues += e.value;
  232638. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232639. }
  232640. }
  232641. cookies [numCookies++] = 0;
  232642. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232643. static const char buttonPatterns[] =
  232644. {
  232645. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232646. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232647. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232648. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232649. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232650. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232651. 0x1f, 0x12, 0x04, 0x02, 0,
  232652. 0x1f, 0x12, 0x03, 0x02, 0,
  232653. 0x1f, 0x12, 0x1f, 0x12, 0,
  232654. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232655. 19, 0
  232656. };
  232657. int buttonNum = (int) menuButton;
  232658. int i = 0;
  232659. while (i < numElementsInArray (buttonPatterns))
  232660. {
  232661. if (strcmp (cookies, buttonPatterns + i) == 0)
  232662. {
  232663. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232664. break;
  232665. }
  232666. i += (int) strlen (buttonPatterns + i) + 1;
  232667. ++buttonNum;
  232668. }
  232669. }
  232670. #endif
  232671. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232672. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232673. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232674. // compiled on its own).
  232675. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232676. #if JUCE_MAC
  232677. END_JUCE_NAMESPACE
  232678. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232679. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232680. {
  232681. CriticalSection* contextLock;
  232682. bool needsUpdate;
  232683. }
  232684. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232685. - (bool) makeActive;
  232686. - (void) makeInactive;
  232687. - (void) reshape;
  232688. - (void) rightMouseDown: (NSEvent*) ev;
  232689. - (void) rightMouseUp: (NSEvent*) ev;
  232690. @end
  232691. @implementation ThreadSafeNSOpenGLView
  232692. - (id) initWithFrame: (NSRect) frameRect
  232693. pixelFormat: (NSOpenGLPixelFormat*) format
  232694. {
  232695. contextLock = new CriticalSection();
  232696. self = [super initWithFrame: frameRect pixelFormat: format];
  232697. if (self != nil)
  232698. [[NSNotificationCenter defaultCenter] addObserver: self
  232699. selector: @selector (_surfaceNeedsUpdate:)
  232700. name: NSViewGlobalFrameDidChangeNotification
  232701. object: self];
  232702. return self;
  232703. }
  232704. - (void) dealloc
  232705. {
  232706. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232707. delete contextLock;
  232708. [super dealloc];
  232709. }
  232710. - (bool) makeActive
  232711. {
  232712. const ScopedLock sl (*contextLock);
  232713. if ([self openGLContext] == 0)
  232714. return false;
  232715. [[self openGLContext] makeCurrentContext];
  232716. if (needsUpdate)
  232717. {
  232718. [super update];
  232719. needsUpdate = false;
  232720. }
  232721. return true;
  232722. }
  232723. - (void) makeInactive
  232724. {
  232725. const ScopedLock sl (*contextLock);
  232726. [NSOpenGLContext clearCurrentContext];
  232727. }
  232728. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232729. {
  232730. (void) notification;
  232731. const ScopedLock sl (*contextLock);
  232732. needsUpdate = true;
  232733. }
  232734. - (void) update
  232735. {
  232736. const ScopedLock sl (*contextLock);
  232737. needsUpdate = true;
  232738. }
  232739. - (void) reshape
  232740. {
  232741. const ScopedLock sl (*contextLock);
  232742. needsUpdate = true;
  232743. }
  232744. - (void) rightMouseDown: (NSEvent*) ev
  232745. {
  232746. [[self superview] rightMouseDown: ev];
  232747. }
  232748. - (void) rightMouseUp: (NSEvent*) ev
  232749. {
  232750. [[self superview] rightMouseUp: ev];
  232751. }
  232752. @end
  232753. BEGIN_JUCE_NAMESPACE
  232754. class WindowedGLContext : public OpenGLContext
  232755. {
  232756. public:
  232757. WindowedGLContext (Component& component,
  232758. const OpenGLPixelFormat& pixelFormat_,
  232759. NSOpenGLContext* sharedContext)
  232760. : renderContext (0),
  232761. pixelFormat (pixelFormat_)
  232762. {
  232763. NSOpenGLPixelFormatAttribute attribs [64];
  232764. int n = 0;
  232765. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232766. attribs[n++] = NSOpenGLPFAAccelerated;
  232767. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232768. attribs[n++] = NSOpenGLPFAColorSize;
  232769. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232770. pixelFormat.greenBits,
  232771. pixelFormat.blueBits);
  232772. attribs[n++] = NSOpenGLPFAAlphaSize;
  232773. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232774. attribs[n++] = NSOpenGLPFADepthSize;
  232775. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232776. attribs[n++] = NSOpenGLPFAStencilSize;
  232777. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232778. attribs[n++] = NSOpenGLPFAAccumSize;
  232779. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232780. pixelFormat.accumulationBufferGreenBits,
  232781. pixelFormat.accumulationBufferBlueBits,
  232782. pixelFormat.accumulationBufferAlphaBits);
  232783. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232784. attribs[n++] = NSOpenGLPFASampleBuffers;
  232785. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232786. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232787. attribs[n++] = NSOpenGLPFANoRecovery;
  232788. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232789. NSOpenGLPixelFormat* format
  232790. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232791. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232792. pixelFormat: format];
  232793. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232794. shareContext: sharedContext] autorelease];
  232795. const GLint swapInterval = 1;
  232796. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232797. [view setOpenGLContext: renderContext];
  232798. [format release];
  232799. viewHolder = new NSViewComponentInternal (view, component);
  232800. }
  232801. ~WindowedGLContext()
  232802. {
  232803. deleteContext();
  232804. viewHolder = 0;
  232805. }
  232806. void deleteContext()
  232807. {
  232808. makeInactive();
  232809. [renderContext clearDrawable];
  232810. [renderContext setView: nil];
  232811. [view setOpenGLContext: nil];
  232812. renderContext = nil;
  232813. }
  232814. bool makeActive() const throw()
  232815. {
  232816. jassert (renderContext != 0);
  232817. if ([renderContext view] != view)
  232818. [renderContext setView: view];
  232819. [view makeActive];
  232820. return isActive();
  232821. }
  232822. bool makeInactive() const throw()
  232823. {
  232824. [view makeInactive];
  232825. return true;
  232826. }
  232827. bool isActive() const throw()
  232828. {
  232829. return [NSOpenGLContext currentContext] == renderContext;
  232830. }
  232831. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232832. void* getRawContext() const throw() { return renderContext; }
  232833. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232834. {
  232835. }
  232836. void swapBuffers()
  232837. {
  232838. [renderContext flushBuffer];
  232839. }
  232840. bool setSwapInterval (const int numFramesPerSwap)
  232841. {
  232842. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232843. forParameter: NSOpenGLCPSwapInterval];
  232844. return true;
  232845. }
  232846. int getSwapInterval() const
  232847. {
  232848. GLint numFrames = 0;
  232849. [renderContext getValues: &numFrames
  232850. forParameter: NSOpenGLCPSwapInterval];
  232851. return numFrames;
  232852. }
  232853. void repaint()
  232854. {
  232855. // we need to invalidate the juce view that holds this gl view, to make it
  232856. // cause a repaint callback
  232857. NSView* v = (NSView*) viewHolder->view;
  232858. NSRect r = [v frame];
  232859. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232860. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232861. // repaint message, thus never causing our paint() callback, and never repainting
  232862. // the comp. So invalidating just a little bit around the edge helps..
  232863. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232864. }
  232865. void* getNativeWindowHandle() const { return viewHolder->view; }
  232866. NSOpenGLContext* renderContext;
  232867. ThreadSafeNSOpenGLView* view;
  232868. private:
  232869. OpenGLPixelFormat pixelFormat;
  232870. ScopedPointer <NSViewComponentInternal> viewHolder;
  232871. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232872. };
  232873. OpenGLContext* OpenGLComponent::createContext()
  232874. {
  232875. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232876. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232877. return (c->renderContext != 0) ? c.release() : 0;
  232878. }
  232879. void* OpenGLComponent::getNativeWindowHandle() const
  232880. {
  232881. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232882. : 0;
  232883. }
  232884. void juce_glViewport (const int w, const int h)
  232885. {
  232886. glViewport (0, 0, w, h);
  232887. }
  232888. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232889. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232890. {
  232891. /* GLint attribs [64];
  232892. int n = 0;
  232893. attribs[n++] = AGL_RGBA;
  232894. attribs[n++] = AGL_DOUBLEBUFFER;
  232895. attribs[n++] = AGL_ACCELERATED;
  232896. attribs[n++] = AGL_NO_RECOVERY;
  232897. attribs[n++] = AGL_NONE;
  232898. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232899. while (p != 0)
  232900. {
  232901. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232902. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232903. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232904. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232905. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232906. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232907. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232908. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232909. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232910. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232911. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232912. results.add (pf);
  232913. p = aglNextPixelFormat (p);
  232914. }*/
  232915. //jassertfalse // can't see how you do this in cocoa!
  232916. }
  232917. #else
  232918. END_JUCE_NAMESPACE
  232919. @interface JuceGLView : UIView
  232920. {
  232921. }
  232922. + (Class) layerClass;
  232923. @end
  232924. @implementation JuceGLView
  232925. + (Class) layerClass
  232926. {
  232927. return [CAEAGLLayer class];
  232928. }
  232929. @end
  232930. BEGIN_JUCE_NAMESPACE
  232931. class GLESContext : public OpenGLContext
  232932. {
  232933. public:
  232934. GLESContext (UIViewComponentPeer* peer,
  232935. Component* const component_,
  232936. const OpenGLPixelFormat& pixelFormat_,
  232937. const GLESContext* const sharedContext,
  232938. NSUInteger apiType)
  232939. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232940. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232941. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232942. {
  232943. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232944. view.opaque = YES;
  232945. view.hidden = NO;
  232946. view.backgroundColor = [UIColor blackColor];
  232947. view.userInteractionEnabled = NO;
  232948. glLayer = (CAEAGLLayer*) [view layer];
  232949. [peer->view addSubview: view];
  232950. if (sharedContext != 0)
  232951. context = [[EAGLContext alloc] initWithAPI: apiType
  232952. sharegroup: [sharedContext->context sharegroup]];
  232953. else
  232954. context = [[EAGLContext alloc] initWithAPI: apiType];
  232955. createGLBuffers();
  232956. }
  232957. ~GLESContext()
  232958. {
  232959. deleteContext();
  232960. [view removeFromSuperview];
  232961. [view release];
  232962. freeGLBuffers();
  232963. }
  232964. void deleteContext()
  232965. {
  232966. makeInactive();
  232967. [context release];
  232968. context = nil;
  232969. }
  232970. bool makeActive() const throw()
  232971. {
  232972. jassert (context != 0);
  232973. [EAGLContext setCurrentContext: context];
  232974. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232975. return true;
  232976. }
  232977. void swapBuffers()
  232978. {
  232979. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232980. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232981. }
  232982. bool makeInactive() const throw()
  232983. {
  232984. return [EAGLContext setCurrentContext: nil];
  232985. }
  232986. bool isActive() const throw()
  232987. {
  232988. return [EAGLContext currentContext] == context;
  232989. }
  232990. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232991. void* getRawContext() const throw() { return glLayer; }
  232992. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232993. {
  232994. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232995. if (lastWidth != w || lastHeight != h)
  232996. {
  232997. lastWidth = w;
  232998. lastHeight = h;
  232999. freeGLBuffers();
  233000. createGLBuffers();
  233001. }
  233002. }
  233003. bool setSwapInterval (const int numFramesPerSwap)
  233004. {
  233005. numFrames = numFramesPerSwap;
  233006. return true;
  233007. }
  233008. int getSwapInterval() const
  233009. {
  233010. return numFrames;
  233011. }
  233012. void repaint()
  233013. {
  233014. }
  233015. void createGLBuffers()
  233016. {
  233017. makeActive();
  233018. glGenFramebuffersOES (1, &frameBufferHandle);
  233019. glGenRenderbuffersOES (1, &colorBufferHandle);
  233020. glGenRenderbuffersOES (1, &depthBufferHandle);
  233021. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233022. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233023. GLint width, height;
  233024. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233025. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233026. if (useDepthBuffer)
  233027. {
  233028. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233029. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233030. }
  233031. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233032. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233033. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233034. if (useDepthBuffer)
  233035. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233036. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233037. }
  233038. void freeGLBuffers()
  233039. {
  233040. if (frameBufferHandle != 0)
  233041. {
  233042. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233043. frameBufferHandle = 0;
  233044. }
  233045. if (colorBufferHandle != 0)
  233046. {
  233047. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233048. colorBufferHandle = 0;
  233049. }
  233050. if (depthBufferHandle != 0)
  233051. {
  233052. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233053. depthBufferHandle = 0;
  233054. }
  233055. }
  233056. private:
  233057. WeakReference<Component> component;
  233058. OpenGLPixelFormat pixelFormat;
  233059. JuceGLView* view;
  233060. CAEAGLLayer* glLayer;
  233061. EAGLContext* context;
  233062. bool useDepthBuffer;
  233063. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233064. int numFrames;
  233065. int lastWidth, lastHeight;
  233066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  233067. };
  233068. OpenGLContext* OpenGLComponent::createContext()
  233069. {
  233070. ScopedAutoReleasePool pool;
  233071. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233072. if (peer != 0)
  233073. return new GLESContext (peer, this, preferredPixelFormat,
  233074. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233075. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233076. return 0;
  233077. }
  233078. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233079. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233080. {
  233081. }
  233082. void juce_glViewport (const int w, const int h)
  233083. {
  233084. glViewport (0, 0, w, h);
  233085. }
  233086. #endif
  233087. #endif
  233088. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233089. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233090. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233091. // compiled on its own).
  233092. #if JUCE_INCLUDED_FILE
  233093. class JuceMainMenuHandler;
  233094. END_JUCE_NAMESPACE
  233095. using namespace JUCE_NAMESPACE;
  233096. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233097. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233098. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233099. #else
  233100. @interface JuceMenuCallback : NSObject
  233101. #endif
  233102. {
  233103. JuceMainMenuHandler* owner;
  233104. }
  233105. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233106. - (void) dealloc;
  233107. - (void) menuItemInvoked: (id) menu;
  233108. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233109. @end
  233110. BEGIN_JUCE_NAMESPACE
  233111. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233112. private DeletedAtShutdown
  233113. {
  233114. public:
  233115. JuceMainMenuHandler()
  233116. : currentModel (0),
  233117. lastUpdateTime (0)
  233118. {
  233119. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233120. }
  233121. ~JuceMainMenuHandler()
  233122. {
  233123. setMenu (0);
  233124. jassert (instance == this);
  233125. instance = 0;
  233126. [callback release];
  233127. }
  233128. void setMenu (MenuBarModel* const newMenuBarModel)
  233129. {
  233130. if (currentModel != newMenuBarModel)
  233131. {
  233132. if (currentModel != 0)
  233133. currentModel->removeListener (this);
  233134. currentModel = newMenuBarModel;
  233135. if (currentModel != 0)
  233136. currentModel->addListener (this);
  233137. menuBarItemsChanged (0);
  233138. }
  233139. }
  233140. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233141. const String& name, const int menuId, const int tag)
  233142. {
  233143. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233144. action: nil
  233145. keyEquivalent: @""];
  233146. [item setTag: tag];
  233147. NSMenu* sub = createMenu (child, name, menuId, tag);
  233148. [parent setSubmenu: sub forItem: item];
  233149. [sub setAutoenablesItems: false];
  233150. [sub release];
  233151. }
  233152. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233153. const String& name, const int menuId, const int tag)
  233154. {
  233155. [parentItem setTag: tag];
  233156. NSMenu* menu = [parentItem submenu];
  233157. [menu setTitle: juceStringToNS (name)];
  233158. while ([menu numberOfItems] > 0)
  233159. [menu removeItemAtIndex: 0];
  233160. PopupMenu::MenuItemIterator iter (menuToCopy);
  233161. while (iter.next())
  233162. addMenuItem (iter, menu, menuId, tag);
  233163. [menu setAutoenablesItems: false];
  233164. [menu update];
  233165. }
  233166. void menuBarItemsChanged (MenuBarModel*)
  233167. {
  233168. lastUpdateTime = Time::getMillisecondCounter();
  233169. StringArray menuNames;
  233170. if (currentModel != 0)
  233171. menuNames = currentModel->getMenuBarNames();
  233172. NSMenu* menuBar = [NSApp mainMenu];
  233173. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233174. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233175. int menuId = 1;
  233176. for (int i = 0; i < menuNames.size(); ++i)
  233177. {
  233178. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233179. if (i >= [menuBar numberOfItems] - 1)
  233180. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233181. else
  233182. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233183. }
  233184. }
  233185. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233186. {
  233187. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233188. if (item != 0)
  233189. flashMenuBar ([item menu]);
  233190. }
  233191. void updateMenus (NSMenu* menu)
  233192. {
  233193. if (PopupMenu::dismissAllActiveMenus())
  233194. {
  233195. // If we were running a juce menu, then we should let that modal loop finish before allowing
  233196. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  233197. if ([menu respondsToSelector: @selector (cancelTracking)])
  233198. [menu performSelector: @selector (cancelTracking)];
  233199. }
  233200. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233201. menuBarItemsChanged (0);
  233202. }
  233203. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233204. {
  233205. if (currentModel != 0)
  233206. {
  233207. if (commandManager != 0)
  233208. {
  233209. ApplicationCommandTarget::InvocationInfo info (commandId);
  233210. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233211. commandManager->invoke (info, true);
  233212. }
  233213. currentModel->menuItemSelected (commandId, topLevelIndex);
  233214. }
  233215. }
  233216. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233217. const int topLevelMenuId, const int topLevelIndex)
  233218. {
  233219. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233220. if (text == 0)
  233221. text = @"";
  233222. if (iter.isSeparator)
  233223. {
  233224. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233225. }
  233226. else if (iter.isSectionHeader)
  233227. {
  233228. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233229. action: nil
  233230. keyEquivalent: @""];
  233231. [item setEnabled: false];
  233232. }
  233233. else if (iter.subMenu != 0)
  233234. {
  233235. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233236. action: nil
  233237. keyEquivalent: @""];
  233238. [item setTag: iter.itemId];
  233239. [item setEnabled: iter.isEnabled];
  233240. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233241. [sub setDelegate: nil];
  233242. [menuToAddTo setSubmenu: sub forItem: item];
  233243. [sub release];
  233244. }
  233245. else
  233246. {
  233247. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233248. action: @selector (menuItemInvoked:)
  233249. keyEquivalent: @""];
  233250. [item setTag: iter.itemId];
  233251. [item setEnabled: iter.isEnabled];
  233252. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233253. [item setTarget: (id) callback];
  233254. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233255. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233256. [item setRepresentedObject: info];
  233257. if (iter.commandManager != 0)
  233258. {
  233259. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233260. ->getKeyPressesAssignedToCommand (iter.itemId));
  233261. if (keyPresses.size() > 0)
  233262. {
  233263. const KeyPress& kp = keyPresses.getReference(0);
  233264. if (kp.getKeyCode() != KeyPress::backspaceKey
  233265. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233266. // every time you press the key while editing text)
  233267. {
  233268. juce_wchar key = kp.getTextCharacter();
  233269. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233270. key = NSBackspaceCharacter;
  233271. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233272. key = NSDeleteCharacter;
  233273. else if (key == 0)
  233274. key = (juce_wchar) kp.getKeyCode();
  233275. unsigned int mods = 0;
  233276. if (kp.getModifiers().isShiftDown())
  233277. mods |= NSShiftKeyMask;
  233278. if (kp.getModifiers().isCtrlDown())
  233279. mods |= NSControlKeyMask;
  233280. if (kp.getModifiers().isAltDown())
  233281. mods |= NSAlternateKeyMask;
  233282. if (kp.getModifiers().isCommandDown())
  233283. mods |= NSCommandKeyMask;
  233284. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233285. [item setKeyEquivalentModifierMask: mods];
  233286. }
  233287. }
  233288. }
  233289. }
  233290. }
  233291. static JuceMainMenuHandler* instance;
  233292. MenuBarModel* currentModel;
  233293. uint32 lastUpdateTime;
  233294. JuceMenuCallback* callback;
  233295. private:
  233296. NSMenu* createMenu (const PopupMenu menu,
  233297. const String& menuName,
  233298. const int topLevelMenuId,
  233299. const int topLevelIndex)
  233300. {
  233301. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233302. [m setAutoenablesItems: false];
  233303. [m setDelegate: callback];
  233304. PopupMenu::MenuItemIterator iter (menu);
  233305. while (iter.next())
  233306. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233307. [m update];
  233308. return m;
  233309. }
  233310. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233311. {
  233312. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233313. {
  233314. NSMenuItem* m = [menu itemAtIndex: i];
  233315. if ([m tag] == info.commandID)
  233316. return m;
  233317. if ([m submenu] != 0)
  233318. {
  233319. NSMenuItem* found = findMenuItem ([m submenu], info);
  233320. if (found != 0)
  233321. return found;
  233322. }
  233323. }
  233324. return 0;
  233325. }
  233326. static void flashMenuBar (NSMenu* menu)
  233327. {
  233328. if ([[menu title] isEqualToString: @"Apple"])
  233329. return;
  233330. [menu retain];
  233331. const unichar f35Key = NSF35FunctionKey;
  233332. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233333. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233334. action: nil
  233335. keyEquivalent: f35String];
  233336. [item setTarget: nil];
  233337. [menu insertItem: item atIndex: [menu numberOfItems]];
  233338. [item release];
  233339. if ([menu indexOfItem: item] >= 0)
  233340. {
  233341. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233342. location: NSZeroPoint
  233343. modifierFlags: NSCommandKeyMask
  233344. timestamp: 0
  233345. windowNumber: 0
  233346. context: [NSGraphicsContext currentContext]
  233347. characters: f35String
  233348. charactersIgnoringModifiers: f35String
  233349. isARepeat: NO
  233350. keyCode: 0];
  233351. [menu performKeyEquivalent: f35Event];
  233352. if ([menu indexOfItem: item] >= 0)
  233353. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233354. }
  233355. [menu release];
  233356. }
  233357. };
  233358. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233359. END_JUCE_NAMESPACE
  233360. @implementation JuceMenuCallback
  233361. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233362. {
  233363. [super init];
  233364. owner = owner_;
  233365. return self;
  233366. }
  233367. - (void) dealloc
  233368. {
  233369. [super dealloc];
  233370. }
  233371. - (void) menuItemInvoked: (id) menu
  233372. {
  233373. NSMenuItem* item = (NSMenuItem*) menu;
  233374. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233375. {
  233376. // 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
  233377. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233378. // into the focused component and let it trigger the menu item indirectly.
  233379. NSEvent* e = [NSApp currentEvent];
  233380. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233381. {
  233382. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233383. {
  233384. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233385. if (peer != 0)
  233386. {
  233387. if ([e type] == NSKeyDown)
  233388. peer->redirectKeyDown (e);
  233389. else
  233390. peer->redirectKeyUp (e);
  233391. return;
  233392. }
  233393. }
  233394. }
  233395. NSArray* info = (NSArray*) [item representedObject];
  233396. owner->invoke ((int) [item tag],
  233397. (ApplicationCommandManager*) (pointer_sized_int)
  233398. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233399. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233400. }
  233401. }
  233402. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233403. {
  233404. if (JuceMainMenuHandler::instance != 0)
  233405. JuceMainMenuHandler::instance->updateMenus (menu);
  233406. }
  233407. @end
  233408. BEGIN_JUCE_NAMESPACE
  233409. namespace MainMenuHelpers
  233410. {
  233411. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233412. {
  233413. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233414. {
  233415. PopupMenu::MenuItemIterator iter (*extraItems);
  233416. while (iter.next())
  233417. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233418. [menu addItem: [NSMenuItem separatorItem]];
  233419. }
  233420. NSMenuItem* item;
  233421. // Services...
  233422. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233423. action: nil keyEquivalent: @""];
  233424. [menu addItem: item];
  233425. [item release];
  233426. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233427. [menu setSubmenu: servicesMenu forItem: item];
  233428. [NSApp setServicesMenu: servicesMenu];
  233429. [servicesMenu release];
  233430. [menu addItem: [NSMenuItem separatorItem]];
  233431. // Hide + Show stuff...
  233432. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233433. action: @selector (hide:) keyEquivalent: @"h"];
  233434. [item setTarget: NSApp];
  233435. [menu addItem: item];
  233436. [item release];
  233437. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233438. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233439. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233440. [item setTarget: NSApp];
  233441. [menu addItem: item];
  233442. [item release];
  233443. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233444. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233445. [item setTarget: NSApp];
  233446. [menu addItem: item];
  233447. [item release];
  233448. [menu addItem: [NSMenuItem separatorItem]];
  233449. // Quit item....
  233450. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233451. action: @selector (terminate:) keyEquivalent: @"q"];
  233452. [item setTarget: NSApp];
  233453. [menu addItem: item];
  233454. [item release];
  233455. return menu;
  233456. }
  233457. // Since our app has no NIB, this initialises a standard app menu...
  233458. void rebuildMainMenu (const PopupMenu* extraItems)
  233459. {
  233460. // this can't be used in a plugin!
  233461. jassert (JUCEApplication::isStandaloneApp());
  233462. if (JUCEApplication::getInstance() != 0)
  233463. {
  233464. const ScopedAutoReleasePool pool;
  233465. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233466. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233467. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233468. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233469. [mainMenu setSubmenu: appMenu forItem: item];
  233470. [NSApp setMainMenu: mainMenu];
  233471. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233472. [appMenu release];
  233473. [mainMenu release];
  233474. }
  233475. }
  233476. }
  233477. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233478. const PopupMenu* extraAppleMenuItems)
  233479. {
  233480. if (getMacMainMenu() != newMenuBarModel)
  233481. {
  233482. const ScopedAutoReleasePool pool;
  233483. if (newMenuBarModel == 0)
  233484. {
  233485. delete JuceMainMenuHandler::instance;
  233486. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233487. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233488. extraAppleMenuItems = 0;
  233489. }
  233490. else
  233491. {
  233492. if (JuceMainMenuHandler::instance == 0)
  233493. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233494. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233495. }
  233496. }
  233497. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233498. if (newMenuBarModel != 0)
  233499. newMenuBarModel->menuItemsChanged();
  233500. }
  233501. MenuBarModel* MenuBarModel::getMacMainMenu()
  233502. {
  233503. return JuceMainMenuHandler::instance != 0
  233504. ? JuceMainMenuHandler::instance->currentModel : 0;
  233505. }
  233506. void juce_initialiseMacMainMenu()
  233507. {
  233508. if (JuceMainMenuHandler::instance == 0)
  233509. MainMenuHelpers::rebuildMainMenu (0);
  233510. }
  233511. #endif
  233512. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233513. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233514. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233515. // compiled on its own).
  233516. #if JUCE_INCLUDED_FILE
  233517. #if JUCE_MAC
  233518. END_JUCE_NAMESPACE
  233519. using namespace JUCE_NAMESPACE;
  233520. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233521. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233522. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233523. #else
  233524. @interface JuceFileChooserDelegate : NSObject
  233525. #endif
  233526. {
  233527. StringArray* filters;
  233528. }
  233529. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233530. - (void) dealloc;
  233531. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233532. @end
  233533. @implementation JuceFileChooserDelegate
  233534. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233535. {
  233536. [super init];
  233537. filters = filters_;
  233538. return self;
  233539. }
  233540. - (void) dealloc
  233541. {
  233542. delete filters;
  233543. [super dealloc];
  233544. }
  233545. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233546. {
  233547. (void) sender;
  233548. const File f (nsStringToJuce (filename));
  233549. for (int i = filters->size(); --i >= 0;)
  233550. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233551. return true;
  233552. return f.isDirectory();
  233553. }
  233554. @end
  233555. BEGIN_JUCE_NAMESPACE
  233556. void FileChooser::showPlatformDialog (Array<File>& results,
  233557. const String& title,
  233558. const File& currentFileOrDirectory,
  233559. const String& filter,
  233560. bool selectsDirectory,
  233561. bool selectsFiles,
  233562. bool isSaveDialogue,
  233563. bool /*warnAboutOverwritingExistingFiles*/,
  233564. bool selectMultipleFiles,
  233565. FilePreviewComponent* /*extraInfoComponent*/)
  233566. {
  233567. const ScopedAutoReleasePool pool;
  233568. StringArray* filters = new StringArray();
  233569. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233570. filters->trim();
  233571. filters->removeEmptyStrings();
  233572. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233573. [delegate autorelease];
  233574. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233575. : [NSOpenPanel openPanel];
  233576. [panel setTitle: juceStringToNS (title)];
  233577. if (! isSaveDialogue)
  233578. {
  233579. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233580. [openPanel setCanChooseDirectories: selectsDirectory];
  233581. [openPanel setCanChooseFiles: selectsFiles];
  233582. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233583. }
  233584. [panel setDelegate: delegate];
  233585. if (isSaveDialogue || selectsDirectory)
  233586. [panel setCanCreateDirectories: YES];
  233587. String directory, filename;
  233588. if (currentFileOrDirectory.isDirectory())
  233589. {
  233590. directory = currentFileOrDirectory.getFullPathName();
  233591. }
  233592. else
  233593. {
  233594. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233595. filename = currentFileOrDirectory.getFileName();
  233596. }
  233597. if ([panel runModalForDirectory: juceStringToNS (directory)
  233598. file: juceStringToNS (filename)]
  233599. == NSOKButton)
  233600. {
  233601. if (isSaveDialogue)
  233602. {
  233603. results.add (File (nsStringToJuce ([panel filename])));
  233604. }
  233605. else
  233606. {
  233607. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233608. NSArray* urls = [openPanel filenames];
  233609. for (unsigned int i = 0; i < [urls count]; ++i)
  233610. {
  233611. NSString* f = [urls objectAtIndex: i];
  233612. results.add (File (nsStringToJuce (f)));
  233613. }
  233614. }
  233615. }
  233616. [panel setDelegate: nil];
  233617. }
  233618. #else
  233619. void FileChooser::showPlatformDialog (Array<File>& results,
  233620. const String& title,
  233621. const File& currentFileOrDirectory,
  233622. const String& filter,
  233623. bool selectsDirectory,
  233624. bool selectsFiles,
  233625. bool isSaveDialogue,
  233626. bool warnAboutOverwritingExistingFiles,
  233627. bool selectMultipleFiles,
  233628. FilePreviewComponent* extraInfoComponent)
  233629. {
  233630. const ScopedAutoReleasePool pool;
  233631. jassertfalse; //xxx to do
  233632. }
  233633. #endif
  233634. #endif
  233635. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233636. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233637. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233638. // compiled on its own).
  233639. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233640. END_JUCE_NAMESPACE
  233641. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233642. @interface NonInterceptingQTMovieView : QTMovieView
  233643. {
  233644. }
  233645. - (id) initWithFrame: (NSRect) frame;
  233646. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233647. - (NSView*) hitTest: (NSPoint) p;
  233648. @end
  233649. @implementation NonInterceptingQTMovieView
  233650. - (id) initWithFrame: (NSRect) frame
  233651. {
  233652. self = [super initWithFrame: frame];
  233653. [self setNextResponder: [self superview]];
  233654. return self;
  233655. }
  233656. - (void) dealloc
  233657. {
  233658. [super dealloc];
  233659. }
  233660. - (NSView*) hitTest: (NSPoint) point
  233661. {
  233662. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233663. }
  233664. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233665. {
  233666. return YES;
  233667. }
  233668. @end
  233669. BEGIN_JUCE_NAMESPACE
  233670. #define theMovie (static_cast <QTMovie*> (movie))
  233671. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233672. : movie (0)
  233673. {
  233674. setOpaque (true);
  233675. setVisible (true);
  233676. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233677. setView (view);
  233678. [view release];
  233679. }
  233680. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233681. {
  233682. closeMovie();
  233683. setView (0);
  233684. }
  233685. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233686. {
  233687. return true;
  233688. }
  233689. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233690. {
  233691. // unfortunately, QTMovie objects can only be created on the main thread..
  233692. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233693. QTMovie* movie = 0;
  233694. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233695. if (fin != 0)
  233696. {
  233697. movieFile = fin->getFile();
  233698. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233699. error: nil];
  233700. }
  233701. else
  233702. {
  233703. MemoryBlock temp;
  233704. movieStream->readIntoMemoryBlock (temp);
  233705. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233706. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233707. {
  233708. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233709. length: temp.getSize()]
  233710. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233711. MIMEType: @""]
  233712. error: nil];
  233713. if (movie != 0)
  233714. break;
  233715. }
  233716. }
  233717. return movie;
  233718. }
  233719. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233720. const bool isControllerVisible_)
  233721. {
  233722. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233723. }
  233724. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233725. const bool controllerVisible_)
  233726. {
  233727. closeMovie();
  233728. if (getPeer() == 0)
  233729. {
  233730. // To open a movie, this component must be visible inside a functioning window, so that
  233731. // the QT control can be assigned to the window.
  233732. jassertfalse;
  233733. return false;
  233734. }
  233735. movie = openMovieFromStream (movieStream, movieFile);
  233736. [theMovie retain];
  233737. QTMovieView* view = (QTMovieView*) getView();
  233738. [view setMovie: theMovie];
  233739. [view setControllerVisible: controllerVisible_];
  233740. setLooping (looping);
  233741. return movie != nil;
  233742. }
  233743. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233744. const bool isControllerVisible_)
  233745. {
  233746. // unfortunately, QTMovie objects can only be created on the main thread..
  233747. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233748. closeMovie();
  233749. if (getPeer() == 0)
  233750. {
  233751. // To open a movie, this component must be visible inside a functioning window, so that
  233752. // the QT control can be assigned to the window.
  233753. jassertfalse;
  233754. return false;
  233755. }
  233756. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233757. NSError* err;
  233758. if ([QTMovie canInitWithURL: url])
  233759. movie = [QTMovie movieWithURL: url error: &err];
  233760. [theMovie retain];
  233761. QTMovieView* view = (QTMovieView*) getView();
  233762. [view setMovie: theMovie];
  233763. [view setControllerVisible: controllerVisible];
  233764. setLooping (looping);
  233765. return movie != nil;
  233766. }
  233767. void QuickTimeMovieComponent::closeMovie()
  233768. {
  233769. stop();
  233770. QTMovieView* view = (QTMovieView*) getView();
  233771. [view setMovie: nil];
  233772. [theMovie release];
  233773. movie = 0;
  233774. movieFile = File::nonexistent;
  233775. }
  233776. bool QuickTimeMovieComponent::isMovieOpen() const
  233777. {
  233778. return movie != nil;
  233779. }
  233780. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233781. {
  233782. return movieFile;
  233783. }
  233784. void QuickTimeMovieComponent::play()
  233785. {
  233786. [theMovie play];
  233787. }
  233788. void QuickTimeMovieComponent::stop()
  233789. {
  233790. [theMovie stop];
  233791. }
  233792. bool QuickTimeMovieComponent::isPlaying() const
  233793. {
  233794. return movie != 0 && [theMovie rate] != 0;
  233795. }
  233796. void QuickTimeMovieComponent::setPosition (const double seconds)
  233797. {
  233798. if (movie != 0)
  233799. {
  233800. QTTime t;
  233801. t.timeValue = (uint64) (100000.0 * seconds);
  233802. t.timeScale = 100000;
  233803. t.flags = 0;
  233804. [theMovie setCurrentTime: t];
  233805. }
  233806. }
  233807. double QuickTimeMovieComponent::getPosition() const
  233808. {
  233809. if (movie == 0)
  233810. return 0.0;
  233811. QTTime t = [theMovie currentTime];
  233812. return t.timeValue / (double) t.timeScale;
  233813. }
  233814. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233815. {
  233816. [theMovie setRate: newSpeed];
  233817. }
  233818. double QuickTimeMovieComponent::getMovieDuration() const
  233819. {
  233820. if (movie == 0)
  233821. return 0.0;
  233822. QTTime t = [theMovie duration];
  233823. return t.timeValue / (double) t.timeScale;
  233824. }
  233825. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233826. {
  233827. looping = shouldLoop;
  233828. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233829. forKey: QTMovieLoopsAttribute];
  233830. }
  233831. bool QuickTimeMovieComponent::isLooping() const
  233832. {
  233833. return looping;
  233834. }
  233835. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233836. {
  233837. [theMovie setVolume: newVolume];
  233838. }
  233839. float QuickTimeMovieComponent::getMovieVolume() const
  233840. {
  233841. return movie != 0 ? [theMovie volume] : 0.0f;
  233842. }
  233843. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233844. {
  233845. width = 0;
  233846. height = 0;
  233847. if (movie != 0)
  233848. {
  233849. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233850. width = (int) s.width;
  233851. height = (int) s.height;
  233852. }
  233853. }
  233854. void QuickTimeMovieComponent::paint (Graphics& g)
  233855. {
  233856. if (movie == 0)
  233857. g.fillAll (Colours::black);
  233858. }
  233859. bool QuickTimeMovieComponent::isControllerVisible() const
  233860. {
  233861. return controllerVisible;
  233862. }
  233863. void QuickTimeMovieComponent::goToStart()
  233864. {
  233865. setPosition (0.0);
  233866. }
  233867. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233868. const RectanglePlacement& placement)
  233869. {
  233870. int normalWidth, normalHeight;
  233871. getMovieNormalSize (normalWidth, normalHeight);
  233872. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233873. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233874. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233875. else
  233876. setBounds (spaceToFitWithin);
  233877. }
  233878. #if ! (JUCE_MAC && JUCE_64BIT)
  233879. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233880. {
  233881. if (movieStream == 0)
  233882. return false;
  233883. File file;
  233884. QTMovie* movie = openMovieFromStream (movieStream, file);
  233885. if (movie != nil)
  233886. result = [movie quickTimeMovie];
  233887. return movie != nil;
  233888. }
  233889. #endif
  233890. #endif
  233891. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233892. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233893. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233894. // compiled on its own).
  233895. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233896. const int kilobytesPerSecond1x = 176;
  233897. END_JUCE_NAMESPACE
  233898. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233899. @interface OpenDiskDevice : NSObject
  233900. {
  233901. @public
  233902. DRDevice* device;
  233903. NSMutableArray* tracks;
  233904. bool underrunProtection;
  233905. }
  233906. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233907. - (void) dealloc;
  233908. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233909. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233910. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233911. @end
  233912. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233913. @interface AudioTrackProducer : NSObject
  233914. {
  233915. JUCE_NAMESPACE::AudioSource* source;
  233916. int readPosition, lengthInFrames;
  233917. }
  233918. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233919. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233920. - (void) dealloc;
  233921. - (void) setupTrackProperties: (DRTrack*) track;
  233922. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233923. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233924. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233925. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233926. toMedia:(NSDictionary*)mediaInfo;
  233927. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233928. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233929. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233930. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233931. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233932. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233933. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233934. ioFlags:(uint32_t*)flags;
  233935. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233936. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233937. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233938. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233939. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233940. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233941. ioFlags:(uint32_t*)flags;
  233942. @end
  233943. @implementation OpenDiskDevice
  233944. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233945. {
  233946. [super init];
  233947. device = device_;
  233948. tracks = [[NSMutableArray alloc] init];
  233949. underrunProtection = true;
  233950. return self;
  233951. }
  233952. - (void) dealloc
  233953. {
  233954. [tracks release];
  233955. [super dealloc];
  233956. }
  233957. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233958. {
  233959. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233960. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233961. [p setupTrackProperties: t];
  233962. [tracks addObject: t];
  233963. [t release];
  233964. [p release];
  233965. }
  233966. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233967. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233968. {
  233969. DRBurn* burn = [DRBurn burnForDevice: device];
  233970. if (! [device acquireExclusiveAccess])
  233971. {
  233972. *error = "Couldn't open or write to the CD device";
  233973. return;
  233974. }
  233975. [device acquireMediaReservation];
  233976. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233977. [d autorelease];
  233978. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233979. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233980. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233981. if (burnSpeed > 0)
  233982. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233983. if (! underrunProtection)
  233984. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233985. [burn setProperties: d];
  233986. [burn writeLayout: tracks];
  233987. for (;;)
  233988. {
  233989. JUCE_NAMESPACE::Thread::sleep (300);
  233990. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233991. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233992. {
  233993. [burn abort];
  233994. *error = "User cancelled the write operation";
  233995. break;
  233996. }
  233997. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233998. {
  233999. *error = "Write operation failed";
  234000. break;
  234001. }
  234002. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234003. {
  234004. break;
  234005. }
  234006. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234007. objectForKey: DRErrorStatusErrorStringKey];
  234008. if ([err length] > 0)
  234009. {
  234010. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234011. break;
  234012. }
  234013. }
  234014. [device releaseMediaReservation];
  234015. [device releaseExclusiveAccess];
  234016. }
  234017. @end
  234018. @implementation AudioTrackProducer
  234019. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234020. {
  234021. lengthInFrames = lengthInFrames_;
  234022. readPosition = 0;
  234023. return self;
  234024. }
  234025. - (void) setupTrackProperties: (DRTrack*) track
  234026. {
  234027. NSMutableDictionary* p = [[track properties] mutableCopy];
  234028. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234029. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234030. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234031. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234032. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234033. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234034. [track setProperties: p];
  234035. [p release];
  234036. }
  234037. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234038. {
  234039. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234040. if (s != nil)
  234041. s->source = source_;
  234042. return s;
  234043. }
  234044. - (void) dealloc
  234045. {
  234046. if (source != 0)
  234047. {
  234048. source->releaseResources();
  234049. delete source;
  234050. }
  234051. [super dealloc];
  234052. }
  234053. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234054. {
  234055. (void) track;
  234056. }
  234057. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234058. {
  234059. (void) track;
  234060. return true;
  234061. }
  234062. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234063. {
  234064. (void) track;
  234065. return lengthInFrames;
  234066. }
  234067. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234068. toMedia: (NSDictionary*) mediaInfo
  234069. {
  234070. (void) track; (void) burn; (void) mediaInfo;
  234071. if (source != 0)
  234072. source->prepareToPlay (44100 / 75, 44100);
  234073. readPosition = 0;
  234074. return true;
  234075. }
  234076. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234077. {
  234078. (void) track;
  234079. if (source != 0)
  234080. source->prepareToPlay (44100 / 75, 44100);
  234081. return true;
  234082. }
  234083. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234084. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234085. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234086. {
  234087. (void) track; (void) address; (void) blockSize; (void) flags;
  234088. if (source != 0)
  234089. {
  234090. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234091. if (numSamples > 0)
  234092. {
  234093. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234094. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234095. info.buffer = &tempBuffer;
  234096. info.startSample = 0;
  234097. info.numSamples = numSamples;
  234098. source->getNextAudioBlock (info);
  234099. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234100. JUCE_NAMESPACE::AudioData::LittleEndian,
  234101. JUCE_NAMESPACE::AudioData::Interleaved,
  234102. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234103. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234104. JUCE_NAMESPACE::AudioData::NativeEndian,
  234105. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234106. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234107. CDSampleFormat left (buffer, 2);
  234108. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234109. CDSampleFormat right (buffer + 2, 2);
  234110. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234111. readPosition += numSamples;
  234112. }
  234113. return numSamples * 4;
  234114. }
  234115. return 0;
  234116. }
  234117. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234118. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234119. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234120. ioFlags: (uint32_t*) flags
  234121. {
  234122. (void) track; (void) address; (void) blockSize; (void) flags;
  234123. zeromem (buffer, bufferLength);
  234124. return bufferLength;
  234125. }
  234126. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234127. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234128. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234129. {
  234130. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  234131. return true;
  234132. }
  234133. @end
  234134. BEGIN_JUCE_NAMESPACE
  234135. class AudioCDBurner::Pimpl : public Timer
  234136. {
  234137. public:
  234138. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234139. : device (0), owner (owner_)
  234140. {
  234141. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234142. if (dev != 0)
  234143. {
  234144. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234145. lastState = getDiskState();
  234146. startTimer (1000);
  234147. }
  234148. }
  234149. ~Pimpl()
  234150. {
  234151. stopTimer();
  234152. [device release];
  234153. }
  234154. void timerCallback()
  234155. {
  234156. const DiskState state = getDiskState();
  234157. if (state != lastState)
  234158. {
  234159. lastState = state;
  234160. owner.sendChangeMessage();
  234161. }
  234162. }
  234163. DiskState getDiskState() const
  234164. {
  234165. if ([device->device isValid])
  234166. {
  234167. NSDictionary* status = [device->device status];
  234168. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234169. if ([state isEqualTo: DRDeviceMediaStateNone])
  234170. {
  234171. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234172. return trayOpen;
  234173. return noDisc;
  234174. }
  234175. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234176. {
  234177. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234178. return writableDiskPresent;
  234179. else
  234180. return readOnlyDiskPresent;
  234181. }
  234182. }
  234183. return unknown;
  234184. }
  234185. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234186. const Array<int> getAvailableWriteSpeeds() const
  234187. {
  234188. Array<int> results;
  234189. if ([device->device isValid])
  234190. {
  234191. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234192. for (unsigned int i = 0; i < [speeds count]; ++i)
  234193. {
  234194. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234195. results.add (kbPerSec / kilobytesPerSecond1x);
  234196. }
  234197. }
  234198. return results;
  234199. }
  234200. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234201. {
  234202. if ([device->device isValid])
  234203. {
  234204. device->underrunProtection = shouldBeEnabled;
  234205. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234206. }
  234207. return false;
  234208. }
  234209. int getNumAvailableAudioBlocks() const
  234210. {
  234211. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234212. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234213. }
  234214. OpenDiskDevice* device;
  234215. private:
  234216. DiskState lastState;
  234217. AudioCDBurner& owner;
  234218. };
  234219. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234220. {
  234221. pimpl = new Pimpl (*this, deviceIndex);
  234222. }
  234223. AudioCDBurner::~AudioCDBurner()
  234224. {
  234225. }
  234226. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234227. {
  234228. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234229. if (b->pimpl->device == 0)
  234230. b = 0;
  234231. return b.release();
  234232. }
  234233. namespace
  234234. {
  234235. NSArray* findDiskBurnerDevices()
  234236. {
  234237. NSMutableArray* results = [NSMutableArray array];
  234238. NSArray* devs = [DRDevice devices];
  234239. for (int i = 0; i < [devs count]; ++i)
  234240. {
  234241. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234242. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234243. if (name != nil)
  234244. [results addObject: name];
  234245. }
  234246. return results;
  234247. }
  234248. }
  234249. const StringArray AudioCDBurner::findAvailableDevices()
  234250. {
  234251. NSArray* names = findDiskBurnerDevices();
  234252. StringArray s;
  234253. for (unsigned int i = 0; i < [names count]; ++i)
  234254. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234255. return s;
  234256. }
  234257. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234258. {
  234259. return pimpl->getDiskState();
  234260. }
  234261. bool AudioCDBurner::isDiskPresent() const
  234262. {
  234263. return getDiskState() == writableDiskPresent;
  234264. }
  234265. bool AudioCDBurner::openTray()
  234266. {
  234267. return pimpl->openTray();
  234268. }
  234269. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234270. {
  234271. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234272. DiskState oldState = getDiskState();
  234273. DiskState newState = oldState;
  234274. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234275. {
  234276. newState = getDiskState();
  234277. Thread::sleep (100);
  234278. }
  234279. return newState;
  234280. }
  234281. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234282. {
  234283. return pimpl->getAvailableWriteSpeeds();
  234284. }
  234285. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234286. {
  234287. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234288. }
  234289. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234290. {
  234291. return pimpl->getNumAvailableAudioBlocks();
  234292. }
  234293. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234294. {
  234295. if ([pimpl->device->device isValid])
  234296. {
  234297. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234298. return true;
  234299. }
  234300. return false;
  234301. }
  234302. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234303. bool ejectDiscAfterwards,
  234304. bool performFakeBurnForTesting,
  234305. int writeSpeed)
  234306. {
  234307. String error ("Couldn't open or write to the CD device");
  234308. if ([pimpl->device->device isValid])
  234309. {
  234310. error = String::empty;
  234311. [pimpl->device burn: listener
  234312. errorString: &error
  234313. ejectAfterwards: ejectDiscAfterwards
  234314. isFake: performFakeBurnForTesting
  234315. speed: writeSpeed];
  234316. }
  234317. return error;
  234318. }
  234319. #endif
  234320. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234321. void AudioCDReader::ejectDisk()
  234322. {
  234323. const ScopedAutoReleasePool p;
  234324. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234325. }
  234326. #endif
  234327. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234328. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234329. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234330. // compiled on its own).
  234331. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234332. namespace CDReaderHelpers
  234333. {
  234334. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234335. {
  234336. forEachXmlChildElementWithTagName (xml, child, "key")
  234337. if (child->getAllSubText().trim() == key)
  234338. return child->getNextElement();
  234339. return 0;
  234340. }
  234341. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234342. {
  234343. const XmlElement* const block = getElementForKey (xml, key);
  234344. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234345. }
  234346. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234347. // Returns NULL on success, otherwise a const char* representing an error.
  234348. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234349. {
  234350. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234351. if (xml == 0)
  234352. return "Couldn't parse XML in file";
  234353. const XmlElement* const dict = xml->getChildByName ("dict");
  234354. if (dict == 0)
  234355. return "Couldn't get top level dictionary";
  234356. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234357. if (sessions == 0)
  234358. return "Couldn't find sessions key";
  234359. const XmlElement* const session = sessions->getFirstChildElement();
  234360. if (session == 0)
  234361. return "Couldn't find first session";
  234362. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234363. if (leadOut < 0)
  234364. return "Couldn't find Leadout Block";
  234365. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234366. if (trackArray == 0)
  234367. return "Couldn't find Track Array";
  234368. forEachXmlChildElement (*trackArray, track)
  234369. {
  234370. const int trackValue = getIntValueForKey (*track, "Start Block");
  234371. if (trackValue < 0)
  234372. return "Couldn't find Start Block in the track";
  234373. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234374. }
  234375. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234376. return 0;
  234377. }
  234378. static void findDevices (Array<File>& cds)
  234379. {
  234380. File volumes ("/Volumes");
  234381. volumes.findChildFiles (cds, File::findDirectories, false);
  234382. for (int i = cds.size(); --i >= 0;)
  234383. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234384. cds.remove (i);
  234385. }
  234386. struct TrackSorter
  234387. {
  234388. static int getCDTrackNumber (const File& file)
  234389. {
  234390. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234391. }
  234392. static int compareElements (const File& first, const File& second)
  234393. {
  234394. const int firstTrack = getCDTrackNumber (first);
  234395. const int secondTrack = getCDTrackNumber (second);
  234396. jassert (firstTrack > 0 && secondTrack > 0);
  234397. return firstTrack - secondTrack;
  234398. }
  234399. };
  234400. }
  234401. const StringArray AudioCDReader::getAvailableCDNames()
  234402. {
  234403. Array<File> cds;
  234404. CDReaderHelpers::findDevices (cds);
  234405. StringArray names;
  234406. for (int i = 0; i < cds.size(); ++i)
  234407. names.add (cds.getReference(i).getFileName());
  234408. return names;
  234409. }
  234410. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234411. {
  234412. Array<File> cds;
  234413. CDReaderHelpers::findDevices (cds);
  234414. if (cds[index].exists())
  234415. return new AudioCDReader (cds[index]);
  234416. return 0;
  234417. }
  234418. AudioCDReader::AudioCDReader (const File& volume)
  234419. : AudioFormatReader (0, "CD Audio"),
  234420. volumeDir (volume),
  234421. currentReaderTrack (-1),
  234422. reader (0)
  234423. {
  234424. sampleRate = 44100.0;
  234425. bitsPerSample = 16;
  234426. numChannels = 2;
  234427. usesFloatingPointData = false;
  234428. refreshTrackLengths();
  234429. }
  234430. AudioCDReader::~AudioCDReader()
  234431. {
  234432. }
  234433. void AudioCDReader::refreshTrackLengths()
  234434. {
  234435. tracks.clear();
  234436. trackStartSamples.clear();
  234437. lengthInSamples = 0;
  234438. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234439. CDReaderHelpers::TrackSorter sorter;
  234440. tracks.sort (sorter);
  234441. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234442. if (toc.exists())
  234443. {
  234444. XmlDocument doc (toc);
  234445. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234446. (void) error; // could be logged..
  234447. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234448. }
  234449. }
  234450. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234451. int64 startSampleInFile, int numSamples)
  234452. {
  234453. while (numSamples > 0)
  234454. {
  234455. int track = -1;
  234456. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234457. {
  234458. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234459. {
  234460. track = i;
  234461. break;
  234462. }
  234463. }
  234464. if (track < 0)
  234465. return false;
  234466. if (track != currentReaderTrack)
  234467. {
  234468. reader = 0;
  234469. FileInputStream* const in = tracks [track].createInputStream();
  234470. if (in != 0)
  234471. {
  234472. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234473. AiffAudioFormat format;
  234474. reader = format.createReaderFor (bin, true);
  234475. if (reader == 0)
  234476. currentReaderTrack = -1;
  234477. else
  234478. currentReaderTrack = track;
  234479. }
  234480. }
  234481. if (reader == 0)
  234482. return false;
  234483. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234484. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234485. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234486. numSamples -= numAvailable;
  234487. startSampleInFile += numAvailable;
  234488. }
  234489. return true;
  234490. }
  234491. bool AudioCDReader::isCDStillPresent() const
  234492. {
  234493. return volumeDir.exists();
  234494. }
  234495. bool AudioCDReader::isTrackAudio (int trackNum) const
  234496. {
  234497. return tracks [trackNum].hasFileExtension (".aiff");
  234498. }
  234499. void AudioCDReader::enableIndexScanning (bool)
  234500. {
  234501. // any way to do this on a Mac??
  234502. }
  234503. int AudioCDReader::getLastIndex() const
  234504. {
  234505. return 0;
  234506. }
  234507. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  234508. {
  234509. return Array <int>();
  234510. }
  234511. #endif
  234512. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234513. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234514. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234515. // compiled on its own).
  234516. #if JUCE_INCLUDED_FILE
  234517. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234518. for example having more than one juce plugin loaded into a host, then when a
  234519. method is called, the actual code that runs might actually be in a different module
  234520. than the one you expect... So any calls to library functions or statics that are
  234521. made inside obj-c methods will probably end up getting executed in a different DLL's
  234522. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234523. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234524. virtual methods of an object that's known to live inside the right module's space.
  234525. */
  234526. class AppDelegateRedirector
  234527. {
  234528. public:
  234529. AppDelegateRedirector()
  234530. {
  234531. }
  234532. virtual ~AppDelegateRedirector()
  234533. {
  234534. }
  234535. virtual NSApplicationTerminateReply shouldTerminate()
  234536. {
  234537. if (JUCEApplication::getInstance() != 0)
  234538. {
  234539. JUCEApplication::getInstance()->systemRequestedQuit();
  234540. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234541. return NSTerminateCancel;
  234542. }
  234543. return NSTerminateNow;
  234544. }
  234545. virtual void willTerminate()
  234546. {
  234547. JUCEApplication::appWillTerminateByForce();
  234548. }
  234549. virtual BOOL openFile (NSString* filename)
  234550. {
  234551. if (JUCEApplication::getInstance() != 0)
  234552. {
  234553. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  234554. return YES;
  234555. }
  234556. return NO;
  234557. }
  234558. virtual void openFiles (NSArray* filenames)
  234559. {
  234560. StringArray files;
  234561. for (unsigned int i = 0; i < [filenames count]; ++i)
  234562. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  234563. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234564. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234565. }
  234566. virtual void focusChanged()
  234567. {
  234568. juce_HandleProcessFocusChange();
  234569. }
  234570. struct CallbackMessagePayload
  234571. {
  234572. MessageCallbackFunction* function;
  234573. void* parameter;
  234574. void* volatile result;
  234575. bool volatile hasBeenExecuted;
  234576. };
  234577. virtual void performCallback (CallbackMessagePayload* pl)
  234578. {
  234579. pl->result = (*pl->function) (pl->parameter);
  234580. pl->hasBeenExecuted = true;
  234581. }
  234582. virtual void deleteSelf()
  234583. {
  234584. delete this;
  234585. }
  234586. void postMessage (Message* const m)
  234587. {
  234588. messageQueue.post (m);
  234589. }
  234590. private:
  234591. CFRunLoopRef runLoop;
  234592. CFRunLoopSourceRef runLoopSource;
  234593. MessageQueue messageQueue;
  234594. static const String quotedIfContainsSpaces (NSString* file)
  234595. {
  234596. String s (nsStringToJuce (file));
  234597. if (s.containsChar (' '))
  234598. s = s.quoted ('"');
  234599. return s;
  234600. }
  234601. };
  234602. END_JUCE_NAMESPACE
  234603. using namespace JUCE_NAMESPACE;
  234604. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234605. @interface JuceAppDelegate : NSObject
  234606. {
  234607. @private
  234608. id oldDelegate;
  234609. @public
  234610. AppDelegateRedirector* redirector;
  234611. }
  234612. - (JuceAppDelegate*) init;
  234613. - (void) dealloc;
  234614. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234615. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234616. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234617. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234618. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234619. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234620. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234621. - (void) performCallback: (id) info;
  234622. - (void) dummyMethod;
  234623. @end
  234624. @implementation JuceAppDelegate
  234625. - (JuceAppDelegate*) init
  234626. {
  234627. [super init];
  234628. redirector = new AppDelegateRedirector();
  234629. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234630. if (JUCEApplication::isStandaloneApp())
  234631. {
  234632. oldDelegate = [NSApp delegate];
  234633. [NSApp setDelegate: self];
  234634. }
  234635. else
  234636. {
  234637. oldDelegate = 0;
  234638. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234639. name: NSApplicationDidResignActiveNotification object: NSApp];
  234640. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234641. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234642. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234643. name: NSApplicationWillUnhideNotification object: NSApp];
  234644. }
  234645. return self;
  234646. }
  234647. - (void) dealloc
  234648. {
  234649. if (oldDelegate != 0)
  234650. [NSApp setDelegate: oldDelegate];
  234651. redirector->deleteSelf();
  234652. [super dealloc];
  234653. }
  234654. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234655. {
  234656. (void) app;
  234657. return redirector->shouldTerminate();
  234658. }
  234659. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234660. {
  234661. (void) aNotification;
  234662. redirector->willTerminate();
  234663. }
  234664. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234665. {
  234666. (void) app;
  234667. return redirector->openFile (filename);
  234668. }
  234669. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234670. {
  234671. (void) sender;
  234672. return redirector->openFiles (filenames);
  234673. }
  234674. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234675. {
  234676. (void) notification;
  234677. redirector->focusChanged();
  234678. }
  234679. - (void) applicationDidResignActive: (NSNotification*) notification
  234680. {
  234681. (void) notification;
  234682. redirector->focusChanged();
  234683. }
  234684. - (void) applicationWillUnhide: (NSNotification*) notification
  234685. {
  234686. (void) notification;
  234687. redirector->focusChanged();
  234688. }
  234689. - (void) performCallback: (id) info
  234690. {
  234691. if ([info isKindOfClass: [NSData class]])
  234692. {
  234693. AppDelegateRedirector::CallbackMessagePayload* pl
  234694. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234695. if (pl != 0)
  234696. redirector->performCallback (pl);
  234697. }
  234698. else
  234699. {
  234700. jassertfalse; // should never get here!
  234701. }
  234702. }
  234703. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234704. @end
  234705. BEGIN_JUCE_NAMESPACE
  234706. static JuceAppDelegate* juceAppDelegate = 0;
  234707. void MessageManager::runDispatchLoop()
  234708. {
  234709. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234710. {
  234711. const ScopedAutoReleasePool pool;
  234712. // must only be called by the message thread!
  234713. jassert (isThisTheMessageThread());
  234714. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234715. @try
  234716. {
  234717. [NSApp run];
  234718. }
  234719. @catch (NSException* e)
  234720. {
  234721. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234722. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234723. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234724. }
  234725. @finally
  234726. {
  234727. }
  234728. #else
  234729. [NSApp run];
  234730. #endif
  234731. }
  234732. }
  234733. void MessageManager::stopDispatchLoop()
  234734. {
  234735. quitMessagePosted = true;
  234736. [NSApp stop: nil];
  234737. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234738. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234739. }
  234740. namespace
  234741. {
  234742. bool isEventBlockedByModalComps (NSEvent* e)
  234743. {
  234744. if (Component::getNumCurrentlyModalComponents() == 0)
  234745. return false;
  234746. NSWindow* const w = [e window];
  234747. if (w == 0 || [w worksWhenModal])
  234748. return false;
  234749. bool isKey = false, isInputAttempt = false;
  234750. switch ([e type])
  234751. {
  234752. case NSKeyDown:
  234753. case NSKeyUp:
  234754. isKey = isInputAttempt = true;
  234755. break;
  234756. case NSLeftMouseDown:
  234757. case NSRightMouseDown:
  234758. case NSOtherMouseDown:
  234759. isInputAttempt = true;
  234760. break;
  234761. case NSLeftMouseDragged:
  234762. case NSRightMouseDragged:
  234763. case NSLeftMouseUp:
  234764. case NSRightMouseUp:
  234765. case NSOtherMouseUp:
  234766. case NSOtherMouseDragged:
  234767. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234768. return false;
  234769. break;
  234770. case NSMouseMoved:
  234771. case NSMouseEntered:
  234772. case NSMouseExited:
  234773. case NSCursorUpdate:
  234774. case NSScrollWheel:
  234775. case NSTabletPoint:
  234776. case NSTabletProximity:
  234777. break;
  234778. default:
  234779. return false;
  234780. }
  234781. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234782. {
  234783. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234784. NSView* const compView = (NSView*) peer->getNativeHandle();
  234785. if ([compView window] == w)
  234786. {
  234787. if (isKey)
  234788. {
  234789. if (compView == [w firstResponder])
  234790. return false;
  234791. }
  234792. else
  234793. {
  234794. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234795. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234796. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234797. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234798. return false;
  234799. }
  234800. }
  234801. }
  234802. if (isInputAttempt)
  234803. {
  234804. if (! [NSApp isActive])
  234805. [NSApp activateIgnoringOtherApps: YES];
  234806. Component* const modal = Component::getCurrentlyModalComponent (0);
  234807. if (modal != 0)
  234808. modal->inputAttemptWhenModal();
  234809. }
  234810. return true;
  234811. }
  234812. }
  234813. #if JUCE_MODAL_LOOPS_PERMITTED
  234814. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234815. {
  234816. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234817. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234818. while (! quitMessagePosted)
  234819. {
  234820. const ScopedAutoReleasePool pool;
  234821. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234822. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234823. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234824. inMode: NSDefaultRunLoopMode
  234825. dequeue: YES];
  234826. if (e != 0 && ! isEventBlockedByModalComps (e))
  234827. [NSApp sendEvent: e];
  234828. if (Time::getMillisecondCounter() >= endTime)
  234829. break;
  234830. }
  234831. return ! quitMessagePosted;
  234832. }
  234833. #endif
  234834. void MessageManager::doPlatformSpecificInitialisation()
  234835. {
  234836. if (juceAppDelegate == 0)
  234837. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234838. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234839. // correctly (needed prior to 10.5)
  234840. if (! [NSThread isMultiThreaded])
  234841. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234842. toTarget: juceAppDelegate
  234843. withObject: nil];
  234844. }
  234845. void MessageManager::doPlatformSpecificShutdown()
  234846. {
  234847. if (juceAppDelegate != 0)
  234848. {
  234849. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234850. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234851. [juceAppDelegate release];
  234852. juceAppDelegate = 0;
  234853. }
  234854. }
  234855. bool juce_postMessageToSystemQueue (Message* message)
  234856. {
  234857. juceAppDelegate->redirector->postMessage (message);
  234858. return true;
  234859. }
  234860. void MessageManager::broadcastMessage (const String&)
  234861. {
  234862. }
  234863. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234864. {
  234865. if (isThisTheMessageThread())
  234866. {
  234867. return (*callback) (data);
  234868. }
  234869. else
  234870. {
  234871. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234872. // deadlock because the message manager is blocked from running, so can never
  234873. // call your function..
  234874. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234875. const ScopedAutoReleasePool pool;
  234876. AppDelegateRedirector::CallbackMessagePayload cmp;
  234877. cmp.function = callback;
  234878. cmp.parameter = data;
  234879. cmp.result = 0;
  234880. cmp.hasBeenExecuted = false;
  234881. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234882. withObject: [NSData dataWithBytesNoCopy: &cmp
  234883. length: sizeof (cmp)
  234884. freeWhenDone: NO]
  234885. waitUntilDone: YES];
  234886. return cmp.result;
  234887. }
  234888. }
  234889. #endif
  234890. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234891. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234892. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234893. // compiled on its own).
  234894. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234895. #if JUCE_MAC
  234896. END_JUCE_NAMESPACE
  234897. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234898. @interface DownloadClickDetector : NSObject
  234899. {
  234900. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234901. }
  234902. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234903. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234904. request: (NSURLRequest*) request
  234905. frame: (WebFrame*) frame
  234906. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234907. @end
  234908. @implementation DownloadClickDetector
  234909. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234910. {
  234911. [super init];
  234912. ownerComponent = ownerComponent_;
  234913. return self;
  234914. }
  234915. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234916. request: (NSURLRequest*) request
  234917. frame: (WebFrame*) frame
  234918. decisionListener: (id <WebPolicyDecisionListener>) listener
  234919. {
  234920. (void) sender;
  234921. (void) request;
  234922. (void) frame;
  234923. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234924. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234925. [listener use];
  234926. else
  234927. [listener ignore];
  234928. }
  234929. @end
  234930. BEGIN_JUCE_NAMESPACE
  234931. class WebBrowserComponentInternal : public NSViewComponent
  234932. {
  234933. public:
  234934. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234935. {
  234936. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234937. frameName: @""
  234938. groupName: @""];
  234939. setView (webView);
  234940. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234941. [webView setPolicyDelegate: clickListener];
  234942. }
  234943. ~WebBrowserComponentInternal()
  234944. {
  234945. [webView setPolicyDelegate: nil];
  234946. [clickListener release];
  234947. setView (0);
  234948. }
  234949. void goToURL (const String& url,
  234950. const StringArray* headers,
  234951. const MemoryBlock* postData)
  234952. {
  234953. NSMutableURLRequest* r
  234954. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234955. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234956. timeoutInterval: 30.0];
  234957. if (postData != 0 && postData->getSize() > 0)
  234958. {
  234959. [r setHTTPMethod: @"POST"];
  234960. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234961. length: postData->getSize()]];
  234962. }
  234963. if (headers != 0)
  234964. {
  234965. for (int i = 0; i < headers->size(); ++i)
  234966. {
  234967. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234968. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234969. [r setValue: juceStringToNS (headerValue)
  234970. forHTTPHeaderField: juceStringToNS (headerName)];
  234971. }
  234972. }
  234973. stop();
  234974. [[webView mainFrame] loadRequest: r];
  234975. }
  234976. void goBack()
  234977. {
  234978. [webView goBack];
  234979. }
  234980. void goForward()
  234981. {
  234982. [webView goForward];
  234983. }
  234984. void stop()
  234985. {
  234986. [webView stopLoading: nil];
  234987. }
  234988. void refresh()
  234989. {
  234990. [webView reload: nil];
  234991. }
  234992. void mouseMove (const MouseEvent&)
  234993. {
  234994. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234995. // them work is to push them via this non-public method..
  234996. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234997. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234998. }
  234999. private:
  235000. WebView* webView;
  235001. DownloadClickDetector* clickListener;
  235002. };
  235003. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235004. : browser (0),
  235005. blankPageShown (false),
  235006. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235007. {
  235008. setOpaque (true);
  235009. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235010. }
  235011. WebBrowserComponent::~WebBrowserComponent()
  235012. {
  235013. deleteAndZero (browser);
  235014. }
  235015. void WebBrowserComponent::goToURL (const String& url,
  235016. const StringArray* headers,
  235017. const MemoryBlock* postData)
  235018. {
  235019. lastURL = url;
  235020. lastHeaders.clear();
  235021. if (headers != 0)
  235022. lastHeaders = *headers;
  235023. lastPostData.setSize (0);
  235024. if (postData != 0)
  235025. lastPostData = *postData;
  235026. blankPageShown = false;
  235027. browser->goToURL (url, headers, postData);
  235028. }
  235029. void WebBrowserComponent::stop()
  235030. {
  235031. browser->stop();
  235032. }
  235033. void WebBrowserComponent::goBack()
  235034. {
  235035. lastURL = String::empty;
  235036. blankPageShown = false;
  235037. browser->goBack();
  235038. }
  235039. void WebBrowserComponent::goForward()
  235040. {
  235041. lastURL = String::empty;
  235042. browser->goForward();
  235043. }
  235044. void WebBrowserComponent::refresh()
  235045. {
  235046. browser->refresh();
  235047. }
  235048. void WebBrowserComponent::paint (Graphics&)
  235049. {
  235050. }
  235051. void WebBrowserComponent::checkWindowAssociation()
  235052. {
  235053. if (isShowing())
  235054. {
  235055. if (blankPageShown)
  235056. goBack();
  235057. }
  235058. else
  235059. {
  235060. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235061. {
  235062. // when the component becomes invisible, some stuff like flash
  235063. // carries on playing audio, so we need to force it onto a blank
  235064. // page to avoid this, (and send it back when it's made visible again).
  235065. blankPageShown = true;
  235066. browser->goToURL ("about:blank", 0, 0);
  235067. }
  235068. }
  235069. }
  235070. void WebBrowserComponent::reloadLastURL()
  235071. {
  235072. if (lastURL.isNotEmpty())
  235073. {
  235074. goToURL (lastURL, &lastHeaders, &lastPostData);
  235075. lastURL = String::empty;
  235076. }
  235077. }
  235078. void WebBrowserComponent::parentHierarchyChanged()
  235079. {
  235080. checkWindowAssociation();
  235081. }
  235082. void WebBrowserComponent::resized()
  235083. {
  235084. browser->setSize (getWidth(), getHeight());
  235085. }
  235086. void WebBrowserComponent::visibilityChanged()
  235087. {
  235088. checkWindowAssociation();
  235089. }
  235090. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235091. {
  235092. return true;
  235093. }
  235094. #else
  235095. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235096. {
  235097. }
  235098. WebBrowserComponent::~WebBrowserComponent()
  235099. {
  235100. }
  235101. void WebBrowserComponent::goToURL (const String& url,
  235102. const StringArray* headers,
  235103. const MemoryBlock* postData)
  235104. {
  235105. }
  235106. void WebBrowserComponent::stop()
  235107. {
  235108. }
  235109. void WebBrowserComponent::goBack()
  235110. {
  235111. }
  235112. void WebBrowserComponent::goForward()
  235113. {
  235114. }
  235115. void WebBrowserComponent::refresh()
  235116. {
  235117. }
  235118. void WebBrowserComponent::paint (Graphics& g)
  235119. {
  235120. }
  235121. void WebBrowserComponent::checkWindowAssociation()
  235122. {
  235123. }
  235124. void WebBrowserComponent::reloadLastURL()
  235125. {
  235126. }
  235127. void WebBrowserComponent::parentHierarchyChanged()
  235128. {
  235129. }
  235130. void WebBrowserComponent::resized()
  235131. {
  235132. }
  235133. void WebBrowserComponent::visibilityChanged()
  235134. {
  235135. }
  235136. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235137. {
  235138. return true;
  235139. }
  235140. #endif
  235141. #endif
  235142. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235143. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235144. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235145. // compiled on its own).
  235146. #if JUCE_INCLUDED_FILE
  235147. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235148. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235149. #endif
  235150. #undef log
  235151. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235152. #define log(a) Logger::writeToLog (a)
  235153. #else
  235154. #define log(a)
  235155. #endif
  235156. #undef OK
  235157. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235158. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235159. {
  235160. if (err == noErr)
  235161. return true;
  235162. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235163. jassertfalse;
  235164. return false;
  235165. }
  235166. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235167. #else
  235168. #define OK(a) (a == noErr)
  235169. #endif
  235170. class CoreAudioInternal : public Timer
  235171. {
  235172. public:
  235173. CoreAudioInternal (AudioDeviceID id)
  235174. : inputLatency (0),
  235175. outputLatency (0),
  235176. callback (0),
  235177. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235178. audioProcID (0),
  235179. #endif
  235180. isSlaveDevice (false),
  235181. deviceID (id),
  235182. started (false),
  235183. sampleRate (0),
  235184. bufferSize (512),
  235185. numInputChans (0),
  235186. numOutputChans (0),
  235187. callbacksAllowed (true),
  235188. numInputChannelInfos (0),
  235189. numOutputChannelInfos (0)
  235190. {
  235191. jassert (deviceID != 0);
  235192. updateDetailsFromDevice();
  235193. AudioObjectPropertyAddress pa;
  235194. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235195. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235196. pa.mElement = kAudioObjectPropertyElementWildcard;
  235197. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235198. }
  235199. ~CoreAudioInternal()
  235200. {
  235201. AudioObjectPropertyAddress pa;
  235202. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235203. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235204. pa.mElement = kAudioObjectPropertyElementWildcard;
  235205. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235206. stop (false);
  235207. }
  235208. void allocateTempBuffers()
  235209. {
  235210. const int tempBufSize = bufferSize + 4;
  235211. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235212. tempInputBuffers.calloc (numInputChans + 2);
  235213. tempOutputBuffers.calloc (numOutputChans + 2);
  235214. int i, count = 0;
  235215. for (i = 0; i < numInputChans; ++i)
  235216. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235217. for (i = 0; i < numOutputChans; ++i)
  235218. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235219. }
  235220. // returns the number of actual available channels
  235221. void fillInChannelInfo (const bool input)
  235222. {
  235223. int chanNum = 0;
  235224. UInt32 size;
  235225. AudioObjectPropertyAddress pa;
  235226. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235227. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235228. pa.mElement = kAudioObjectPropertyElementMaster;
  235229. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235230. {
  235231. HeapBlock <AudioBufferList> bufList;
  235232. bufList.calloc (size, 1);
  235233. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235234. {
  235235. const int numStreams = bufList->mNumberBuffers;
  235236. for (int i = 0; i < numStreams; ++i)
  235237. {
  235238. const AudioBuffer& b = bufList->mBuffers[i];
  235239. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235240. {
  235241. String name;
  235242. {
  235243. char channelName [256];
  235244. zerostruct (channelName);
  235245. UInt32 nameSize = sizeof (channelName);
  235246. UInt32 channelNum = chanNum + 1;
  235247. pa.mSelector = kAudioDevicePropertyChannelName;
  235248. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235249. name = String::fromUTF8 (channelName, nameSize);
  235250. }
  235251. if (input)
  235252. {
  235253. if (activeInputChans[chanNum])
  235254. {
  235255. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235256. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235257. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235258. ++numInputChannelInfos;
  235259. }
  235260. if (name.isEmpty())
  235261. name << "Input " << (chanNum + 1);
  235262. inChanNames.add (name);
  235263. }
  235264. else
  235265. {
  235266. if (activeOutputChans[chanNum])
  235267. {
  235268. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235269. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235270. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235271. ++numOutputChannelInfos;
  235272. }
  235273. if (name.isEmpty())
  235274. name << "Output " << (chanNum + 1);
  235275. outChanNames.add (name);
  235276. }
  235277. ++chanNum;
  235278. }
  235279. }
  235280. }
  235281. }
  235282. }
  235283. void updateDetailsFromDevice()
  235284. {
  235285. stopTimer();
  235286. if (deviceID == 0)
  235287. return;
  235288. const ScopedLock sl (callbackLock);
  235289. Float64 sr;
  235290. UInt32 size = sizeof (Float64);
  235291. AudioObjectPropertyAddress pa;
  235292. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235293. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235294. pa.mElement = kAudioObjectPropertyElementMaster;
  235295. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235296. sampleRate = sr;
  235297. UInt32 framesPerBuf;
  235298. size = sizeof (framesPerBuf);
  235299. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235300. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235301. {
  235302. bufferSize = framesPerBuf;
  235303. allocateTempBuffers();
  235304. }
  235305. bufferSizes.clear();
  235306. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235307. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235308. {
  235309. HeapBlock <AudioValueRange> ranges;
  235310. ranges.calloc (size, 1);
  235311. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235312. {
  235313. bufferSizes.add ((int) ranges[0].mMinimum);
  235314. for (int i = 32; i < 2048; i += 32)
  235315. {
  235316. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235317. {
  235318. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235319. {
  235320. bufferSizes.addIfNotAlreadyThere (i);
  235321. break;
  235322. }
  235323. }
  235324. }
  235325. if (bufferSize > 0)
  235326. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235327. }
  235328. }
  235329. if (bufferSizes.size() == 0 && bufferSize > 0)
  235330. bufferSizes.add (bufferSize);
  235331. sampleRates.clear();
  235332. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235333. String rates;
  235334. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235335. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235336. {
  235337. HeapBlock <AudioValueRange> ranges;
  235338. ranges.calloc (size, 1);
  235339. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235340. {
  235341. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235342. {
  235343. bool ok = false;
  235344. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235345. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235346. ok = true;
  235347. if (ok)
  235348. {
  235349. sampleRates.add (possibleRates[i]);
  235350. rates << possibleRates[i] << ' ';
  235351. }
  235352. }
  235353. }
  235354. }
  235355. if (sampleRates.size() == 0 && sampleRate > 0)
  235356. {
  235357. sampleRates.add (sampleRate);
  235358. rates << sampleRate;
  235359. }
  235360. log ("sr: " + rates);
  235361. inputLatency = 0;
  235362. outputLatency = 0;
  235363. UInt32 lat;
  235364. size = sizeof (lat);
  235365. pa.mSelector = kAudioDevicePropertyLatency;
  235366. pa.mScope = kAudioDevicePropertyScopeInput;
  235367. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235368. inputLatency = (int) lat;
  235369. pa.mScope = kAudioDevicePropertyScopeOutput;
  235370. size = sizeof (lat);
  235371. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235372. outputLatency = (int) lat;
  235373. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235374. inChanNames.clear();
  235375. outChanNames.clear();
  235376. inputChannelInfo.calloc (numInputChans + 2);
  235377. numInputChannelInfos = 0;
  235378. outputChannelInfo.calloc (numOutputChans + 2);
  235379. numOutputChannelInfos = 0;
  235380. fillInChannelInfo (true);
  235381. fillInChannelInfo (false);
  235382. }
  235383. const StringArray getSources (bool input)
  235384. {
  235385. StringArray s;
  235386. HeapBlock <OSType> types;
  235387. const int num = getAllDataSourcesForDevice (deviceID, types);
  235388. for (int i = 0; i < num; ++i)
  235389. {
  235390. AudioValueTranslation avt;
  235391. char buffer[256];
  235392. avt.mInputData = &(types[i]);
  235393. avt.mInputDataSize = sizeof (UInt32);
  235394. avt.mOutputData = buffer;
  235395. avt.mOutputDataSize = 256;
  235396. UInt32 transSize = sizeof (avt);
  235397. AudioObjectPropertyAddress pa;
  235398. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235399. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235400. pa.mElement = kAudioObjectPropertyElementMaster;
  235401. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235402. {
  235403. DBG (buffer);
  235404. s.add (buffer);
  235405. }
  235406. }
  235407. return s;
  235408. }
  235409. int getCurrentSourceIndex (bool input) const
  235410. {
  235411. OSType currentSourceID = 0;
  235412. UInt32 size = sizeof (currentSourceID);
  235413. int result = -1;
  235414. AudioObjectPropertyAddress pa;
  235415. pa.mSelector = kAudioDevicePropertyDataSource;
  235416. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235417. pa.mElement = kAudioObjectPropertyElementMaster;
  235418. if (deviceID != 0)
  235419. {
  235420. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235421. {
  235422. HeapBlock <OSType> types;
  235423. const int num = getAllDataSourcesForDevice (deviceID, types);
  235424. for (int i = 0; i < num; ++i)
  235425. {
  235426. if (types[num] == currentSourceID)
  235427. {
  235428. result = i;
  235429. break;
  235430. }
  235431. }
  235432. }
  235433. }
  235434. return result;
  235435. }
  235436. void setCurrentSourceIndex (int index, bool input)
  235437. {
  235438. if (deviceID != 0)
  235439. {
  235440. HeapBlock <OSType> types;
  235441. const int num = getAllDataSourcesForDevice (deviceID, types);
  235442. if (isPositiveAndBelow (index, num))
  235443. {
  235444. AudioObjectPropertyAddress pa;
  235445. pa.mSelector = kAudioDevicePropertyDataSource;
  235446. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235447. pa.mElement = kAudioObjectPropertyElementMaster;
  235448. OSType typeId = types[index];
  235449. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235450. }
  235451. }
  235452. }
  235453. const String reopen (const BigInteger& inputChannels,
  235454. const BigInteger& outputChannels,
  235455. double newSampleRate,
  235456. int bufferSizeSamples)
  235457. {
  235458. String error;
  235459. log ("CoreAudio reopen");
  235460. callbacksAllowed = false;
  235461. stopTimer();
  235462. stop (false);
  235463. activeInputChans = inputChannels;
  235464. activeInputChans.setRange (inChanNames.size(),
  235465. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235466. false);
  235467. activeOutputChans = outputChannels;
  235468. activeOutputChans.setRange (outChanNames.size(),
  235469. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235470. false);
  235471. numInputChans = activeInputChans.countNumberOfSetBits();
  235472. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235473. // set sample rate
  235474. AudioObjectPropertyAddress pa;
  235475. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235476. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235477. pa.mElement = kAudioObjectPropertyElementMaster;
  235478. Float64 sr = newSampleRate;
  235479. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235480. {
  235481. error = "Couldn't change sample rate";
  235482. }
  235483. else
  235484. {
  235485. // change buffer size
  235486. UInt32 framesPerBuf = bufferSizeSamples;
  235487. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235488. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235489. {
  235490. error = "Couldn't change buffer size";
  235491. }
  235492. else
  235493. {
  235494. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235495. // correctly report their new settings until some random time in the future, so
  235496. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235497. // to make sure we're using the correct numbers..
  235498. updateDetailsFromDevice();
  235499. sampleRate = newSampleRate;
  235500. bufferSize = bufferSizeSamples;
  235501. if (sampleRates.size() == 0)
  235502. error = "Device has no available sample-rates";
  235503. else if (bufferSizes.size() == 0)
  235504. error = "Device has no available buffer-sizes";
  235505. else if (inputDevice != 0)
  235506. error = inputDevice->reopen (inputChannels,
  235507. outputChannels,
  235508. newSampleRate,
  235509. bufferSizeSamples);
  235510. }
  235511. }
  235512. callbacksAllowed = true;
  235513. return error;
  235514. }
  235515. bool start (AudioIODeviceCallback* cb)
  235516. {
  235517. if (! started)
  235518. {
  235519. callback = 0;
  235520. if (deviceID != 0)
  235521. {
  235522. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235523. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235524. #else
  235525. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235526. #endif
  235527. {
  235528. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235529. {
  235530. started = true;
  235531. }
  235532. else
  235533. {
  235534. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235535. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235536. #else
  235537. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235538. audioProcID = 0;
  235539. #endif
  235540. }
  235541. }
  235542. }
  235543. }
  235544. if (started)
  235545. {
  235546. const ScopedLock sl (callbackLock);
  235547. callback = cb;
  235548. }
  235549. if (inputDevice != 0)
  235550. return started && inputDevice->start (cb);
  235551. else
  235552. return started;
  235553. }
  235554. void stop (bool leaveInterruptRunning)
  235555. {
  235556. {
  235557. const ScopedLock sl (callbackLock);
  235558. callback = 0;
  235559. }
  235560. if (started
  235561. && (deviceID != 0)
  235562. && ! leaveInterruptRunning)
  235563. {
  235564. OK (AudioDeviceStop (deviceID, audioIOProc));
  235565. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235566. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235567. #else
  235568. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235569. audioProcID = 0;
  235570. #endif
  235571. started = false;
  235572. { const ScopedLock sl (callbackLock); }
  235573. // wait until it's definately stopped calling back..
  235574. for (int i = 40; --i >= 0;)
  235575. {
  235576. Thread::sleep (50);
  235577. UInt32 running = 0;
  235578. UInt32 size = sizeof (running);
  235579. AudioObjectPropertyAddress pa;
  235580. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235581. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235582. pa.mElement = kAudioObjectPropertyElementMaster;
  235583. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235584. if (running == 0)
  235585. break;
  235586. }
  235587. const ScopedLock sl (callbackLock);
  235588. }
  235589. if (inputDevice != 0)
  235590. inputDevice->stop (leaveInterruptRunning);
  235591. }
  235592. double getSampleRate() const
  235593. {
  235594. return sampleRate;
  235595. }
  235596. int getBufferSize() const
  235597. {
  235598. return bufferSize;
  235599. }
  235600. void audioCallback (const AudioBufferList* inInputData,
  235601. AudioBufferList* outOutputData)
  235602. {
  235603. int i;
  235604. const ScopedLock sl (callbackLock);
  235605. if (callback != 0)
  235606. {
  235607. if (inputDevice == 0)
  235608. {
  235609. for (i = numInputChans; --i >= 0;)
  235610. {
  235611. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235612. float* dest = tempInputBuffers [i];
  235613. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235614. + info.dataOffsetSamples;
  235615. const int stride = info.dataStrideSamples;
  235616. if (stride != 0) // if this is zero, info is invalid
  235617. {
  235618. for (int j = bufferSize; --j >= 0;)
  235619. {
  235620. *dest++ = *src;
  235621. src += stride;
  235622. }
  235623. }
  235624. }
  235625. }
  235626. if (! isSlaveDevice)
  235627. {
  235628. if (inputDevice == 0)
  235629. {
  235630. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235631. numInputChans,
  235632. tempOutputBuffers,
  235633. numOutputChans,
  235634. bufferSize);
  235635. }
  235636. else
  235637. {
  235638. jassert (inputDevice->bufferSize == bufferSize);
  235639. // Sometimes the two linked devices seem to get their callbacks in
  235640. // parallel, so we need to lock both devices to stop the input data being
  235641. // changed while inside our callback..
  235642. const ScopedLock sl2 (inputDevice->callbackLock);
  235643. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235644. inputDevice->numInputChans,
  235645. tempOutputBuffers,
  235646. numOutputChans,
  235647. bufferSize);
  235648. }
  235649. for (i = numOutputChans; --i >= 0;)
  235650. {
  235651. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235652. const float* src = tempOutputBuffers [i];
  235653. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235654. + info.dataOffsetSamples;
  235655. const int stride = info.dataStrideSamples;
  235656. if (stride != 0) // if this is zero, info is invalid
  235657. {
  235658. for (int j = bufferSize; --j >= 0;)
  235659. {
  235660. *dest = *src++;
  235661. dest += stride;
  235662. }
  235663. }
  235664. }
  235665. }
  235666. }
  235667. else
  235668. {
  235669. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235670. {
  235671. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235672. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235673. + info.dataOffsetSamples;
  235674. const int stride = info.dataStrideSamples;
  235675. if (stride != 0) // if this is zero, info is invalid
  235676. {
  235677. for (int j = bufferSize; --j >= 0;)
  235678. {
  235679. *dest = 0.0f;
  235680. dest += stride;
  235681. }
  235682. }
  235683. }
  235684. }
  235685. }
  235686. // called by callbacks
  235687. void deviceDetailsChanged()
  235688. {
  235689. if (callbacksAllowed)
  235690. startTimer (100);
  235691. }
  235692. void timerCallback()
  235693. {
  235694. stopTimer();
  235695. log ("CoreAudio device changed callback");
  235696. const double oldSampleRate = sampleRate;
  235697. const int oldBufferSize = bufferSize;
  235698. updateDetailsFromDevice();
  235699. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235700. {
  235701. callbacksAllowed = false;
  235702. stop (false);
  235703. updateDetailsFromDevice();
  235704. callbacksAllowed = true;
  235705. }
  235706. }
  235707. CoreAudioInternal* getRelatedDevice() const
  235708. {
  235709. UInt32 size = 0;
  235710. ScopedPointer <CoreAudioInternal> result;
  235711. AudioObjectPropertyAddress pa;
  235712. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235713. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235714. pa.mElement = kAudioObjectPropertyElementMaster;
  235715. if (deviceID != 0
  235716. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235717. && size > 0)
  235718. {
  235719. HeapBlock <AudioDeviceID> devs;
  235720. devs.calloc (size, 1);
  235721. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235722. {
  235723. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235724. {
  235725. if (devs[i] != deviceID && devs[i] != 0)
  235726. {
  235727. result = new CoreAudioInternal (devs[i]);
  235728. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235729. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235730. if (thisIsInput != otherIsInput
  235731. || (inChanNames.size() + outChanNames.size() == 0)
  235732. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235733. break;
  235734. result = 0;
  235735. }
  235736. }
  235737. }
  235738. }
  235739. return result.release();
  235740. }
  235741. int inputLatency, outputLatency;
  235742. BigInteger activeInputChans, activeOutputChans;
  235743. StringArray inChanNames, outChanNames;
  235744. Array <double> sampleRates;
  235745. Array <int> bufferSizes;
  235746. AudioIODeviceCallback* callback;
  235747. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235748. AudioDeviceIOProcID audioProcID;
  235749. #endif
  235750. ScopedPointer<CoreAudioInternal> inputDevice;
  235751. bool isSlaveDevice;
  235752. private:
  235753. CriticalSection callbackLock;
  235754. AudioDeviceID deviceID;
  235755. bool started;
  235756. double sampleRate;
  235757. int bufferSize;
  235758. HeapBlock <float> audioBuffer;
  235759. int numInputChans, numOutputChans;
  235760. bool callbacksAllowed;
  235761. struct CallbackDetailsForChannel
  235762. {
  235763. int streamNum;
  235764. int dataOffsetSamples;
  235765. int dataStrideSamples;
  235766. };
  235767. int numInputChannelInfos, numOutputChannelInfos;
  235768. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235769. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235770. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235771. const AudioTimeStamp* /*inNow*/,
  235772. const AudioBufferList* inInputData,
  235773. const AudioTimeStamp* /*inInputTime*/,
  235774. AudioBufferList* outOutputData,
  235775. const AudioTimeStamp* /*inOutputTime*/,
  235776. void* device)
  235777. {
  235778. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235779. return noErr;
  235780. }
  235781. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235782. {
  235783. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235784. switch (pa->mSelector)
  235785. {
  235786. case kAudioDevicePropertyBufferSize:
  235787. case kAudioDevicePropertyBufferFrameSize:
  235788. case kAudioDevicePropertyNominalSampleRate:
  235789. case kAudioDevicePropertyStreamFormat:
  235790. case kAudioDevicePropertyDeviceIsAlive:
  235791. intern->deviceDetailsChanged();
  235792. break;
  235793. case kAudioDevicePropertyBufferSizeRange:
  235794. case kAudioDevicePropertyVolumeScalar:
  235795. case kAudioDevicePropertyMute:
  235796. case kAudioDevicePropertyPlayThru:
  235797. case kAudioDevicePropertyDataSource:
  235798. case kAudioDevicePropertyDeviceIsRunning:
  235799. break;
  235800. }
  235801. return noErr;
  235802. }
  235803. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235804. {
  235805. AudioObjectPropertyAddress pa;
  235806. pa.mSelector = kAudioDevicePropertyDataSources;
  235807. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235808. pa.mElement = kAudioObjectPropertyElementMaster;
  235809. UInt32 size = 0;
  235810. if (deviceID != 0
  235811. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235812. {
  235813. types.calloc (size, 1);
  235814. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235815. return size / (int) sizeof (OSType);
  235816. }
  235817. return 0;
  235818. }
  235819. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235820. };
  235821. class CoreAudioIODevice : public AudioIODevice
  235822. {
  235823. public:
  235824. CoreAudioIODevice (const String& deviceName,
  235825. AudioDeviceID inputDeviceId,
  235826. const int inputIndex_,
  235827. AudioDeviceID outputDeviceId,
  235828. const int outputIndex_)
  235829. : AudioIODevice (deviceName, "CoreAudio"),
  235830. inputIndex (inputIndex_),
  235831. outputIndex (outputIndex_),
  235832. isOpen_ (false),
  235833. isStarted (false)
  235834. {
  235835. CoreAudioInternal* device = 0;
  235836. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235837. {
  235838. jassert (inputDeviceId != 0);
  235839. device = new CoreAudioInternal (inputDeviceId);
  235840. }
  235841. else
  235842. {
  235843. device = new CoreAudioInternal (outputDeviceId);
  235844. if (inputDeviceId != 0)
  235845. {
  235846. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235847. device->inputDevice = secondDevice;
  235848. secondDevice->isSlaveDevice = true;
  235849. }
  235850. }
  235851. internal = device;
  235852. AudioObjectPropertyAddress pa;
  235853. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235854. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235855. pa.mElement = kAudioObjectPropertyElementWildcard;
  235856. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235857. }
  235858. ~CoreAudioIODevice()
  235859. {
  235860. AudioObjectPropertyAddress pa;
  235861. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235862. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235863. pa.mElement = kAudioObjectPropertyElementWildcard;
  235864. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235865. }
  235866. const StringArray getOutputChannelNames()
  235867. {
  235868. return internal->outChanNames;
  235869. }
  235870. const StringArray getInputChannelNames()
  235871. {
  235872. if (internal->inputDevice != 0)
  235873. return internal->inputDevice->inChanNames;
  235874. else
  235875. return internal->inChanNames;
  235876. }
  235877. int getNumSampleRates()
  235878. {
  235879. return internal->sampleRates.size();
  235880. }
  235881. double getSampleRate (int index)
  235882. {
  235883. return internal->sampleRates [index];
  235884. }
  235885. int getNumBufferSizesAvailable()
  235886. {
  235887. return internal->bufferSizes.size();
  235888. }
  235889. int getBufferSizeSamples (int index)
  235890. {
  235891. return internal->bufferSizes [index];
  235892. }
  235893. int getDefaultBufferSize()
  235894. {
  235895. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235896. if (getBufferSizeSamples(i) >= 512)
  235897. return getBufferSizeSamples(i);
  235898. return 512;
  235899. }
  235900. const String open (const BigInteger& inputChannels,
  235901. const BigInteger& outputChannels,
  235902. double sampleRate,
  235903. int bufferSizeSamples)
  235904. {
  235905. isOpen_ = true;
  235906. if (bufferSizeSamples <= 0)
  235907. bufferSizeSamples = getDefaultBufferSize();
  235908. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235909. isOpen_ = lastError.isEmpty();
  235910. return lastError;
  235911. }
  235912. void close()
  235913. {
  235914. isOpen_ = false;
  235915. internal->stop (false);
  235916. }
  235917. bool isOpen()
  235918. {
  235919. return isOpen_;
  235920. }
  235921. int getCurrentBufferSizeSamples()
  235922. {
  235923. return internal != 0 ? internal->getBufferSize() : 512;
  235924. }
  235925. double getCurrentSampleRate()
  235926. {
  235927. return internal != 0 ? internal->getSampleRate() : 0;
  235928. }
  235929. int getCurrentBitDepth()
  235930. {
  235931. return 32; // no way to find out, so just assume it's high..
  235932. }
  235933. const BigInteger getActiveOutputChannels() const
  235934. {
  235935. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235936. }
  235937. const BigInteger getActiveInputChannels() const
  235938. {
  235939. BigInteger chans;
  235940. if (internal != 0)
  235941. {
  235942. chans = internal->activeInputChans;
  235943. if (internal->inputDevice != 0)
  235944. chans |= internal->inputDevice->activeInputChans;
  235945. }
  235946. return chans;
  235947. }
  235948. int getOutputLatencyInSamples()
  235949. {
  235950. if (internal == 0)
  235951. return 0;
  235952. // this seems like a good guess at getting the latency right - comparing
  235953. // this with a round-trip measurement, it gets it to within a few millisecs
  235954. // for the built-in mac soundcard
  235955. return internal->outputLatency + internal->getBufferSize() * 2;
  235956. }
  235957. int getInputLatencyInSamples()
  235958. {
  235959. if (internal == 0)
  235960. return 0;
  235961. return internal->inputLatency + internal->getBufferSize() * 2;
  235962. }
  235963. void start (AudioIODeviceCallback* callback)
  235964. {
  235965. if (internal != 0 && ! isStarted)
  235966. {
  235967. if (callback != 0)
  235968. callback->audioDeviceAboutToStart (this);
  235969. isStarted = true;
  235970. internal->start (callback);
  235971. }
  235972. }
  235973. void stop()
  235974. {
  235975. if (isStarted && internal != 0)
  235976. {
  235977. AudioIODeviceCallback* const lastCallback = internal->callback;
  235978. isStarted = false;
  235979. internal->stop (true);
  235980. if (lastCallback != 0)
  235981. lastCallback->audioDeviceStopped();
  235982. }
  235983. }
  235984. bool isPlaying()
  235985. {
  235986. if (internal->callback == 0)
  235987. isStarted = false;
  235988. return isStarted;
  235989. }
  235990. const String getLastError()
  235991. {
  235992. return lastError;
  235993. }
  235994. int inputIndex, outputIndex;
  235995. private:
  235996. ScopedPointer<CoreAudioInternal> internal;
  235997. bool isOpen_, isStarted;
  235998. String lastError;
  235999. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236000. {
  236001. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236002. switch (pa->mSelector)
  236003. {
  236004. case kAudioHardwarePropertyDevices:
  236005. intern->deviceDetailsChanged();
  236006. break;
  236007. case kAudioHardwarePropertyDefaultOutputDevice:
  236008. case kAudioHardwarePropertyDefaultInputDevice:
  236009. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236010. break;
  236011. }
  236012. return noErr;
  236013. }
  236014. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  236015. };
  236016. class CoreAudioIODeviceType : public AudioIODeviceType
  236017. {
  236018. public:
  236019. CoreAudioIODeviceType()
  236020. : AudioIODeviceType ("CoreAudio"),
  236021. hasScanned (false)
  236022. {
  236023. }
  236024. ~CoreAudioIODeviceType()
  236025. {
  236026. }
  236027. void scanForDevices()
  236028. {
  236029. hasScanned = true;
  236030. inputDeviceNames.clear();
  236031. outputDeviceNames.clear();
  236032. inputIds.clear();
  236033. outputIds.clear();
  236034. UInt32 size;
  236035. AudioObjectPropertyAddress pa;
  236036. pa.mSelector = kAudioHardwarePropertyDevices;
  236037. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236038. pa.mElement = kAudioObjectPropertyElementMaster;
  236039. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236040. {
  236041. HeapBlock <AudioDeviceID> devs;
  236042. devs.calloc (size, 1);
  236043. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236044. {
  236045. const int num = size / (int) sizeof (AudioDeviceID);
  236046. for (int i = 0; i < num; ++i)
  236047. {
  236048. char name [1024];
  236049. size = sizeof (name);
  236050. pa.mSelector = kAudioDevicePropertyDeviceName;
  236051. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236052. {
  236053. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236054. const int numIns = getNumChannels (devs[i], true);
  236055. const int numOuts = getNumChannels (devs[i], false);
  236056. if (numIns > 0)
  236057. {
  236058. inputDeviceNames.add (nameString);
  236059. inputIds.add (devs[i]);
  236060. }
  236061. if (numOuts > 0)
  236062. {
  236063. outputDeviceNames.add (nameString);
  236064. outputIds.add (devs[i]);
  236065. }
  236066. }
  236067. }
  236068. }
  236069. }
  236070. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236071. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236072. }
  236073. const StringArray getDeviceNames (bool wantInputNames) const
  236074. {
  236075. jassert (hasScanned); // need to call scanForDevices() before doing this
  236076. if (wantInputNames)
  236077. return inputDeviceNames;
  236078. else
  236079. return outputDeviceNames;
  236080. }
  236081. int getDefaultDeviceIndex (bool forInput) const
  236082. {
  236083. jassert (hasScanned); // need to call scanForDevices() before doing this
  236084. AudioDeviceID deviceID;
  236085. UInt32 size = sizeof (deviceID);
  236086. // if they're asking for any input channels at all, use the default input, so we
  236087. // get the built-in mic rather than the built-in output with no inputs..
  236088. AudioObjectPropertyAddress pa;
  236089. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236090. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236091. pa.mElement = kAudioObjectPropertyElementMaster;
  236092. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236093. {
  236094. if (forInput)
  236095. {
  236096. for (int i = inputIds.size(); --i >= 0;)
  236097. if (inputIds[i] == deviceID)
  236098. return i;
  236099. }
  236100. else
  236101. {
  236102. for (int i = outputIds.size(); --i >= 0;)
  236103. if (outputIds[i] == deviceID)
  236104. return i;
  236105. }
  236106. }
  236107. return 0;
  236108. }
  236109. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236110. {
  236111. jassert (hasScanned); // need to call scanForDevices() before doing this
  236112. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236113. if (d == 0)
  236114. return -1;
  236115. return asInput ? d->inputIndex
  236116. : d->outputIndex;
  236117. }
  236118. bool hasSeparateInputsAndOutputs() const { return true; }
  236119. AudioIODevice* createDevice (const String& outputDeviceName,
  236120. const String& inputDeviceName)
  236121. {
  236122. jassert (hasScanned); // need to call scanForDevices() before doing this
  236123. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236124. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236125. String deviceName (outputDeviceName);
  236126. if (deviceName.isEmpty())
  236127. deviceName = inputDeviceName;
  236128. if (index >= 0)
  236129. return new CoreAudioIODevice (deviceName,
  236130. inputIds [inputIndex],
  236131. inputIndex,
  236132. outputIds [outputIndex],
  236133. outputIndex);
  236134. return 0;
  236135. }
  236136. private:
  236137. StringArray inputDeviceNames, outputDeviceNames;
  236138. Array <AudioDeviceID> inputIds, outputIds;
  236139. bool hasScanned;
  236140. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236141. {
  236142. int total = 0;
  236143. UInt32 size;
  236144. AudioObjectPropertyAddress pa;
  236145. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236146. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236147. pa.mElement = kAudioObjectPropertyElementMaster;
  236148. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236149. {
  236150. HeapBlock <AudioBufferList> bufList;
  236151. bufList.calloc (size, 1);
  236152. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236153. {
  236154. const int numStreams = bufList->mNumberBuffers;
  236155. for (int i = 0; i < numStreams; ++i)
  236156. {
  236157. const AudioBuffer& b = bufList->mBuffers[i];
  236158. total += b.mNumberChannels;
  236159. }
  236160. }
  236161. }
  236162. return total;
  236163. }
  236164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  236165. };
  236166. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio()
  236167. {
  236168. return new CoreAudioIODeviceType();
  236169. }
  236170. #undef log
  236171. #endif
  236172. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236173. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236174. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236175. // compiled on its own).
  236176. #if JUCE_INCLUDED_FILE
  236177. #if JUCE_MAC
  236178. namespace CoreMidiHelpers
  236179. {
  236180. bool logError (const OSStatus err, const int lineNum)
  236181. {
  236182. if (err == noErr)
  236183. return true;
  236184. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236185. jassertfalse;
  236186. return false;
  236187. }
  236188. #undef CHECK_ERROR
  236189. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236190. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236191. {
  236192. String result;
  236193. CFStringRef str = 0;
  236194. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236195. if (str != 0)
  236196. {
  236197. result = PlatformUtilities::cfStringToJuceString (str);
  236198. CFRelease (str);
  236199. str = 0;
  236200. }
  236201. MIDIEntityRef entity = 0;
  236202. MIDIEndpointGetEntity (endpoint, &entity);
  236203. if (entity == 0)
  236204. return result; // probably virtual
  236205. if (result.isEmpty())
  236206. {
  236207. // endpoint name has zero length - try the entity
  236208. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236209. if (str != 0)
  236210. {
  236211. result += PlatformUtilities::cfStringToJuceString (str);
  236212. CFRelease (str);
  236213. str = 0;
  236214. }
  236215. }
  236216. // now consider the device's name
  236217. MIDIDeviceRef device = 0;
  236218. MIDIEntityGetDevice (entity, &device);
  236219. if (device == 0)
  236220. return result;
  236221. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236222. if (str != 0)
  236223. {
  236224. const String s (PlatformUtilities::cfStringToJuceString (str));
  236225. CFRelease (str);
  236226. // if an external device has only one entity, throw away
  236227. // the endpoint name and just use the device name
  236228. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236229. {
  236230. result = s;
  236231. }
  236232. else if (! result.startsWithIgnoreCase (s))
  236233. {
  236234. // prepend the device name to the entity name
  236235. result = (s + " " + result).trimEnd();
  236236. }
  236237. }
  236238. return result;
  236239. }
  236240. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236241. {
  236242. String result;
  236243. // Does the endpoint have connections?
  236244. CFDataRef connections = 0;
  236245. int numConnections = 0;
  236246. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236247. if (connections != 0)
  236248. {
  236249. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236250. if (numConnections > 0)
  236251. {
  236252. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236253. for (int i = 0; i < numConnections; ++i, ++pid)
  236254. {
  236255. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236256. MIDIObjectRef connObject;
  236257. MIDIObjectType connObjectType;
  236258. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236259. if (err == noErr)
  236260. {
  236261. String s;
  236262. if (connObjectType == kMIDIObjectType_ExternalSource
  236263. || connObjectType == kMIDIObjectType_ExternalDestination)
  236264. {
  236265. // Connected to an external device's endpoint (10.3 and later).
  236266. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236267. }
  236268. else
  236269. {
  236270. // Connected to an external device (10.2) (or something else, catch-all)
  236271. CFStringRef str = 0;
  236272. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236273. if (str != 0)
  236274. {
  236275. s = PlatformUtilities::cfStringToJuceString (str);
  236276. CFRelease (str);
  236277. }
  236278. }
  236279. if (s.isNotEmpty())
  236280. {
  236281. if (result.isNotEmpty())
  236282. result += ", ";
  236283. result += s;
  236284. }
  236285. }
  236286. }
  236287. }
  236288. CFRelease (connections);
  236289. }
  236290. if (result.isNotEmpty())
  236291. return result;
  236292. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236293. return getEndpointName (endpoint, false);
  236294. }
  236295. MIDIClientRef getGlobalMidiClient()
  236296. {
  236297. static MIDIClientRef globalMidiClient = 0;
  236298. if (globalMidiClient == 0)
  236299. {
  236300. String name ("JUCE");
  236301. if (JUCEApplication::getInstance() != 0)
  236302. name = JUCEApplication::getInstance()->getApplicationName();
  236303. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236304. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236305. CFRelease (appName);
  236306. }
  236307. return globalMidiClient;
  236308. }
  236309. class MidiPortAndEndpoint
  236310. {
  236311. public:
  236312. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236313. : port (port_), endPoint (endPoint_)
  236314. {
  236315. }
  236316. ~MidiPortAndEndpoint()
  236317. {
  236318. if (port != 0)
  236319. MIDIPortDispose (port);
  236320. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236321. MIDIEndpointDispose (endPoint);
  236322. }
  236323. void send (const MIDIPacketList* const packets)
  236324. {
  236325. if (port != 0)
  236326. MIDISend (port, endPoint, packets);
  236327. else
  236328. MIDIReceived (endPoint, packets);
  236329. }
  236330. MIDIPortRef port;
  236331. MIDIEndpointRef endPoint;
  236332. };
  236333. class MidiPortAndCallback;
  236334. CriticalSection callbackLock;
  236335. Array<MidiPortAndCallback*> activeCallbacks;
  236336. class MidiPortAndCallback
  236337. {
  236338. public:
  236339. MidiPortAndCallback (MidiInputCallback& callback_)
  236340. : input (0), active (false), callback (callback_), concatenator (2048)
  236341. {
  236342. }
  236343. ~MidiPortAndCallback()
  236344. {
  236345. active = false;
  236346. {
  236347. const ScopedLock sl (callbackLock);
  236348. activeCallbacks.removeValue (this);
  236349. }
  236350. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236351. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236352. }
  236353. void handlePackets (const MIDIPacketList* const pktlist)
  236354. {
  236355. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236356. const ScopedLock sl (callbackLock);
  236357. if (activeCallbacks.contains (this) && active)
  236358. {
  236359. const MIDIPacket* packet = &pktlist->packet[0];
  236360. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236361. {
  236362. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236363. input, callback);
  236364. packet = MIDIPacketNext (packet);
  236365. }
  236366. }
  236367. }
  236368. MidiInput* input;
  236369. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236370. volatile bool active;
  236371. private:
  236372. MidiInputCallback& callback;
  236373. MidiDataConcatenator concatenator;
  236374. };
  236375. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236376. {
  236377. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236378. }
  236379. }
  236380. const StringArray MidiOutput::getDevices()
  236381. {
  236382. StringArray s;
  236383. const ItemCount num = MIDIGetNumberOfDestinations();
  236384. for (ItemCount i = 0; i < num; ++i)
  236385. {
  236386. MIDIEndpointRef dest = MIDIGetDestination (i);
  236387. if (dest != 0)
  236388. {
  236389. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236390. if (name.isEmpty())
  236391. name = "<error>";
  236392. s.add (name);
  236393. }
  236394. else
  236395. {
  236396. s.add ("<error>");
  236397. }
  236398. }
  236399. return s;
  236400. }
  236401. int MidiOutput::getDefaultDeviceIndex()
  236402. {
  236403. return 0;
  236404. }
  236405. MidiOutput* MidiOutput::openDevice (int index)
  236406. {
  236407. MidiOutput* mo = 0;
  236408. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  236409. {
  236410. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236411. CFStringRef pname;
  236412. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236413. {
  236414. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236415. MIDIPortRef port;
  236416. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236417. {
  236418. mo = new MidiOutput();
  236419. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236420. }
  236421. CFRelease (pname);
  236422. }
  236423. }
  236424. return mo;
  236425. }
  236426. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236427. {
  236428. MidiOutput* mo = 0;
  236429. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236430. MIDIEndpointRef endPoint;
  236431. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236432. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236433. {
  236434. mo = new MidiOutput();
  236435. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236436. }
  236437. CFRelease (name);
  236438. return mo;
  236439. }
  236440. MidiOutput::~MidiOutput()
  236441. {
  236442. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236443. }
  236444. void MidiOutput::reset()
  236445. {
  236446. }
  236447. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236448. {
  236449. return false;
  236450. }
  236451. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236452. {
  236453. }
  236454. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236455. {
  236456. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236457. if (message.isSysEx())
  236458. {
  236459. const int maxPacketSize = 256;
  236460. int pos = 0, bytesLeft = message.getRawDataSize();
  236461. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236462. HeapBlock <MIDIPacketList> packets;
  236463. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236464. packets->numPackets = numPackets;
  236465. MIDIPacket* p = packets->packet;
  236466. for (int i = 0; i < numPackets; ++i)
  236467. {
  236468. p->timeStamp = AudioGetCurrentHostTime();
  236469. p->length = jmin (maxPacketSize, bytesLeft);
  236470. memcpy (p->data, message.getRawData() + pos, p->length);
  236471. pos += p->length;
  236472. bytesLeft -= p->length;
  236473. p = MIDIPacketNext (p);
  236474. }
  236475. mpe->send (packets);
  236476. }
  236477. else
  236478. {
  236479. MIDIPacketList packets;
  236480. packets.numPackets = 1;
  236481. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  236482. packets.packet[0].length = message.getRawDataSize();
  236483. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236484. mpe->send (&packets);
  236485. }
  236486. }
  236487. const StringArray MidiInput::getDevices()
  236488. {
  236489. StringArray s;
  236490. const ItemCount num = MIDIGetNumberOfSources();
  236491. for (ItemCount i = 0; i < num; ++i)
  236492. {
  236493. MIDIEndpointRef source = MIDIGetSource (i);
  236494. if (source != 0)
  236495. {
  236496. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236497. if (name.isEmpty())
  236498. name = "<error>";
  236499. s.add (name);
  236500. }
  236501. else
  236502. {
  236503. s.add ("<error>");
  236504. }
  236505. }
  236506. return s;
  236507. }
  236508. int MidiInput::getDefaultDeviceIndex()
  236509. {
  236510. return 0;
  236511. }
  236512. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236513. {
  236514. jassert (callback != 0);
  236515. using namespace CoreMidiHelpers;
  236516. MidiInput* newInput = 0;
  236517. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236518. {
  236519. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236520. if (endPoint != 0)
  236521. {
  236522. CFStringRef name;
  236523. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236524. {
  236525. MIDIClientRef client = getGlobalMidiClient();
  236526. if (client != 0)
  236527. {
  236528. MIDIPortRef port;
  236529. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236530. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236531. {
  236532. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236533. {
  236534. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236535. newInput = new MidiInput (getDevices() [index]);
  236536. mpc->input = newInput;
  236537. newInput->internal = mpc;
  236538. const ScopedLock sl (callbackLock);
  236539. activeCallbacks.add (mpc.release());
  236540. }
  236541. else
  236542. {
  236543. CHECK_ERROR (MIDIPortDispose (port));
  236544. }
  236545. }
  236546. }
  236547. }
  236548. CFRelease (name);
  236549. }
  236550. }
  236551. return newInput;
  236552. }
  236553. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236554. {
  236555. jassert (callback != 0);
  236556. using namespace CoreMidiHelpers;
  236557. MidiInput* mi = 0;
  236558. MIDIClientRef client = getGlobalMidiClient();
  236559. if (client != 0)
  236560. {
  236561. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236562. mpc->active = false;
  236563. MIDIEndpointRef endPoint;
  236564. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236565. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236566. {
  236567. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236568. mi = new MidiInput (deviceName);
  236569. mpc->input = mi;
  236570. mi->internal = mpc;
  236571. const ScopedLock sl (callbackLock);
  236572. activeCallbacks.add (mpc.release());
  236573. }
  236574. CFRelease (name);
  236575. }
  236576. return mi;
  236577. }
  236578. MidiInput::MidiInput (const String& name_)
  236579. : name (name_)
  236580. {
  236581. }
  236582. MidiInput::~MidiInput()
  236583. {
  236584. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236585. }
  236586. void MidiInput::start()
  236587. {
  236588. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236589. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236590. }
  236591. void MidiInput::stop()
  236592. {
  236593. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236594. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236595. }
  236596. #undef CHECK_ERROR
  236597. #else // Stubs for iOS...
  236598. MidiOutput::~MidiOutput() {}
  236599. void MidiOutput::reset() {}
  236600. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236601. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236602. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236603. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236604. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236605. const StringArray MidiInput::getDevices() { return StringArray(); }
  236606. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236607. #endif
  236608. #endif
  236609. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236610. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236611. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236612. // compiled on its own).
  236613. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236614. #if ! JUCE_QUICKTIME
  236615. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236616. #endif
  236617. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236618. class QTCameraDeviceInteral;
  236619. END_JUCE_NAMESPACE
  236620. @interface QTCaptureCallbackDelegate : NSObject
  236621. {
  236622. @public
  236623. CameraDevice* owner;
  236624. QTCameraDeviceInteral* internal;
  236625. int64 firstPresentationTime;
  236626. int64 averageTimeOffset;
  236627. }
  236628. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236629. - (void) dealloc;
  236630. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236631. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236632. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236633. fromConnection: (QTCaptureConnection*) connection;
  236634. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236635. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236636. fromConnection: (QTCaptureConnection*) connection;
  236637. @end
  236638. BEGIN_JUCE_NAMESPACE
  236639. class QTCameraDeviceInteral
  236640. {
  236641. public:
  236642. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236643. {
  236644. const ScopedAutoReleasePool pool;
  236645. session = [[QTCaptureSession alloc] init];
  236646. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236647. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236648. input = 0;
  236649. audioInput = 0;
  236650. audioDevice = 0;
  236651. fileOutput = 0;
  236652. imageOutput = 0;
  236653. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236654. internalDev: this];
  236655. NSError* err = 0;
  236656. [device retain];
  236657. [device open: &err];
  236658. if (err == 0)
  236659. {
  236660. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236661. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236662. [session addInput: input error: &err];
  236663. if (err == 0)
  236664. {
  236665. resetFile();
  236666. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236667. [imageOutput setDelegate: callbackDelegate];
  236668. if (err == 0)
  236669. {
  236670. [session startRunning];
  236671. return;
  236672. }
  236673. }
  236674. }
  236675. openingError = nsStringToJuce ([err description]);
  236676. DBG (openingError);
  236677. }
  236678. ~QTCameraDeviceInteral()
  236679. {
  236680. [session stopRunning];
  236681. [session removeOutput: imageOutput];
  236682. [session release];
  236683. [input release];
  236684. [device release];
  236685. [audioDevice release];
  236686. [audioInput release];
  236687. [fileOutput release];
  236688. [imageOutput release];
  236689. [callbackDelegate release];
  236690. }
  236691. void resetFile()
  236692. {
  236693. [fileOutput recordToOutputFileURL: nil];
  236694. [session removeOutput: fileOutput];
  236695. [fileOutput release];
  236696. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236697. [session removeInput: audioInput];
  236698. [audioInput release];
  236699. audioInput = 0;
  236700. [audioDevice release];
  236701. audioDevice = 0;
  236702. [fileOutput setDelegate: callbackDelegate];
  236703. }
  236704. void addDefaultAudioInput()
  236705. {
  236706. NSError* err = nil;
  236707. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236708. if ([audioDevice open: &err])
  236709. [audioDevice retain];
  236710. else
  236711. audioDevice = nil;
  236712. if (audioDevice != 0)
  236713. {
  236714. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236715. [session addInput: audioInput error: &err];
  236716. }
  236717. }
  236718. void addListener (CameraDevice::Listener* listenerToAdd)
  236719. {
  236720. const ScopedLock sl (listenerLock);
  236721. if (listeners.size() == 0)
  236722. [session addOutput: imageOutput error: nil];
  236723. listeners.addIfNotAlreadyThere (listenerToAdd);
  236724. }
  236725. void removeListener (CameraDevice::Listener* listenerToRemove)
  236726. {
  236727. const ScopedLock sl (listenerLock);
  236728. listeners.removeValue (listenerToRemove);
  236729. if (listeners.size() == 0)
  236730. [session removeOutput: imageOutput];
  236731. }
  236732. void callListeners (CIImage* frame, int w, int h)
  236733. {
  236734. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236735. Image image (cgImage);
  236736. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236737. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236738. CGContextFlush (cgImage->context);
  236739. const ScopedLock sl (listenerLock);
  236740. for (int i = listeners.size(); --i >= 0;)
  236741. {
  236742. CameraDevice::Listener* const l = listeners[i];
  236743. if (l != 0)
  236744. l->imageReceived (image);
  236745. }
  236746. }
  236747. QTCaptureDevice* device;
  236748. QTCaptureDeviceInput* input;
  236749. QTCaptureDevice* audioDevice;
  236750. QTCaptureDeviceInput* audioInput;
  236751. QTCaptureSession* session;
  236752. QTCaptureMovieFileOutput* fileOutput;
  236753. QTCaptureDecompressedVideoOutput* imageOutput;
  236754. QTCaptureCallbackDelegate* callbackDelegate;
  236755. String openingError;
  236756. Array<CameraDevice::Listener*> listeners;
  236757. CriticalSection listenerLock;
  236758. };
  236759. END_JUCE_NAMESPACE
  236760. @implementation QTCaptureCallbackDelegate
  236761. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236762. internalDev: (QTCameraDeviceInteral*) d
  236763. {
  236764. [super init];
  236765. owner = owner_;
  236766. internal = d;
  236767. firstPresentationTime = 0;
  236768. averageTimeOffset = 0;
  236769. return self;
  236770. }
  236771. - (void) dealloc
  236772. {
  236773. [super dealloc];
  236774. }
  236775. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236776. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236777. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236778. fromConnection: (QTCaptureConnection*) connection
  236779. {
  236780. if (internal->listeners.size() > 0)
  236781. {
  236782. const ScopedAutoReleasePool pool;
  236783. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236784. CVPixelBufferGetWidth (videoFrame),
  236785. CVPixelBufferGetHeight (videoFrame));
  236786. }
  236787. }
  236788. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236789. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236790. fromConnection: (QTCaptureConnection*) connection
  236791. {
  236792. const Time now (Time::getCurrentTime());
  236793. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236794. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236795. #else
  236796. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236797. #endif
  236798. int64 presentationTime = (hosttime != nil)
  236799. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236800. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236801. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236802. if (firstPresentationTime == 0)
  236803. {
  236804. firstPresentationTime = presentationTime;
  236805. averageTimeOffset = timeDiff;
  236806. }
  236807. else
  236808. {
  236809. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236810. }
  236811. }
  236812. @end
  236813. BEGIN_JUCE_NAMESPACE
  236814. class QTCaptureViewerComp : public NSViewComponent
  236815. {
  236816. public:
  236817. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236818. {
  236819. const ScopedAutoReleasePool pool;
  236820. captureView = [[QTCaptureView alloc] init];
  236821. [captureView setCaptureSession: internal->session];
  236822. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236823. setView (captureView);
  236824. }
  236825. ~QTCaptureViewerComp()
  236826. {
  236827. setView (0);
  236828. [captureView setCaptureSession: nil];
  236829. [captureView release];
  236830. }
  236831. QTCaptureView* captureView;
  236832. };
  236833. CameraDevice::CameraDevice (const String& name_, int index)
  236834. : name (name_)
  236835. {
  236836. isRecording = false;
  236837. internal = new QTCameraDeviceInteral (this, index);
  236838. }
  236839. CameraDevice::~CameraDevice()
  236840. {
  236841. stopRecording();
  236842. delete static_cast <QTCameraDeviceInteral*> (internal);
  236843. internal = 0;
  236844. }
  236845. Component* CameraDevice::createViewerComponent()
  236846. {
  236847. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236848. }
  236849. const String CameraDevice::getFileExtension()
  236850. {
  236851. return ".mov";
  236852. }
  236853. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236854. {
  236855. stopRecording();
  236856. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236857. d->callbackDelegate->firstPresentationTime = 0;
  236858. file.deleteFile();
  236859. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236860. // out wrong, so we'll put some audio in there too..,
  236861. d->addDefaultAudioInput();
  236862. [d->session addOutput: d->fileOutput error: nil];
  236863. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236864. for (;;)
  236865. {
  236866. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236867. if (connection == 0)
  236868. break;
  236869. QTCompressionOptions* options = 0;
  236870. NSString* mediaType = [connection mediaType];
  236871. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236872. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236873. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236874. : @"QTCompressionOptions240SizeH264Video"];
  236875. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236876. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236877. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236878. }
  236879. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236880. isRecording = true;
  236881. }
  236882. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236883. {
  236884. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236885. if (d->callbackDelegate->firstPresentationTime != 0)
  236886. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236887. return Time();
  236888. }
  236889. void CameraDevice::stopRecording()
  236890. {
  236891. if (isRecording)
  236892. {
  236893. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236894. isRecording = false;
  236895. }
  236896. }
  236897. void CameraDevice::addListener (Listener* listenerToAdd)
  236898. {
  236899. if (listenerToAdd != 0)
  236900. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236901. }
  236902. void CameraDevice::removeListener (Listener* listenerToRemove)
  236903. {
  236904. if (listenerToRemove != 0)
  236905. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236906. }
  236907. const StringArray CameraDevice::getAvailableDevices()
  236908. {
  236909. const ScopedAutoReleasePool pool;
  236910. StringArray results;
  236911. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236912. for (int i = 0; i < (int) [devs count]; ++i)
  236913. {
  236914. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236915. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236916. }
  236917. return results;
  236918. }
  236919. CameraDevice* CameraDevice::openDevice (int index,
  236920. int minWidth, int minHeight,
  236921. int maxWidth, int maxHeight)
  236922. {
  236923. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236924. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236925. return d.release();
  236926. return 0;
  236927. }
  236928. #endif
  236929. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236930. #endif
  236931. #endif
  236932. END_JUCE_NAMESPACE
  236933. #endif
  236934. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236935. #elif JUCE_ANDROID
  236936. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236937. /*
  236938. This file wraps together all the android-specific code, so that
  236939. we can include all the native headers just once, and compile all our
  236940. platform-specific stuff in one big lump, keeping it out of the way of
  236941. the rest of the codebase.
  236942. */
  236943. #if JUCE_ANDROID
  236944. #undef JUCE_BUILD_NATIVE
  236945. #define JUCE_BUILD_NATIVE 1
  236946. BEGIN_JUCE_NAMESPACE
  236947. #define JUCE_JNI_CALLBACK(className, methodName, returnType, params) \
  236948. extern "C" __attribute__ ((visibility("default"))) returnType Java_com_juce_ ## className ## _ ## methodName params
  236949. #define JUCE_JNI_CLASSES(JAVACLASS) \
  236950. JAVACLASS (activityClass, "com/juce/JuceAppActivity") \
  236951. JAVACLASS (componentPeerViewClass, "com/juce/ComponentPeerView") \
  236952. JAVACLASS (fileClass, "java/io/File") \
  236953. JAVACLASS (contextClass, "android/content/Context") \
  236954. JAVACLASS (canvasClass, "android/graphics/Canvas") \
  236955. JAVACLASS (paintClass, "android/graphics/Paint") \
  236956. JAVACLASS (pathClass, "android/graphics/Path") \
  236957. JAVACLASS (bitmapClass, "android/graphics/Bitmap") \
  236958. JAVACLASS (bitmapConfigClass, "android/graphics/Bitmap$Config") \
  236959. JAVACLASS (matrixClass, "android/graphics/Matrix") \
  236960. JAVACLASS (rectClass, "android/graphics/Rect") \
  236961. JAVACLASS (regionClass, "android/graphics/Region") \
  236962. JAVACLASS (shaderClass, "android/graphics/Shader") \
  236963. JAVACLASS (typefaceClass, "android/graphics/Typeface") \
  236964. JAVACLASS (shaderTileModeClass, "android/graphics/Shader$TileMode") \
  236965. JAVACLASS (linearGradientClass, "android/graphics/LinearGradient") \
  236966. JAVACLASS (radialGradientClass, "android/graphics/RadialGradient") \
  236967. #define JUCE_JNI_METHODS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  236968. \
  236969. STATICMETHOD (activityClass, printToConsole, "printToConsole", "(Ljava/lang/String;)V") \
  236970. METHOD (activityClass, createNewView, "createNewView", "(Z)Lcom/juce/ComponentPeerView;") \
  236971. METHOD (activityClass, deleteView, "deleteView", "(Lcom/juce/ComponentPeerView;)V") \
  236972. METHOD (activityClass, postMessage, "postMessage", "(J)V") \
  236973. METHOD (activityClass, finish, "finish", "()V") \
  236974. METHOD (activityClass, getClipboardContent, "getClipboardContent", "()Ljava/lang/String;") \
  236975. METHOD (activityClass, setClipboardContent, "setClipboardContent", "(Ljava/lang/String;)V") \
  236976. METHOD (activityClass, excludeClipRegion, "excludeClipRegion", "(Landroid/graphics/Canvas;FFFF)V") \
  236977. METHOD (activityClass, createPathForGlyph, "createPathForGlyph", "(Landroid/graphics/Paint;C)Ljava/lang/String;") \
  236978. \
  236979. METHOD (fileClass, fileExists, "exists", "()Z") \
  236980. \
  236981. METHOD (componentPeerViewClass, setViewName, "setViewName", "(Ljava/lang/String;)V") \
  236982. METHOD (componentPeerViewClass, layout, "layout", "(IIII)V") \
  236983. METHOD (componentPeerViewClass, getLeft, "getLeft", "()I") \
  236984. METHOD (componentPeerViewClass, getTop, "getTop", "()I") \
  236985. METHOD (componentPeerViewClass, getWidth, "getWidth", "()I") \
  236986. METHOD (componentPeerViewClass, getHeight, "getHeight", "()I") \
  236987. METHOD (componentPeerViewClass, getLocationOnScreen, "getLocationOnScreen", "([I)V") \
  236988. METHOD (componentPeerViewClass, bringToFront, "bringToFront", "()V") \
  236989. METHOD (componentPeerViewClass, requestFocus, "requestFocus", "()Z") \
  236990. METHOD (componentPeerViewClass, setVisible, "setVisible", "(Z)V") \
  236991. METHOD (componentPeerViewClass, isVisible, "isVisible", "()Z") \
  236992. METHOD (componentPeerViewClass, hasFocus, "hasFocus", "()Z") \
  236993. METHOD (componentPeerViewClass, invalidate, "invalidate", "(IIII)V") \
  236994. METHOD (componentPeerViewClass, containsPoint, "containsPoint", "(II)Z") \
  236995. \
  236996. METHOD (canvasClass, canvasBitmapConstructor, "<init>", "(Landroid/graphics/Bitmap;)V") \
  236997. METHOD (canvasClass, drawRect, "drawRect", "(FFFFLandroid/graphics/Paint;)V") \
  236998. METHOD (canvasClass, translate, "translate", "(FF)V") \
  236999. METHOD (canvasClass, clipPath, "clipPath", "(Landroid/graphics/Path;)Z") \
  237000. METHOD (canvasClass, clipRect, "clipRect", "(FFFF)Z") \
  237001. METHOD (canvasClass, clipRegion, "clipRegion", "(Landroid/graphics/Region;)Z") \
  237002. METHOD (canvasClass, concat, "concat", "(Landroid/graphics/Matrix;)V") \
  237003. METHOD (canvasClass, drawBitmap, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Matrix;Landroid/graphics/Paint;)V") \
  237004. METHOD (canvasClass, drawMemoryBitmap, "drawBitmap", "([IIIFFIIZLandroid/graphics/Paint;)V") \
  237005. METHOD (canvasClass, drawLine, "drawLine", "(FFFFLandroid/graphics/Paint;)V") \
  237006. METHOD (canvasClass, drawPath, "drawPath", "(Landroid/graphics/Path;Landroid/graphics/Paint;)V") \
  237007. METHOD (canvasClass, drawText, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V") \
  237008. METHOD (canvasClass, getClipBounds, "getClipBounds", "(Landroid/graphics/Rect;)Z") \
  237009. METHOD (canvasClass, getClipBounds2, "getClipBounds", "()Landroid/graphics/Rect;") \
  237010. METHOD (canvasClass, getMatrix, "getMatrix", "()Landroid/graphics/Matrix;") \
  237011. METHOD (canvasClass, save, "save", "()I") \
  237012. METHOD (canvasClass, restore, "restore", "()V") \
  237013. METHOD (canvasClass, saveLayerAlpha, "saveLayerAlpha", "(FFFFII)I") \
  237014. \
  237015. METHOD (paintClass, paintClassConstructor, "<init>", "(I)V") \
  237016. METHOD (paintClass, setColor, "setColor", "(I)V") \
  237017. METHOD (paintClass, setAlpha, "setAlpha", "(I)V") \
  237018. METHOD (paintClass, setShader, "setShader", "(Landroid/graphics/Shader;)Landroid/graphics/Shader;") \
  237019. METHOD (paintClass, setTypeface, "setTypeface", "(Landroid/graphics/Typeface;)Landroid/graphics/Typeface;") \
  237020. METHOD (paintClass, ascent, "ascent", "()F") \
  237021. METHOD (paintClass, descent, "descent", "()F") \
  237022. METHOD (paintClass, setTextSize, "setTextSize", "(F)V") \
  237023. METHOD (paintClass, getTextWidths, "getTextWidths", "(Ljava/lang/String;[F)I") \
  237024. \
  237025. METHOD (shaderClass, setLocalMatrix, "setLocalMatrix", "(Landroid/graphics/Matrix;)V") \
  237026. STATICFIELD (shaderTileModeClass, clampMode, "CLAMP", "Landroid/graphics/Shader$TileMode;") \
  237027. \
  237028. METHOD (pathClass, pathClassConstructor, "<init>", "()V") \
  237029. METHOD (pathClass, moveTo, "moveTo", "(FF)V") \
  237030. METHOD (pathClass, lineTo, "lineTo", "(FF)V") \
  237031. METHOD (pathClass, quadTo, "quadTo", "(FFFF)V") \
  237032. METHOD (pathClass, cubicTo, "cubicTo", "(FFFFFF)V") \
  237033. METHOD (pathClass, closePath, "close", "()V") \
  237034. \
  237035. STATICMETHOD (bitmapClass, createBitmap, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;") \
  237036. STATICFIELD (bitmapConfigClass, ARGB_8888, "ARGB_8888", "Landroid/graphics/Bitmap$Config;") \
  237037. METHOD (bitmapClass, bitmapCopy, "copy", "(Landroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;") \
  237038. METHOD (bitmapClass, getPixels, "getPixels", "([IIIIIII)V") \
  237039. METHOD (bitmapClass, setPixels, "setPixels", "([IIIIIII)V") \
  237040. METHOD (bitmapClass, recycle, "recycle", "()V") \
  237041. \
  237042. METHOD (matrixClass, matrixClassConstructor, "<init>", "()V") \
  237043. METHOD (matrixClass, setValues, "setValues", "([F)V") \
  237044. \
  237045. STATICMETHOD (typefaceClass, create, "create", "(Ljava/lang/String;I)Landroid/graphics/Typeface;") \
  237046. \
  237047. METHOD (rectClass, rectConstructor, "<init>", "(IIII)V") \
  237048. FIELD (rectClass, rectLeft, "left", "I") \
  237049. FIELD (rectClass, rectRight, "right", "I") \
  237050. FIELD (rectClass, rectTop, "top", "I") \
  237051. FIELD (rectClass, rectBottom, "bottom", "I") \
  237052. \
  237053. METHOD (linearGradientClass, linearGradientConstructor, "<init>", "(FFFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  237054. \
  237055. METHOD (radialGradientClass, radialGradientConstructor, "<init>", "(FFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  237056. \
  237057. METHOD (regionClass, regionConstructor, "<init>", "()V"); \
  237058. METHOD (regionClass, regionUnion, "union", "(Landroid/graphics/Rect;)Z"); \
  237059. class ThreadLocalJNIEnvHolder
  237060. {
  237061. public:
  237062. ThreadLocalJNIEnvHolder()
  237063. : jvm (0)
  237064. {
  237065. zeromem (threads, sizeof (threads));
  237066. zeromem (envs, sizeof (envs));
  237067. }
  237068. void initialise (JNIEnv* env)
  237069. {
  237070. env->GetJavaVM (&jvm);
  237071. addEnv (env);
  237072. }
  237073. void attach()
  237074. {
  237075. JNIEnv* env = 0;
  237076. jvm->AttachCurrentThread (&env, 0);
  237077. if (env != 0)
  237078. addEnv (env);
  237079. }
  237080. void detach()
  237081. {
  237082. jvm->DetachCurrentThread();
  237083. const pthread_t thisThread = pthread_self();
  237084. ScopedLock sl (addRemoveLock);
  237085. for (int i = 0; i < maxThreads; ++i)
  237086. if (threads[i] == thisThread)
  237087. threads[i] = 0;
  237088. }
  237089. JNIEnv* get() const throw()
  237090. {
  237091. const pthread_t thisThread = pthread_self();
  237092. for (int i = 0; i < maxThreads; ++i)
  237093. if (threads[i] == thisThread)
  237094. return envs[i];
  237095. return 0;
  237096. }
  237097. enum { maxThreads = 16 };
  237098. private:
  237099. JavaVM* jvm;
  237100. pthread_t threads [maxThreads];
  237101. JNIEnv* envs [maxThreads];
  237102. CriticalSection addRemoveLock;
  237103. void addEnv (JNIEnv* env)
  237104. {
  237105. ScopedLock sl (addRemoveLock);
  237106. if (get() == 0)
  237107. {
  237108. const pthread_t thisThread = pthread_self();
  237109. for (int i = 0; i < maxThreads; ++i)
  237110. {
  237111. if (threads[i] == 0)
  237112. {
  237113. envs[i] = env;
  237114. threads[i] = thisThread;
  237115. return;
  237116. }
  237117. }
  237118. }
  237119. jassertfalse; // too many threads!
  237120. }
  237121. };
  237122. static ThreadLocalJNIEnvHolder threadLocalJNIEnvHolder;
  237123. struct AndroidThreadScope
  237124. {
  237125. AndroidThreadScope() { threadLocalJNIEnvHolder.attach(); }
  237126. ~AndroidThreadScope() { threadLocalJNIEnvHolder.detach(); }
  237127. };
  237128. static inline JNIEnv* getEnv() throw()
  237129. {
  237130. return threadLocalJNIEnvHolder.get();
  237131. }
  237132. class GlobalRef
  237133. {
  237134. public:
  237135. inline GlobalRef() throw()
  237136. : obj (0)
  237137. {
  237138. }
  237139. inline explicit GlobalRef (jobject obj_)
  237140. : obj (retain (obj_))
  237141. {
  237142. }
  237143. inline GlobalRef (const GlobalRef& other)
  237144. : obj (retain (other.obj))
  237145. {
  237146. }
  237147. ~GlobalRef()
  237148. {
  237149. clear();
  237150. }
  237151. inline void clear()
  237152. {
  237153. if (obj != 0)
  237154. {
  237155. getEnv()->DeleteGlobalRef (obj);
  237156. obj = 0;
  237157. }
  237158. }
  237159. inline GlobalRef& operator= (const GlobalRef& other)
  237160. {
  237161. clear();
  237162. obj = retain (other.obj);
  237163. return *this;
  237164. }
  237165. inline operator jobject() const throw() { return obj; }
  237166. inline jobject get() const throw() { return obj; }
  237167. #define DECLARE_CALL_TYPE_METHOD(returnType, typeName) \
  237168. returnType call##typeName##Method (jmethodID methodID, ... ) const \
  237169. { \
  237170. va_list args; \
  237171. va_start (args, methodID); \
  237172. returnType result = getEnv()->Call##typeName##MethodV (obj, methodID, args); \
  237173. va_end (args); \
  237174. return result; \
  237175. }
  237176. DECLARE_CALL_TYPE_METHOD (jobject, Object)
  237177. DECLARE_CALL_TYPE_METHOD (jboolean, Boolean)
  237178. DECLARE_CALL_TYPE_METHOD (jbyte, Byte)
  237179. DECLARE_CALL_TYPE_METHOD (jchar, Char)
  237180. DECLARE_CALL_TYPE_METHOD (jshort, Short)
  237181. DECLARE_CALL_TYPE_METHOD (jint, Int)
  237182. DECLARE_CALL_TYPE_METHOD (jlong, Long)
  237183. DECLARE_CALL_TYPE_METHOD (jfloat, Float)
  237184. DECLARE_CALL_TYPE_METHOD (jdouble, Double)
  237185. #undef DECLARE_CALL_TYPE_METHOD
  237186. void callVoidMethod (jmethodID methodID, ... ) const
  237187. {
  237188. va_list args;
  237189. va_start (args, methodID);
  237190. getEnv()->CallVoidMethodV (obj, methodID, args);
  237191. va_end (args);
  237192. }
  237193. private:
  237194. jobject obj;
  237195. static inline jobject retain (jobject obj_)
  237196. {
  237197. return obj_ == 0 ? 0 : getEnv()->NewGlobalRef (obj_);
  237198. }
  237199. };
  237200. template <typename JavaType>
  237201. class LocalRef
  237202. {
  237203. public:
  237204. explicit inline LocalRef (JavaType obj_) throw()
  237205. : obj (obj_)
  237206. {
  237207. }
  237208. inline LocalRef (const LocalRef& other) throw()
  237209. : obj (retain (other.obj))
  237210. {
  237211. }
  237212. ~LocalRef()
  237213. {
  237214. if (obj != 0)
  237215. getEnv()->DeleteLocalRef (obj);
  237216. }
  237217. LocalRef& operator= (const LocalRef& other)
  237218. {
  237219. if (obj != other.obj)
  237220. {
  237221. if (obj != 0)
  237222. getEnv()->DeleteLocalRef (obj);
  237223. obj = retain (other.obj);
  237224. }
  237225. return *this;
  237226. }
  237227. inline operator JavaType() const throw() { return obj; }
  237228. inline JavaType get() const throw() { return obj; }
  237229. private:
  237230. JavaType obj;
  237231. static JavaType retain (JavaType obj_)
  237232. {
  237233. return obj_ == 0 ? 0 : (JavaType) getEnv()->NewLocalRef (obj_);
  237234. }
  237235. };
  237236. static const String juceString (jstring s)
  237237. {
  237238. JNIEnv* env = getEnv();
  237239. jboolean isCopy;
  237240. const char* const utf8 = env->GetStringUTFChars (s, &isCopy);
  237241. CharPointer_UTF8 utf8CP (utf8);
  237242. const String result (utf8CP);
  237243. env->ReleaseStringUTFChars (s, utf8);
  237244. return result;
  237245. }
  237246. static const LocalRef<jstring> javaString (const String& s)
  237247. {
  237248. return LocalRef<jstring> (getEnv()->NewStringUTF (s.toUTF8()));
  237249. }
  237250. static const LocalRef<jstring> javaStringFromChar (const juce_wchar c)
  237251. {
  237252. char utf8[5] = { 0 };
  237253. CharPointer_UTF8 (utf8).write (c);
  237254. return LocalRef<jstring> (getEnv()->NewStringUTF (utf8));
  237255. }
  237256. class AndroidJavaCallbacks
  237257. {
  237258. public:
  237259. AndroidJavaCallbacks() : screenWidth (0), screenHeight (0)
  237260. {
  237261. }
  237262. void initialise (JNIEnv* env, jobject activity_,
  237263. jstring appFile_, jstring appDataDir_,
  237264. int screenWidth_, int screenHeight_)
  237265. {
  237266. threadLocalJNIEnvHolder.initialise (env);
  237267. activity = GlobalRef (activity_);
  237268. appFile = juceString (appFile_);
  237269. appDataDir = juceString (appDataDir_);
  237270. screenWidth = screenWidth_;
  237271. screenHeight = screenHeight_;
  237272. #define CREATE_JNI_CLASS(className, path) \
  237273. className = (jclass) env->NewGlobalRef (env->FindClass (path)); \
  237274. jassert (className != 0);
  237275. JUCE_JNI_CLASSES (CREATE_JNI_CLASS);
  237276. #undef CREATE_JNI_CLASS
  237277. #define CREATE_JNI_METHOD(ownerClass, methodID, stringName, params) \
  237278. methodID = env->GetMethodID (ownerClass, stringName, params); \
  237279. jassert (methodID != 0);
  237280. #define CREATE_JNI_STATICMETHOD(ownerClass, methodID, stringName, params) \
  237281. methodID = env->GetStaticMethodID (ownerClass, stringName, params); \
  237282. jassert (methodID != 0);
  237283. #define CREATE_JNI_FIELD(ownerClass, fieldID, stringName, signature) \
  237284. fieldID = env->GetFieldID (ownerClass, stringName, signature); \
  237285. jassert (fieldID != 0);
  237286. #define CREATE_JNI_STATICFIELD(ownerClass, fieldID, stringName, signature) \
  237287. fieldID = env->GetStaticFieldID (ownerClass, stringName, signature); \
  237288. jassert (fieldID != 0);
  237289. JUCE_JNI_METHODS (CREATE_JNI_METHOD, CREATE_JNI_STATICMETHOD, CREATE_JNI_FIELD, CREATE_JNI_STATICFIELD);
  237290. #undef CREATE_JNI_METHOD
  237291. }
  237292. void shutdown()
  237293. {
  237294. JNIEnv* env = getEnv();
  237295. if (env != 0)
  237296. {
  237297. #define RELEASE_JNI_CLASS(className, path) env->DeleteGlobalRef (className);
  237298. JUCE_JNI_CLASSES (RELEASE_JNI_CLASS);
  237299. #undef RELEASE_JNI_CLASS
  237300. activity.clear();
  237301. }
  237302. }
  237303. GlobalRef activity;
  237304. String appFile, appDataDir;
  237305. int screenWidth, screenHeight;
  237306. jobject createPaint()
  237307. {
  237308. const jint constructorFlags = 1 /*ANTI_ALIAS_FLAG*/
  237309. | 2 /*FILTER_BITMAP_FLAG*/
  237310. | 4 /*DITHER_FLAG*/
  237311. | 128 /*SUBPIXEL_TEXT_FLAG*/;
  237312. return getEnv()->NewObject (paintClass, paintClassConstructor, constructorFlags);
  237313. }
  237314. #define DECLARE_JNI_CLASS(className, path) jclass className;
  237315. JUCE_JNI_CLASSES (DECLARE_JNI_CLASS);
  237316. #undef DECLARE_JNI_CLASS
  237317. #define DECLARE_JNI_METHOD(ownerClass, methodID, stringName, params) jmethodID methodID;
  237318. #define DECLARE_JNI_FIELD(ownerClass, fieldID, stringName, signature) jfieldID fieldID;
  237319. JUCE_JNI_METHODS (DECLARE_JNI_METHOD, DECLARE_JNI_METHOD, DECLARE_JNI_FIELD, DECLARE_JNI_FIELD);
  237320. #undef DECLARE_JNI_METHOD
  237321. };
  237322. static AndroidJavaCallbacks android;
  237323. #define JUCE_INCLUDED_FILE 1
  237324. // Now include the actual code files..
  237325. /*** Start of inlined file: juce_android_Misc.cpp ***/
  237326. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237327. // compiled on its own).
  237328. #if JUCE_INCLUDED_FILE
  237329. END_JUCE_NAMESPACE
  237330. extern JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  237331. BEGIN_JUCE_NAMESPACE
  237332. JUCE_JNI_CALLBACK (JuceAppActivity, launchApp, void, (JNIEnv* env, jobject activity,
  237333. jstring appFile, jstring appDataDir,
  237334. int screenWidth, int screenHeight))
  237335. {
  237336. android.initialise (env, activity, appFile, appDataDir, screenWidth, screenHeight);
  237337. JUCEApplication::createInstance = &juce_CreateApplication;
  237338. initialiseJuce_GUI();
  237339. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  237340. exit (0);
  237341. }
  237342. JUCE_JNI_CALLBACK (JuceAppActivity, quitApp, void, (JNIEnv* env, jobject activity))
  237343. {
  237344. JUCEApplication::appWillTerminateByForce();
  237345. android.shutdown();
  237346. }
  237347. void PlatformUtilities::beep()
  237348. {
  237349. }
  237350. void Logger::outputDebugString (const String& text)
  237351. {
  237352. getEnv()->CallStaticVoidMethod (android.activityClass, android.printToConsole,
  237353. javaString (text).get());
  237354. }
  237355. void SystemClipboard::copyTextToClipboard (const String& text)
  237356. {
  237357. const LocalRef<jstring> t (javaString (text));
  237358. android.activity.callVoidMethod (android.setClipboardContent, t.get());
  237359. }
  237360. const String SystemClipboard::getTextFromClipboard()
  237361. {
  237362. const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (android.getClipboardContent));
  237363. return juceString (text);
  237364. }
  237365. #endif
  237366. /*** End of inlined file: juce_android_Misc.cpp ***/
  237367. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  237368. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237369. // compiled on its own).
  237370. #if JUCE_INCLUDED_FILE
  237371. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  237372. {
  237373. return Android;
  237374. }
  237375. const String SystemStats::getOperatingSystemName()
  237376. {
  237377. return "Android";
  237378. }
  237379. bool SystemStats::isOperatingSystem64Bit()
  237380. {
  237381. #if JUCE_64BIT
  237382. return true;
  237383. #else
  237384. return false;
  237385. #endif
  237386. }
  237387. namespace AndroidStatsHelpers
  237388. {
  237389. // TODO
  237390. const String getCpuInfo (const char* const key)
  237391. {
  237392. StringArray lines;
  237393. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  237394. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  237395. if (lines[i].startsWithIgnoreCase (key))
  237396. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  237397. return String::empty;
  237398. }
  237399. }
  237400. const String SystemStats::getCpuVendor()
  237401. {
  237402. return AndroidStatsHelpers::getCpuInfo ("vendor_id");
  237403. }
  237404. int SystemStats::getCpuSpeedInMegaherz()
  237405. {
  237406. return roundToInt (AndroidStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  237407. }
  237408. int SystemStats::getMemorySizeInMegabytes()
  237409. {
  237410. struct sysinfo sysi;
  237411. if (sysinfo (&sysi) == 0)
  237412. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  237413. return 0;
  237414. }
  237415. int SystemStats::getPageSize()
  237416. {
  237417. // TODO
  237418. return sysconf (_SC_PAGESIZE);
  237419. }
  237420. const String SystemStats::getLogonName()
  237421. {
  237422. // TODO
  237423. const char* user = getenv ("USER");
  237424. if (user == 0)
  237425. {
  237426. struct passwd* const pw = getpwuid (getuid());
  237427. if (pw != 0)
  237428. user = pw->pw_name;
  237429. }
  237430. return String::fromUTF8 (user);
  237431. }
  237432. const String SystemStats::getFullUserName()
  237433. {
  237434. return getLogonName();
  237435. }
  237436. void SystemStats::initialiseStats()
  237437. {
  237438. // TODO
  237439. const String flags (AndroidStatsHelpers::getCpuInfo ("flags"));
  237440. cpuFlags.hasMMX = flags.contains ("mmx");
  237441. cpuFlags.hasSSE = flags.contains ("sse");
  237442. cpuFlags.hasSSE2 = flags.contains ("sse2");
  237443. cpuFlags.has3DNow = flags.contains ("3dnow");
  237444. cpuFlags.numCpus = jmax (1, sysconf (_SC_NPROCESSORS_ONLN));
  237445. }
  237446. void PlatformUtilities::fpuReset() {}
  237447. uint32 juce_millisecondsSinceStartup() throw()
  237448. {
  237449. // TODO
  237450. timespec t;
  237451. clock_gettime (CLOCK_MONOTONIC, &t);
  237452. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  237453. }
  237454. int64 Time::getHighResolutionTicks() throw()
  237455. {
  237456. // TODO
  237457. timespec t;
  237458. clock_gettime (CLOCK_MONOTONIC, &t);
  237459. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  237460. }
  237461. int64 Time::getHighResolutionTicksPerSecond() throw()
  237462. {
  237463. // TODO
  237464. return 1000000; // (microseconds)
  237465. }
  237466. double Time::getMillisecondCounterHiRes() throw()
  237467. {
  237468. return getHighResolutionTicks() * 0.001;
  237469. }
  237470. bool Time::setSystemTimeToThisTime() const
  237471. {
  237472. jassertfalse;
  237473. return false;
  237474. }
  237475. #endif
  237476. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  237477. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  237478. /*
  237479. This file contains posix routines that are common to both the Linux and Mac builds.
  237480. It gets included directly in the cpp files for these platforms.
  237481. */
  237482. CriticalSection::CriticalSection() throw()
  237483. {
  237484. pthread_mutexattr_t atts;
  237485. pthread_mutexattr_init (&atts);
  237486. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  237487. #if ! JUCE_ANDROID
  237488. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  237489. #endif
  237490. pthread_mutex_init (&internal, &atts);
  237491. }
  237492. CriticalSection::~CriticalSection() throw()
  237493. {
  237494. pthread_mutex_destroy (&internal);
  237495. }
  237496. void CriticalSection::enter() const throw()
  237497. {
  237498. pthread_mutex_lock (&internal);
  237499. }
  237500. bool CriticalSection::tryEnter() const throw()
  237501. {
  237502. return pthread_mutex_trylock (&internal) == 0;
  237503. }
  237504. void CriticalSection::exit() const throw()
  237505. {
  237506. pthread_mutex_unlock (&internal);
  237507. }
  237508. class WaitableEventImpl
  237509. {
  237510. public:
  237511. WaitableEventImpl (const bool manualReset_)
  237512. : triggered (false),
  237513. manualReset (manualReset_)
  237514. {
  237515. pthread_cond_init (&condition, 0);
  237516. pthread_mutexattr_t atts;
  237517. pthread_mutexattr_init (&atts);
  237518. #if ! JUCE_ANDROID
  237519. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  237520. #endif
  237521. pthread_mutex_init (&mutex, &atts);
  237522. }
  237523. ~WaitableEventImpl()
  237524. {
  237525. pthread_cond_destroy (&condition);
  237526. pthread_mutex_destroy (&mutex);
  237527. }
  237528. bool wait (const int timeOutMillisecs) throw()
  237529. {
  237530. pthread_mutex_lock (&mutex);
  237531. if (! triggered)
  237532. {
  237533. if (timeOutMillisecs < 0)
  237534. {
  237535. do
  237536. {
  237537. pthread_cond_wait (&condition, &mutex);
  237538. }
  237539. while (! triggered);
  237540. }
  237541. else
  237542. {
  237543. struct timeval now;
  237544. gettimeofday (&now, 0);
  237545. struct timespec time;
  237546. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  237547. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  237548. if (time.tv_nsec >= 1000000000)
  237549. {
  237550. time.tv_nsec -= 1000000000;
  237551. time.tv_sec++;
  237552. }
  237553. do
  237554. {
  237555. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  237556. {
  237557. pthread_mutex_unlock (&mutex);
  237558. return false;
  237559. }
  237560. }
  237561. while (! triggered);
  237562. }
  237563. }
  237564. if (! manualReset)
  237565. triggered = false;
  237566. pthread_mutex_unlock (&mutex);
  237567. return true;
  237568. }
  237569. void signal() throw()
  237570. {
  237571. pthread_mutex_lock (&mutex);
  237572. triggered = true;
  237573. pthread_cond_broadcast (&condition);
  237574. pthread_mutex_unlock (&mutex);
  237575. }
  237576. void reset() throw()
  237577. {
  237578. pthread_mutex_lock (&mutex);
  237579. triggered = false;
  237580. pthread_mutex_unlock (&mutex);
  237581. }
  237582. private:
  237583. pthread_cond_t condition;
  237584. pthread_mutex_t mutex;
  237585. bool triggered;
  237586. const bool manualReset;
  237587. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  237588. };
  237589. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  237590. : internal (new WaitableEventImpl (manualReset))
  237591. {
  237592. }
  237593. WaitableEvent::~WaitableEvent() throw()
  237594. {
  237595. delete static_cast <WaitableEventImpl*> (internal);
  237596. }
  237597. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  237598. {
  237599. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  237600. }
  237601. void WaitableEvent::signal() const throw()
  237602. {
  237603. static_cast <WaitableEventImpl*> (internal)->signal();
  237604. }
  237605. void WaitableEvent::reset() const throw()
  237606. {
  237607. static_cast <WaitableEventImpl*> (internal)->reset();
  237608. }
  237609. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  237610. {
  237611. struct timespec time;
  237612. time.tv_sec = millisecs / 1000;
  237613. time.tv_nsec = (millisecs % 1000) * 1000000;
  237614. nanosleep (&time, 0);
  237615. }
  237616. const juce_wchar File::separator = '/';
  237617. const String File::separatorString ("/");
  237618. const File File::getCurrentWorkingDirectory()
  237619. {
  237620. HeapBlock<char> heapBuffer;
  237621. char localBuffer [1024];
  237622. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  237623. int bufferSize = 4096;
  237624. while (cwd == 0 && errno == ERANGE)
  237625. {
  237626. heapBuffer.malloc (bufferSize);
  237627. cwd = getcwd (heapBuffer, bufferSize - 1);
  237628. bufferSize += 1024;
  237629. }
  237630. return File (String::fromUTF8 (cwd));
  237631. }
  237632. bool File::setAsCurrentWorkingDirectory() const
  237633. {
  237634. return chdir (getFullPathName().toUTF8()) == 0;
  237635. }
  237636. namespace
  237637. {
  237638. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237639. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  237640. #else
  237641. typedef struct stat juce_statStruct;
  237642. #endif
  237643. bool juce_stat (const String& fileName, juce_statStruct& info)
  237644. {
  237645. return fileName.isNotEmpty()
  237646. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237647. && (stat64 (fileName.toUTF8(), &info) == 0);
  237648. #else
  237649. && (stat (fileName.toUTF8(), &info) == 0);
  237650. #endif
  237651. }
  237652. // if this file doesn't exist, find a parent of it that does..
  237653. bool juce_doStatFS (File f, struct statfs& result)
  237654. {
  237655. for (int i = 5; --i >= 0;)
  237656. {
  237657. if (f.exists())
  237658. break;
  237659. f = f.getParentDirectory();
  237660. }
  237661. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  237662. }
  237663. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  237664. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237665. {
  237666. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  237667. {
  237668. juce_statStruct info;
  237669. const bool statOk = juce_stat (path, info);
  237670. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  237671. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  237672. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  237673. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  237674. }
  237675. if (isReadOnly != 0)
  237676. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  237677. }
  237678. }
  237679. bool File::isDirectory() const
  237680. {
  237681. juce_statStruct info;
  237682. return fullPath.isEmpty()
  237683. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  237684. }
  237685. bool File::exists() const
  237686. {
  237687. juce_statStruct info;
  237688. return fullPath.isNotEmpty()
  237689. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237690. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  237691. #else
  237692. && (lstat (fullPath.toUTF8(), &info) == 0);
  237693. #endif
  237694. }
  237695. bool File::existsAsFile() const
  237696. {
  237697. return exists() && ! isDirectory();
  237698. }
  237699. int64 File::getSize() const
  237700. {
  237701. juce_statStruct info;
  237702. return juce_stat (fullPath, info) ? info.st_size : 0;
  237703. }
  237704. bool File::hasWriteAccess() const
  237705. {
  237706. if (exists())
  237707. return access (fullPath.toUTF8(), W_OK) == 0;
  237708. if ((! isDirectory()) && fullPath.containsChar (separator))
  237709. return getParentDirectory().hasWriteAccess();
  237710. return false;
  237711. }
  237712. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  237713. {
  237714. juce_statStruct info;
  237715. if (! juce_stat (fullPath, info))
  237716. return false;
  237717. info.st_mode &= 0777; // Just permissions
  237718. if (shouldBeReadOnly)
  237719. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  237720. else
  237721. // Give everybody write permission?
  237722. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  237723. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  237724. }
  237725. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  237726. {
  237727. modificationTime = 0;
  237728. accessTime = 0;
  237729. creationTime = 0;
  237730. juce_statStruct info;
  237731. if (juce_stat (fullPath, info))
  237732. {
  237733. modificationTime = (int64) info.st_mtime * 1000;
  237734. accessTime = (int64) info.st_atime * 1000;
  237735. creationTime = (int64) info.st_ctime * 1000;
  237736. }
  237737. }
  237738. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  237739. {
  237740. juce_statStruct info;
  237741. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  237742. {
  237743. struct utimbuf times;
  237744. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  237745. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  237746. return utime (fullPath.toUTF8(), &times) == 0;
  237747. }
  237748. return false;
  237749. }
  237750. bool File::deleteFile() const
  237751. {
  237752. if (! exists())
  237753. return true;
  237754. if (isDirectory())
  237755. return rmdir (fullPath.toUTF8()) == 0;
  237756. return remove (fullPath.toUTF8()) == 0;
  237757. }
  237758. bool File::moveInternal (const File& dest) const
  237759. {
  237760. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  237761. return true;
  237762. if (hasWriteAccess() && copyInternal (dest))
  237763. {
  237764. if (deleteFile())
  237765. return true;
  237766. dest.deleteFile();
  237767. }
  237768. return false;
  237769. }
  237770. void File::createDirectoryInternal (const String& fileName) const
  237771. {
  237772. mkdir (fileName.toUTF8(), 0777);
  237773. }
  237774. int64 juce_fileSetPosition (void* handle, int64 pos)
  237775. {
  237776. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  237777. return pos;
  237778. return -1;
  237779. }
  237780. void FileInputStream::openHandle()
  237781. {
  237782. totalSize = file.getSize();
  237783. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  237784. if (f != -1)
  237785. fileHandle = (void*) f;
  237786. }
  237787. void FileInputStream::closeHandle()
  237788. {
  237789. if (fileHandle != 0)
  237790. {
  237791. close ((int) (pointer_sized_int) fileHandle);
  237792. fileHandle = 0;
  237793. }
  237794. }
  237795. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  237796. {
  237797. if (fileHandle != 0)
  237798. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  237799. return 0;
  237800. }
  237801. void FileOutputStream::openHandle()
  237802. {
  237803. if (file.exists())
  237804. {
  237805. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  237806. if (f != -1)
  237807. {
  237808. currentPosition = lseek (f, 0, SEEK_END);
  237809. if (currentPosition >= 0)
  237810. fileHandle = (void*) f;
  237811. else
  237812. close (f);
  237813. }
  237814. }
  237815. else
  237816. {
  237817. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  237818. if (f != -1)
  237819. fileHandle = (void*) f;
  237820. }
  237821. }
  237822. void FileOutputStream::closeHandle()
  237823. {
  237824. if (fileHandle != 0)
  237825. {
  237826. close ((int) (pointer_sized_int) fileHandle);
  237827. fileHandle = 0;
  237828. }
  237829. }
  237830. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  237831. {
  237832. if (fileHandle != 0)
  237833. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  237834. return 0;
  237835. }
  237836. void FileOutputStream::flushInternal()
  237837. {
  237838. if (fileHandle != 0)
  237839. fsync ((int) (pointer_sized_int) fileHandle);
  237840. }
  237841. const File juce_getExecutableFile()
  237842. {
  237843. #if JUCE_ANDROID
  237844. return File (android.appFile);
  237845. #else
  237846. Dl_info exeInfo;
  237847. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  237848. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  237849. #endif
  237850. }
  237851. int64 File::getBytesFreeOnVolume() const
  237852. {
  237853. struct statfs buf;
  237854. if (juce_doStatFS (*this, buf))
  237855. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  237856. return 0;
  237857. }
  237858. int64 File::getVolumeTotalSize() const
  237859. {
  237860. struct statfs buf;
  237861. if (juce_doStatFS (*this, buf))
  237862. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  237863. return 0;
  237864. }
  237865. const String File::getVolumeLabel() const
  237866. {
  237867. #if JUCE_MAC
  237868. struct VolAttrBuf
  237869. {
  237870. u_int32_t length;
  237871. attrreference_t mountPointRef;
  237872. char mountPointSpace [MAXPATHLEN];
  237873. } attrBuf;
  237874. struct attrlist attrList;
  237875. zerostruct (attrList);
  237876. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  237877. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  237878. File f (*this);
  237879. for (;;)
  237880. {
  237881. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  237882. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  237883. (int) attrBuf.mountPointRef.attr_length);
  237884. const File parent (f.getParentDirectory());
  237885. if (f == parent)
  237886. break;
  237887. f = parent;
  237888. }
  237889. #endif
  237890. return String::empty;
  237891. }
  237892. int File::getVolumeSerialNumber() const
  237893. {
  237894. int result = 0;
  237895. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  237896. char info [512];
  237897. #ifndef HDIO_GET_IDENTITY
  237898. #define HDIO_GET_IDENTITY 0x030d
  237899. #endif
  237900. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  237901. {
  237902. DBG (String (info + 20, 20));
  237903. result = String (info + 20, 20).trim().getIntValue();
  237904. }
  237905. close (fd);*/
  237906. return result;
  237907. }
  237908. void juce_runSystemCommand (const String& command)
  237909. {
  237910. int result = system (command.toUTF8());
  237911. (void) result;
  237912. }
  237913. const String juce_getOutputFromCommand (const String& command)
  237914. {
  237915. // slight bodge here, as we just pipe the output into a temp file and read it...
  237916. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  237917. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  237918. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  237919. String result (tempFile.loadFileAsString());
  237920. tempFile.deleteFile();
  237921. return result;
  237922. }
  237923. class InterProcessLock::Pimpl
  237924. {
  237925. public:
  237926. Pimpl (const String& name, const int timeOutMillisecs)
  237927. : handle (0), refCount (1)
  237928. {
  237929. #if JUCE_MAC
  237930. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  237931. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  237932. #else
  237933. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  237934. #endif
  237935. temp.create();
  237936. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  237937. if (handle != 0)
  237938. {
  237939. struct flock fl;
  237940. zerostruct (fl);
  237941. fl.l_whence = SEEK_SET;
  237942. fl.l_type = F_WRLCK;
  237943. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  237944. for (;;)
  237945. {
  237946. const int result = fcntl (handle, F_SETLK, &fl);
  237947. if (result >= 0)
  237948. return;
  237949. if (errno != EINTR)
  237950. {
  237951. if (timeOutMillisecs == 0
  237952. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  237953. break;
  237954. Thread::sleep (10);
  237955. }
  237956. }
  237957. }
  237958. closeFile();
  237959. }
  237960. ~Pimpl()
  237961. {
  237962. closeFile();
  237963. }
  237964. void closeFile()
  237965. {
  237966. if (handle != 0)
  237967. {
  237968. struct flock fl;
  237969. zerostruct (fl);
  237970. fl.l_whence = SEEK_SET;
  237971. fl.l_type = F_UNLCK;
  237972. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  237973. {}
  237974. close (handle);
  237975. handle = 0;
  237976. }
  237977. }
  237978. int handle, refCount;
  237979. };
  237980. InterProcessLock::InterProcessLock (const String& name_)
  237981. : name (name_)
  237982. {
  237983. }
  237984. InterProcessLock::~InterProcessLock()
  237985. {
  237986. }
  237987. bool InterProcessLock::enter (const int timeOutMillisecs)
  237988. {
  237989. const ScopedLock sl (lock);
  237990. if (pimpl == 0)
  237991. {
  237992. pimpl = new Pimpl (name, timeOutMillisecs);
  237993. if (pimpl->handle == 0)
  237994. pimpl = 0;
  237995. }
  237996. else
  237997. {
  237998. pimpl->refCount++;
  237999. }
  238000. return pimpl != 0;
  238001. }
  238002. void InterProcessLock::exit()
  238003. {
  238004. const ScopedLock sl (lock);
  238005. // Trying to release the lock too many times!
  238006. jassert (pimpl != 0);
  238007. if (pimpl != 0 && --(pimpl->refCount) == 0)
  238008. pimpl = 0;
  238009. }
  238010. void JUCE_API juce_threadEntryPoint (void*);
  238011. void* threadEntryProc (void* userData)
  238012. {
  238013. JUCE_AUTORELEASEPOOL
  238014. #if JUCE_ANDROID
  238015. const AndroidThreadScope androidEnv;
  238016. #endif
  238017. juce_threadEntryPoint (userData);
  238018. return 0;
  238019. }
  238020. void Thread::launchThread()
  238021. {
  238022. threadHandle_ = 0;
  238023. pthread_t handle = 0;
  238024. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  238025. {
  238026. pthread_detach (handle);
  238027. threadHandle_ = (void*) handle;
  238028. threadId_ = (ThreadID) threadHandle_;
  238029. }
  238030. }
  238031. void Thread::closeThreadHandle()
  238032. {
  238033. threadId_ = 0;
  238034. threadHandle_ = 0;
  238035. }
  238036. void Thread::killThread()
  238037. {
  238038. if (threadHandle_ != 0)
  238039. {
  238040. #if JUCE_ANDROID
  238041. jassertfalse; // pthread_cancel not available!
  238042. #else
  238043. pthread_cancel ((pthread_t) threadHandle_);
  238044. #endif
  238045. }
  238046. }
  238047. void Thread::setCurrentThreadName (const String& name)
  238048. {
  238049. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  238050. pthread_setname_np (name.toUTF8());
  238051. #elif JUCE_LINUX
  238052. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  238053. #endif
  238054. }
  238055. bool Thread::setThreadPriority (void* handle, int priority)
  238056. {
  238057. struct sched_param param;
  238058. int policy;
  238059. priority = jlimit (0, 10, priority);
  238060. if (handle == 0)
  238061. handle = (void*) pthread_self();
  238062. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  238063. return false;
  238064. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  238065. const int minPriority = sched_get_priority_min (policy);
  238066. const int maxPriority = sched_get_priority_max (policy);
  238067. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  238068. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  238069. }
  238070. Thread::ThreadID Thread::getCurrentThreadId()
  238071. {
  238072. return (ThreadID) pthread_self();
  238073. }
  238074. void Thread::yield()
  238075. {
  238076. sched_yield();
  238077. }
  238078. /* Remove this macro if you're having problems compiling the cpu affinity
  238079. calls (the API for these has changed about quite a bit in various Linux
  238080. versions, and a lot of distros seem to ship with obsolete versions)
  238081. */
  238082. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  238083. #define SUPPORT_AFFINITIES 1
  238084. #endif
  238085. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  238086. {
  238087. #if SUPPORT_AFFINITIES
  238088. cpu_set_t affinity;
  238089. CPU_ZERO (&affinity);
  238090. for (int i = 0; i < 32; ++i)
  238091. if ((affinityMask & (1 << i)) != 0)
  238092. CPU_SET (i, &affinity);
  238093. /*
  238094. N.B. If this line causes a compile error, then you've probably not got the latest
  238095. version of glibc installed.
  238096. If you don't want to update your copy of glibc and don't care about cpu affinities,
  238097. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  238098. */
  238099. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  238100. sched_yield();
  238101. #else
  238102. /* affinities aren't supported because either the appropriate header files weren't found,
  238103. or the SUPPORT_AFFINITIES macro was turned off
  238104. */
  238105. jassertfalse;
  238106. (void) affinityMask;
  238107. #endif
  238108. }
  238109. /*** End of inlined file: juce_posix_SharedCode.h ***/
  238110. /*** Start of inlined file: juce_android_Files.cpp ***/
  238111. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238112. // compiled on its own).
  238113. #if JUCE_INCLUDED_FILE
  238114. bool File::copyInternal (const File& dest) const
  238115. {
  238116. // TODO
  238117. FileInputStream in (*this);
  238118. if (dest.deleteFile())
  238119. {
  238120. {
  238121. FileOutputStream out (dest);
  238122. if (out.failedToOpen())
  238123. return false;
  238124. if (out.writeFromInputStream (in, -1) == getSize())
  238125. return true;
  238126. }
  238127. dest.deleteFile();
  238128. }
  238129. return false;
  238130. }
  238131. void File::findFileSystemRoots (Array<File>& destArray)
  238132. {
  238133. // TODO
  238134. destArray.add (File ("/"));
  238135. }
  238136. bool File::isOnCDRomDrive() const
  238137. {
  238138. return false;
  238139. }
  238140. bool File::isOnHardDisk() const
  238141. {
  238142. return true;
  238143. }
  238144. bool File::isOnRemovableDrive() const
  238145. {
  238146. return false;
  238147. }
  238148. bool File::isHidden() const
  238149. {
  238150. // TODO
  238151. return getFileName().startsWithChar ('.');
  238152. }
  238153. namespace
  238154. {
  238155. const File juce_readlink (const String& file, const File& defaultFile)
  238156. {
  238157. const int size = 8192;
  238158. HeapBlock<char> buffer;
  238159. buffer.malloc (size + 4);
  238160. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  238161. if (numBytes > 0 && numBytes <= size)
  238162. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  238163. return defaultFile;
  238164. }
  238165. }
  238166. const File File::getLinkedTarget() const
  238167. {
  238168. // TODO
  238169. return juce_readlink (getFullPathName().toUTF8(), *this);
  238170. }
  238171. const File File::getSpecialLocation (const SpecialLocationType type)
  238172. {
  238173. switch (type)
  238174. {
  238175. case userHomeDirectory:
  238176. case userDocumentsDirectory:
  238177. case userMusicDirectory:
  238178. case userMoviesDirectory:
  238179. case userApplicationDataDirectory:
  238180. return File (android.appDataDir);
  238181. case userDesktopDirectory:
  238182. return File ("~/Desktop");
  238183. case commonApplicationDataDirectory:
  238184. return File (android.appDataDir);
  238185. case globalApplicationsDirectory:
  238186. return File ("/usr");
  238187. case tempDirectory:
  238188. return File ("~/.temp");
  238189. case invokedExecutableFile:
  238190. case currentExecutableFile:
  238191. case currentApplicationFile:
  238192. case hostApplicationPath:
  238193. return juce_getExecutableFile();
  238194. default:
  238195. jassertfalse; // unknown type?
  238196. break;
  238197. }
  238198. return File::nonexistent;
  238199. }
  238200. const String File::getVersion() const
  238201. {
  238202. return String::empty;
  238203. }
  238204. bool File::moveToTrash() const
  238205. {
  238206. if (! exists())
  238207. return true;
  238208. // TODO
  238209. return false;
  238210. }
  238211. class DirectoryIterator::NativeIterator::Pimpl
  238212. {
  238213. public:
  238214. Pimpl (const File& directory, const String& wildCard_)
  238215. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  238216. wildCard (wildCard_),
  238217. dir (opendir (directory.getFullPathName().toUTF8()))
  238218. {
  238219. wildcardUTF8 = wildCard.toUTF8();
  238220. }
  238221. ~Pimpl()
  238222. {
  238223. if (dir != 0)
  238224. closedir (dir);
  238225. }
  238226. bool next (String& filenameFound,
  238227. bool* const isDir, bool* const isHidden, int64* const fileSize,
  238228. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  238229. {
  238230. if (dir != 0)
  238231. {
  238232. for (;;)
  238233. {
  238234. struct dirent* const de = readdir (dir);
  238235. if (de == 0)
  238236. break;
  238237. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  238238. {
  238239. filenameFound = String::fromUTF8 (de->d_name);
  238240. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  238241. if (isHidden != 0)
  238242. *isHidden = filenameFound.startsWithChar ('.');
  238243. return true;
  238244. }
  238245. }
  238246. }
  238247. return false;
  238248. }
  238249. private:
  238250. String parentDir, wildCard;
  238251. const char* wildcardUTF8;
  238252. DIR* dir;
  238253. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  238254. };
  238255. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  238256. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  238257. {
  238258. }
  238259. DirectoryIterator::NativeIterator::~NativeIterator()
  238260. {
  238261. }
  238262. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  238263. bool* const isDir, bool* const isHidden, int64* const fileSize,
  238264. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  238265. {
  238266. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  238267. }
  238268. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  238269. {
  238270. }
  238271. void File::revealToUser() const
  238272. {
  238273. }
  238274. #endif
  238275. /*** End of inlined file: juce_android_Files.cpp ***/
  238276. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  238277. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  238278. // compiled on its own).
  238279. #if JUCE_INCLUDED_FILE
  238280. struct NamedPipeInternal
  238281. {
  238282. String pipeInName, pipeOutName;
  238283. int pipeIn, pipeOut;
  238284. bool volatile createdPipe, blocked, stopReadOperation;
  238285. static void signalHandler (int) {}
  238286. };
  238287. void NamedPipe::cancelPendingReads()
  238288. {
  238289. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  238290. {
  238291. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238292. intern->stopReadOperation = true;
  238293. char buffer [1] = { 0 };
  238294. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  238295. (void) bytesWritten;
  238296. int timeout = 2000;
  238297. while (intern->blocked && --timeout >= 0)
  238298. Thread::sleep (2);
  238299. intern->stopReadOperation = false;
  238300. }
  238301. }
  238302. void NamedPipe::close()
  238303. {
  238304. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238305. if (intern != 0)
  238306. {
  238307. internal = 0;
  238308. if (intern->pipeIn != -1)
  238309. ::close (intern->pipeIn);
  238310. if (intern->pipeOut != -1)
  238311. ::close (intern->pipeOut);
  238312. if (intern->createdPipe)
  238313. {
  238314. unlink (intern->pipeInName.toUTF8());
  238315. unlink (intern->pipeOutName.toUTF8());
  238316. }
  238317. delete intern;
  238318. }
  238319. }
  238320. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  238321. {
  238322. close();
  238323. NamedPipeInternal* const intern = new NamedPipeInternal();
  238324. internal = intern;
  238325. intern->createdPipe = createPipe;
  238326. intern->blocked = false;
  238327. intern->stopReadOperation = false;
  238328. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  238329. siginterrupt (SIGPIPE, 1);
  238330. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  238331. intern->pipeInName = pipePath + "_in";
  238332. intern->pipeOutName = pipePath + "_out";
  238333. intern->pipeIn = -1;
  238334. intern->pipeOut = -1;
  238335. if (createPipe)
  238336. {
  238337. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  238338. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  238339. {
  238340. delete intern;
  238341. internal = 0;
  238342. return false;
  238343. }
  238344. }
  238345. return true;
  238346. }
  238347. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  238348. {
  238349. int bytesRead = -1;
  238350. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238351. if (intern != 0)
  238352. {
  238353. intern->blocked = true;
  238354. if (intern->pipeIn == -1)
  238355. {
  238356. if (intern->createdPipe)
  238357. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  238358. else
  238359. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  238360. if (intern->pipeIn == -1)
  238361. {
  238362. intern->blocked = false;
  238363. return -1;
  238364. }
  238365. }
  238366. bytesRead = 0;
  238367. char* p = static_cast<char*> (destBuffer);
  238368. while (bytesRead < maxBytesToRead)
  238369. {
  238370. const int bytesThisTime = maxBytesToRead - bytesRead;
  238371. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  238372. if (numRead <= 0 || intern->stopReadOperation)
  238373. {
  238374. bytesRead = -1;
  238375. break;
  238376. }
  238377. bytesRead += numRead;
  238378. p += bytesRead;
  238379. }
  238380. intern->blocked = false;
  238381. }
  238382. return bytesRead;
  238383. }
  238384. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  238385. {
  238386. int bytesWritten = -1;
  238387. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238388. if (intern != 0)
  238389. {
  238390. if (intern->pipeOut == -1)
  238391. {
  238392. if (intern->createdPipe)
  238393. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  238394. else
  238395. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  238396. if (intern->pipeOut == -1)
  238397. {
  238398. return -1;
  238399. }
  238400. }
  238401. const char* p = static_cast<const char*> (sourceBuffer);
  238402. bytesWritten = 0;
  238403. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  238404. while (bytesWritten < numBytesToWrite
  238405. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  238406. {
  238407. const int bytesThisTime = numBytesToWrite - bytesWritten;
  238408. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  238409. if (numWritten <= 0)
  238410. {
  238411. bytesWritten = -1;
  238412. break;
  238413. }
  238414. bytesWritten += numWritten;
  238415. p += bytesWritten;
  238416. }
  238417. }
  238418. return bytesWritten;
  238419. }
  238420. #endif
  238421. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  238422. /*** Start of inlined file: juce_android_Threads.cpp ***/
  238423. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238424. // compiled on its own).
  238425. #if JUCE_INCLUDED_FILE
  238426. /*
  238427. Note that a lot of methods that you'd expect to find in this file actually
  238428. live in juce_posix_SharedCode.h!
  238429. */
  238430. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  238431. void Process::setPriority (ProcessPriority prior)
  238432. {
  238433. // TODO
  238434. struct sched_param param;
  238435. int policy, maxp, minp;
  238436. const int p = (int) prior;
  238437. if (p <= 1)
  238438. policy = SCHED_OTHER;
  238439. else
  238440. policy = SCHED_RR;
  238441. minp = sched_get_priority_min (policy);
  238442. maxp = sched_get_priority_max (policy);
  238443. if (p < 2)
  238444. param.sched_priority = 0;
  238445. else if (p == 2 )
  238446. // Set to middle of lower realtime priority range
  238447. param.sched_priority = minp + (maxp - minp) / 4;
  238448. else
  238449. // Set to middle of higher realtime priority range
  238450. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  238451. pthread_setschedparam (pthread_self(), policy, &param);
  238452. }
  238453. void Process::terminate()
  238454. {
  238455. // TODO
  238456. exit (0);
  238457. }
  238458. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  238459. {
  238460. return false;
  238461. }
  238462. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  238463. {
  238464. return juce_isRunningUnderDebugger();
  238465. }
  238466. void Process::raisePrivilege() {}
  238467. void Process::lowerPrivilege() {}
  238468. #endif
  238469. /*** End of inlined file: juce_android_Threads.cpp ***/
  238470. /*** Start of inlined file: juce_android_Network.cpp ***/
  238471. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238472. // compiled on its own).
  238473. #if JUCE_INCLUDED_FILE
  238474. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  238475. {
  238476. // TODO
  238477. }
  238478. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  238479. const String& emailSubject,
  238480. const String& bodyText,
  238481. const StringArray& filesToAttach)
  238482. {
  238483. // TODO
  238484. return false;
  238485. }
  238486. class WebInputStream : public InputStream
  238487. {
  238488. public:
  238489. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  238490. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  238491. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  238492. {
  238493. // TODO
  238494. openedOk = false;
  238495. }
  238496. ~WebInputStream()
  238497. {
  238498. }
  238499. bool isExhausted()
  238500. {
  238501. return true; // TODO
  238502. }
  238503. int64 getPosition()
  238504. {
  238505. return 0; // TODO
  238506. }
  238507. int64 getTotalLength()
  238508. {
  238509. return -1; // TODO
  238510. }
  238511. int read (void* buffer, int bytesToRead)
  238512. {
  238513. // TODO
  238514. return 0;
  238515. }
  238516. bool setPosition (int64 wantedPos)
  238517. {
  238518. // TODO
  238519. return false;
  238520. }
  238521. bool openedOk;
  238522. private:
  238523. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  238524. };
  238525. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  238526. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  238527. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  238528. {
  238529. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  238530. progressCallback, progressCallbackContext,
  238531. headers, timeOutMs, responseHeaders));
  238532. return wi->openedOk ? wi.release() : 0;
  238533. }
  238534. #endif
  238535. /*** End of inlined file: juce_android_Network.cpp ***/
  238536. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  238537. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238538. // compiled on its own).
  238539. #if JUCE_INCLUDED_FILE
  238540. void MessageManager::doPlatformSpecificInitialisation() {}
  238541. void MessageManager::doPlatformSpecificShutdown() {}
  238542. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  238543. {
  238544. Logger::outputDebugString ("*** Modal loops are not possible in Android!! Exiting...");
  238545. exit (1);
  238546. return true;
  238547. }
  238548. bool juce_postMessageToSystemQueue (Message* message)
  238549. {
  238550. message->incReferenceCount();
  238551. getEnv()->CallVoidMethod (android.activity, android.postMessage, (jlong) (pointer_sized_uint) message);
  238552. return true;
  238553. }
  238554. JUCE_JNI_CALLBACK (JuceAppActivity, deliverMessage, void, (jobject activity, jlong value))
  238555. {
  238556. Message* const message = (Message*) (pointer_sized_uint) value;
  238557. MessageManager::getInstance()->deliverMessage (message);
  238558. message->decReferenceCount();
  238559. }
  238560. class AsyncFunctionCaller : public AsyncUpdater
  238561. {
  238562. public:
  238563. static void* call (MessageCallbackFunction* func_, void* parameter_)
  238564. {
  238565. if (MessageManager::getInstance()->isThisTheMessageThread())
  238566. return func_ (parameter_);
  238567. AsyncFunctionCaller caller (func_, parameter_);
  238568. caller.triggerAsyncUpdate();
  238569. caller.finished.wait();
  238570. return caller.result;
  238571. }
  238572. void handleAsyncUpdate()
  238573. {
  238574. result = (*func) (parameter);
  238575. finished.signal();
  238576. }
  238577. private:
  238578. WaitableEvent finished;
  238579. MessageCallbackFunction* func;
  238580. void* parameter;
  238581. void* volatile result;
  238582. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  238583. : result (0), func (func_), parameter (parameter_)
  238584. {}
  238585. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  238586. };
  238587. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  238588. {
  238589. return AsyncFunctionCaller::call (func, parameter);
  238590. }
  238591. void MessageManager::broadcastMessage (const String&)
  238592. {
  238593. }
  238594. void MessageManager::runDispatchLoop()
  238595. {
  238596. }
  238597. class QuitCallback : public CallbackMessage
  238598. {
  238599. public:
  238600. QuitCallback() {}
  238601. void messageCallback()
  238602. {
  238603. android.activity.callVoidMethod (android.finish);
  238604. }
  238605. };
  238606. void MessageManager::stopDispatchLoop()
  238607. {
  238608. (new QuitCallback())->post();
  238609. quitMessagePosted = true;
  238610. }
  238611. #endif
  238612. /*** End of inlined file: juce_android_Messaging.cpp ***/
  238613. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  238614. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238615. // compiled on its own).
  238616. #if JUCE_INCLUDED_FILE
  238617. const StringArray Font::findAllTypefaceNames()
  238618. {
  238619. StringArray results;
  238620. Array<File> fonts;
  238621. File ("/system/fonts").findChildFiles (fonts, File::findFiles, false, "*.ttf");
  238622. for (int i = 0; i < fonts.size(); ++i)
  238623. results.add (fonts.getReference(i).getFileNameWithoutExtension());
  238624. return results;
  238625. }
  238626. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  238627. {
  238628. defaultSans = "sans";
  238629. defaultSerif = "serif";
  238630. defaultFixed = "monospace";
  238631. defaultFallback = "sans";
  238632. }
  238633. class AndroidTypeface : public Typeface
  238634. {
  238635. public:
  238636. AndroidTypeface (const Font& font)
  238637. : Typeface (font.getTypefaceName()),
  238638. ascent (0),
  238639. descent (0)
  238640. {
  238641. jint flags = 0;
  238642. if (font.isBold()) flags = 1;
  238643. if (font.isItalic()) flags += 2;
  238644. typeface = GlobalRef (getEnv()->CallStaticObjectMethod (android.typefaceClass, android.create,
  238645. javaString (getName()).get(), flags));
  238646. paint = GlobalRef (android.createPaint());
  238647. const LocalRef<jobject> ignored (paint.callObjectMethod (android.setTypeface, typeface.get()));
  238648. const float standardSize = 256.0f;
  238649. paint.callVoidMethod (android.setTextSize, standardSize);
  238650. ascent = std::abs (paint.callFloatMethod (android.ascent)) / standardSize;
  238651. descent = paint.callFloatMethod (android.descent) / standardSize;
  238652. const float height = ascent + descent;
  238653. unitsToHeightScaleFactor = 1.0f / (height * standardSize);
  238654. }
  238655. float getAscent() const { return ascent; }
  238656. float getDescent() const { return descent; }
  238657. float getStringWidth (const String& text)
  238658. {
  238659. JNIEnv* env = getEnv();
  238660. const int numChars = text.length();
  238661. jfloatArray widths = env->NewFloatArray (numChars);
  238662. const int numDone = paint.callIntMethod (android.getTextWidths, javaString (text).get(), widths);
  238663. HeapBlock<jfloat> localWidths (numDone);
  238664. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  238665. env->DeleteLocalRef (widths);
  238666. float x = 0;
  238667. for (int i = 0; i < numDone; ++i)
  238668. x += localWidths[i];
  238669. return x * unitsToHeightScaleFactor;
  238670. }
  238671. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  238672. {
  238673. JNIEnv* env = getEnv();
  238674. const int numChars = text.length();
  238675. jfloatArray widths = env->NewFloatArray (numChars);
  238676. const int numDone = paint.callIntMethod (android.getTextWidths, javaString (text).get(), widths);
  238677. HeapBlock<jfloat> localWidths (numDone);
  238678. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  238679. env->DeleteLocalRef (widths);
  238680. String::CharPointerType s (text.getCharPointer());
  238681. xOffsets.add (0);
  238682. float x = 0;
  238683. for (int i = 0; i < numDone; ++i)
  238684. {
  238685. glyphs.add ((int) s.getAndAdvance());
  238686. x += localWidths[i];
  238687. xOffsets.add (x * unitsToHeightScaleFactor);
  238688. }
  238689. }
  238690. bool getOutlineForGlyph (int glyphNumber, Path& destPath)
  238691. {
  238692. LocalRef<jstring> s ((jstring) android.activity.callObjectMethod (android.createPathForGlyph, paint.get(), (jchar) glyphNumber));
  238693. if (s == 0)
  238694. return false;
  238695. const String ourString (juceString (s));
  238696. destPath.restoreFromString (ourString);
  238697. return ourString.isNotEmpty();
  238698. }
  238699. GlobalRef typeface, paint;
  238700. float ascent, descent, unitsToHeightScaleFactor;
  238701. private:
  238702. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  238703. };
  238704. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  238705. {
  238706. return new AndroidTypeface (font);
  238707. }
  238708. #endif
  238709. /*** End of inlined file: juce_android_Fonts.cpp ***/
  238710. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  238711. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238712. // compiled on its own).
  238713. #if JUCE_INCLUDED_FILE
  238714. class AndroidImage : public Image::SharedImage
  238715. {
  238716. public:
  238717. AndroidImage (const int width_, const int height_, const bool clearImage)
  238718. : Image::SharedImage (Image::ARGB, width_, height_)
  238719. {
  238720. JNIEnv* env = getEnv();
  238721. jobject mode = env->GetStaticObjectField (android.bitmapConfigClass, android.ARGB_8888);
  238722. bitmap = GlobalRef (env->CallStaticObjectMethod (android.bitmapClass, android.createBitmap, width_, height_, mode));
  238723. env->DeleteLocalRef (mode);
  238724. }
  238725. AndroidImage (const int width_, const int height_, const GlobalRef& bitmap_)
  238726. : Image::SharedImage (Image::ARGB, width_, height_),
  238727. bitmap (bitmap_)
  238728. {
  238729. }
  238730. ~AndroidImage()
  238731. {
  238732. bitmap.callVoidMethod (android.recycle);
  238733. }
  238734. Image::ImageType getType() const { return Image::NativeImage; }
  238735. LowLevelGraphicsContext* createLowLevelContext();
  238736. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode mode)
  238737. {
  238738. bm.lineStride = width * sizeof (jint);
  238739. bm.pixelStride = sizeof (jint);
  238740. bm.pixelFormat = Image::ARGB;
  238741. bm.dataReleaser = new CopyHandler (*this, bm, x, y, mode);
  238742. }
  238743. SharedImage* clone()
  238744. {
  238745. JNIEnv* env = getEnv();
  238746. jobject mode = env->GetStaticObjectField (android.bitmapConfigClass, android.ARGB_8888);
  238747. GlobalRef newCopy (bitmap.callObjectMethod (android.bitmapCopy, mode, true));
  238748. env->DeleteLocalRef (mode);
  238749. return new AndroidImage (width, height, newCopy);
  238750. }
  238751. GlobalRef bitmap;
  238752. private:
  238753. class CopyHandler : public Image::BitmapData::BitmapDataReleaser
  238754. {
  238755. public:
  238756. CopyHandler (AndroidImage& owner_, Image::BitmapData& bitmapData_,
  238757. const int x_, const int y_, const Image::BitmapData::ReadWriteMode mode_)
  238758. : owner (owner_), bitmapData (bitmapData_), mode (mode_), x (x_), y (y_)
  238759. {
  238760. JNIEnv* env = getEnv();
  238761. intArray = env->NewIntArray (bitmapData.width * bitmapData.height);
  238762. if (mode != Image::BitmapData::writeOnly)
  238763. owner_.bitmap.callVoidMethod (android.getPixels, intArray, 0, bitmapData.width, x_, y_,
  238764. bitmapData.width, bitmapData.height);
  238765. bitmapData.data = (uint8*) env->GetIntArrayElements (intArray, 0);
  238766. if (mode != Image::BitmapData::writeOnly)
  238767. {
  238768. for (int yy = 0; yy < bitmapData.height; ++yy)
  238769. {
  238770. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  238771. for (int xx = 0; xx < bitmapData.width; ++xx)
  238772. p[xx].premultiply();
  238773. }
  238774. }
  238775. }
  238776. ~CopyHandler()
  238777. {
  238778. JNIEnv* env = getEnv();
  238779. if (mode != Image::BitmapData::readOnly)
  238780. {
  238781. for (int yy = 0; yy < bitmapData.height; ++yy)
  238782. {
  238783. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  238784. for (int xx = 0; xx < bitmapData.width; ++xx)
  238785. p[xx].unpremultiply();
  238786. }
  238787. }
  238788. env->ReleaseIntArrayElements (intArray, (jint*) bitmapData.data, 0);
  238789. if (mode != Image::BitmapData::readOnly)
  238790. owner.bitmap.callVoidMethod (android.setPixels, intArray, 0, bitmapData.width, x, y,
  238791. bitmapData.width, bitmapData.height);
  238792. env->DeleteLocalRef (intArray);
  238793. }
  238794. private:
  238795. AndroidImage& owner;
  238796. Image::BitmapData& bitmapData;
  238797. jintArray intArray;
  238798. const Image::BitmapData::ReadWriteMode mode;
  238799. const int x, y;
  238800. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CopyHandler);
  238801. };
  238802. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidImage);
  238803. };
  238804. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  238805. {
  238806. if (format == Image::SingleChannel)
  238807. return createSoftwareImage (format, width, height, clearImage);
  238808. else
  238809. return new AndroidImage (width, height, clearImage);
  238810. }
  238811. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  238812. {
  238813. public:
  238814. AndroidLowLevelGraphicsContext (jobject canvas_)
  238815. : canvas (canvas_),
  238816. currentState (new SavedState())
  238817. {
  238818. setFill (Colours::black);
  238819. }
  238820. bool isVectorDevice() const { return false; }
  238821. void setOrigin (int x, int y)
  238822. {
  238823. canvas.callVoidMethod (android.translate, (float) x, (float) y);
  238824. }
  238825. void addTransform (const AffineTransform& transform)
  238826. {
  238827. canvas.callVoidMethod (android.concat, createMatrix (getEnv(), transform).get());
  238828. }
  238829. float getScaleFactor()
  238830. {
  238831. return 1.0f;
  238832. }
  238833. bool clipToRectangle (const Rectangle<int>& r)
  238834. {
  238835. return canvas.callBooleanMethod (android.clipRect, (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  238836. }
  238837. bool clipToRectangleList (const RectangleList& clipRegion)
  238838. {
  238839. RectangleList excluded (getClipBounds());
  238840. excluded.subtract (clipRegion);
  238841. const int numRects = excluded.getNumRectangles();
  238842. for (int i = 0; i < numRects; ++i)
  238843. excludeClipRectangle (excluded.getRectangle(i));
  238844. }
  238845. void excludeClipRectangle (const Rectangle<int>& r)
  238846. {
  238847. android.activity.callVoidMethod (android.excludeClipRegion, canvas.get(),
  238848. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  238849. }
  238850. void clipToPath (const Path& path, const AffineTransform& transform)
  238851. {
  238852. (void) canvas.callBooleanMethod (android.clipPath, createPath (getEnv(), path, transform).get());
  238853. }
  238854. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  238855. {
  238856. // TODO xxx
  238857. }
  238858. bool clipRegionIntersects (const Rectangle<int>& r)
  238859. {
  238860. return getClipBounds().intersects (r);
  238861. }
  238862. const Rectangle<int> getClipBounds() const
  238863. {
  238864. JNIEnv* env = getEnv();
  238865. jobject rect = canvas.callObjectMethod (android.getClipBounds2);
  238866. const int left = env->GetIntField (rect, android.rectLeft);
  238867. const int top = env->GetIntField (rect, android.rectTop);
  238868. const int right = env->GetIntField (rect, android.rectRight);
  238869. const int bottom = env->GetIntField (rect, android.rectBottom);
  238870. env->DeleteLocalRef (rect);
  238871. return Rectangle<int> (left, top, right - left, bottom - top);
  238872. }
  238873. bool isClipEmpty() const
  238874. {
  238875. LocalRef<jobject> tempRect (getEnv()->NewObject (android.rectClass, android.rectConstructor, 0, 0, 0, 0));
  238876. return ! canvas.callBooleanMethod (android.getClipBounds, tempRect.get());
  238877. }
  238878. void setFill (const FillType& fillType)
  238879. {
  238880. currentState->setFillType (fillType);
  238881. }
  238882. void setOpacity (float newOpacity)
  238883. {
  238884. currentState->setAlpha (newOpacity);
  238885. }
  238886. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  238887. {
  238888. // TODO xxx
  238889. }
  238890. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  238891. {
  238892. canvas.callVoidMethod (android.drawRect,
  238893. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom(),
  238894. getCurrentPaint());
  238895. }
  238896. void fillPath (const Path& path, const AffineTransform& transform)
  238897. {
  238898. canvas.callVoidMethod (android.drawPath, createPath (getEnv(), path, transform).get(),
  238899. getCurrentPaint());
  238900. }
  238901. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  238902. {
  238903. AndroidImage* androidImage = dynamic_cast <AndroidImage*> (sourceImage.getSharedImage());
  238904. if (androidImage != 0)
  238905. {
  238906. JNIEnv* env = getEnv();
  238907. canvas.callVoidMethod (android.drawBitmap, androidImage->bitmap.get(),
  238908. createMatrix (env, transform).get(), getImagePaint());
  238909. }
  238910. else
  238911. {
  238912. if (transform.isOnlyTranslation())
  238913. {
  238914. JNIEnv* env = getEnv();
  238915. Image::BitmapData bm (sourceImage, Image::BitmapData::readOnly);
  238916. jintArray imageData = env->NewIntArray (bm.width * bm.height);
  238917. jint* dest = env->GetIntArrayElements (imageData, 0);
  238918. if (dest != 0)
  238919. {
  238920. const uint8* srcLine = bm.getLinePointer (0);
  238921. jint* dstLine = dest;
  238922. for (int y = 0; y < bm.height; ++y)
  238923. {
  238924. switch (bm.pixelFormat)
  238925. {
  238926. case Image::ARGB: copyPixels (dstLine, (PixelARGB*) srcLine, bm.width, bm.pixelStride); break;
  238927. case Image::RGB: copyPixels (dstLine, (PixelRGB*) srcLine, bm.width, bm.pixelStride); break;
  238928. case Image::SingleChannel: copyPixels (dstLine, (PixelAlpha*) srcLine, bm.width, bm.pixelStride); break;
  238929. default: jassertfalse; break;
  238930. }
  238931. srcLine += bm.lineStride;
  238932. dstLine += bm.width;
  238933. }
  238934. canvas.callVoidMethod (android.drawMemoryBitmap, imageData, 0, bm.width,
  238935. transform.getTranslationX(), transform.getTranslationY(),
  238936. bm.width, bm.height, true, getImagePaint());
  238937. env->ReleaseIntArrayElements (imageData, dest, 0);
  238938. env->DeleteLocalRef (imageData);
  238939. }
  238940. }
  238941. else
  238942. {
  238943. saveState();
  238944. addTransform (transform);
  238945. drawImage (sourceImage, AffineTransform::identity, fillEntireClipAsTiles);
  238946. restoreState();
  238947. }
  238948. }
  238949. }
  238950. void drawLine (const Line <float>& line)
  238951. {
  238952. canvas.callVoidMethod (android.drawLine, line.getStartX(), line.getStartY(),
  238953. line.getEndX(), line.getEndY(),
  238954. getCurrentPaint());
  238955. }
  238956. void drawVerticalLine (int x, float top, float bottom)
  238957. {
  238958. canvas.callVoidMethod (android.drawRect, (float) x, top, x + 1.0f, bottom, getCurrentPaint());
  238959. }
  238960. void drawHorizontalLine (int y, float left, float right)
  238961. {
  238962. canvas.callVoidMethod (android.drawRect, left, (float) y, right, y + 1.0f, getCurrentPaint());
  238963. }
  238964. void setFont (const Font& newFont)
  238965. {
  238966. if (currentState->font != newFont)
  238967. {
  238968. currentState->font = newFont;
  238969. currentState->typefaceNeedsUpdate = true;
  238970. }
  238971. }
  238972. const Font getFont()
  238973. {
  238974. return currentState->font;
  238975. }
  238976. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  238977. {
  238978. if (transform.isOnlyTranslation())
  238979. {
  238980. canvas.callVoidMethod (android.drawText, javaStringFromChar ((juce_wchar) glyphNumber).get(),
  238981. transform.getTranslationX(), transform.getTranslationY(),
  238982. currentState->getPaintForTypeface());
  238983. }
  238984. else
  238985. {
  238986. saveState();
  238987. addTransform (transform);
  238988. drawGlyph (glyphNumber, AffineTransform::identity);
  238989. restoreState();
  238990. }
  238991. }
  238992. void saveState()
  238993. {
  238994. (void) canvas.callIntMethod (android.save);
  238995. stateStack.add (new SavedState (*currentState));
  238996. }
  238997. void restoreState()
  238998. {
  238999. canvas.callVoidMethod (android.restore);
  239000. SavedState* const top = stateStack.getLast();
  239001. if (top != 0)
  239002. {
  239003. currentState = top;
  239004. stateStack.removeLast (1, false);
  239005. }
  239006. else
  239007. {
  239008. jassertfalse; // trying to pop with an empty stack!
  239009. }
  239010. }
  239011. void beginTransparencyLayer (float opacity)
  239012. {
  239013. // TODO xxx
  239014. }
  239015. void endTransparencyLayer()
  239016. {
  239017. // TODO xxx
  239018. }
  239019. class SavedState
  239020. {
  239021. public:
  239022. SavedState()
  239023. : font (1.0f), fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  239024. {
  239025. }
  239026. SavedState (const SavedState& other)
  239027. : fillType (other.fillType), font (other.font), fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  239028. {
  239029. }
  239030. void setFillType (const FillType& newType)
  239031. {
  239032. fillNeedsUpdate = true;
  239033. fillType = newType;
  239034. }
  239035. void setAlpha (float alpha)
  239036. {
  239037. fillNeedsUpdate = true;
  239038. fillType.colour = fillType.colour.withAlpha (alpha);
  239039. }
  239040. jobject getPaint()
  239041. {
  239042. if (fillNeedsUpdate)
  239043. {
  239044. JNIEnv* env = getEnv();
  239045. if (paint.get() == 0)
  239046. paint = GlobalRef (android.createPaint());
  239047. if (fillType.isColour())
  239048. {
  239049. env->DeleteLocalRef (paint.callObjectMethod (android.setShader, (jobject) 0));
  239050. paint.callVoidMethod (android.setColor, colourToInt (fillType.colour));
  239051. }
  239052. else if (fillType.isGradient())
  239053. {
  239054. const ColourGradient& g = *fillType.gradient;
  239055. const Point<float> p1 (g.point1);
  239056. const Point<float> p2 (g.point2);
  239057. const int numColours = g.getNumColours();
  239058. jintArray coloursArray = env->NewIntArray (numColours);
  239059. jfloatArray positionsArray = env->NewFloatArray (numColours);
  239060. {
  239061. HeapBlock<int> colours (numColours);
  239062. HeapBlock<float> positions (numColours);
  239063. for (int i = 0; i < numColours; ++i)
  239064. {
  239065. colours[i] = colourToInt (g.getColour (i));
  239066. positions[i] = (float) g.getColourPosition(i);
  239067. }
  239068. env->SetIntArrayRegion (coloursArray, 0, numColours, colours.getData());
  239069. env->SetFloatArrayRegion (positionsArray, 0, numColours, positions.getData());
  239070. }
  239071. jobject tileMode = env->GetStaticObjectField (android.shaderTileModeClass, android.clampMode);
  239072. jobject shader;
  239073. if (fillType.gradient->isRadial)
  239074. {
  239075. shader = env->NewObject (android.radialGradientClass,
  239076. android.radialGradientConstructor,
  239077. p1.getX(), p1.getY(),
  239078. p1.getDistanceFrom (p2),
  239079. coloursArray, positionsArray,
  239080. tileMode);
  239081. }
  239082. else
  239083. {
  239084. shader = env->NewObject (android.linearGradientClass,
  239085. android.linearGradientConstructor,
  239086. p1.getX(), p1.getY(), p2.getX(), p2.getY(),
  239087. coloursArray, positionsArray,
  239088. tileMode);
  239089. }
  239090. env->DeleteLocalRef (tileMode);
  239091. env->DeleteLocalRef (coloursArray);
  239092. env->DeleteLocalRef (positionsArray);
  239093. env->CallVoidMethod (shader, android.setLocalMatrix, createMatrix (env, fillType.transform).get());
  239094. env->DeleteLocalRef (paint.callObjectMethod (android.setShader, shader));
  239095. env->DeleteLocalRef (shader);
  239096. }
  239097. else
  239098. {
  239099. }
  239100. }
  239101. return paint.get();
  239102. }
  239103. jobject getPaintForTypeface()
  239104. {
  239105. jobject p = getPaint();
  239106. if (typefaceNeedsUpdate)
  239107. {
  239108. typefaceNeedsUpdate = false;
  239109. const Typeface::Ptr t (font.getTypeface());
  239110. AndroidTypeface* atf = dynamic_cast <AndroidTypeface*> (t.getObject());
  239111. if (atf != 0)
  239112. {
  239113. paint.callObjectMethod (android.setTypeface, atf->typeface.get());
  239114. paint.callVoidMethod (android.setTextSize, font.getHeight());
  239115. }
  239116. fillNeedsUpdate = true;
  239117. paint.callVoidMethod (android.setAlpha, (jint) fillType.colour.getAlpha());
  239118. }
  239119. return p;
  239120. }
  239121. jobject getImagePaint()
  239122. {
  239123. jobject p = getPaint();
  239124. paint.callVoidMethod (android.setAlpha, (jint) fillType.colour.getAlpha());
  239125. fillNeedsUpdate = true;
  239126. return p;
  239127. }
  239128. FillType fillType;
  239129. Font font;
  239130. GlobalRef paint;
  239131. bool fillNeedsUpdate, typefaceNeedsUpdate;
  239132. };
  239133. private:
  239134. GlobalRef canvas;
  239135. ScopedPointer <SavedState> currentState;
  239136. OwnedArray <SavedState> stateStack;
  239137. jobject getCurrentPaint() const { return currentState->getPaint(); }
  239138. jobject getImagePaint() const { return currentState->getImagePaint(); }
  239139. static const LocalRef<jobject> createPath (JNIEnv* env, const Path& path)
  239140. {
  239141. jobject p = env->NewObject (android.pathClass, android.pathClassConstructor);
  239142. Path::Iterator i (path);
  239143. while (i.next())
  239144. {
  239145. switch (i.elementType)
  239146. {
  239147. case Path::Iterator::startNewSubPath: env->CallVoidMethod (p, android.moveTo, i.x1, i.y1); break;
  239148. case Path::Iterator::lineTo: env->CallVoidMethod (p, android.lineTo, i.x1, i.y1); break;
  239149. case Path::Iterator::quadraticTo: env->CallVoidMethod (p, android.quadTo, i.x1, i.y1, i.x2, i.y2); break;
  239150. case Path::Iterator::cubicTo: env->CallVoidMethod (p, android.cubicTo, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  239151. case Path::Iterator::closePath: env->CallVoidMethod (p, android.closePath); break;
  239152. default: jassertfalse; break;
  239153. }
  239154. }
  239155. return LocalRef<jobject> (p);
  239156. }
  239157. static const LocalRef<jobject> createPath (JNIEnv* env, const Path& path, const AffineTransform& transform)
  239158. {
  239159. if (transform.isIdentity())
  239160. return createPath (env, path);
  239161. Path tempPath (path);
  239162. tempPath.applyTransform (transform);
  239163. return createPath (env, tempPath);
  239164. }
  239165. static const LocalRef<jobject> createMatrix (JNIEnv* env, const AffineTransform& t)
  239166. {
  239167. jobject m = env->NewObject (android.matrixClass, android.matrixClassConstructor);
  239168. jfloat values[9] = { t.mat00, t.mat01, t.mat02,
  239169. t.mat10, t.mat11, t.mat12,
  239170. 0.0f, 0.0f, 1.0f };
  239171. jfloatArray javaArray = env->NewFloatArray (9);
  239172. env->SetFloatArrayRegion (javaArray, 0, 9, values);
  239173. env->CallVoidMethod (m, android.setValues, javaArray);
  239174. env->DeleteLocalRef (javaArray);
  239175. return LocalRef<jobject> (m);
  239176. }
  239177. static const LocalRef<jobject> createRect (JNIEnv* env, const Rectangle<int>& r)
  239178. {
  239179. return LocalRef<jobject> (env->NewObject (android.rectClass, android.rectConstructor,
  239180. r.getX(), r.getY(), r.getRight(), r.getBottom()));
  239181. }
  239182. static const LocalRef<jobject> createRegion (JNIEnv* env, const RectangleList& list)
  239183. {
  239184. jobject region = env->NewObject (android.regionClass, android.regionConstructor);
  239185. const int numRects = list.getNumRectangles();
  239186. for (int i = 0; i < numRects; ++i)
  239187. env->CallBooleanMethod (region, android.regionUnion, createRect (env, list.getRectangle(i)).get());
  239188. return LocalRef<jobject> (region);
  239189. }
  239190. static int colourToInt (const Colour& col) throw()
  239191. {
  239192. return col.getARGB();
  239193. }
  239194. template <class PixelType>
  239195. static void copyPixels (jint* const dest, const PixelType* src, const int width, const int pixelStride) throw()
  239196. {
  239197. for (int x = 0; x < width; ++x)
  239198. {
  239199. dest[x] = src->getUnpremultipliedARGB();
  239200. src = addBytesToPointer (src, pixelStride);
  239201. }
  239202. }
  239203. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  239204. };
  239205. LowLevelGraphicsContext* AndroidImage::createLowLevelContext()
  239206. {
  239207. jobject canvas = getEnv()->NewObject (android.canvasClass, android.canvasBitmapConstructor, bitmap.get());
  239208. return new AndroidLowLevelGraphicsContext (canvas);
  239209. }
  239210. #endif
  239211. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  239212. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  239213. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  239214. // compiled on its own).
  239215. #if JUCE_INCLUDED_FILE
  239216. class AndroidComponentPeer : public ComponentPeer
  239217. {
  239218. public:
  239219. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  239220. : ComponentPeer (component, windowStyleFlags),
  239221. view (android.activity.callObjectMethod (android.createNewView, component->isOpaque()))
  239222. {
  239223. if (isFocused())
  239224. handleFocusGain();
  239225. }
  239226. ~AndroidComponentPeer()
  239227. {
  239228. android.activity.callVoidMethod (android.deleteView, view.get());
  239229. view.clear();
  239230. }
  239231. void* getNativeHandle() const
  239232. {
  239233. return (void*) view.get();
  239234. }
  239235. void setVisible (bool shouldBeVisible)
  239236. {
  239237. view.callVoidMethod (android.setVisible, shouldBeVisible);
  239238. }
  239239. void setTitle (const String& title)
  239240. {
  239241. view.callVoidMethod (android.setViewName, javaString (title).get());
  239242. }
  239243. void setPosition (int x, int y)
  239244. {
  239245. const Rectangle<int> pos (getBounds());
  239246. setBounds (x, y, pos.getWidth(), pos.getHeight(), false);
  239247. }
  239248. void setSize (int w, int h)
  239249. {
  239250. const Rectangle<int> pos (getBounds());
  239251. setBounds (pos.getX(), pos.getY(), w, h, false);
  239252. }
  239253. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  239254. {
  239255. view.callVoidMethod (android.layout, x, y, x + w, y + h);
  239256. }
  239257. const Rectangle<int> getBounds() const
  239258. {
  239259. return Rectangle<int> (view.callIntMethod (android.getLeft),
  239260. view.callIntMethod (android.getTop),
  239261. view.callIntMethod (android.getWidth),
  239262. view.callIntMethod (android.getHeight));
  239263. }
  239264. const Point<int> getScreenPosition() const
  239265. {
  239266. /*JNIEnv* const env = getEnv();
  239267. jintArray pos = env->NewIntArray (2);
  239268. view.callVoidMethod (android.getLocationOnScreen, pos);
  239269. jint coords[2];
  239270. env->GetIntArrayRegion (pos, 0, 2, coords);
  239271. env->DeleteLocalRef (pos);
  239272. return Point<int> (coords[0], coords[1]);*/
  239273. return Point<int> (view.callIntMethod (android.getLeft),
  239274. view.callIntMethod (android.getTop));
  239275. }
  239276. const Point<int> localToGlobal (const Point<int>& relativePosition)
  239277. {
  239278. return relativePosition + getScreenPosition();
  239279. }
  239280. const Point<int> globalToLocal (const Point<int>& screenPosition)
  239281. {
  239282. return screenPosition - getScreenPosition();
  239283. }
  239284. void setMinimised (bool shouldBeMinimised)
  239285. {
  239286. // TODO
  239287. }
  239288. bool isMinimised() const
  239289. {
  239290. return false;
  239291. }
  239292. void setFullScreen (bool shouldBeFullScreen)
  239293. {
  239294. // TODO
  239295. }
  239296. bool isFullScreen() const
  239297. {
  239298. // TODO
  239299. return false;
  239300. }
  239301. void setIcon (const Image& newIcon)
  239302. {
  239303. // TODO
  239304. }
  239305. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  239306. {
  239307. return isPositiveAndBelow (position.getX(), component->getWidth())
  239308. && isPositiveAndBelow (position.getY(), component->getHeight())
  239309. && ((! trueIfInAChildWindow) || view.callBooleanMethod (android.containsPoint, position.getX(), position.getY()));
  239310. }
  239311. const BorderSize<int> getFrameSize() const
  239312. {
  239313. // TODO
  239314. return BorderSize<int>();
  239315. }
  239316. bool setAlwaysOnTop (bool alwaysOnTop)
  239317. {
  239318. // TODO
  239319. return false;
  239320. }
  239321. void toFront (bool makeActive)
  239322. {
  239323. view.callVoidMethod (android.bringToFront);
  239324. if (makeActive)
  239325. grabFocus();
  239326. handleBroughtToFront();
  239327. }
  239328. void toBehind (ComponentPeer* other)
  239329. {
  239330. // TODO
  239331. }
  239332. void handleMouseDownCallback (float x, float y, int64 time)
  239333. {
  239334. lastMousePos.setXY ((int) x, (int) y);
  239335. currentModifiers = currentModifiers.withoutMouseButtons();
  239336. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239337. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  239338. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239339. }
  239340. void handleMouseDragCallback (float x, float y, int64 time)
  239341. {
  239342. lastMousePos.setXY ((int) x, (int) y);
  239343. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239344. }
  239345. void handleMouseUpCallback (float x, float y, int64 time)
  239346. {
  239347. lastMousePos.setXY ((int) x, (int) y);
  239348. currentModifiers = currentModifiers.withoutMouseButtons();
  239349. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239350. }
  239351. bool isFocused() const
  239352. {
  239353. return view.callBooleanMethod (android.hasFocus);
  239354. }
  239355. void grabFocus()
  239356. {
  239357. view.callBooleanMethod (android.requestFocus);
  239358. }
  239359. void handleFocusChangeCallback (bool hasFocus)
  239360. {
  239361. if (hasFocus)
  239362. handleFocusGain();
  239363. else
  239364. handleFocusLoss();
  239365. }
  239366. void textInputRequired (const Point<int>& position)
  239367. {
  239368. // TODO
  239369. }
  239370. void handlePaintCallback (JNIEnv* env, jobject canvas)
  239371. {
  239372. AndroidLowLevelGraphicsContext g (canvas);
  239373. handlePaint (g);
  239374. }
  239375. void repaint (const Rectangle<int>& area)
  239376. {
  239377. view.callVoidMethod (android.invalidate, area.getX(), area.getY(), area.getRight(), area.getBottom());
  239378. }
  239379. void performAnyPendingRepaintsNow()
  239380. {
  239381. // TODO
  239382. }
  239383. void setAlpha (float newAlpha)
  239384. {
  239385. // TODO
  239386. }
  239387. static AndroidComponentPeer* findPeerForJavaView (jobject viewToFind)
  239388. {
  239389. for (int i = getNumPeers(); --i >= 0;)
  239390. {
  239391. AndroidComponentPeer* const ap = static_cast <AndroidComponentPeer*> (getPeer(i));
  239392. jassert (dynamic_cast <AndroidComponentPeer*> (getPeer(i)) != 0);
  239393. if (ap->view == viewToFind)
  239394. return ap;
  239395. }
  239396. return 0;
  239397. }
  239398. static ModifierKeys currentModifiers;
  239399. static Point<int> lastMousePos;
  239400. private:
  239401. GlobalRef view;
  239402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  239403. };
  239404. ModifierKeys AndroidComponentPeer::currentModifiers = 0;
  239405. Point<int> AndroidComponentPeer::lastMousePos;
  239406. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  239407. JUCE_JNI_CALLBACK (ComponentPeerView, javaMethodName, returnType, params) \
  239408. { \
  239409. AndroidComponentPeer* const peer = AndroidComponentPeer::findPeerForJavaView (view); \
  239410. if (peer != 0) \
  239411. peer->juceMethodInvocation; \
  239412. }
  239413. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject view, jobject canvas),
  239414. handlePaintCallback (env, canvas))
  239415. JUCE_VIEW_CALLBACK (void, handleMouseDown, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239416. handleMouseDownCallback ((float) x, (float) y, (int64) time))
  239417. JUCE_VIEW_CALLBACK (void, handleMouseDrag, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239418. handleMouseDragCallback ((float) x, (float) y, (int64) time))
  239419. JUCE_VIEW_CALLBACK (void, handleMouseUp, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239420. handleMouseUpCallback ((float) x, (float) y, (int64) time))
  239421. JUCE_VIEW_CALLBACK (void, viewSizeChanged, (JNIEnv*, jobject view),
  239422. handleMovedOrResized())
  239423. JUCE_VIEW_CALLBACK (void, focusChanged, (JNIEnv*, jobject view, jboolean hasFocus),
  239424. handleFocusChangeCallback (hasFocus))
  239425. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  239426. {
  239427. return new AndroidComponentPeer (this, styleFlags);
  239428. }
  239429. bool Desktop::canUseSemiTransparentWindows() throw()
  239430. {
  239431. return true; // TODO
  239432. }
  239433. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  239434. {
  239435. // TODO
  239436. return upright;
  239437. }
  239438. void Desktop::createMouseInputSources()
  239439. {
  239440. // This creates a mouse input source for each possible finger
  239441. for (int i = 0; i < 10; ++i)
  239442. mouseSources.add (new MouseInputSource (i, false));
  239443. }
  239444. const Point<int> MouseInputSource::getCurrentMousePosition()
  239445. {
  239446. return AndroidComponentPeer::lastMousePos;
  239447. }
  239448. void Desktop::setMousePosition (const Point<int>& newPosition)
  239449. {
  239450. // not needed
  239451. }
  239452. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  239453. {
  239454. // TODO
  239455. return false;
  239456. }
  239457. void ModifierKeys::updateCurrentModifiers() throw()
  239458. {
  239459. currentModifiers = AndroidComponentPeer::currentModifiers;
  239460. }
  239461. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  239462. {
  239463. return AndroidComponentPeer::currentModifiers;
  239464. }
  239465. bool Process::isForegroundProcess()
  239466. {
  239467. return true; // TODO
  239468. }
  239469. bool AlertWindow::showNativeDialogBox (const String& title,
  239470. const String& bodyText,
  239471. bool isOkCancel)
  239472. {
  239473. // TODO
  239474. }
  239475. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  239476. {
  239477. // TODO
  239478. }
  239479. bool Desktop::isScreenSaverEnabled()
  239480. {
  239481. return true;
  239482. }
  239483. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  239484. {
  239485. }
  239486. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  239487. {
  239488. monitorCoords.add (Rectangle<int> (0, 0, android.screenWidth, android.screenHeight));
  239489. }
  239490. const Image juce_createIconForFile (const File& file)
  239491. {
  239492. Image image;
  239493. // TODO
  239494. return image;
  239495. }
  239496. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  239497. {
  239498. return 0;
  239499. }
  239500. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  239501. {
  239502. }
  239503. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  239504. {
  239505. return 0;
  239506. }
  239507. void MouseCursor::showInWindow (ComponentPeer*) const {}
  239508. void MouseCursor::showInAllWindows() const {}
  239509. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  239510. {
  239511. return false;
  239512. }
  239513. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  239514. {
  239515. return false;
  239516. }
  239517. const int extendedKeyModifier = 0x10000;
  239518. const int KeyPress::spaceKey = ' ';
  239519. const int KeyPress::returnKey = 0x0d;
  239520. const int KeyPress::escapeKey = 0x1b;
  239521. const int KeyPress::backspaceKey = 0x7f;
  239522. const int KeyPress::leftKey = extendedKeyModifier + 1;
  239523. const int KeyPress::rightKey = extendedKeyModifier + 2;
  239524. const int KeyPress::upKey = extendedKeyModifier + 3;
  239525. const int KeyPress::downKey = extendedKeyModifier + 4;
  239526. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  239527. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  239528. const int KeyPress::endKey = extendedKeyModifier + 7;
  239529. const int KeyPress::homeKey = extendedKeyModifier + 8;
  239530. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  239531. const int KeyPress::insertKey = -1;
  239532. const int KeyPress::tabKey = 9;
  239533. const int KeyPress::F1Key = extendedKeyModifier + 10;
  239534. const int KeyPress::F2Key = extendedKeyModifier + 11;
  239535. const int KeyPress::F3Key = extendedKeyModifier + 12;
  239536. const int KeyPress::F4Key = extendedKeyModifier + 13;
  239537. const int KeyPress::F5Key = extendedKeyModifier + 14;
  239538. const int KeyPress::F6Key = extendedKeyModifier + 16;
  239539. const int KeyPress::F7Key = extendedKeyModifier + 17;
  239540. const int KeyPress::F8Key = extendedKeyModifier + 18;
  239541. const int KeyPress::F9Key = extendedKeyModifier + 19;
  239542. const int KeyPress::F10Key = extendedKeyModifier + 20;
  239543. const int KeyPress::F11Key = extendedKeyModifier + 21;
  239544. const int KeyPress::F12Key = extendedKeyModifier + 22;
  239545. const int KeyPress::F13Key = extendedKeyModifier + 23;
  239546. const int KeyPress::F14Key = extendedKeyModifier + 24;
  239547. const int KeyPress::F15Key = extendedKeyModifier + 25;
  239548. const int KeyPress::F16Key = extendedKeyModifier + 26;
  239549. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  239550. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  239551. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  239552. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  239553. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  239554. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  239555. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  239556. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  239557. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  239558. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  239559. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  239560. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  239561. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  239562. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  239563. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  239564. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  239565. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  239566. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  239567. const int KeyPress::playKey = extendedKeyModifier + 45;
  239568. const int KeyPress::stopKey = extendedKeyModifier + 46;
  239569. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  239570. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  239571. #endif
  239572. /*** End of inlined file: juce_android_Windowing.cpp ***/
  239573. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  239574. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239575. // compiled on its own).
  239576. #if JUCE_INCLUDED_FILE
  239577. void FileChooser::showPlatformDialog (Array<File>& results,
  239578. const String& title,
  239579. const File& currentFileOrDirectory,
  239580. const String& filter,
  239581. bool selectsDirectory,
  239582. bool selectsFiles,
  239583. bool isSaveDialogue,
  239584. bool warnAboutOverwritingExistingFiles,
  239585. bool selectMultipleFiles,
  239586. FilePreviewComponent* extraInfoComponent)
  239587. {
  239588. // TODO
  239589. }
  239590. #endif
  239591. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  239592. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  239593. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239594. // compiled on its own).
  239595. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  239596. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  239597. : browser (0),
  239598. blankPageShown (false),
  239599. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  239600. {
  239601. setOpaque (true);
  239602. }
  239603. WebBrowserComponent::~WebBrowserComponent()
  239604. {
  239605. }
  239606. void WebBrowserComponent::goToURL (const String& url,
  239607. const StringArray* headers,
  239608. const MemoryBlock* postData)
  239609. {
  239610. lastURL = url;
  239611. lastHeaders.clear();
  239612. if (headers != 0)
  239613. lastHeaders = *headers;
  239614. lastPostData.setSize (0);
  239615. if (postData != 0)
  239616. lastPostData = *postData;
  239617. blankPageShown = false;
  239618. }
  239619. void WebBrowserComponent::stop()
  239620. {
  239621. }
  239622. void WebBrowserComponent::goBack()
  239623. {
  239624. lastURL = String::empty;
  239625. blankPageShown = false;
  239626. }
  239627. void WebBrowserComponent::goForward()
  239628. {
  239629. lastURL = String::empty;
  239630. }
  239631. void WebBrowserComponent::refresh()
  239632. {
  239633. }
  239634. void WebBrowserComponent::paint (Graphics& g)
  239635. {
  239636. g.fillAll (Colours::white);
  239637. }
  239638. void WebBrowserComponent::checkWindowAssociation()
  239639. {
  239640. }
  239641. void WebBrowserComponent::reloadLastURL()
  239642. {
  239643. if (lastURL.isNotEmpty())
  239644. {
  239645. goToURL (lastURL, &lastHeaders, &lastPostData);
  239646. lastURL = String::empty;
  239647. }
  239648. }
  239649. void WebBrowserComponent::parentHierarchyChanged()
  239650. {
  239651. checkWindowAssociation();
  239652. }
  239653. void WebBrowserComponent::resized()
  239654. {
  239655. }
  239656. void WebBrowserComponent::visibilityChanged()
  239657. {
  239658. checkWindowAssociation();
  239659. }
  239660. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  239661. {
  239662. return true;
  239663. }
  239664. #endif
  239665. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  239666. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  239667. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239668. // compiled on its own).
  239669. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  239670. // TODO
  239671. OpenGLContext* OpenGLComponent::createContext()
  239672. {
  239673. return 0;
  239674. }
  239675. void* OpenGLComponent::getNativeWindowHandle() const
  239676. {
  239677. return 0;
  239678. }
  239679. void juce_glViewport (const int w, const int h)
  239680. {
  239681. // glViewport (0, 0, w, h);
  239682. }
  239683. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  239684. OwnedArray <OpenGLPixelFormat>& results)
  239685. {
  239686. }
  239687. #endif
  239688. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  239689. /*** Start of inlined file: juce_android_Midi.cpp ***/
  239690. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239691. // compiled on its own).
  239692. #if JUCE_INCLUDED_FILE
  239693. const StringArray MidiOutput::getDevices()
  239694. {
  239695. StringArray devices;
  239696. return devices;
  239697. }
  239698. int MidiOutput::getDefaultDeviceIndex()
  239699. {
  239700. return 0;
  239701. }
  239702. MidiOutput* MidiOutput::openDevice (int index)
  239703. {
  239704. return 0;
  239705. }
  239706. MidiOutput::~MidiOutput()
  239707. {
  239708. }
  239709. void MidiOutput::reset()
  239710. {
  239711. }
  239712. bool MidiOutput::getVolume (float&, float&)
  239713. {
  239714. return false;
  239715. }
  239716. void MidiOutput::setVolume (float, float)
  239717. {
  239718. }
  239719. void MidiOutput::sendMessageNow (const MidiMessage&)
  239720. {
  239721. }
  239722. MidiInput::MidiInput (const String& name_)
  239723. : name (name_),
  239724. internal (0)
  239725. {
  239726. }
  239727. MidiInput::~MidiInput()
  239728. {
  239729. }
  239730. void MidiInput::start()
  239731. {
  239732. }
  239733. void MidiInput::stop()
  239734. {
  239735. }
  239736. int MidiInput::getDefaultDeviceIndex()
  239737. {
  239738. return 0;
  239739. }
  239740. const StringArray MidiInput::getDevices()
  239741. {
  239742. StringArray devs;
  239743. return devs;
  239744. }
  239745. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  239746. {
  239747. return 0;
  239748. }
  239749. #endif
  239750. /*** End of inlined file: juce_android_Midi.cpp ***/
  239751. /*** Start of inlined file: juce_android_Audio.cpp ***/
  239752. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239753. // compiled on its own).
  239754. #if JUCE_INCLUDED_FILE
  239755. class AndroidAudioIODevice : public AudioIODevice
  239756. {
  239757. public:
  239758. AndroidAudioIODevice (const String& deviceName)
  239759. : AudioIODevice (deviceName, "Audio"),
  239760. callback (0),
  239761. sampleRate (0),
  239762. numInputChannels (0),
  239763. numOutputChannels (0),
  239764. actualBufferSize (0),
  239765. isRunning (false)
  239766. {
  239767. numInputChannels = 2;
  239768. numOutputChannels = 2;
  239769. // TODO
  239770. }
  239771. ~AndroidAudioIODevice()
  239772. {
  239773. close();
  239774. }
  239775. const StringArray getOutputChannelNames()
  239776. {
  239777. StringArray s;
  239778. s.add ("Left"); // TODO
  239779. s.add ("Right");
  239780. return s;
  239781. }
  239782. const StringArray getInputChannelNames()
  239783. {
  239784. StringArray s;
  239785. s.add ("Left");
  239786. s.add ("Right");
  239787. return s;
  239788. }
  239789. int getNumSampleRates() { return 1;}
  239790. double getSampleRate (int index) { return sampleRate; }
  239791. int getNumBufferSizesAvailable() { return 1; }
  239792. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  239793. int getDefaultBufferSize() { return 1024; }
  239794. const String open (const BigInteger& inputChannels,
  239795. const BigInteger& outputChannels,
  239796. double sampleRate,
  239797. int bufferSize)
  239798. {
  239799. close();
  239800. lastError = String::empty;
  239801. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  239802. activeOutputChans = outputChannels;
  239803. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  239804. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  239805. activeInputChans = inputChannels;
  239806. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  239807. numInputChannels = activeInputChans.countNumberOfSetBits();
  239808. // TODO
  239809. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  239810. isRunning = true;
  239811. return lastError;
  239812. }
  239813. void close()
  239814. {
  239815. if (isRunning)
  239816. {
  239817. isRunning = false;
  239818. // TODO
  239819. }
  239820. }
  239821. int getOutputLatencyInSamples()
  239822. {
  239823. return 0; // TODO
  239824. }
  239825. int getInputLatencyInSamples()
  239826. {
  239827. return 0; // TODO
  239828. }
  239829. bool isOpen() { return isRunning; }
  239830. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  239831. int getCurrentBitDepth() { return 16; }
  239832. double getCurrentSampleRate() { return sampleRate; }
  239833. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  239834. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  239835. const String getLastError() { return lastError; }
  239836. bool isPlaying() { return isRunning && callback != 0; }
  239837. // TODO
  239838. void start (AudioIODeviceCallback* newCallback)
  239839. {
  239840. if (isRunning && callback != newCallback)
  239841. {
  239842. if (newCallback != 0)
  239843. newCallback->audioDeviceAboutToStart (this);
  239844. const ScopedLock sl (callbackLock);
  239845. callback = newCallback;
  239846. }
  239847. }
  239848. void stop()
  239849. {
  239850. if (isRunning)
  239851. {
  239852. AudioIODeviceCallback* lastCallback;
  239853. {
  239854. const ScopedLock sl (callbackLock);
  239855. lastCallback = callback;
  239856. callback = 0;
  239857. }
  239858. if (lastCallback != 0)
  239859. lastCallback->audioDeviceStopped();
  239860. }
  239861. }
  239862. private:
  239863. CriticalSection callbackLock;
  239864. AudioIODeviceCallback* callback;
  239865. double sampleRate;
  239866. int numInputChannels, numOutputChannels;
  239867. int actualBufferSize;
  239868. bool isRunning;
  239869. String lastError;
  239870. BigInteger activeOutputChans, activeInputChans;
  239871. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  239872. };
  239873. // TODO
  239874. class AndroidAudioIODeviceType : public AudioIODeviceType
  239875. {
  239876. public:
  239877. AndroidAudioIODeviceType()
  239878. : AudioIODeviceType ("Android Audio")
  239879. {
  239880. }
  239881. void scanForDevices()
  239882. {
  239883. }
  239884. const StringArray getDeviceNames (bool wantInputNames) const
  239885. {
  239886. StringArray s;
  239887. s.add ("Android Audio");
  239888. return s;
  239889. }
  239890. int getDefaultDeviceIndex (bool forInput) const
  239891. {
  239892. return 0;
  239893. }
  239894. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  239895. {
  239896. return device != 0 ? 0 : -1;
  239897. }
  239898. bool hasSeparateInputsAndOutputs() const { return false; }
  239899. AudioIODevice* createDevice (const String& outputDeviceName,
  239900. const String& inputDeviceName)
  239901. {
  239902. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  239903. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  239904. : inputDeviceName);
  239905. return 0;
  239906. }
  239907. private:
  239908. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  239909. };
  239910. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  239911. {
  239912. return new AndroidAudioIODeviceType();
  239913. }
  239914. #endif
  239915. /*** End of inlined file: juce_android_Audio.cpp ***/
  239916. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  239917. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  239918. // compiled on its own).
  239919. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  239920. // TODO
  239921. class AndroidCameraInternal
  239922. {
  239923. public:
  239924. AndroidCameraInternal()
  239925. {
  239926. }
  239927. ~AndroidCameraInternal()
  239928. {
  239929. }
  239930. private:
  239931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  239932. };
  239933. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  239934. : name (name_)
  239935. {
  239936. internal = new AndroidCameraInternal();
  239937. // TODO
  239938. }
  239939. CameraDevice::~CameraDevice()
  239940. {
  239941. stopRecording();
  239942. delete static_cast <AndroidCameraInternal*> (internal);
  239943. internal = 0;
  239944. }
  239945. Component* CameraDevice::createViewerComponent()
  239946. {
  239947. // TODO
  239948. return 0;
  239949. }
  239950. const String CameraDevice::getFileExtension()
  239951. {
  239952. return ".m4a"; // TODO correct?
  239953. }
  239954. void CameraDevice::startRecordingToFile (const File& file, int quality)
  239955. {
  239956. // TODO
  239957. }
  239958. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  239959. {
  239960. // TODO
  239961. return Time();
  239962. }
  239963. void CameraDevice::stopRecording()
  239964. {
  239965. // TODO
  239966. }
  239967. void CameraDevice::addListener (Listener* listenerToAdd)
  239968. {
  239969. // TODO
  239970. }
  239971. void CameraDevice::removeListener (Listener* listenerToRemove)
  239972. {
  239973. // TODO
  239974. }
  239975. const StringArray CameraDevice::getAvailableDevices()
  239976. {
  239977. StringArray devs;
  239978. // TODO
  239979. return devs;
  239980. }
  239981. CameraDevice* CameraDevice::openDevice (int index,
  239982. int minWidth, int minHeight,
  239983. int maxWidth, int maxHeight)
  239984. {
  239985. // TODO
  239986. return 0;
  239987. }
  239988. #endif
  239989. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  239990. END_JUCE_NAMESPACE
  239991. #endif
  239992. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  239993. #endif
  239994. #endif